blob_id
large_stringlengths 40
40
| language
large_stringclasses 1
value | repo_name
large_stringlengths 5
119
| path
large_stringlengths 4
271
| score
float64 2.52
4.84
| int_score
int64 3
5
| text
stringlengths 26
4.09M
|
|---|---|---|---|---|---|---|
24566596057cfa4ce4f77e3d11035bff0f0703f8
|
C#
|
gimlichael/CuemonNetFramework
|
/Cuemon/Diagnostics/ITimeMeasuring.cs
| 2.859375
| 3
|
using System;
using System.Diagnostics;
namespace Cuemon.Diagnostics
{
/// <summary>
/// Specifies a simple way to measure elapsed time for events or similar.
/// </summary>
public interface ITimeMeasuring
{
/// <summary>
/// Gets the timer that is used to accurately measure elapsed time.
/// </summary>
/// <value>The timer that is used to accurately measure elapsed time.</value>
Stopwatch Timer { get; }
/// <summary>
/// Gets or sets the callback delegate for the measured elapsed time.
/// </summary>
/// <value>The callback delegate for the measured elapsed time.</value>
Act<string, TimeSpan> TimeMeasuringCallback { get; set; }
/// <summary>
/// Gets or sets a value indicating whether time measuring is enabled.
/// </summary>
/// <value><c>true</c> if time measuring is enabled; otherwise, <c>false</c>.</value>
bool EnableTimeMeasuring { get; set; }
}
}
|
c594d4f96bceeffa404f37c2d11d7e1d9ddd8af3
|
C#
|
guiboars/GeneratorControl
|
/Tests/SensorTest.cs
| 2.78125
| 3
|
using GeneratorControl;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace Tests
{
/// <summary>
///This is a test class for SensorTest and is intended
///to contain all SensorTest Unit Tests
///</summary>
[TestClass()]
public class SensorTest
{
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
//You can use the following additional attributes as you write your tests:
//
//Use ClassInitialize to run code before running the first test in the class
//[ClassInitialize()]
//public static void MyClassInitialize(TestContext testContext)
//{
//}
//
//Use ClassCleanup to run code after all tests in a class have run
//[ClassCleanup()]
//public static void MyClassCleanup()
//{
//}
//
//Use TestInitialize to run code before running each test
//[TestInitialize()]
//public void MyTestInitialize()
//{
//}
//
//Use TestCleanup to run code after each test has run
//[TestCleanup()]
//public void MyTestCleanup()
//{
//}
//
#endregion
/// <summary>
///A test for Sensor Constructor
///</summary>
[TestMethod()]
public void SensorConstructorTest()
{
var target = new Sensor.Sensor();
Assert.IsNotNull(target); // this should be sufficient for now.
}
/// <summary>
///A test for Status
///</summary>
[TestMethod()]
public void StatusTest()
{
var sensorFalse = new Sensor.Sensor() { Status = false };
var sensorTrue = new Sensor.Sensor() { Status = true };
Assert.IsNotNull(sensorFalse);
Assert.IsNotNull(sensorTrue);
Assert.IsTrue(sensorTrue.Status);
Assert.IsFalse(sensorFalse.Status);
}
}
}
|
7fcdeb8002ecbd009acdb1a12d6f1df7b4e9fd97
|
C#
|
Infarh/MathCore
|
/MathCore/Graphs/LambdaGraphNode.cs
| 2.84375
| 3
|
#nullable enable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
// ReSharper disable UnusedMember.Global
namespace MathCore.Graphs;
public class LambdaGraphNode<TValue, TWeight> : IGraphNode<TValue, TWeight>, IEquatable<LambdaGraphNode<TValue, TWeight>>
{
private readonly Func<TValue, IEnumerable<TValue>> _GetChilds;
private readonly Func<TValue, TValue, TWeight> _GetWeight;
private readonly bool _Buffered;
private IGraphLink<TValue, TWeight>[]? _Links;
/// <inheritdoc />
public IEnumerable<IGraphLink<TValue, TWeight>> Links => _Buffered
? _Links ??= (_GetChilds(Value) ?? Enumerable.Empty<TValue>())
.Select(v => new LambdaGraphNode<TValue, TWeight>(v, _GetChilds, _GetWeight, _Buffered))
.Select(to => new LambdaGraphLink<TValue, TWeight>(this, to, _GetWeight, _Buffered))
.Cast<IGraphLink<TValue, TWeight>>().ToArray()
: (_GetChilds(Value) ?? Enumerable.Empty<TValue>())
.Select(v => new LambdaGraphNode<TValue, TWeight>(v, _GetChilds, _GetWeight))
.Select(to => new LambdaGraphLink<TValue, TWeight>(this, to, _GetWeight))
.Cast<IGraphLink<TValue, TWeight>>();
public TValue Value { get; }
public LambdaGraphNode<TValue, TWeight>[] Childs => this.Cast<LambdaGraphNode<TValue, TWeight>>().ToArray();
public LambdaGraphNode(TValue Value, Func<TValue, IEnumerable<TValue>> GetChilds, Func<TValue, TValue, TWeight> GetWeight, bool Buffered = false)
{
_GetChilds = GetChilds;
_GetWeight = GetWeight;
_Buffered = Buffered;
this.Value = Value;
}
public override int GetHashCode()
{
unchecked
{
var hash = _GetChilds?.GetHashCode() ?? 0;
hash = (hash * 397) ^ (_GetWeight?.GetHashCode() ?? 0);
hash = (hash * 397) ^ EqualityComparer<TValue>.Default.GetHashCode(Value);
return hash;
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
[DST]
public static bool operator ==(LambdaGraphNode<TValue, TWeight>? left, LambdaGraphNode<TValue, TWeight>? right) => Equals(left, right);
[DST]
public static bool operator !=(LambdaGraphNode<TValue, TWeight>? left, LambdaGraphNode<TValue, TWeight>? right) => !Equals(left, right);
public override bool Equals(object? obj) => obj != null &&
(ReferenceEquals(this, obj) ||
obj.GetType() == GetType() &&
Equals((LambdaGraphNode<TValue, TWeight>)obj));
public bool Equals(LambdaGraphNode<TValue, TWeight>? other) => other != null
&& (ReferenceEquals(this, other)
|| Equals(_GetChilds, other._GetChilds)
&& Equals(_GetWeight, other._GetWeight)
&& EqualityComparer<TValue>.Default.Equals(Value, other.Value));
[DST]
public IEnumerator<IGraphNode<TValue, TWeight>> GetEnumerator() => Links.Select(link => link.Node).GetEnumerator();
[DST] public override string ToString() => $"λ[{(Value is null ? string.Empty : Value.ToString())}]";
}
public class LambdaGraphNode<V> : IGraphNode<V>, IEquatable<LambdaGraphNode<V>>
{
private readonly Func<V, IEnumerable<V>> _GetChilds;
private readonly bool _Buffered;
private IEnumerable<IGraphNode<V>>? _Childs;
/// <summary>Связи узла</summary>
public IEnumerable<IGraphNode<V>> Childs => _Buffered
? _Childs ??= (_GetChilds(Value) ?? Enumerable.Empty<V>())
.Select(value => new LambdaGraphNode<V>(value, _GetChilds, _Buffered))
.Cast<IGraphNode<V>>()
.ToArray()
: (_GetChilds(Value) ?? Enumerable.Empty<V>()).Select(value => new LambdaGraphNode<V>(value, _GetChilds, _Buffered));
/// <summary>Значение узла</summary>
public V Value { get; set; }
public LambdaGraphNode<V>[] ChildsArray => Childs.Cast<LambdaGraphNode<V>>().ToArray();
public LambdaGraphNode(V Value, Func<V, IEnumerable<V>> GetChilds, bool Buffered = false)
{
_GetChilds = GetChilds;
_Buffered = Buffered;
this.Value = Value;
}
/// <inheritdoc />
[DST]
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
/// <inheritdoc />
[DST]
public IEnumerator<IGraphNode<V>> GetEnumerator() => Childs.GetEnumerator();
/// <inheritdoc />
[DST]
public override string ToString() => $"λ:{Value}";
/// <inheritdoc />
public bool Equals(LambdaGraphNode<V>? other) => other != null
&& (ReferenceEquals(this, other)
|| EqualityComparer<V>.Default.Equals(Value, other.Value));
/// <inheritdoc />
public override bool Equals(object? obj) => Equals(obj as LambdaGraphNode<V>);
/// <inheritdoc />
public override int GetHashCode() => EqualityComparer<V>.Default.GetHashCode(Value);
}
|
eda5d1fc2152627ad5a534c5491674fb548bcd9e
|
C#
|
iavnish/SharedExchangeEmailActivity
|
/ExchangeSharedMailBoxActivities/ExchangeSharedMailBoxActivities/SendEmail.cs
| 2.6875
| 3
|
using System;
using System.Activities;
using System.ComponentModel;
using Microsoft.Exchange.WebServices.Data;
namespace ExchangeSharedMailBoxActivities
{
public class SendEmail : CodeActivity
{
/// <summary>
/// Exchange Service as input
/// </summary>
[Category("Input")]
[DisplayName("1.Exchange Service")]
[Description("Exchange Service as input")]
[RequiredArgument]
public InArgument<ExchangeService> ObjExchangeService { get; set; }
/// <summary>
/// Mail Subject as string for sending mail
/// </summary>
[Category("Input")]
[DisplayName("2.Subject")]
[Description("Subject of mail")]
[RequiredArgument]
public InArgument<String> Subject { get; set; }
/// <summary>
/// Mail Body string
/// </summary>
[Category("Input")]
[DisplayName("3.Body")]
[Description("Body Text")]
[RequiredArgument]
public InArgument<String> Body { get; set; }
/// <summary>
/// Email address of recipient
/// </summary>
[Category("Input")]
[DisplayName("4.Recipients Emails")]
[Description("Email addresses of recipients, use ; for multiple emails")]
[RequiredArgument]
public InArgument<String> RecipientEmail { get; set; }
/// <summary>
/// Email of sender or Shared Mailbox
/// Access is required for shared mailbox
/// </summary>
[Category("Input")]
[DisplayName("5.Sender")]
[Description("Email of sender or Shared Mailbox")]
[RequiredArgument]
public InArgument<String> Sender { get; set; }
/// <summary>
/// Bool value for is HTML body content
/// </summary>
[Category("Options")]
[DisplayName("1.IsBodyHTML")]
[Description("True if body is HTML else False")]
[DefaultValue(false)]
public InArgument<bool> IsBodyHTML { get; set; }
/// <summary>
/// Copy email address of recipient
/// </summary>
[Category("Options")]
[DisplayName("2.Cc")]
[Description("The secondary recipients of the mail, use ; for multiple emails")]
public InArgument<String> Cc { get; set; }
/// <summary>
/// Email of sender or Shared Mailbox
/// Access is required for shared mailbox
/// </summary>
[Category("Options")]
[DisplayName("3.Attachments")]
[Description("File paths of a attachment as a string array")]
//public List<InArgument<String>> Attachments { get; set; }
public InArgument<string[]> Attachments { get; set; }
/// <summary>
/// Bcc recipient of the mail
/// </summary>
[Category("Options")]
[DisplayName("4.Bcc")]
[Description("Bcc recipient of the mail")]
public InArgument<String> Bcc { get; set; }
/// <summary>
/// This function for this class
/// It will send mails
/// Having option to have attachment
/// </summary>
/// <param name="context"></param>
protected override void Execute(CodeActivityContext context)
{
// getting the input values ************************
ExchangeService objExchangeService = ObjExchangeService.Get(context);
string subject = Subject.Get(context);
string body = Body.Get(context);
string sender = Sender.Get(context);
bool isBodyHTML = IsBodyHTML.Get(context);
string recipientEmail = RecipientEmail.Get(context);
string cc = Cc.Get(context);
string bcc = Bcc.Get(context);
string[] attachments = Attachments.Get(context);
//***** Sending mail Logic ******
EmailMessage email = new EmailMessage(objExchangeService);
//Check for if body is a HTML content
if (isBodyHTML)
email.Body = new MessageBody(BodyType.HTML, body);
else
email.Body = body;
// Adding Subject to mail
email.Subject = subject;
//Adding recipients to mail
string[] recipients = recipientEmail.Split(';');
foreach (string recipient in recipients)
{
email.ToRecipients.Add(recipient);
}
//If attachments
if (attachments != null && attachments.Length > 0)
foreach (string attachment in attachments)
{
email.Attachments.AddFileAttachment(attachment);
}
//If CC is available
if (cc != null && cc.Length > 0)
{
//Adding recipients to mail
string[] recipientsCC = cc.Split(';');
foreach (string recipient in recipientsCC)
{
email.CcRecipients.Add(recipient);
}
}
//If BCC is available
if (bcc != null && bcc.Length > 0)
{
//Adding recipients to mail
string[] recipientsBcc = bcc.Split(';');
foreach (string recipient in recipientsBcc)
{
email.BccRecipients.Add(recipient);
}
}
//Sending mail and saving it into sent folder
email.From = sender;
FolderView view = new FolderView(10000);
view.PropertySet = new PropertySet(BasePropertySet.IdOnly);
view.PropertySet.Add(FolderSchema.DisplayName);
view.Traversal = FolderTraversal.Deep;
Mailbox mailbox = new Mailbox(sender);
FindFoldersResults findFolderResults = objExchangeService.FindFolders(new FolderId(WellKnownFolderName.MsgFolderRoot, mailbox), view);
foreach (Folder folder in findFolderResults)
{
if(folder.DisplayName == "Sent Items")
{
email.SendAndSaveCopy(folder.Id);
}
}
}
}
}
|
0dc6115bd538f30df2c565529a6448dbdc06aac5
|
C#
|
Novaetra/MVP
|
/Assets/Final/Scripts/Objects/Elevator.cs
| 2.75
| 3
|
using UnityEngine;
using System.Collections;
public class Elevator : MonoBehaviour
{
private bool isDown = true;
private bool isMoving = false;
private GameObject player;
public void interact(object[] paramtrs)
{
player = (GameObject)paramtrs[1];
//If the elevator isn't moving
if (!isMoving)
{
//If the elevator is downstairs, make it go up
if(isDown)
{
GetComponent<Animation>().Play("ElevatorUp");
isDown = false;
isMoving = true;
}
//if the elevator is upstairs, make it go down
else
{
GetComponent<Animation>().Play("ElevatorDown");
isDown = true;
isMoving = true;
}
player.transform.parent = transform;
}
}
//Reset the player's parent so it isn't attached to elevator anymore
private void resetPlayerParent()
{
player.transform.parent = null;
}
//Sets moving to false so it can be interacted with again
private void stoppedMoving()
{
isMoving = false;
}
//Once the player leaves the elevator, remove him as a child
private void OnTriggerExit(Collider col)
{
if(player!=null && col.tag == "Player")
{
resetPlayerParent();
}
}
}
|
7e637e0a18b92d49d478b772db834969d0d68c2f
|
C#
|
CraigBanach/openmtg
|
/MTGEngine/Zones/Deck.cs
| 2.875
| 3
|
using System.Collections.Generic;
namespace MTGEngine
{
public class Library : Stack<Card>
{
public Library(IEnumerable<Card> cards)
: base(cards)
{
}
public Card Draw()
{
return this.Pop();
}
}
}
|
d3daf867eae79246a0c95d04957c201c41cdfe65
|
C#
|
Genghis-Khan2/Project01_7095_28225_dotNet5780
|
/BE/Comparer.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text;
namespace BE
{
public class HostComparer : IEqualityComparer<Host>
{
public bool Equals(Host a, Host b)
{
if (ReferenceEquals(a, b))
{
return true;
}
if (ReferenceEquals(a, null) || Object.ReferenceEquals(b, null))
{
return false;
}
return a.HostKey == b.HostKey;
}
public int GetHashCode(Host obj)
{
return obj.HostKey.GetHashCode();
}
}
public class GuestRequestComparer : IEqualityComparer<GuestRequest>
{
public bool Equals(GuestRequest a, GuestRequest b)
{
if (ReferenceEquals(a, b))
{
return true;
}
if (ReferenceEquals(a, null) || Object.ReferenceEquals(b, null))
{
return false;
}
return a.GuestRequestKey == b.GuestRequestKey;
}
public int GetHashCode(GuestRequest obj)
{
return obj.GuestRequestKey.GetHashCode();
}
}
public class OrderComparer : IEqualityComparer<Order>
{
public bool Equals(Order a, Order b)
{
if (ReferenceEquals(a, b))
{
return true;
}
if (ReferenceEquals(a, null) || Object.ReferenceEquals(b, null))
{
return false;
}
return a.OrderKey == b.OrderKey;
}
public int GetHashCode(Order obj)
{
return obj.OrderKey.GetHashCode();
}
}
}
|
25095cc3640ea30032e0011c6986ed97305d81f2
|
C#
|
yonasu/Viidya
|
/VidyaTutorial/VidyaTutorial/MouseController.cs
| 2.953125
| 3
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
namespace VidyaTutorial
{
public class MouseController
{
private readonly int _centerScreenX;
private readonly int _centerScreenY;
private const float RotateScale = MathHelper.PiOver2;
public MouseController(int windowWidth, int windowHeight)
{
_centerScreenX = windowWidth / 2;
_centerScreenY = windowHeight / 2;
}
public void Move(Camera camera, GameTime gameTime)
{
var mouseState = Mouse.GetState();
var elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
if(mouseState.X > _centerScreenX)
{
camera.RotationY = MathHelper.WrapAngle(camera.RotationY - (RotateScale * elapsed));
}
if(mouseState.X < _centerScreenX)
{
camera.RotationY = MathHelper.WrapAngle(camera.RotationY + (RotateScale * elapsed));
}
if(mouseState.Y > _centerScreenY)
{
camera.RotationX = MathHelper.WrapAngle(camera.RotationX - (RotateScale * elapsed));
}
if(mouseState.Y < _centerScreenY)
{
camera.RotationX = MathHelper.WrapAngle(camera.RotationX + (RotateScale * elapsed));
}
}
public void Draw()
{
Mouse.SetPosition(_centerScreenX, _centerScreenY);
}
}
}
|
41a3fba304e41dc6e67cfe99eaeea365e7b0f09e
|
C#
|
huda-mokhtar/Restaurant-delivery-online
|
/Restaurant delivery online/Controllers/CustomersController.cs
| 2.640625
| 3
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Restaurant_delivery_online.IServices;
using Restaurant_delivery_online.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Restaurant_delivery_online.Controllers
{
[Route("[controller]")]
[ApiController]
public class CustomersController : ControllerBase
{
private IGenericService<Customer> _repo;
public CustomersController(IGenericService<Customer> repo)
{
_repo = repo;
}
// GET: /Restaurants
[HttpGet]
public async Task<ActionResult<List<Customer>>> Get()
{
List<Customer> Customers = _repo.GetAll();
if (Customers.Count == 0)
{
return NoContent();
}
if (Customers == null)
{
return BadRequest();
}
return Ok(Customers);
}
// GET /Customers/5
[HttpGet("{id}")]
public async Task<IActionResult> GetById(int id)
{
if (id <= 0)
{
return BadRequest();
}
Customer Customer = _repo.GetById(id);
if (Customer == null)
{
return NotFound();
}
return Ok(Customer);
}
// POST /Customers
[HttpPost]
public async Task<IActionResult> Post([FromBody] Customer Customer)
{
if (Customer == null)
{
return BadRequest();
}
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
List<Customer> Customers = _repo.Add(Customer);
if (Customers == null)
{
return BadRequest();
}
return Ok(Customers);
}
//Patch /Customers/5
[HttpPatch("{id}")]
public async Task<ActionResult<Customer>> Patch(int id, [FromBody] Customer customer)
{
if (customer == null || customer.Id != id)
{
return BadRequest();
}
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Customer Customer = _repo.GetById(id);
if (Customer == null)
{
return NotFound();
}
var Customers = _repo.Update(customer);
if (Customers == null)
{
return BadRequest();
}
return Ok(Customers);
}
// DELETE /Customers/5
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
if (id <= 0)
{
return null;
}
var existing = _repo.GetById(id);
if (existing == null)
{
return NotFound();
}
var Customers = _repo.Delete(id);
if (Customers == null)
{
return new NoContentResult();
}
return Ok(Customers);
}
}
}
|
7c37579ce2c686852b6bf79f2f9c6e7c84ddf98a
|
C#
|
Jothaka/TabletopAdventures
|
/Pokemon Tabletop Adventures Companion/Assets/Scripts/Conditions/OrCondition.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
[Serializable]
public class OrCondition : Condition
{
public List<Condition> ConditionsToCheck = new List<Condition>();
public override bool TrainerMeetsCondition(Trainer trainer)
{
if (ConditionsToCheck.Count > 0)
{
for (int i = 0; i < ConditionsToCheck.Count; i++)
{
if (ConditionsToCheck[i].TrainerMeetsCondition(trainer))
return true;
}
return false;
}
return true;
}
}
|
579fb5a273e087e9e631624e73af51645dbfcd5b
|
C#
|
owsir/RDemoViaCSharp
|
/RDemoViaCSharp.RServeCLI/SexpArrayBool.cs
| 3.09375
| 3
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SexpArrayBool.cs" company="Oliver M. Haynold">
// Copyright (c) 2011, Oliver M. Haynold
// All rights reserved.
// </copyright>
// <summary>
// An array of (trivalue, i.e., including NA) booleans.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace RserveCli
{
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// An array of (trivalue, i.e., including NA) booleans.
/// </summary>
public class SexpArrayBool : SexpGenericList
{
#region Constants and Fields
#endregion
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="SexpArrayBool"/> class.
/// </summary>
public SexpArrayBool()
{
this.Value = new List<SexpBoolValue>();
}
/// <summary>
/// Initializes a new instance of the <see cref="SexpArrayBool"/> class.
/// </summary>
/// <param name="theValue">
/// The value.
/// </param>
public SexpArrayBool(IEnumerable<SexpBoolValue> theValue)
{
this.Value = new List<SexpBoolValue>();
this.Value.AddRange(theValue);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets a value indicating whether [as bool].
/// </summary>
/// <value>
/// <c>true</c> if [as bool]; otherwise, <c>false</c>.
/// </value>
public override bool AsBool
{
get
{
if (this.Value.Count == 1)
{
return new SexpBool(this.Value[0]).AsBool;
}
throw new IndexOutOfRangeException("Can only convert numeric arrays of length 1 to double.");
}
}
/// <summary>
/// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <returns>
/// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </returns>
public override int Count
{
get
{
return this.Value.Count;
}
}
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
/// </summary>
/// <returns>true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false.
/// </returns>
public override bool IsReadOnly
{
get
{
return false;
}
}
/// <summary>
/// Gets the values stored in the list
/// </summary>
internal List<SexpBoolValue> Value { get; private set; }
#endregion
#region Indexers
/// <summary>
/// Gets or sets the element at the specified index.
/// </summary>
/// <param name="index">The index of the element.</param>
/// <returns>
/// The element at the specified index.
/// </returns>
public override Sexp this[int index]
{
get
{
return new SexpBool(this.Value[index]);
}
set
{
this.Value[index] = value.AsSexpBool;
}
}
#endregion
#region Public Methods
/// <summary>
/// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <param name="item">
/// The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </param>
public override void Add(Sexp item)
{
this.Value.Add(item.AsSexpBool);
}
/// <summary>
/// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <exception cref="T:System.NotSupportedException">
/// The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
/// </exception>
public override void Clear()
{
this.Value.Clear();
}
/// <summary>
/// Copies to.
/// </summary>
/// <param name="array">
/// The array.
/// </param>
/// <param name="arrayIndex">
/// Index of the array.
/// </param>
public override void CopyTo(Sexp[] array, int arrayIndex)
{
for (int i = 0; i < this.Value.Count; i++)
{
array[arrayIndex + i] = new SexpBool(this.Value[i]);
}
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
public override IEnumerator<Sexp> GetEnumerator()
{
return (from a in this.Value select (Sexp)(new SexpBool(a))).GetEnumerator();
}
/// <summary>
/// Determines the index of a specific item in the <see cref="T:System.Collections.Generic.IList`1"/>.
/// </summary>
/// <param name="item">
/// The object to locate in the <see cref="T:System.Collections.Generic.IList`1"/>.
/// </param>
/// <returns>
/// The index of <paramref name="item"/> if found in the list; otherwise, -1.
/// </returns>
public override int IndexOf(Sexp item)
{
return this.Value.IndexOf(item.IsNa ? SexpBool.Na : item.AsSexpBool);
}
/// <summary>
/// Inserts an item to the <see cref="T:System.Collections.Generic.IList`1"/> at the specified index.
/// </summary>
/// <param name="index">
/// The zero-based index at which <paramref name="item"/> should be inserted.
/// </param>
/// <param name="item">
/// The object to insert into the <see cref="T:System.Collections.Generic.IList`1"/>.
/// </param>
public override void Insert(int index, Sexp item)
{
this.Value.Insert(index, item.AsSexpBool);
}
/// <summary>
/// Removes the <see cref="T:System.Collections.Generic.IList`1"/> item at the specified index.
/// </summary>
/// <param name="index">
/// The zero-based index of the item to remove.
/// </param>
public override void RemoveAt(int index)
{
this.Value.RemoveAt(index);
}
/// <summary>
/// Converts the Sexp into the most appropriate native representation. Use with caution--this is more a rapid prototyping than
/// a production feature.
/// </summary>
/// <returns>
/// A CLI native representation of the Sexp
/// </returns>
public override object ToNative()
{
return this.Value.ToArray();
}
#endregion
}
}
|
93dd16374c70bcbe42db10786d488bf115c4457d
|
C#
|
linaZaytseva/Teem_Project
|
/TeemProject/Form2.cs
| 2.71875
| 3
|
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 TeemProject
{
public partial class Form2 : Form
{
public Form2(int data, List<Dish> list)
{
InitializeComponent();
caloriesNorm = data;
Dishes = list;
}
List<Dish> Dishes = new List<Dish>();
int caloriesNorm;
List<String> typeList = new List<string>();
int avaliableCalories = 0;
// Method for avaliable meal generation
List<Dish> MakeList(List<String> list)
{
List<Dish> avaliableDishes = new List<Dish>();
foreach (Dish item in Dishes)
{
if (list.IndexOf(item.MealCategories.Name) >= 0)
{
avaliableDishes.Add(item);
}
}
return avaliableDishes;
}
private void btnBreakfast_Click(object sender, EventArgs e)
{
typeList.Clear();
typeList.Add("Beverage");
typeList.Add("Poridge&Breakfast");
typeList.Add("Fruit");
avaliableCalories = (int)(Math.Round(0.25 * caloriesNorm));
Form3 f = new Form3(MakeList(typeList), avaliableCalories);
f.ShowDialog();
}
private void btnLunch_Click(object sender, EventArgs e)
{
typeList.Clear();
typeList.Add("Beverage");
typeList.Add("Toast");
typeList.Add("Fruit");
avaliableCalories = (int)(Math.Round(0.1 * caloriesNorm));
Form3 f = new Form3(MakeList(typeList), avaliableCalories);
f.ShowDialog();
}
private void btnDinner_Click(object sender, EventArgs e)
{
typeList.Clear();
typeList.Add("Beverage");
typeList.Add("First Course");
typeList.Add("Garnish");
typeList.Add("Entree");
avaliableCalories = (int)(Math.Round(0.32 * caloriesNorm));
Form3 f = new Form3(MakeList(typeList), avaliableCalories);
f.ShowDialog();
}
private void btnAfternoonSnack_Click(object sender, EventArgs e)
{
typeList.Clear();
typeList.Add("Beverage");
typeList.Add("Salad");
typeList.Add("Toast");
typeList.Add("Vegetables");
avaliableCalories = (int)(Math.Round(0.12 * caloriesNorm));
Form3 f = new Form3(MakeList(typeList), avaliableCalories);
f.ShowDialog();
}
private void btnSupper_Click(object sender, EventArgs e)
{
typeList.Clear();
typeList.Add("Beverage");
typeList.Add("Salad");
//typeList.Add("Garnish");
typeList.Add("Entree");
typeList.Add("Vegetables");
avaliableCalories = (int)(Math.Round(0.18 * caloriesNorm));
Form3 f = new Form3(MakeList(typeList), avaliableCalories);
f.ShowDialog();
}
}
}
|
86b948ec6dc835a069530ba68f86f993137c48ad
|
C#
|
Granddisap/laba1_2sem
|
/ComplexCal/MainForm.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace WindowsFormsApp1
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void String2Complex(String str, ref ComplexCal num)
{
Regex regex = new Regex(@"\d*\,?\d+[+|-]\d*\,?\d+i");
if (!regex.IsMatch(str))
{
label2.Text = "Некорректные данные";
return;
}
String n1 = null, n2 = null;
Boolean minus_sign = false;
int i, index = 0, first_index = 0;
if (str[0] == '-' || str[0] == '+')
{
n1 += str[0];
first_index = 1;
}
for (i = first_index; i < str.Length; i++)
{
if (str[i] == '+' || str[i] == '-')
{
num.Re = Convert.ToSingle(n1);
minus_sign = (str[i] == '-') ? true : false;
index = i + 1;
break;
}
n1 += str[i];
}
if (minus_sign)
{
n2 = "-";
}
for (i = index; i < str.Length; i++)
{
if (str[i] == 'i')
{
num.Im = Convert.ToSingle(n2);
break;
}
n2 += str[i];
}
}
ComplexCal res = new ComplexCal();
ComplexCal left_num = new ComplexCal();
ComplexCal right_num = new ComplexCal();
private void button1_Click(object sender, EventArgs e)
{
String2Complex(textBox1.Text, ref left_num);
String2Complex(textBox2.Text, ref right_num);
if (!(label2.Text == "Неверно введены данные!"))
{
res = left_num + right_num;
if (res.Im >= 0)
label2.Text = res.Re.ToString() + "+" + res.Im.ToString() + "i";
else
label2.Text = res.Re.ToString() + res.Im.ToString() + "i";
label8.Text = res.GetAbs().ToString();
label10.Text = res.GetArg().ToString();
}
}
private void button2_Click(object sender, EventArgs e)
{
String2Complex(textBox3.Text, ref left_num);
String2Complex(textBox4.Text, ref right_num);
if (!(label2.Text == "Неверно введены данные!"))
{
res = left_num - right_num;
if (res.Im >= 0)
label2.Text = res.Re.ToString() + "+" + res.Im.ToString() + "i";
else
label2.Text = res.Re.ToString() + res.Im.ToString() + "i";
label8.Text = res.GetAbs().ToString();
label10.Text = res.GetArg().ToString();
}
}
private void button3_Click(object sender, EventArgs e)
{
String2Complex(textBox5.Text, ref left_num);
String2Complex(textBox6.Text, ref right_num);
if (!(label2.Text == "Неверно введены данные!"))
{
res = left_num * right_num;
if (res.Im >= 0)
label2.Text = res.Re.ToString() + "+" + res.Im.ToString() + "i";
else
label2.Text = res.Re.ToString() + res.Im.ToString() + "i";
label8.Text = res.GetAbs().ToString();
label10.Text = res.GetArg().ToString();
}
}
private void button4_Click(object sender, EventArgs e)
{
String2Complex(textBox7.Text, ref left_num);
String2Complex(textBox8.Text, ref right_num);
if (!(label2.Text == "Неверно введены данные!"))
{
res = left_num / right_num;
if (res.Im >= 0)
label2.Text = res.Re.ToString() + "+" + res.Im.ToString() + "i";
else
label2.Text = res.Re.ToString() + res.Im.ToString() + "i";
label8.Text = res.GetAbs().ToString();
label10.Text = res.GetArg().ToString();
}
}
private void MainForm_Load(object sender, EventArgs e)
{
}
}
}
|
feeb0903451ee6ad3f3412e379573747cae16507
|
C#
|
guibass96/ManagerBarber-Api
|
/Services/ClienteService.cs
| 2.78125
| 3
|
using System.Collections.Generic;
using System.Threading.Tasks;
using ManagerBarber_Api.Domain.Repositories;
using ManagerBarber_Api.Domain.Models;
using System.Linq;
using System.Text;
using System;
namespace ManagerBarber_Api.Services
{
public class ClienteService
{
private readonly IClientesRepository<Cliente> _clienteRepository;
public ClienteService(IClientesRepository<Cliente> clienteRepository)
{
_clienteRepository = clienteRepository;
}
public async Task<IEnumerable<Cliente>> ListAsync()
{
return await _clienteRepository.ListAsync();
}
public async Task<Cliente> AddPerson(Cliente cliente)
{
return await _clienteRepository.Create(cliente);
}
public bool UpdatePerson(Cliente person)
{
try
{
_clienteRepository.Update(person);
return true;
}
catch (Exception)
{
return false;
}
}
public bool DeletePerson(int id)
{
try
{
var clienteDelete = _clienteRepository.GetAll().Where(c=> c.Id == id).FirstOrDefault();
_clienteRepository.Delete(clienteDelete);
return true;
}
catch (Exception)
{
return true;
}
}
}
}
|
e85ac8883b409f3b980ae8a66e46e7881a123a37
|
C#
|
kobr4/direct3D-projects
|
/MyHelloWorldSlimDxWithMMV/Camera.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SlimDX;
using SlimDX.Multimedia;
using SlimDX.RawInput;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace MyHelloWorldSlimDxWithMMV
{
public class Camera
{
private Vector3 mPosition = new Vector3();
private float[] mYawpitchroll = new float[3];
private Vector3 mForward = new Vector3();
private Boolean isFollowPath;
private long currentPathTime;
private List<Vector3> mListPos;
public void setPosition(float x, float y, float z)
{
this.mPosition[0] = x;
this.mPosition[1] = y;
this.mPosition[2] = z;
}
public Vector3 getPosition()
{
return mPosition;
}
public void setRotateX(float x)
{
this.mYawpitchroll[0] = x;
}
public void setRotateY(float y)
{
this.mYawpitchroll[1] = y;
}
public void setRotateZ(float z)
{
this.mYawpitchroll[2] = z;
}
public float getRotateX()
{
return this.mYawpitchroll[0];
}
public float getRotateY()
{
return this.mYawpitchroll[1];
}
public float getRotateZ()
{
return this.mYawpitchroll[2];
}
private Vector3 computePosition(List<Vector3> pos, long totaltime,int timeByPos)
{
int currentPos = (int)((totaltime / timeByPos) % pos.Count);
int antePos = currentPos - 1;
if (currentPos == 0)
antePos = pos.Count - 1;
Vector3 p1 = pos[antePos];
Vector3 p2 = pos[currentPos];
Vector3 p3 = pos[(currentPos + 1) % pos.Count];
Vector3 p4 = pos[(currentPos + 2) % pos.Count];
int delta = (int)(totaltime % timeByPos);
float t = (float)delta / (float)timeByPos;
Vector3 computedPos = Vector3.CatmullRom(p1, p2, p3, p4,t);
return computedPos;
}
private void startPath()
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<Vector3>));
System.IO.FileStream fs = new System.IO.FileStream("outputFile.txt", System.IO.FileMode.Open);
this.mListPos = (List<Vector3>)serializer.Deserialize(fs);
fs.Close();
this.isFollowPath = true;
this.currentPathTime = 0;
Renderer.DebugLog("Starting auto-camera");
}
private void stopPath()
{
this.isFollowPath = false;
Renderer.DebugLog("Stopping auto-camera");
}
public void updateCamera(int dt)
{
if (this.isFollowPath)
{
this.currentPathTime += dt;
this.mPosition = computePosition(this.mListPos,this.currentPathTime,10000);
}
}
private void writePositionToFile()
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<Vector3>));
List<Vector3> pos = new List<Vector3>();
if (System.IO.File.Exists("outputFile.txt"))
{
System.IO.FileStream fs = new System.IO.FileStream("outputFile.txt", System.IO.FileMode.Open);
pos = (List < Vector3 >)serializer.Deserialize(fs);
fs.Close();
}
pos.Add(this.getPosition());
System.IO.FileStream fs2 = new System.IO.FileStream("outputFile.txt", System.IO.FileMode.OpenOrCreate);
serializer.Serialize(fs2, pos);
fs2.Close();
Renderer.DebugLog("Writing camera position to outputFile.txt " + pos.Count + " elements");
}
public Camera()
{
SlimDX.RawInput.Device.RegisterDevice(UsagePage.Generic, UsageId.Keyboard, DeviceFlags.None);
SlimDX.RawInput.Device.RegisterDevice(UsagePage.Generic, UsageId.Mouse, DeviceFlags.None);
SlimDX.RawInput.Device.KeyboardInput += Device_KeyboardInput;
SlimDX.RawInput.Device.MouseInput += Device_MouseInput;
mForward = new Vector3(0f, 0f, 0.5f);
}
public static Vector3 Matrix33Xvector(Matrix matrix3x3, Vector3 vector)
{
Vector3 product = new Vector3();
product.X = matrix3x3.M11 * vector.X + matrix3x3.M12 * vector.Y + matrix3x3.M13 * vector.Z;
product.Y = matrix3x3.M21 * vector.X + matrix3x3.M22 * vector.Y + matrix3x3.M23 * vector.Z;
product.Z = matrix3x3.M31 * vector.X + matrix3x3.M32 * vector.Y + matrix3x3.M33 * vector.Z;
return product;
}
private Vector3 getForwardVector()
{
Quaternion q1 = new Quaternion(new Vector3(0, 1, 0), this.mYawpitchroll[1]);
Quaternion q2 = new Quaternion(new Vector3(1, 0, 0), this.mYawpitchroll[0]);
Quaternion q3 = new Quaternion(new Vector3(0, 0, 1), 0);
Matrix m = Matrix.RotationQuaternion(Quaternion.Normalize(q1 * q2 * q3));
return Matrix33Xvector(m, this.mForward);
}
private void Device_MouseInput(object sender, MouseInputEventArgs e)
{
//process input here
switch (e.ButtonFlags)
{
case MouseButtonFlags.None :
if (0 < e.X)
this.mYawpitchroll[1] = this.mYawpitchroll[1] + 0.01f;
else
if (0 > e.X)
this.mYawpitchroll[1] = this.mYawpitchroll[1] - 0.01f;
if (0 < e.Y)
this.mYawpitchroll[0] -= 0.01f;
if (0 > e.Y)
this.mYawpitchroll[0] += 0.01f;
break;
}
/*
if (this.mYawpitchroll[1] > (float)Math.PI)
{
this.mYawpitchroll[1] = -(float)Math.PI;
}
if (this.mYawpitchroll[1] < -(float)Math.PI)
{
this.mYawpitchroll[1] = (float)Math.PI;
}
if (this.mYawpitchroll[0] > (float)Math.PI)
{
this.mYawpitchroll[0] = -(float)Math.PI;
}
if (this.mYawpitchroll[0] < -(float)Math.PI)
{
this.mYawpitchroll[0] = (float)Math.PI;
}
*/
}
private void Device_KeyboardInput(object sender, KeyboardInputEventArgs e)
{
//process input here
switch (e.Key)
{
case System.Windows.Forms.Keys.Up :
this.mPosition += getForwardVector();
break;
case System.Windows.Forms.Keys.Down:
this.mPosition -= getForwardVector();
break;
case System.Windows.Forms.Keys.Left:
this.mPosition[0] -= 1f;
break;
case System.Windows.Forms.Keys.Right:
this.mPosition[0] += 1f;
break;
case System.Windows.Forms.Keys.O:
if (e.State == KeyState.Released)
{
Renderer.DebugLog("Toto");
}
break;
case System.Windows.Forms.Keys.P:
if (e.State == KeyState.Released)
{
this.writePositionToFile();
}
break;
case System.Windows.Forms.Keys.A:
if (e.State == KeyState.Released)
{
if (this.isFollowPath == false)
this.startPath();
else this.stopPath();
}
break;
}
}
public Matrix generateViewMatrix()
{
Quaternion q1 = new Quaternion(new Vector3(0, 1, 0), this.mYawpitchroll[1]);
Quaternion q2 = new Quaternion(new Vector3(1, 0, 0), this.mYawpitchroll[0]);
//Quaternion q2 = new Quaternion(new Vector3(1, 0, 0), 0);
Quaternion q3 = new Quaternion(new Vector3(0, 0, 1), 0);
// Order of operations:
// First pitch up/down, then rotate around up,
// then translate by position. Note that you want
// the inverse transform of the camera's transform,
// as it goes from the world, to the camera.
Matrix m = Matrix.Translation(-this.getPosition()) * Matrix.RotationQuaternion(Quaternion.Normalize((q1 * q2 * q3)));
//Matrix m = Matrix.Translation(this.getPosition()) * Matrix.RotationY(this.mYawpitchroll[1]) * Matrix.RotationX(this.mYawpitchroll[0]);
return m;
}
}
}
|
855e099b718f46a3c974ca1f98d6b658c7ecc7fc
|
C#
|
hhsherrill/YuQing
|
/szlibInfoThreads/szlibMeitiThread.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using System.Web;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using szlibInfoUtil;
namespace szlibInfoThreads
{
public class szlibMeitiThread
{
private Thread m_thread;
private static string m_url = "http://www.szlib.com/stzx/dynamicInformation.aspx?id=9";
private static string base_url = "http://www.szlib.com/stzx/";
public szlibMeitiThread()
{
m_thread = new Thread(szlibMeitiThread.DoWork);
}
public void Start()
{
m_thread.Start(this);
}
public void Abort()
{
m_thread.Abort();
}
public static void DoWork(object data)
{
while (true)
{
try
{
//获取页面
string webcontent = getWebContent.Fetch(m_url);
//获取新闻列表
List<string> newslist = getNews(webcontent);
foreach (string news in newslist)
{
try
{
string newsurl = base_url + news.Substring(news.IndexOf('\'') + 1, news.LastIndexOf('\'') - news.IndexOf('\'') - 1);
if (newsurl != null)
{
string newsid = Utility.Hash(newsurl);
//如果库中已有该链接,表示已抓取过,后面的不用再抓取
if (SQLServerUtil.existNewsId(newsid)) break;
//没有就保存
string newstitle = news.Substring(news.LastIndexOf('\'') + 2, news.IndexOf("</a>") - news.LastIndexOf('\'') - 2);
string source = newstitle.Substring(newstitle.IndexOf('【') + 1, newstitle.IndexOf('】') - newstitle.IndexOf('【') - 1);
string contentHTML = getWebContent.Fetch(newsurl);
string time = null;
string timepat = @"<span id=""lblTime"">[^<>]+</span>";
Match match = Regex.Match(contentHTML, timepat);
if (match.Success)
{
time = match.Value.Substring(match.Value.IndexOf('>') + 1, match.Value.LastIndexOf('<') - match.Value.IndexOf('>') - 1);
time = Regex.Replace(time, "\\s{2,}", " ");
}
string content = null;
string contentpat = @"<span id=""lblcontent"">[\s\S]+?</span>";
Match match2 = Regex.Match(contentHTML, contentpat);
if (match2.Success) content = match2.Value.Replace("<br>", "\n");
content = content.Substring(content.IndexOf('>') + 1, content.LastIndexOf('<') - content.IndexOf('>') - 1);
content = Regex.Replace(content, @"<[^<>]+?>", "");
SQLServerUtil.addNews(newsid, newstitle, Utility.Encode(content), time, source, newsurl, "本馆网站", null, DateTime.Now.ToString(), DateTime.Now.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
Thread.Sleep(3 * 60 * 60 * 1000);//每隔3小时执行一次
}
catch (InvalidOperationException)
{
Thread.Sleep(5 * 1000);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
//获取新闻列表
private static List<string> getNews(string html)
{
List<string> newslist = new List<string>();
string s = html;
s = Regex.Replace(s, "\\s{3,}", "");
s = s.Replace("\r", "");
s = s.Replace("\n", "");
string pat = @"<div id=""blogs"">[\s\S]+</div>[\s\S]*<!-- blogs -->";
Match match = Regex.Match(s, pat);
if (match.Success) s = match.Value;
string pat2 = @"<h3><a href[ ]*=[ ]*[""']([^#<])+</a></h3>";
MatchCollection mc = Regex.Matches(s, pat2);
foreach (Match m in mc)
{
newslist.Add(m.Value);
}
return newslist;
}
}
}
|
5b230057ea582d15422800a6f5c9d199027560e7
|
C#
|
DennysRivera/DARP_00026919_2EP
|
/DARP_00026919_2EP/Vista/frmAdmin.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace DARP_00026919_2EP
{
public partial class frmAdmin : Form
{
private AppUser usuario;
public frmAdmin(AppUser user)
{
InitializeComponent();
usuario = user;
}
private void frmAdmin_Load(object sender, EventArgs e)
{
ActualizaControles();
}
private void ActualizaControles()
{
List<Business> listaB = BusinessQuery.getLista();
dataGridView3.DataSource = null;
dataGridView3.DataSource = listaB;
cmbNegocio.DataSource = null;
cmbNegocio.ValueMember = "idBusiness";
cmbNegocio.DisplayMember = "name";
cmbNegocio.DataSource = listaB;
cmbNegocio2.DataSource = null;
cmbNegocio2.ValueMember = "idBusiness";
cmbNegocio2.DisplayMember = "name";
cmbNegocio2.DataSource = listaB;
cmbNegocioP.DataSource = null;
cmbNegocioP.ValueMember = "idBusiness";
cmbNegocioP.DisplayMember = "name";
cmbNegocioP.DataSource = listaB;
cmbNegocioEP.DataSource = null;
cmbNegocioEP.ValueMember = "idBusiness";
cmbNegocioEP.DisplayMember = "name";
cmbNegocioEP.DataSource = listaB;
cmbProducto.DataSource = null;
cmbProducto.ValueMember = "idProduct";
cmbProducto.DisplayMember = "name";
cmbProducto.DataSource = ProductQuery.getLista();
}
private void btnMostrarU_Click(object sender, EventArgs e)
{
try
{
var dt = Connection.ExecuteQuery($"SELECT * FROM APPUSER");
dataGridView1.DataSource = dt;
MessageBox.Show("Datos obtenidos exitosamente");
}
catch (Exception ex)
{
MessageBox.Show("Ha ocurrido un error");
}
}
private void btnAgregarU_Click(object sender, EventArgs e)
{
if (txtNombre.Text.Equals("") || txtApellido.Text.Equals("") || txtUsuario.Text.Equals(""))
{
MessageBox.Show("Hay campos vacíos");
}
else
{
try
{
AppUser nuevo = new AppUser();
nuevo.fullname = txtNombre.Text + " " + txtApellido.Text;
nuevo.username = txtUsuario.Text;
nuevo.password = txtUsuario.Text;
nuevo.admin = radAdmin.Checked;
AppUserQuery.newUser(nuevo);
MessageBox.Show("Usuario creado con los datos: \nNombre de usuario: " + txtUsuario.Text +
", contraseña: " + txtUsuario.Text);
txtNombre.Text = "";
txtApellido.Text = "";
txtUsuario.Text = "";
}
catch (Exception ex)
{
MessageBox.Show("Ocurrió un error");
}
}
}
private void btnEliminarU_Click(object sender, EventArgs e)
{
frmDeleteUser ventana = new frmDeleteUser();
ventana.ShowDialog();
}
private void btnAgregarN_Click(object sender, EventArgs e)
{
List<Business> lista = BusinessQuery.getLista();
bool flag = true;
foreach (var bu in lista)
if (txtNegocio.Text.Equals(bu.name))
{
flag = false;
break;
}
if (flag)
{
try
{
BusinessQuery.newBusiness(txtNegocio.Text, textBox1.Text);
MessageBox.Show("Negocio agregado");
ActualizaControles();
textBox1.Clear();
txtNegocio.Clear();
}
catch (Exception ex)
{
MessageBox.Show("Ocurrió un error");
}
}
else
MessageBox.Show("Ya hay un negocio con ese nombre");
}
private void btnEliminarN_Click(object sender, EventArgs e)
{
string name;
try
{
name = cmbNegocio.Text;
BusinessQuery.deleteBusiness(name);
MessageBox.Show("Negocio eliminado");
ActualizaControles();
}
catch (Exception ex)
{
MessageBox.Show("Ocurrió un error");
}
}
private void btnMostrarN_Click(object sender, EventArgs e)
{
try
{
var dt = Connection.ExecuteQuery($"SELECT * FROM BUSINESS");
dataGridView2.DataSource = dt;
MessageBox.Show("Datos obtenidos exitosamente");
}
catch (Exception ex)
{
MessageBox.Show("Ha ocurrido un error");
}
}
private void btnAgregarP_Click(object sender, EventArgs e)
{
try
{
Business bu = (Business) cmbNegocioP.SelectedItem;
ProductQuery.newProduct(bu.idBusiness, txtProducto.Text);
MessageBox.Show("Producto agregado");
}
catch (Exception ex)
{
MessageBox.Show("Ocurrió un error");
}
}
private void btnEliminarP_Click(object sender, EventArgs e)
{
try
{
List<Product> lista = ProductQuery.getLista();
foreach (Product pr in lista)
{
if (cmbProducto.Text.Equals(pr.name))
{
ProductQuery.deleteProduct(pr.idProduct);
MessageBox.Show("Se eliminó el producto");
}
}
}
catch (Exception ex)
{
MessageBox.Show("Ocurrió un error");
}
}
private void ActualizarProducto(Business bu)
{
cmbProducto.DataSource = null;
cmbProducto.ValueMember = "idProduct";
cmbProducto.DisplayMember = "name";
cmbProducto.DataSource = Connection.ExecuteQuery($"SELECT p.idProduct, p.name " +
$"FROM PRODUCT p " +
$"WHERE idBusiness = {bu.idBusiness}");
}
private void cmbNegocioEP_SelectedIndexChanged(object sender, EventArgs e)
{
ActualizarProducto((Business) cmbNegocioEP.SelectedItem);
}
private void frmAdmin_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("¿Seguro que desea salir, " + usuario.username + "?",
"Salir", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
e.Cancel = true;
}
else
{
try
{
e.Cancel = false;
}
catch (Exception)
{
MessageBox.Show("Ocurrió un error",
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void frmAdmin_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
private void cmbNegocio2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
var bu = (Business) cmbNegocio2.SelectedItem;
var dt = Connection.ExecuteQuery($"SELECT p.idProduct, p.name " +
$"FROM PRODUCT p " +
$"WHERE idBusiness = {bu.idBusiness}");
dataGridView3.DataSource = dt;
//MessageBox.Show("Datos obtenidos exitosamente");
}
catch (Exception ex)
{
MessageBox.Show("Ha ocurrido un error");
}
}
private void btnMostrarO_Click(object sender, EventArgs e)
{
try
{
var dt = Connection.ExecuteQuery($"SELECT ao.idOrder, ao.createDate, " +
"pr.name, au.fullname, ad.address " +
"FROM APPORDER ao, ADDRESS ad, PRODUCT pr, APPUSER au " +
"WHERE ao.idProduct = pr.idProduct " +
"AND ao.idAddress = ad.idAddress " +
"AND ad.idUser = au.idUser ");
dataGridView4.DataSource = dt;
MessageBox.Show("Datos obtenidos exitosamente");
}
catch (Exception ex)
{
MessageBox.Show("Ha ocurrido un error");
}
}
private void button1_Click(object sender, EventArgs e)
{
frmChangePass ventana = new frmChangePass(usuario);
ventana.ShowDialog();
}
}
}
|
41450f483e6593633a7dfc91416b176c637d4772
|
C#
|
nwillems/truckplanner
|
/model/model.cs
| 2.90625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
namespace Truckplanner
{
namespace Model
{
public class TruckPlannerContext : DbContext
{
public DbSet<Driver> Drivers { get; set; }
public DbSet<TruckPlan> TruckPlans { get; set; }
public DbSet<Truck> Trucks { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseSqlite("Data source=../truckplanner.db");
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<LocationLogEntry>()
.HasKey(l => new { l.TruckId, l.Time });
modelBuilder.Entity<TruckPlan>()
.HasOne(tp => tp.Driver)
.WithMany()
.IsRequired();
modelBuilder.Entity<TruckPlan>()
.HasOne(tp => tp.Truck)
.WithMany()
.IsRequired();
}
}
//TODO: Make data classes immuteable
public class Truck
{
public int Id { get; set; }
public List<LocationLogEntry> LocationLog { get; set; }
}
public class LocationLogEntry
{
public DateTime Time { get; set; }
public int TruckId { get; set; }
public float Longitude { get; set; }
public float Latitude { get; set; }
}
public class TruckPlan
{
public int Id { get; set; }
public DateTime Start { get; set; }
public TimeSpan Length { get; set; }
public Driver Driver { get; set; }
/* I desired to make this a propper slice of the LocationLog,
* However, that was slightly impractical, with the times as
* indicies into the list.
*
* It could be done, and probably would, if more time was allocated.
* TODO, for version 2.
*/
public Truck Truck { get; set; }
[NotMapped]
public IEnumerable<LocationLogEntry> LocationLog
{
get
{
return (from ll in this.Truck.LocationLog
where ll.Time >= this.Start && ll.Time <= (this.Start.Add(this.Length))
select ll).AsEnumerable();
}
}
public override string ToString()
{
return string.Format("{0}( {1}, {2}, {3}, {4}, {5})", base.ToString(), Id, Driver, Start, Length, Truck);
}
}
public class Driver
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime Birthdate { get; set; }
}
}
}
|
c1b7d1b2a736cedd02835c8a606a7107fcb9d862
|
C#
|
swneng/Diaview
|
/WCF/DiaView.WCF/demo/security/basicHttpBinding_Message_Certificate/WCFService/Contract.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.Security.Principal;
using System.Threading;
using System.Security.Permissions;
namespace WCFService
{
[ServiceContract(Namespace = "http://chnking.com")]
public interface IGetIdentity
{
[OperationContract]
string Get(string ClientIdentity);
}
public class GetIdentity : IGetIdentity
{
//[PrincipalPermission(SecurityAction.Demand, Role = "manager")]
public string Get(string ClientIdentity)
{
IPrincipal myWindowsPrincipal = (IPrincipal)Thread.CurrentPrincipal;
return ("Identity of server is'" + ServiceSecurityContext.Current.PrimaryIdentity.Name +
"'\n\rIdentity of client is '" + ClientIdentity + "'");
}
}
}
|
e4b9dabf066faa431254fafbfdf06a00bd036c30
|
C#
|
tkaledkowski/kwmonitor
|
/KWMonitor/KWMonitor/Services/DistrictService.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KoronaWirusMonitor3.Models;
using KoronaWirusMonitor3.Repository;
using Microsoft.EntityFrameworkCore;
namespace KWMonitor.Services
{
public class DistrictService : IDistrictService
{
private readonly KWMContext _context;
public DistrictService(KWMContext context)
{
_context = context;
}
public async Task<List<District>> GetAll()
{
return await _context.Districts.Include(r => r.Region).ToListAsync();
}
public District GetById(int id)
{
return _context.Districts.Include(d => d.Region).FirstOrDefault(d => d.Id == id);
}
public async Task<bool> Update(District district)
{
_context.Entry(district).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!DistrictExists(district.Id))
return false;
throw;
}
return true;
}
private bool DistrictExists(int id)
{
return _context.Districts.Any(e => e.Id == id);
}
}
}
|
596e2cea3c6dee56de2337b78b258190a46fa643
|
C#
|
omarwasfi/W-SmartShop
|
/W-SmartShopSelution/SmartShopClassLibrary/LogicalClasses/InstallmentProduct/InstallmentProduct.cs
| 2.734375
| 3
|
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Library
{
public static class InstallmentProduct
{
/// <summary>
/// Foreach InstallmentProduct in The Installment , save it in the database
/// </summary>
/// <param name="installment"></param>
/// <param name="db"></param>
public static void SaveInstallmentProductToTheDatabase(InstallmentModel installment , string db)
{
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(GlobalConfig.CnnVal(db)))
{
foreach(InstallmentProductModel installmentProduct in installment.Products)
{
var o = new DynamicParameters();
o.Add("@InstallmentId", installment.Id);
o.Add("@ProductId", installmentProduct.Product.Id);
o.Add("@Quantity", installmentProduct.Quantity);
o.Add("@InstallmentPrice", installmentProduct.InstallmentPrice);
o.Add("@Discount", installmentProduct.Discount);
connection.Execute("dbo.spInstallmentProduct_Create", o, commandType: CommandType.StoredProcedure);
}
}
}
}
}
|
eab7541c96cb659e3359d82e94f3d484e6205429
|
C#
|
tStandalone/tStandalone
|
/patches/tModLoader/Terraria/ModLoader/Core/MemoryTracking.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
namespace Terraria.ModLoader.Core
{
internal class ModMemoryUsage
{
internal long managed;
internal long sounds;
internal long textures;
internal long code;
internal long total => managed + code + sounds + textures;
}
internal static class MemoryTracking
{
internal static Dictionary<string, ModMemoryUsage> modMemoryUsageEstimates = new Dictionary<string, ModMemoryUsage>();
private static long previousMemory;
internal static void Clear() {
modMemoryUsageEstimates.Clear();
}
internal static ModMemoryUsage Update(string modName) {
if (!modMemoryUsageEstimates.TryGetValue(modName, out var usage))
modMemoryUsageEstimates[modName] = usage = new ModMemoryUsage();
if (ModLoader.showMemoryEstimates) {
var newMemory = GC.GetTotalMemory(true);
usage.managed += Math.Max(0, newMemory - previousMemory);
previousMemory = newMemory;
}
return usage;
}
internal static void Checkpoint() {
if (ModLoader.showMemoryEstimates)
previousMemory = GC.GetTotalMemory(true);
}
internal static void Finish() {
foreach (var mod in ModLoader.Mods) {
var usage = modMemoryUsageEstimates[mod.Name];
usage.textures = mod.Assets
.EnumerateLoadedAssets<Texture2D>()
.Select(asset => asset.Value)
.Sum(tex => tex.Width * tex.Height * 4);
usage.sounds = mod.Assets
.EnumerateLoadedAssets<SoundEffect>()
.Select(asset => asset.Value)
.Sum(sound => (long)sound.Duration.TotalSeconds * 44100 * 2 * 2);
}
}
}
}
|
5aac686af4ece75d16d6da37a3cb51c9945a0c07
|
C#
|
isle-studios/CowDog
|
/Assets/Scripts/PlayerSprite.cs
| 2.640625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerSprite : MonoBehaviour {
private float horizontal;
private float vertical;
private bool facingRight;
void Update () {
horizontal = Input.GetAxisRaw("Horizontal");
vertical = Input.GetAxisRaw("Vertical");
updateScale();
}
private void updateScale()
{
if (horizontal < 0)
{
facingRight = false;
transform.localScale = new Vector3(Mathf.Abs(transform.localScale.x) * -1,
transform.localScale.y,
transform.localScale.z);
}
else if (horizontal > 0)
{
facingRight = true;
transform.localScale = new Vector3(Mathf.Abs(transform.localScale.x),
transform.localScale.y,
transform.localScale.z);
}
}
}
|
2563b526c38bd97d2e2e3a4388484ab5e2bd6948
|
C#
|
AndresDaCosta/.NET
|
/ConsoleApplication1/Program.cs
| 3.5
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int numero;
String palabra = null;
palabra = Console.ReadLine();
numero = int.Parse(palabra);
if (numero > 0) {
Console.WriteLine("el numero es positivo");
}
else if (numero == 0)
{
Console.WriteLine("el numero no es negativo ni positivo");
}
else {
Console.WriteLine("el numero es negativo");
}
Console.ReadLine();
}
}
}
|
70d0a733cc86ed2a3361afcd08923395f135426d
|
C#
|
wangvic-0921/HenXinSMS
|
/Demo/Models/CheckRepeat.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace HengXinSMS.Models
{
public class CheckRepeat
{
public int search( string check)
{
using (var context = new HenXinSMSContext())
{
var user_check = from w in context.Users
where w.UserName ==check
select w;
if (user_check.FirstOrDefault() == null)
{
return 0;
}
else
{
return 1;
}
}
}
public int verify(string username,string password)
{
using (var context = new HenXinSMSContext())
{
var user_verify = from w in context.Users
where w.UserName == username && w.PassWord == password
select w;
if (user_verify.FirstOrDefault() == null)
{
return 0;
}
else
{
return 1;
}
}
}
public int update_pwd(string username,string password,string newpassword)
{
using (var context = new HenXinSMSContext())
{
var user_update = from w in context.Users
where w.UserName == username&&w.PassWord==password
select w;
if (user_update.FirstOrDefault() == null)
{
return 0;
}
else
{
var users = context.Users;
var userToUpdate = users.First(d=>d.UserName==username);
userToUpdate.PassWord= newpassword;
context.SaveChanges();
return 1;
}
}
}
}
}
|
da7a8ca16f5f0cfe176e43e48d0a417018df7709
|
C#
|
Bobris/Njsast
|
/Njsast/Ast/AstDefault.cs
| 2.71875
| 3
|
using Njsast.Output;
using Njsast.Reader;
namespace Njsast.Ast;
/// A `default` switch branch
public class AstDefault : AstSwitchBranch
{
public AstDefault(string? source, Position startPos, Position endPos) : base(source, startPos, endPos)
{
}
public override AstNode ShallowClone()
{
var res = new AstDefault(Source, Start, End);
res.Body.AddRange(Body.AsReadOnlySpan());
return res;
}
public override void CodeGen(OutputContext output)
{
output.Print("default:");
output.Newline();
for (var i = 0u; i < Body.Count; i++)
{
output.Indent();
Body[i].Print(output);
output.Newline();
}
}
}
|
ee26e4653b5b984130473e067fab2b859a825546
|
C#
|
Joan1114/Ejercicios-7
|
/Ejercicio N5 (2)/Ejercicio N5 (2)/Program.cs
| 3.34375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ejercicio_N5__2_
{
class Program
{
static void Main(string[] args)
{
int d = 0, m = 0, cant = 0;
string mes1 = "";
int[] mes = new int[12];
mes[0] = 31;
mes[1] = 28;
mes[2] = 30;
mes[3] = 31;
mes[4] = 30;
mes[5] = 31;
mes[6] = 30;
mes[7] = 31;
mes[8] = 30;
mes[9] = 31;
mes[10] = 30;
mes[11] = 31;
Console.Write("Escriba un numero del mes: ");
m = int.Parse(Console.ReadLine());
switch (m)
{
case 1:
mes1 = "Enero";
break;
case 2:
mes1 = "Febrero";
break;
case 3:
mes1 = "Marzo";
break;
case 4:
mes1 = "Abril";
break;
case 5:
mes1 = "Mayo";
break;
case 6:
mes1 = "Junio";
break;
case 7:
mes1 = "Julio";
break;
case 8:
mes1 = "Agosto";
break;
case 9:
mes1 = "Septiembre";
break;
case 10:
mes1 = "Octubre";
break;
case 11:
mes1 = "Noviembre";
break;
case 12:
mes1 = "Diciembre";
break;
default:
break;
}
for (int i = 0; i < m - 1; i++)
{
cant = cant + mes[i];
}
Console.Write("\nEscriba el numero del dia dentro del mes: ");
d = int.Parse(Console.ReadLine());
cant = cant + d;
Console.WriteLine("\nEl dia " + d + " de " + mes1 + " es el dia numero " + cant + " del año");
Console.ReadKey();
}
}
}
|
6899862e9fb3149e02e6e44b8749fcd6b5b85022
|
C#
|
W0lfCr0w/maternity-ward-system
|
/SousChef.cs
| 2.9375
| 3
|
namespace maternity_ward_system
{
public class SousChef: Cook, IExpertEmployee
{
public double ExpertHourlyPay{get; private set;}
public SousChef(string fname, string lname, string id, int age, double hours)
:base(fname, lname, id, age, hours)
{
ExpertHourlyPay = HourlyPay * 1.3;
MyEmployeeType = EmployeeType.SousChef.ToString();
}
public SousChef(string fname, string lname, string id, int age) :this(fname, lname, id, age, 0){}
public override double EndOfMonthSalary()
{
return ExpertHourlyPay * this.workInformation.HoursWorked;
}
}
}
|
6c33a96d47512bc7acc427500be41cfc73b9d65f
|
C#
|
siyamandayubi/Orchardcollaboration
|
/src/Orchard.Web/Modules/S22.IMAP/Provider/Auth/Sasl/Mechanisms/Ntlm/Type1Message.cs
| 2.796875
| 3
|
using System;
using System.Text;
namespace S22.Imap.Provider.Auth.Sasl.Mechanisms.Ntlm {
/// <summary>
/// Represents an NTLM Type 1 Message.
/// </summary>
internal class Type1Message {
/// <summary>
/// The NTLM message signature which is always "NTLMSSP".
/// </summary>
static readonly string signature = "NTLMSSP";
/// <summary>
/// The NTML message type which is always 1 for an NTLM Type 1 message.
/// </summary>
static readonly MessageType type = MessageType.Type1;
/// <summary>
/// The NTLM flags set on this instance.
/// </summary>
internal Flags Flags {
get;
set;
}
/// <summary>
/// The supplied domain name as an array of bytes in the ASCII
/// range.
/// </summary>
byte[] domain {
get;
set;
}
/// <summary>
/// The offset within the message where the domain name data starts.
/// </summary>
int domainOffset {
get {
// We send a version 3 NTLM type 1 message.
return 40;
}
}
/// <summary>
/// The supplied workstation name as an array of bytes in the
/// ASCII range.
/// </summary>
byte[] workstation {
get;
set;
}
/// <summary>
/// The offset within the message where the workstation name data starts.
/// </summary>
int workstationOffset {
get {
return domainOffset + domain.Length;
}
}
/// <summary>
/// The length of the supplied workstation name as a 16-bit short value.
/// </summary>
short workstationLength {
get {
return Convert.ToInt16(workstation.Length);
}
}
/// <summary>
/// Contains information about the client's OS version.
/// </summary>
OSVersion OSVersion {
get;
set;
}
/// <summary>
/// Creates a new instance of the Type1Message class using the specified
/// domain and workstation names.
/// </summary>
/// <param name="domain">The domain in which the client's workstation has
/// membership.</param>
/// <param name="workstation">The client's workstation name.</param>
/// <exception cref="ArgumentNullException">Thrown if the domain or the
/// workstation parameter is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown if the domain
/// or the workstation name exceeds the maximum allowed string
/// length.</exception>
/// <remarks>The domain as well as the workstation name is restricted
/// to ASCII characters and must not be longer than 65536 characters.
/// </remarks>
public Type1Message(string domain, string workstation) {
// Fixme: Is domain mandatory?
domain.ThrowIfNull("domain");
workstation.ThrowIfNull("workstation");
this.domain = Encoding.ASCII.GetBytes(domain);
if (this.domain.Length >= Int16.MaxValue) {
throw new ArgumentOutOfRangeException("The supplied domain name must " +
"not be longer than " + Int16.MaxValue);
}
this.workstation = Encoding.ASCII.GetBytes(workstation);
if (this.workstation.Length >= Int16.MaxValue) {
throw new ArgumentOutOfRangeException("The supplied workstation name " +
"must not be longer than " + Int16.MaxValue);
}
Flags = Flags.NegotiateUnicode | Flags.RequestTarget | Flags.NegotiateNTLM |
Flags.NegotiateDomainSupplied | Flags.NegotiateWorkstationSupplied;
// We spoof an OS version of Windows 7 Build 7601.
OSVersion = new OSVersion(6, 1, 7601);
}
/// <summary>
/// Serializes this instance of the Type1 class to an array of bytes.
/// </summary>
/// <returns>An array of bytes representing this instance of the Type1
/// class.</returns>
public byte[] Serialize() {
return new ByteBuilder()
.Append(signature + "\0")
.Append((int) type)
.Append((int) Flags)
.Append(new SecurityBuffer(domain, domainOffset).Serialize())
.Append(new SecurityBuffer(workstation, workstationOffset).Serialize())
.Append(OSVersion.Serialize())
.Append(domain)
.Append(workstation)
.ToArray();
}
}
}
|
10cbe59c8139b7366d76f8eca0fe0cf3805ab457
|
C#
|
TechieGuy12/PlexServerAutoUpdater
|
/Log.cs
| 3.15625
| 3
|
using System;
using System.Collections.Generic;
using static System.Environment;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TE
{
/// <summary>
/// Contains the properties and methods to write a log file.
/// </summary>
public static class Log
{
/// <summary>
/// The name of the updater log file.
/// </summary>
private const string LogFileName = "plex-updater.txt";
private static string _defaultFolder;
/// <summary>
/// Gets the the full path to the log file.
/// </summary>
public static string FilePath { get; private set; }
/// <summary>
/// Gets the folder to the log file.
/// </summary>
public static string Folder { get; private set; }
/// <summary>
/// Initializes an instance of the <see cref="Log"/> class.
/// </summary>
static Log()
{
_defaultFolder = Path.GetTempPath();
Folder = _defaultFolder;
// Set the full path to the log file
FilePath = Path.Combine(Folder, LogFileName);
}
/// <summary>
/// Gets the formatted timestamp value.
/// </summary>
/// <returns>
/// A string representation of the timestamp.
/// </returns>
private static string GetTimeStamp()
{
return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ");
}
/// <summary>
/// Deletes the log file.
/// </summary>
public static void Delete()
{
File.Delete(FilePath);
}
/// <summary>
/// Sets the full path to the log file.
/// </summary>
/// <param name="path">
/// The full path to the log file.
/// </param>
public static void SetFolder(string path)
{
try
{
// Call this to validate the path
Path.GetFullPath(path);
Folder = Path.GetDirectoryName(path);
if (!Directory.Exists(Folder))
{
Directory.CreateDirectory(Folder);
}
FilePath = Path.Combine(Folder, LogFileName);
}
catch
{
Folder = _defaultFolder;
FilePath = Path.Combine(Folder, LogFileName);
}
}
/// <summary>
/// Writes a string value to the log file.
/// </summary>
public static void Write(string text, bool appendDate = true)
{
string timeStamp = string.Empty;
if (appendDate)
{
timeStamp = GetTimeStamp();
}
File.AppendAllText(FilePath, $"{timeStamp}{text}{NewLine}");
}
/// <summary>
/// Writes information about an exception to the log file.
/// </summary>
/// <param name="ex">
/// The <see cref="Exception"/> object that contains information to write to
/// the log file.
/// </param>
public static void Write(Exception ex, bool appendDate = true)
{
if (ex == null)
{
return;
}
string timeStamp = string.Empty;
if (appendDate)
{
timeStamp = GetTimeStamp();
}
File.AppendAllText(
FilePath,
$"{timeStamp}Message:{NewLine}{ex.Message}{NewLine}{NewLine}Inner Exception:{NewLine}{ex.InnerException}{NewLine}{NewLine}Stack Trace:{NewLine}{ex.StackTrace}{NewLine}");
}
}
}
|
e554cbfbf00a6630e9454e709e108b2b4eefdb68
|
C#
|
as495969/leetcode
|
/easy-905/Program.cs
| 3.421875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace easy_905
{
class Program
{
static void Main(string[] args)
{
int[] ints = Solution.SortArrayByParity(new int[] { 3, 1, 2, 4 });
Console.ReadKey();
}
}
public class Solution
{
public static int[] SortArrayByParity(int[] A)
{
int[] ReArray = new int[A.Length];
int LeftCount = 0;
int RightCount = A.Length - 1;
for (int i = 0; i < A.Length; i++)
{
if (A[i] % 2 == 0)
{
ReArray[LeftCount] = A[i];
LeftCount++;
}
else
{
ReArray[RightCount] = A[i];
RightCount--;
}
}
return ReArray;
}
}
}
|
409231f04d085939673e8b435c213f58cb00396f
|
C#
|
michael-hawker/UWPCommunityToolkit
|
/Microsoft.Toolkit.Uwp.UI.Controls/ControlHelpers.Math.cs
| 2.953125
| 3
|
// ******************************************************************
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THE CODE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE CODE OR THE USE OR OTHER DEALINGS IN THE CODE.
// ******************************************************************
namespace Microsoft.Toolkit.Uwp
{
/// <summary>
/// Internal class used to provide helpers for controls
/// </summary>
internal static partial class ControlHelpers
{
/// <summary>
/// Gets the positive modulo of an integer
/// </summary>
/// <param name="value">Value to use</param>
/// <param name="module">Module to use</param>
/// <returns>Positive modulo</returns>
public static int Mod(this int value, int module)
{
int result = value % module;
return result >= 0 ? result : (result + module) % module;
}
/// <summary>
/// Gets modulo of value + 1
/// </summary>
/// <param name="value">Value to use</param>
/// <param name="module">Module to use</param>
/// <returns>Modulo of value + 1</returns>
public static int IncMod(this int value, int module)
{
return (value + 1).Mod(module);
}
/// <summary>
/// Gets modulo of value - 1
/// </summary>
/// <param name="value">Value to use</param>
/// <param name="module">Module to use</param>
/// <returns>Modulo of value - 1</returns>
public static int DecMod(this int value, int module)
{
return (value - 1).Mod(module);
}
/// <summary>
/// Gets the positive modulo of a double
/// </summary>
/// <param name="value">Value to use</param>
/// <param name="module">Module to use</param>
/// <returns>Positive modulo</returns>
public static double Mod(this double value, double module)
{
double res = value % module;
return res >= 0 ? res : (res + module) % module;
}
}
}
|
0426591a24c19792c3e549afb9cd7f5f7060a718
|
C#
|
dgw2jr/NHibernateDDD
|
/NHibernateDDD/Employee.cs
| 2.953125
| 3
|
using System;
using CSharpFunctionalExtensions;
using NHibernateDDD.Events;
namespace NHibernateDDD
{
public class Employee : Entity
{
protected Employee()
{
EmployeeId = Guid.NewGuid();
}
private Employee(EmployeeName name, EmploymentRole role) : this()
{
Name = name;
EmploymentRole = role;
}
public static Result<Employee> Create(string firstName, string lastName, EmploymentRole role)
{
var name = EmployeeName.Create(firstName, lastName);
if (name.IsFailure)
{
return Result.Fail<Employee>(name.Error);
}
if (role == null)
{
return Result.Fail<Employee>("EmploymentRole cannot be null");
}
return Result.Ok(new Employee(name.Value, role));
}
public virtual Guid EmployeeId { get; protected set; }
public virtual EmployeeName Name { get; protected set; }
public virtual EmploymentRole EmploymentRole { get; set; }
public virtual decimal Bonus => EmploymentRole.CalculateBonus();
public virtual void PromoteTo(EmploymentRole role)
{
EmploymentRole = role;
DomainEvents.Add(new EmployeeWasPromotedEvent { Employee = this });
}
public virtual Result ChangeName(string firstName, string lastName)
{
return EmployeeName.Create(firstName, lastName)
.OnSuccess(r => Name = r);
}
}
}
|
1953a52f47046a3dfd22102bcdfbe3e0c3964b03
|
C#
|
danieljt/Breakout
|
/Assets/Scripts/Physics/PaddleSurfaceController.cs
| 2.765625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace StupidGirlGames.BreakOut
{
/// <summary>
/// Controls the surface of the paddle. A paddle can affect incoming balls depending on
/// the collision point on the paddle surface or the paddle speed. By keeping that information
/// in this class, we can add different scripts
///
/// </summary>
public class PaddleSurfaceController : MonoBehaviour
{
[Tooltip("The minimum deflection angle from the paddles transform.up")]
public float minDeflectionAngle;
[Tooltip("The maximum deflection angle from the paddles transform.up")]
public float maxDeflectionAngle;
[Tooltip("The Paddle material. If no material is added, the reflections will be perfect.")]
public PaddleSurfaceMaterial material;
private BoxCollider2D paddleCollider;
private void Awake()
{
paddleCollider = GetComponent<BoxCollider2D>();
}
/// <summary>
/// This is where the magic happens. The paddle has an affect on the ball depending on the
/// paddle surface material. Since this method comes after fixed update the collision will
/// already be resolved before this event. This event is therefore a correction of
/// collision event.
/// </summary>
/// <param name="collision"></param>
private void OnCollisionEnter2D(Collision2D collision)
{
BallController ball = collision.gameObject.GetComponent<BallController>();
if (ball != null)
{
Rigidbody2D ballBody = collision.rigidbody;
if (ballBody != null)
{
ContactPoint2D contactPoint = collision.GetContact(0);
// We check if the collision normal is equal to the paddles transform up.
// This is the case where we can do fun stuff with the ball reflections
// Note that the == operator for Vector2s and Vector3s is an
// approximatly equal operator.
if (contactPoint.normal == -(Vector2)transform.up)
{
// We find the position of the top center of the collider. This takes rotation
// into consideration
Vector2 topMiddle = paddleCollider.bounds.center + transform.up * paddleCollider.size.y / 2;
// We find the distance between the contact point and the paddle top center
Vector2 distance = topMiddle - contactPoint.point;
// We find the signed length from the contact point. We must cast to vector3 to be able to find the sign. We use the
// cross product to see if the contact point is to the left or right of the transform up.
float signedLength = Mathf.Sign(Vector3.Cross((Vector3)distance, (Vector3)contactPoint.normal).z)*distance.magnitude;
if (material != null)
{
// We calculate the new angles added by the collision point from the ball and the paddle velocity
float posAngle = material.CalculateAngleToAddFromCollision(signedLength, paddleCollider.size.x/2);
// Calculate the new direction of the ball. Remember, the balls velocity is already reflected from the fixed update, so we
// must add the angles in a way that is consistent with the outward velocity.
Vector3 ballDirection = ballBody.velocity;
Vector3 newDirection = Quaternion.AngleAxis(posAngle, transform.forward) * ballDirection;
ball.SetDirection(newDirection);
}
}
}
}
}
}
}
|
1722d0725233aa160968796b76a9dc324fb7b7ee
|
C#
|
MSzmaj/pokedexapi
|
/src/Api/Controllers/PokemonController.cs
| 2.546875
| 3
|
using Microsoft.AspNetCore.Mvc;
using PokedexApi.Common.Query;
using PokedexApi.Service.Services.Pokemon;
using System.Threading.Tasks;
using AutoMapper;
using PokedexApi.Api.Common.Filters;
using PokedexApi.Api.InputModels;
namespace PokedexApi.Api.Controllers {
[ApiController]
[ServiceFilter(typeof(ExceptionFilter))]
public class PokemonController : ControllerBase {
private readonly IQueryHandler<PokemonSearchQuery, PokemonSearchResult> _pokemonSearchHandler;
private readonly IMapper _mapper;
public PokemonController (
IQueryHandler<PokemonSearchQuery, PokemonSearchResult> pokemonSearchHandler,
IMapper mapper) {
_pokemonSearchHandler = pokemonSearchHandler;
_mapper = mapper;
}
[Route("api/health")]
[HttpGet]
public IActionResult HealthCheck () {
return Ok("TEST");
}
/// <summary>
/// Returns a list of Pokemon based on search criteria
/// </summary>
/// <remarks>
/// Sample request: `/pokemon?hp[gte]=100`
/// </remarks>
/// <param name="searchCriteria"></param>
/// <returns>A list of Pokemon</returns>
/// <response code="200">Returns list of Pokemon</response>d
[Route("api/pokemon")]
[HttpGet]
public async Task<IActionResult> SearchPokemonAsync ([FromQuery] PokemonSearchCriteria searchCriteria) {
var query = _mapper.Map<PokemonSearchQuery>(searchCriteria);
var result = await _pokemonSearchHandler.HandleAsync(query);
return Ok(result);
}
}
}
|
5ff96e6a522d22b0d0baa21b42a208f4ad8678ac
|
C#
|
Felandil/Chiota
|
/Chiota/CEXEngine/Crypto/Cipher/Asymmetric/Sign/RNBW/Arithmetic/RainbowUtil.cs
| 2.953125
| 3
|
#region Directives
using VTDev.Libraries.CEXEngine.Utility;
#endregion
namespace VTDev.Libraries.CEXEngine.Crypto.Cipher.Asymmetric.Sign.RNBW.Arithmetic
{
/// <summary>
/// This class is needed for the conversions while encoding and decoding, as well as for comparison between arrays of some dimensions
/// </summary>
internal static class RainbowUtil
{
/// <summary>
/// This function converts an one-dimensional array of bytes into a one-dimensional array of int
/// </summary>
///
/// <param name="Input">The array to be converted</param>
///
/// <returns>The one-dimensional int-array that corresponds the input</returns>
public static int[] ConvertArraytoInt(byte[] Input)
{
int[] output = new int[Input.Length];
for (int i = 0; i < Input.Length; i++)
output[i] = Input[i] & GF2Field.MASK;
return output;
}
/// <summary>
/// This function converts an one-dimensional array of bytes into a one-dimensional array of type short
/// </summary>
///
/// <param name="Input">The array to be converted</param>
///
/// <returns>A one-dimensional short-array that corresponds the input</returns>
public static short[] ConvertArray(byte[] Input)
{
short[] output = new short[Input.Length];
for (int i = 0; i < Input.Length; i++)
{
output[i] = (short)(Input[i] & GF2Field.MASK);
}
return output;
}
/// <summary>
/// This function converts a matrix of bytes into a matrix of type short
/// </summary>
///
/// <param name="Input">The matrix to be converted</param>
///
/// <returns>A short-matrix that corresponds the input</returns>
public static short[][] ConvertArray(byte[][] Input)
{
short[][] output = ArrayUtils.CreateJagged<short[][]>(Input.Length, Input[0].Length);
for (int i = 0; i < Input.Length; i++)
{
for (int j = 0; j < Input[0].Length; j++)
output[i][j] = (short)(Input[i][j] & GF2Field.MASK);
}
return output;
}
/// <summary>
/// This function converts a 3-dimensional array of bytes into a 3-dimensional array of type short
/// </summary>
///
/// <param name="Input">The array to be converted</param>
///
/// <returns>A short-array that corresponds the input</returns>
public static short[][][] ConvertArray(byte[][][] Input)
{
short[][][] output = ArrayUtils.CreateJagged<short[][][]>(Input.Length, Input[0].Length, Input[0][0].Length);
for (int i = 0; i < Input.Length; i++)
{
for (int j = 0; j < Input[0].Length; j++)
{
for (int k = 0; k < Input[0][0].Length; k++)
output[i][j][k] = (short)(Input[i][j][k] & GF2Field.MASK);
}
}
return output;
}
/// <summary>
/// This function converts an array of type short into an array of type byte
/// </summary>
///
/// <param name="Input">The array to be converted</param>
///
/// <returns>The byte-array that corresponds the input</returns>
public static byte[] ConvertArray(short[] Input)
{
byte[] output = new byte[Input.Length];
for (int i = 0; i < Input.Length; i++)
output[i] = (byte)Input[i];
return output;
}
/// <summary>
/// This function converts an array of type int into an array of type byte
/// </summary>
///
/// <param name="Input">The array to be converted</param>
///
/// <returns>The byte-array that corresponds the input</returns>
public static byte[] ConvertIntArray(int[] Input)
{
byte[] output = new byte[Input.Length];
for (int i = 0; i < Input.Length; i++)
output[i] = (byte)Input[i];
return output;
}
/// <summary>
/// This function converts a matrix of type short into a matrix of type byte
/// </summary>
///
/// <param name="Input">The matrix to be converted</param>
///
/// <returns>The byte-matrix that corresponds the input</returns>
public static byte[][] ConvertArray(short[][] Input)
{
byte[][] output = ArrayUtils.CreateJagged<byte[][]>(Input.Length, Input[0].Length);
for (int i = 0; i < Input.Length; i++)
{
for (int j = 0; j < Input[0].Length; j++)
output[i][j] = (byte)Input[i][j];
}
return output;
}
/// <summary>
/// This function converts a 3-dimensional array of type short into a 3-dimensional array of type byte
/// </summary>
///
/// <param name="Input">The array to be converted</param>
///
/// <returns>The byte-array that corresponds the input</returns>
public static byte[][][] ConvertArray(short[][][] Input)
{
byte[][][] output = ArrayUtils.CreateJagged<byte[][][]>(Input.Length, Input[0].Length, Input[0][0].Length);
for (int i = 0; i < Input.Length; i++)
{
for (int j = 0; j < Input[0].Length; j++)
{
for (int k = 0; k < Input[0][0].Length; k++)
output[i][j][k] = (byte)Input[i][j][k];
}
}
return output;
}
/// <summary>
/// Compare two short arrays
/// </summary>
///
/// <param name="A">The first short array</param>
/// <param name="B">The second short array</param>
///
/// <returns>The result of the comparison</returns>
public static bool Equals(short[] A, short[] B)
{
if (A.Length != B.Length)
return false;
bool result = true;
for (int i = A.Length - 1; i >= 0; i--)
result &= A[i] == B[i];
return result;
}
/// <summary>
/// Compare two two-dimensional short arrays
/// </summary>
///
/// <param name="A">The first short array</param>
/// <param name="B">The second short array</param>
///
/// <returns>The result of the comparison</returns>
public static bool Equals(short[][] A, short[][] B)
{
if (A.Length != B.Length)
return false;
bool result = true;
for (int i = A.Length - 1; i >= 0; i--)
result &= Equals(A[i], B[i]);
return result;
}
/// <summary>
/// Compare two three-dimensional short arrays
/// </summary>
///
/// <param name="A">The first short array</param>
/// <param name="B">The second short array</param>
///
/// <returns>The result of the comparison</returns>
public static bool Equals(short[][][] A, short[][][] B)
{
if (A.Length != B.Length)
return false;
bool result = true;
for (int i = A.Length - 1; i >= 0; i--)
result &= Equals(A[i], B[i]);
return result;
}
}
}
|
9e4bc89ac6bf588caf513bf6c2bdae605827cd99
|
C#
|
overseer25/MyRPG
|
/SOSCSRPG/Engine/Factories/WorldFactory.cs
| 2.859375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Engine.Models;
namespace Engine.Factories
{
/// <summary>
/// Builds Worlds. This class is internal, meaning it can only be used by the Engine project.
/// </summary>
internal static class WorldFactory
{
/// <summary>
/// Function used to build a new World object.
/// </summary>
/// <returns></returns>
internal static World CreateWorld()
{
World newWorld = new World();
// Locations
newWorld.AddLocation(0, 0, "Home", "Your starting location", "/Engine;component/Images/Locations/home.png");
newWorld.AddLocation(1, 0, "Town", "The center of town", "/Engine;component/Images/Locations/town.png");
newWorld.AddLocation(2, 0, "Shop", "Purchase things here", "/Engine;component/Images/Locations/shop.png");
newWorld.AddLocation(0, 1, "Spider Hill", "Home of the Spiders", "/Engine;component/Images/Locations/spider.png");
// Quests
newWorld.GetLocation(0, 1).LocationQuests.Add(QuestFactory.GetQuestByID(1));
return newWorld;
}
}
}
|
f6fd08f6814adc852f1e261c477af1502183eb2f
|
C#
|
GemHu/VViiGGEETT_VV33
|
/DothanTech.Controls/Message/DzMessageBox.cs
| 2.734375
| 3
|
/// <summary>
/// @file DzMessageBox.cs
/// @brief 公共的 MessageBox。
/// @author DothanTech 吴桢楠
///
/// Copyright(C) 2011~2014, DothanTech. All rights reserved.
/// </summary>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Dothan.Controls
{
/// <summary>
/// 公共的 MessageBox。
/// </summary>
public static class DzMessageBox
{
/// <summary>
/// 静态的公共消息框
/// </summary>
private static MessageViewer msgBox { get; set; }
/// <summary>
/// 弹出 只需要信息内容
/// </summary>
/// <param name="message"></param>
public static void Show(string message)
{
msgBox = new MessageViewer();
msgBox.MessageText = message;
msgBox.ShowDialog();
}
/// <summary>
/// 弹出 需要信息内容和确定以后事件
/// </summary>
/// <param name="message"></param>
public static void Show(string message, Action Btn1Clicked)
{
msgBox = new MessageViewer();
msgBox.MessageText = message;
msgBox.Btn1Action = Btn1Clicked;
msgBox.ShowDialog();
}
public static void Show(string message, string title, double width)
{
msgBox = new MessageViewer();
msgBox.Title = title;
msgBox.MessageText = message;
msgBox.Width = width;
msgBox.ShowDialog();
}
/// <summary>
/// 弹出 需要信息内容和标题
/// </summary>
/// <param name="message"></param>
public static void Show(string message, string title)
{
msgBox = new MessageViewer();
msgBox.Title = title;
msgBox.MessageText = message;
msgBox.ShowDialog();
}
/// <summary>
/// 弹出 需要信息内容和确定以后事件
/// </summary>
/// <param name="message"></param>
public static void Show(string message, Action Btn1Clicked, Action Btn2Clicked)
{
msgBox = new MessageViewer();
msgBox.MessageText = message;
msgBox.Btn2Visiblity = System.Windows.Visibility.Visible;
msgBox.Btn1Content = "是";
msgBox.Btn2Content = "否";
msgBox.Btn1Action = Btn1Clicked;
msgBox.Btn2Action = Btn2Clicked;
msgBox.ShowDialog();
}
}
}
|
9e5e0ffedd5b9b4bcf13a05090809a46923a502d
|
C#
|
leejon1122/PracticeProjects
|
/GitHub/GitHub/NummerSwap.cs
| 3.765625
| 4
|
using System;
using System.Collections.Generic;
using System.Text;
namespace GitHub
{
public class NummerSwap
{
public void Swap()
{
Console.Write("Voernummers in: ");
string nummers = Console.ReadLine();
string result = SwapNummer(nummers);
result += " ";
Console.WriteLine("Results: " + result);
Console.ReadLine();
}
public string SwapNummer(string nummers)
{
char[] nummersArray = nummers.ToCharArray();
Array.Reverse(nummersArray);
string result = "";
foreach (char item in nummersArray)
{
result += item;
}
return result;
}
}
}
|
30145b0fe8a479a49e6324d6b587463eff049327
|
C#
|
Little-Prayer/AtCoder
|
/ABC157/D/Program.cs
| 3.171875
| 3
|
using System;
namespace D
{
class Program
{
static void Main(string[] args)
{
var NMK = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
var N = NMK[0]; var M = NMK[1]; var K = NMK[2];
var friendship = new UnionFind(N);
var friend = new int[N + 1];
for (int i = 0; i < M; i++)
{
var read = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
friendship.unite(read[0], read[1]);
friend[read[0]]++;
friend[read[1]]++;
}
var suggestions = new int[N];
for (int i = 0; i < N; i++) suggestions[i] = friendship.RootCount(i + 1) - friend[i + 1] - 1;
for (int i = 0; i < K; i++)
{
var read = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
if (friendship.sameRoot(read[0], read[1]))
{
suggestions[read[0] - 1]--;
suggestions[read[1] - 1]--;
}
}
Console.WriteLine(string.Join(" ", suggestions));
}
}
public class UnionFind
{
private int[] parents;
// 同じ根に属する枝の数を格納する
private int[] rootCount;
public int RootCount(int branch)
{
return rootCount[root(branch)];
}
public UnionFind(int count)
{
parents = new int[count + 1];
rootCount = new int[count + 1];
for (int i = 0; i < count + 1; i++)
{
parents[i] = i;
rootCount[i] = 1;
}
}
private int root(int N)
{
if (parents[N] == N) return N;
return parents[N] = root(parents[N]);
}
//木を併合する際に、枝の数も合算する
public void unite(int X, int Y)
{
int rootX = root(X);
int rootY = root(Y);
if (rootX == rootY) return;
rootCount[rootX] += rootCount[rootY];
parents[rootY] = rootX;
}
public bool sameRoot(int X, int Y)
{
return root(X) == root(Y);
}
}
}
|
738e4587364ade5fac79463ad6c66c86653ee861
|
C#
|
Mazel-Tovr/Optimization
|
/src/lab5/Program.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lab5
{
class Program
{
static void Main(string[] args)
{
nelderMeadMethod();
Console.ReadKey();
}
static float[] X;
static float Z;
static int TEV = 0;
static float[] F;
static void nelderMeadMethod()
{
Console.WriteLine("Симплексный метод Нелдера-Мида");
Console.WriteLine("Функция Z=F(X1,X2,...,XN) вычисляется в строке 5000");
Console.WriteLine("Введите число переменных");
int N = int.Parse(Console.ReadLine());
Console.WriteLine("Начальное приближение");
float[,] S = new float[N + 1, N];
for (int J = 0; J < N; J++)
{
S[0, J] = float.Parse(Console.ReadLine());
}
Console.WriteLine("Введите длину шага");
float K = float.Parse(Console.ReadLine());
for (int i = 1; i < N + 1; i++)
{
for (int j = 0; j < N; j++)
{
if (j == i - 1)
{
S[i, j] = S[0, j] + K;
continue;
}
S[i, j] = S[0, j];
}
}
Console.WriteLine("Введите Alfa,Beta,Gamma");
float AL = float.Parse(Console.ReadLine());
float BE = float.Parse(Console.ReadLine());
float GA = float.Parse(Console.ReadLine());
X = new float[N];
float[] XH = new float[N];
float[] XG = new float[N];
float[] XL = new float[N];
float[] XO = new float[N];
float[] XR = new float[N];
float[] XC = new float[N];
float[] XE = new float[N];
F = new float[N + 1];
for (int i = 0; i < N + 1; i++)
{
for (int j = 0; j < N; j++)
{
X[j] = S[i, j];
}
function();
F[i] = Z;
}
S620:
int H = 0, L = 0;
double FH = -1E+20, FL = 1E+20;
for (int i = 0; i < N + 1; i++)
{
if (F[i] > FH)
{
FH = F[i];
H = i;
}
if (F[i] < FL)
{
FL = F[i];
L = i;
}
}
double FG = -1E+20;
int G = 0;
for (int i = 0; i < N + 1; i++)
{
if (i == H)
continue;
if (F[i] > FG)
{
FG = F[i];
G = i;
}
}
for (int j = 0; j < N; j++)
{
XO[j] = 0;
for (int i = 0; i < N + 1; i++)
{
if (i == H)
continue;
XO[j] = XO[j] + S[i, j];
}
XO[j] = XO[j] / N;
XH[j] = S[H, j];
XG[j] = S[G, j];
XL[j] = S[L, j];
}
for (int j = 0; j < N; j++)
{
X[j] = XO[j];
}
function();
float FO = Z;
Console.WriteLine("Вычислите центр тяжести в строке 1120");
for (int j = 0; j < N; j++)
{
XR[j] = XO[j] + AL * (XO[j] - XH[j]);
X[j] = XR[j];
}
function();
float FR = Z;
Console.WriteLine("Выполните отражение в строке 1220" + Z);
if (FR < FL)
goto S1300;
if (FR > FG)
goto S1600;
goto S1520;
S1300:
for (int j = 0; j < N; j++)
{
XE[j] = GA * XR[j] + (1 - GA) * XO[j];
X[j] = XE[j];
}
function();
float FE = Z;
if (FE < FL)
goto S1440;
goto S1520;
S1440:
for (int j = 0; j < N; j++)
{
S[H, j] = XE[j];
}
F[H] = FE;
Console.WriteLine("Выполните растяжение в строке 1480 " + Z);
goto S2060;
S1520:
for (int j = 0; j < N; j++)
{
S[H, j] = XR[j];
}
F[H] = FR;
Console.WriteLine("Выполните отражение в строке 1560");
goto S2060;
S1600:
if (FR > FH)
goto S1700;
for (int j = 0; j < N; j++)
{
XH[j] = XR[j];
}
F[H] = FR;
S1700:
for (int j = 0; j < N; j++)
{
XC[j] = BE * XH[j] + (1 - BE) * XO[j];
X[j] = XC[j];
}
function();
float FC = Z;
if (FC > FH)
goto S1920;
for (int j = 0; j < N; j++)
{
S[H, j] = XC[j];
}
F[H] = FC;
Console.WriteLine("Выполните сжатие в строке 1880 " + Z);
goto S2060;
S1920:
for (int i = 0; i < N + 1; i++)
{
for (int j = 0; j < N; j++)
{
S[i, j] = (S[i, j] + XL[j]) / 2;
X[j] = S[i, j];
}
function();
F[i] = Z;
}
Console.WriteLine("Выполните редукцию в строке 2040");
goto S2060;
S2060:
float S1 = 0, S2 = 0;
for (int i = 0; i < F.Length; i++)
{
S1 = S1 + F[i];
S2 = S2 + F[i] * F[i];
}
float SIG = S2 - S1 * S1 / F.Length;
SIG = SIG / F.Length;
if (SIG < 1E-10)
goto S2220;
else
goto S620;
S2220:
Console.WriteLine("Минимум найден в точке ");
for (int J = 0; J < N; J++)
{
Console.Write("X " + (J + 1) + " = " + XL[J]);
}
Console.WriteLine();
Console.WriteLine("Значение минимума функции = " + F[L]);
Console.WriteLine("Количество вычислений функции = " + TEV);
}
static void function()
{
TEV = TEV + 1;
// Z = (float)(Math.Pow(Math.Pow(X[0], 2) + X[1] - 11, 2) + Math.Pow(X[0] + Math.Pow(X[1], 2) - 7, 2));
Z = (float)(Math.Pow(1 - X[1], 2) + 100 * Math.Pow(X[1] - Math.Pow(X[0], 2), 2));
// TEV = TEV + 1;
//Z = (float)(100 * Math.Pow(X[1] - Math.Pow(X[0], 2), 2) + Math.Pow(1 - X[0], 2));
//TEV = TEV + 1;
//Z = (float)(Math.Pow(Math.Pow(X[0], 2) + X[1] - 11, 2) + Math.Pow(X[0] + Math.Pow(X[1], 2) - 7, 2));
}
}
}
|
6ab57ee69dd8e7fdf40651bcabd58c2063959f58
|
C#
|
mdailor/CraigSearch
|
/ConfigDialog.cs
| 2.59375
| 3
|
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
namespace CraigSearch
{
public partial class ConfigDialog : Form
{
ArrayList m_alAllLocations = null;
ArrayList m_alAllCategories = null;
ArrayList m_alAllSubcategories = null;
public ConfigDialog(ArrayList alAllLocations, ArrayList alAllCategories, ArrayList alAllSubcategories)
{
InitializeComponent();
m_alAllLocations = alAllLocations;
m_alAllCategories = alAllCategories;
m_alAllSubcategories = alAllSubcategories;
}
private void ConfigDialog_Load(object sender, EventArgs e)
{
// Load the keywords textbox
//
tbKeywords.Text = ConfigurationManager.AppSettings["SearchKeywords"];
// Load the categories combobox
//
int iCategoryIndex = 0;
string sSelectedCategoryID = ConfigurationManager.AppSettings["SearchCategory"];
if (sSelectedCategoryID == "")
sSelectedCategoryID = "jjj";
cbCategories.DisplayMember = "Title";
cbCategories.ValueMember = "ID";
foreach (CategoryInfo ciCategory in m_alAllCategories)
{
cbCategories.Items.Add(new CategoryInfo(ciCategory.Title, ciCategory.ID));
if (ciCategory.ID == sSelectedCategoryID)
cbCategories.SelectedIndex = iCategoryIndex;
iCategoryIndex++;
}
// The subcategories combobox has already been loaded via cbCategories_SelectionChanged,
// set the selected item.
//
int iSubcategoryIndex = 0;
string sSelectedSubcategoryID = ConfigurationManager.AppSettings["SearchSubcategory"];
if (sSelectedSubcategoryID == "")
sSelectedSubcategoryID = "sof";
foreach (SubcategoryInfo siSubcategory in cbSubcategories.Items)
{
if (siSubcategory.ID == sSelectedSubcategoryID)
cbSubcategories.SelectedIndex = iSubcategoryIndex;
iSubcategoryIndex++;
}
// Set title only / entire post radio buttons
//
if (ConfigurationManager.AppSettings["SearchType"] == "T")
rbSearchTitle.Checked = true;
else
rbSearchPost.Checked = true;
}
private void btnConfigSave_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["SearchKeywords"].Value = tbKeywords.Text;
config.AppSettings.Settings["SearchCategory"].Value = ((CategoryInfo)cbCategories.SelectedItem).ID;
config.AppSettings.Settings["SearchSubcategory"].Value = ((SubcategoryInfo)cbSubcategories.SelectedItem).ID;
config.AppSettings.Settings["SearchType"].Value = (string)(rbSearchTitle.Checked ? "T" : "A");
config.AppSettings.Settings["SearchHasImage"].Value = (string)(cbHasImage.Checked ? "Y" : "N");
config.AppSettings.Settings["SearchTelecommute"].Value = (string)(cbTelecommute.Checked ? "Y" : "N");
config.AppSettings.Settings["SearchContract"].Value = (string)(cbContract.Checked ? "Y" : "N");
config.AppSettings.Settings["SearchNonprofit"].Value = (string)(cbNonprofit.Checked ? "Y" : "N");
config.AppSettings.Settings["SearchInternship"].Value = (string)(cbInternship.Checked ? "Y" : "N");
config.AppSettings.Settings["SearchPartTime"].Value = (string)(cbPartTime.Checked ? "Y" : "N");
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("appSettings");
}
private void btnConfigCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
}
private void cbCategories_SelectionChanged(object sender, EventArgs e)
{
// Load the subcategories combobox with selections belonging to the currently selected category
//
CategoryInfo ciSelectedCategory = (CategoryInfo)cbCategories.SelectedItem;
cbSubcategories.Items.Clear();
cbSubcategories.DisplayMember = "Title";
cbSubcategories.ValueMember = "ID";
cbSubcategories.Items.Add(new SubcategoryInfo(ciSelectedCategory.ID, "All", ciSelectedCategory.ID));
foreach (SubcategoryInfo siSubcategory in m_alAllSubcategories)
{
if (siSubcategory.CategoryID == ciSelectedCategory.ID)
cbSubcategories.Items.Add(new SubcategoryInfo(siSubcategory.CategoryID, siSubcategory.Title, siSubcategory.ID));
}
cbSubcategories.SelectedIndex = 0;
// Set show only checkboxes based on the currently selected category
//
cbHasImage.Visible = true;
cbHasImage.Checked = (ConfigurationManager.AppSettings["SearchHasImage"] == "Y");
cbTelecommute.Visible = (ciSelectedCategory.ID == "jjj");
cbTelecommute.Checked = (ConfigurationManager.AppSettings["SearchTelecommute"] == "Y");
cbContract.Visible = (ciSelectedCategory.ID == "jjj");
cbContract.Checked = (ConfigurationManager.AppSettings["SearchContract"] == "Y");
cbNonprofit.Visible = (ciSelectedCategory.ID == "jjj");
cbNonprofit.Checked = (ConfigurationManager.AppSettings["SearchNonprofit"] == "Y");
cbInternship.Visible = (ciSelectedCategory.ID == "jjj");
cbInternship.Checked = (ConfigurationManager.AppSettings["SearchInternship"] == "Y");
cbPartTime.Visible = (ciSelectedCategory.ID == "jjj");
cbPartTime.Checked = (ConfigurationManager.AppSettings["SearchPartTime"] == "Y");
}
}
}
|
57149446607d2aeda05cae7ab88b5101e5b7ffba
|
C#
|
qwertie/Theraot
|
/Core/Theraot/Collections/Specialized/CustomComparer.cs
| 2.890625
| 3
|
using System;
using System.Collections.Generic;
using Theraot.Core;
namespace Theraot.Collections.Specialized
{
[global::System.Diagnostics.DebuggerNonUserCode]
public class CustomComparer<T> : IComparer<T>
{
private readonly Func<T, T, int> _comparison;
public CustomComparer(Func<T, T, int> comparison)
{
_comparison = Check.NotNullArgument(comparison, "comparison");
}
public CustomComparer(Comparison<T> comparison)
{
var __comparison = Check.NotNullArgument(comparison, "comparison");
_comparison = __comparison.Invoke;
}
public int Compare(T x, T y)
{
return _comparison.Invoke(x, y);
}
}
}
|
07192d799af56b51834207faec139a0a69a1a1d1
|
C#
|
TanukiSharp/StudioPostEffect
|
/src/InternalEffect/UIParameters/MousePadControl.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
namespace InternalEffect.UIParameters
{
public partial class MousePadControl : UserControl
{
public delegate void CoordinateHandler(float[] coords);
public event CoordinateHandler CoordinatesChanged;
private Font m_TextFont;
internal enum CoordType
{
ZeroToOne,
MinusOneToOne
}
private CoordType m_CoordType = CoordType.ZeroToOne;
private float[] m_XY = new float[2];
internal CoordType CoordinatesType
{
get
{
return (m_CoordType);
}
set
{
m_CoordType = value;
}
}
public float[] Coordinates
{
get
{
return (m_XY);
}
set
{
if (value.Length != 2)
throw new FormatException();
m_XY = value;
this.Invalidate();
}
}
public MousePadControl()
{
InitializeComponent();
m_TextFont = new Font("arial", 7.0f, FontStyle.Regular);
}
public float[] GetMousePadValue()
{
return (m_XY);
}
protected override void OnPaint(PaintEventArgs e)
{
int width = this.Width;
int height = this.Height - pnlToolBar.Height;
int w2 = width >> 1;
int h2 = height >> 1;
Graphics gr = e.Graphics;
// draw position
gr.FillEllipse(Brushes.Red, (m_XY[0] * width) - 3.0f, (m_XY[1] * height) - 3.0f, 6.0f, 6.0f);
gr.DrawLine(Pens.LightGray, w2, 0, w2, height); // vertical centered line
gr.DrawLine(Pens.LightGray, 0, h2, width, h2); // horizontal centered line
gr.DrawLine(Pens.Black, w2, 0, w2, 3); // vertical centered small gradation
gr.DrawLine(Pens.Black, 0, h2, 3, h2); // horizontal centered small gradation
gr.DrawLine(Pens.Black, width - 1, 0, width - 1, 3); // top right small gradation
gr.DrawLine(Pens.Black, 0, height - 1, 3, height - 1); // bottom left small gradation
//base.OnPaint(e);
if (m_CoordType == CoordType.ZeroToOne)
{
gr.DrawString("0", m_TextFont, Brushes.Black, 2.0f, 2.0f);
gr.DrawString("0.5", m_TextFont, Brushes.LightGray, w2 + 2.0f, 2.0f);
gr.DrawString("0.5", m_TextFont, Brushes.LightGray, 2.0f, h2 + 2.0f);
gr.DrawString("1", m_TextFont, Brushes.Black, width - 10.0f, 2.0f);
gr.DrawString("1", m_TextFont, Brushes.Black, 2.0f, height - 10.0f);
}
else
{
gr.DrawString("-1", m_TextFont, Brushes.Black, 2.0f, 2.0f);
gr.DrawString("0", m_TextFont, Brushes.LightGray, w2 + 2.0f, 2.0f);
gr.DrawString("0", m_TextFont, Brushes.LightGray, 2.0f, h2 + 2.0f);
gr.DrawString("1", m_TextFont, Brushes.Black, width - 10.0f, 2.0f);
gr.DrawString("1", m_TextFont, Brushes.Black, 2.0f, height - 10.0f);
}
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
float x = (float)e.X / (float)this.Width;
float y = (float)e.Y / (float)(this.Height - pnlToolBar.Height);
if (m_CoordType == CoordType.ZeroToOne)
{
m_XY[0] = x;
m_XY[1] = y;
}
else
{
m_XY[0] = (x * 2.0f) - 1.0f;
m_XY[1] = (y * 2.0f) - 1.0f;
}
if (CoordinatesChanged != null)
CoordinatesChanged(m_XY);
this.Invalidate();
}
}
private void cboCoordType_SelectedIndexChanged(object sender, EventArgs e)
{
m_CoordType = (CoordType)cboCoordType.SelectedIndex;
this.Invalidate();
}
}
}
|
ec65b5800973ae787b59e26c26667ebd0144e667
|
C#
|
ErikParso/MyRepo
|
/TroubleShooter/Kros.TroubleShooterClient/ViewModel/ObservableObject.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Kros.TroubleShooterClient.ViewModel
{
/// <summary>
/// view models are implementing this class
/// </summary>
public abstract class ObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(params string[] propertyName)
{
if (PropertyChanged != null)
foreach(string prop in propertyName)
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
}
|
385a01ff641124be42e5a5e74b2ed52c7c87c59a
|
C#
|
pmartin36/LDJAM39
|
/Assets/Resources/Scripts/ItemWeaponType.cs
| 2.53125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.ComponentModel;
public class ItemWeaponType : Item {
public enum WeaponType {
[Description("Single Shot")]
SINGLE,
[Description("Fork Shot")]
FORK,
[Description("Rear Shot")]
FRONTBACK,
[Description("Ring Shot")]
RING
}
public static List<Sprite> WeaponSprites;
public WeaponType weaponType;
public override void Awake() {
base.Awake();
weaponType = GenerateRandomWeaponType();
if(WeaponSprites == null) {
WeaponSprites = new List<Sprite>();
WeaponSprites.AddRange( Resources.LoadAll<Sprite>("Sprites/WeaponSprites") );
}
GetComponent<SpriteRenderer>().sprite = WeaponSprites[(int)weaponType];
}
public override void Start() {
base.Start();
}
public override void Update() {
base.Update();
}
public static WeaponType GenerateRandomWeaponType() {
return (WeaponType) Random.Range(0,4);
}
public static string GetWeaponTypeString(WeaponType w) {
switch (w) {
default:
case WeaponType.SINGLE:
return "Single Shot";
case WeaponType.FORK:
return "Fork Shot";
case WeaponType.FRONTBACK:
return "Rear Shot";
case WeaponType.RING:
return "Ring Shot";
}
}
public override void PickupItem(GameObject picker) {
base.PickupItem(picker);
Player player = picker.GetComponent<Player>();
if(player != null) {
player.ChangeWeaponType( weaponType );
}
}
}
|
2dd42fb3c5781a6c09d55b8e0f44af470ba4da9f
|
C#
|
MarcinBluszcz2020/HuionKeydialSuite
|
/HKS.Core/RoboustDevice.cs
| 2.625
| 3
|
using HidLibrary;
using System;
namespace HKS.Core
{
public class RoboustDevice
{
private readonly DeviceWaiterTask _deviceWaiterTask;
public event EventHandler<HidReport> ReportReceived;
private bool _attached;
public RoboustDevice(Func<HidDevice> deviceAccessor)
{
_deviceWaiterTask = new DeviceWaiterTask(deviceAccessor, TimeSpan.FromSeconds(2), DeviceFound);
_deviceWaiterTask.WaitForDevice();
}
private void DeviceFound(HidDevice device)
{
device.OpenDevice();
device.Inserted += DeviceAttachedHandler;
device.Removed += () => DeviceRemovedHandler(device);
device.MonitorDeviceEvents = true;
device.ReadReport(r => OnReport(r, device));
}
private void DeviceAttachedHandler()
{
_attached = true;
}
private void DeviceRemovedHandler(HidDevice device)
{
_attached = false;
_deviceWaiterTask.WaitForDevice();
}
private void OnReport(HidReport report, HidDevice device)
{
if (!_attached)
{
return;
}
device.ReadReport(r => OnReport(r, device));
if (report.ReadStatus == HidDeviceData.ReadStatus.Success)
{
ReportReceived?.Invoke(this, report);
}
}
}
}
|
ea3ea1aad37f8a01d0d9684afd35ec21ce49b540
|
C#
|
doviledovile/CSHARP.VCS
|
/TestDotNetCore/TestDotNetCore/Controllers/ArraysController.cs
| 2.765625
| 3
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
//namespace TestDotNetCore.Controllers
//{
// [Route("api/[controller]")]
// [ApiController]
// public class ArraysController : ControllerBase
// {
//[HttpGet]
//public IActionResult TryArrays()
//{
// string[] names1 = { "Jonas", "Onute", "Petras" }; // rasai taip, arba -->
// string[] names2 = new string[3];
// names2[0] = "Jonas";
// names2[1] = "Onute";
// names2[2] = "Petras";
// int[] ages = new int[5];
// ages[0] = 45;
// ages[1] = 36;
// ages[3] = 18;
// ages[4] = 20;
// var sum = ages[0] + ages[2] + ages[3] + ages[4];
// double average = (double)sum / ages.Length;
// return new OkObjectResult(average);
//}
// [HttpPost]
// public IActionResult CalculateAverage(int[] ages)
// {
// double sum = 0;
// for (int i = 0; i < ages.Length; i++)
// {
// }
// sum += ages[i];
// }
// double average = ConsumesAttribute / ages.Length;
// return new OkObjectResult(average);
// }
// }
//}
|
9a4efb6c13047fdbe7e347e25e240e4ebedc2acd
|
C#
|
khaki560/FuzzyStudia2
|
/lib/variable/Summarizer.cs
| 2.828125
| 3
|
using lib.database;
using lib.tools;
namespace lib.variable
{
internal class Summarizer : LinguisticVariable
{
string attribute;
public Summarizer(LinguisticVariableParameters par) : base(par)
{
attribute = par.attribute;
}
public override double Compute(string label, double value)
{
int i = 0;
for (i = 0; i < H.Length; i++)
{
if (H[i] == label)
{
break;
}
}
return G[i].Calc(value);
}
public override FuzzySet CreateSet(string label, FuzzyModel data)
{
int i = 0;
for(i = 0; i < H.Length; i++)
{
if(H[i] == label)
{
break;
}
}
return new FuzzySet(data.Get("key").ToArray(), data.Get(attribute).ToArray(), G[i]);
}
public override bool IsRelative()
{
throw new System.NotImplementedException();
}
}
}
|
a6fc4d60b37497b8afbd9ca8f55c21d5f3cd5ff9
|
C#
|
Zubyfrank/LibraryManager
|
/Views/DailyReport.cs
| 2.5625
| 3
|
using MetroFramework.Forms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using LibraryManager.Models;
using Newtonsoft.Json;
namespace LibraryManager.Views
{
public partial class DailyReport : MetroForm
{
private readonly LibraryManagerEntities ctx;
string ReportName, datasetName;
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
public DailyReport(LibraryManagerEntities _ctx)
{
InitializeComponent();
ctx = _ctx;
LoadGrid(DateTime.Now.Date);
}
private void LoadGrid(DateTime date)
{
try
{
DateTime? d = new DateTime?(date);
string currDate = d.ToString();
var allRecord = (from st in ctx.StudentBooks
select new
{
st.BookId,
st.DateBorrowed,
st.DateReturned,
}).ToList();
var output = (from r in allRecord
select new
{
CurrentDate=currDate,
NoBorrowed = allRecord.Where(m=>m.DateBorrowed.ToString() == currDate).Count(),
NoReturned = allRecord.Where(m => m.DateReturned.ToString() == currDate).Count()
}).Distinct().ToList();
if (output != null)
{
dataGridView1.DataSource = output;
DataGridViewButtonColumn button = new DataGridViewButtonColumn();
{
button.Name = "actionButton";
button.HeaderText = "Action";
button.Text = "View Details";
button.UseColumnTextForButtonValue = true;
dataGridView1.Columns.Add(button);
}
}
else
{
dataGridView1.Visible = false;
groupBox2.Visible = false;
}
}
catch (Exception ex)
{
MessageBox.Show("An error occured while loading the report", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void DataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
try
{
if (e.ColumnIndex == dataGridView1.Columns["actionButton"].Index)
{
int index = e.RowIndex;
var selectedRow = dataGridView1.Rows[index];
//this line uses an extension method to get the value of the cell when the header is passed
var currDate = selectedRow.Cells.GetCellValueFromColumnHeader("CurrentDate").ToString();
DateTime? d = new DateTime();
d = DateTime.Parse(currDate);
var borrowed = (from s in ctx.StudentBooks
join sa in ctx.Books on s.BookId equals sa.BookId
where s.DateBorrowed == d
select new { sa.Title, sa.Author, sa.ISBN, s.DateBorrowed, s.DateToReturn})
.OrderByDescending(m=>m.DateBorrowed)
.ToList();
var returned = (from s in ctx.StudentBooks
join sa in ctx.Books on s.BookId equals sa.BookId
where s.DateReturned == d
select new { sa.Title, sa.Author, sa.ISBN, s.DateBorrowed, s.DateReturned }).ToList();
if (borrowed.Count() > 0)
{
gdvBorrowed.DataSource = borrowed;
}
else
{
MessageBox.Show("No Book was borrowed today", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
if (returned.Count() > 0)
{
gdvReturned.DataSource = returned;
}
else
{
MessageBox.Show("No Book was returned today", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch (Exception ex)
{
MessageBox.Show("An error occured during the return operation", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void DateTimePicker1_ValueChanged(object sender, EventArgs e)
{
dataGridView1.Columns.Clear();
gdvBorrowed.DataSource = null;
gdvReturned.DataSource = null;
var date = ddlDatePicker.Value.Date;
LoadGrid(date);
}
private void GroupBox1_Enter(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
try
{
ReportName = "DailyReport.rdlc";
datasetName = "DailyReport";
try
{
var TodayDate = DateTime.Now.Date;
DateTime? d = new DateTime?(TodayDate);
var bor = (from s in ctx.StudentBooks
join sa in ctx.Books on s.BookId equals sa.BookId
where s.DateBorrowed == d
select new
{
Borrowed= sa.Title + " by "+sa.Author,
}).
OrderBy(m => m.Borrowed).ToList();
var ret = (from s in ctx.StudentBooks
join sa in ctx.Books on s.BookId equals sa.BookId
where s.DateReturned == d
select new
{
Returned = sa.Title + " by " + sa.Author,
}).
OrderBy(m => m.Returned).ToList();
if (bor.Count() ==0 && ret.Count() == 0)
{
MessageBox.Show("No books were borrowed or returned today, No report available", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
var r = JsonConvert.SerializeObject(ret);
var b = JsonConvert.SerializeObject(bor);
dt = JsonConvert.DeserializeObject<DataTable>(r);
dt1 = JsonConvert.DeserializeObject<DataTable>(b);
//merge both results into one dt
dt2.Columns.Add("CurrentDate");
dt2.Columns.Add("Borrowed");
dt2.Columns.Add("Returned");
dt2.Rows.Add();
dt2.Rows[0][0] = DateTime.Now.ToString("dddd, dd MMMM yyyy");
if (dt1.Rows.Count > 0)
{
for (int i= 0; i<=dt1.Rows.Count-1; i++)
{
dt2.Rows[i][1] = dt1.Rows[i][0];
dt2.Rows.Add();
}
}
else
{
dt2.Rows[0][1] = "Nil";
}
if (dt1.Rows.Count > 0)
{
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
dt2.Rows[i][2] = dt.Rows[i][0];
}
}
else
{
dt2.Rows[0][2] = "Nil";
}
ReportViewer rp = new ReportViewer(ReportName, dt2, datasetName);
rp.StartPosition = FormStartPosition.CenterScreen;
rp.Show();
dt.Clear();
}
catch (Exception ex)
{
MessageBox.Show("An error occured while loading the report viewer", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception)
{
MessageBox.Show("An error occured while loading the report viewer", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
|
b402125aee4b447fb546af5a2b64878a9248d1b0
|
C#
|
HaKDMoDz/baro-corelibrary
|
/Baro.CoreLibrary/OpenNETCF/Ras/ConnectionOptions.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace OpenNETCF.Net
{
/// <summary>
/// Specifies connection options.
/// </summary>
public enum ConnectionOptions
{
/// <summary>
/// If this flag is set, the CountryCode, and AreaCode members of the RasEntry are used to construct the phone number. If this flag is not set, these members are ignored.
/// </summary>
UseCountryAndAreaCodes = 0x00000001,
/// <summary>
/// If this flag is set, RAS tries to use the IP address specified by RasEntry.IPAddress as the IP address for the dial-up connection. If this flag is not set, the value of the ipaddr member is ignored.
/// </summary>
SpecificIpAddr = 0x00000002,
/// <summary>
/// If this flag is set, RAS uses the RasEntry.IPAddressDns, RasEntry.IPAddressDnsAlt, RasEntry.IPAddressWins, and RasEntry.IPAddressWinsAlt members to specify the name server addresses for the dial-up connection. If this flag is not set, RAS ignores these members.
/// </summary>
SpecificNameServers = 0x00000004,
/// <summary>
/// If this flag is set, RAS disables the PPP LCP extensions defined in RFC 1570. This may be necessary to connect to certain older PPP implementations, but interferes with features such as server callback. Do not set this flag unless specifically required.
/// </summary>
DisableLcpExtensions = 0x00000020,
/// <summary>
/// Specifies connection options.
/// </summary>
TerminalBeforeDial = 0x00000040,
/// <summary>
/// Specifies connection options.
/// </summary>
TerminalAfterDial = 0x00000080,
/// <summary>
/// If this flag is set, RAS uses the user name, password, and domain of the currently logged-on user when dialing this entry.
/// </summary>
UseLogonCredentials = 0x00004000,
/// <summary>
/// Specifies connection options.
/// </summary>
DialAsLocalCall = 0x00020000
}
}
|
2fd15673a0b22cfeddf161c7cb37642402262248
|
C#
|
stporteur/ClashStats
|
/ClashStats/CustomControls/DataGridViewRating/DataGridViewRatingCell.cs
| 2.78125
| 3
|
using ClashStats.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ClashStats.CustomControls.DataGridViewRating
{
public class DataGridViewRatingCell : DataGridViewImageCell
{
public DataGridViewRatingCell()
{
// Value type is an integer.
// Formatted value type is an image since we derive from the ImageCell
this.ValueType = typeof(int);
}
protected override object GetFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle cellStyle, TypeConverter valueTypeConverter, TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context)
{
// Convert integer to star images
return starImages[(int)value];
}
public override object DefaultNewRowValue
{
// default new row to 3 stars
get { return 0; }
}
protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates elementState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
{
Image cellImage = (Image)formattedValue;
int starNumber = GetStarFromMouse(cellBounds, this.DataGridView.PointToClient(Control.MousePosition));
if (starNumber != -1)
cellImage = starHotImages[starNumber];
// surpress painting of selection
base.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, value, cellImage, errorText, cellStyle, advancedBorderStyle, (paintParts & ~DataGridViewPaintParts.SelectionBackground));
}
// Update cell's value when the user clicks on a star
protected override void OnContentClick(DataGridViewCellEventArgs e)
{
base.OnContentClick(e);
int starNumber = GetStarFromMouse(this.DataGridView.GetCellDisplayRectangle(this.DataGridView.CurrentCellAddress.X, this.DataGridView.CurrentCellAddress.Y, false), this.DataGridView.PointToClient(Control.MousePosition));
if (starNumber != -1)
this.Value = starNumber;
}
#region Invalidate cells when mouse moves or leaves the cell
protected override void OnMouseLeave(int rowIndex)
{
base.OnMouseLeave(rowIndex);
this.DataGridView.InvalidateCell(this);
}
protected override void OnMouseMove(DataGridViewCellMouseEventArgs e)
{
base.OnMouseMove(e);
this.DataGridView.InvalidateCell(this);
}
#endregion
#region Private Implementation
static Image[] starImages;
static Image[] starHotImages;
const int IMAGEWIDTH = 58;
private int GetStarFromMouse(Rectangle cellBounds, Point mouseLocation)
{
if (cellBounds.Contains(mouseLocation))
{
int mouseXRelativeToCell = (mouseLocation.X - cellBounds.X);
int imageXArea = (cellBounds.Width / 2) - (IMAGEWIDTH / 2);
if (((mouseXRelativeToCell + 4) < imageXArea) || (mouseXRelativeToCell >= (imageXArea + IMAGEWIDTH)))
return -1;
else
{
int oo = (int)Math.Round((((float)(mouseXRelativeToCell - imageXArea + 5) / (float)IMAGEWIDTH) * 5f), MidpointRounding.AwayFromZero);
if (oo > 5 || oo < 0) System.Diagnostics.Debugger.Break();
return oo;
}
}
else
return -1;
}
// setup star images
#region Load star images
static DataGridViewRatingCell()
{
starImages = new Image[6];
starHotImages = new Image[6];
// load normal stars
for (int i = 0; i <= 5; i++)
starImages[i] = (Image)Resources.ResourceManager.GetObject("star" + i.ToString());
// load hot normal stars
for (int i = 0; i <= 5; i++)
starHotImages[i] = (Image)Resources.ResourceManager.GetObject("starhot" + i.ToString());
}
#endregion
#endregion
}
}
|
3d7476f0de94c1f3d91ae35e8f58b51d08eb523e
|
C#
|
italoaguiar/MASLAB
|
/src/OxyPlot.Avalonia/Plot.Properties.cs
| 2.609375
| 3
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Plot.Properties.cs" company="OxyPlot">
// Copyright (c) 2014 OxyPlot contributors
// </copyright>
// <summary>
// Represents a control that displays a <see cref="PlotModel" />.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
using Avalonia;
using Avalonia.Media;
namespace OxyPlot.Avalonia
{
using global::Avalonia.Metadata;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
/// <summary>
/// Represents a control that displays a <see cref="PlotModel" />.
/// </summary>
/// <remarks>This file contains dependency properties used for defining the Plot in XAML. These properties are only used when Model is <c>null</c>. In this case an internal PlotModel is created and the dependency properties are copied from the control to the internal PlotModel.</remarks>
public partial class Plot
{
/// <summary>
/// Identifies the <see cref="Culture"/> dependency property.
/// </summary>
public static readonly StyledProperty<CultureInfo> CultureProperty = AvaloniaProperty.Register<Plot, CultureInfo>(nameof(Culture), null);
/// <summary>
/// Identifies the <see cref="IsLegendVisible"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsLegendVisibleProperty = AvaloniaProperty.Register<Plot, bool>(nameof(IsLegendVisible), true);
/// <summary>
/// Identifies the <see cref="LegendBackground"/> dependency property.
/// </summary>
public static readonly StyledProperty<Color> LegendBackgroundProperty = AvaloniaProperty.Register<Plot, Color>(nameof(LegendBackground), MoreColors.Undefined);
/// <summary>
/// Identifies the <see cref="LegendBorder"/> dependency property.
/// </summary>
public static readonly StyledProperty<Color> LegendBorderProperty = AvaloniaProperty.Register<Plot, Color>(nameof(LegendBorder), MoreColors.Undefined);
/// <summary>
/// Identifies the <see cref="LegendBorderThickness"/> dependency property.
/// </summary>
public static readonly StyledProperty<double> LegendBorderThicknessProperty = AvaloniaProperty.Register<Plot, double>(nameof(LegendBorderThickness), 1.0);
/// <summary>
/// Identifies the <see cref="LegendFont"/> dependency property.
/// </summary>
public static readonly StyledProperty<string> LegendFontProperty = AvaloniaProperty.Register<Plot, string>(nameof(LegendFont), null);
/// <summary>
/// Identifies the <see cref="LegendFontSize"/> dependency property.
/// </summary>
public static readonly StyledProperty<double> LegendFontSizeProperty = AvaloniaProperty.Register<Plot, double>(nameof(LegendFontSize), 12.0);
/// <summary>
/// Identifies the <see cref="LegendFontWeight"/> dependency property.
/// </summary>
public static readonly StyledProperty<FontWeight> LegendFontWeightProperty = AvaloniaProperty.Register<Plot, FontWeight>(nameof(LegendFontWeight), FontWeight.Normal);
/// <summary>
/// Identifies the <see cref="LegendItemAlignment"/> dependency property.
/// </summary>
public static readonly StyledProperty<global::Avalonia.Layout.HorizontalAlignment> LegendItemAlignmentProperty = AvaloniaProperty.Register<Plot, global::Avalonia.Layout.HorizontalAlignment>(nameof(LegendItemAlignment), global::Avalonia.Layout.HorizontalAlignment.Left);
/// <summary>
/// Identifies the <see cref="LegendItemOrder"/> dependency property.
/// </summary>
public static readonly StyledProperty<LegendItemOrder> LegendItemOrderProperty = AvaloniaProperty.Register<Plot, LegendItemOrder>(nameof(LegendItemOrder), LegendItemOrder.Normal);
/// <summary>
/// Identifies the <see cref="LegendItemSpacing"/> dependency property.
/// </summary>
public static readonly StyledProperty<double> LegendItemSpacingProperty = AvaloniaProperty.Register<Plot, double>(nameof(LegendItemSpacing), 24.0);
/// <summary>
/// Identifies the <see cref="LegendLineSpacing"/> dependency property.
/// </summary>
public static readonly StyledProperty<double> LegendLineSpacingProperty = AvaloniaProperty.Register<Plot, double>(nameof(LegendLineSpacing), 0d);
/// <summary>
/// Identifies the <see cref="LegendMargin"/> dependency property.
/// </summary>
public static readonly StyledProperty<double> LegendMarginProperty = AvaloniaProperty.Register<Plot, double>(nameof(LegendMargin), 8.0);
/// <summary>
/// Identifies the <see cref="LegendMaxHeight"/> dependency property.
/// </summary>
public static readonly StyledProperty<double> LegendMaxHeightProperty = AvaloniaProperty.Register<Plot, double>(nameof(LegendMaxHeight), double.NaN);
/// <summary>
/// Identifies the <see cref="LegendMaxWidth"/> dependency property.
/// </summary>
public static readonly StyledProperty<double> LegendMaxWidthProperty = AvaloniaProperty.Register<Plot, double>(nameof(LegendMaxWidth), double.NaN);
/// <summary>
/// Identifies the <see cref="LegendOrientation"/> dependency property.
/// </summary>
public static readonly StyledProperty<LegendOrientation> LegendOrientationProperty = AvaloniaProperty.Register<Plot, LegendOrientation>(nameof(LegendOrientation), LegendOrientation.Vertical);
/// <summary>
/// Identifies the <see cref="LegendColumnSpacing"/> dependency property.
/// </summary>
public static readonly StyledProperty<double> LegendColumnSpacingProperty = AvaloniaProperty.Register<Plot, double>(nameof(LegendColumnSpacing), 8.0);
/// <summary>
/// Identifies the <see cref="LegendPadding"/> dependency property.
/// </summary>
public static readonly StyledProperty<double> LegendPaddingProperty = AvaloniaProperty.Register<Plot, double>(nameof(LegendPadding), 8.0);
/// <summary>
/// Identifies the <see cref="LegendPlacement"/> dependency property.
/// </summary>
public static readonly StyledProperty<LegendPlacement> LegendPlacementProperty = AvaloniaProperty.Register<Plot, LegendPlacement>(nameof(LegendPlacement), LegendPlacement.Inside);
/// <summary>
/// Identifies the <see cref="LegendPosition"/> dependency property.
/// </summary>
public static readonly StyledProperty<LegendPosition> LegendPositionProperty = AvaloniaProperty.Register<Plot, LegendPosition>(nameof(LegendPosition), LegendPosition.RightTop);
/// <summary>
/// Identifies the <see cref="LegendSymbolLength"/> dependency property.
/// </summary>
public static readonly StyledProperty<double> LegendSymbolLengthProperty = AvaloniaProperty.Register<Plot, double>(nameof(LegendSymbolLength), 16.0);
/// <summary>
/// Identifies the <see cref="LegendSymbolMargin"/> dependency property.
/// </summary>
public static readonly StyledProperty<double> LegendSymbolMarginProperty = AvaloniaProperty.Register<Plot, double>(nameof(LegendSymbolMargin), 4.0);
/// <summary>
/// Identifies the <see cref="LegendSymbolPlacement"/> dependency property.
/// </summary>
public static readonly StyledProperty<LegendSymbolPlacement> LegendSymbolPlacementProperty = AvaloniaProperty.Register<Plot, LegendSymbolPlacement>(nameof(LegendSymbolPlacement), LegendSymbolPlacement.Left);
/// <summary>
/// Identifies the <see cref="SelectionColor"/> dependency property.
/// </summary>
public static readonly StyledProperty<Color> SelectionColorProperty = AvaloniaProperty.Register<Plot, Color>(nameof(SelectionColor), Colors.Yellow);
/// <summary>
/// Identifies the <see cref="RenderingDecorator"/> dependency property.
/// </summary>
public static readonly StyledProperty<Func<IRenderContext, IRenderContext>> RenderingDecoratorProperty = AvaloniaProperty.Register<Plot, Func<IRenderContext, IRenderContext>>(nameof(RenderingDecorator), null);
/// <summary>
/// Identifies the <see cref="SubtitleFont"/> dependency property.
/// </summary>
public static readonly StyledProperty<string> SubtitleFontProperty = AvaloniaProperty.Register<Plot, string>(nameof(SubtitleFont), null);
/// <summary>
/// Identifies the <see cref="TitleColor"/> dependency property.
/// </summary>
public static readonly StyledProperty<Color> TitleColorProperty = AvaloniaProperty.Register<Plot, Color>(nameof(TitleColor), MoreColors.Automatic);
/// <summary>
/// Identifies the <see cref="SubtitleColor"/> dependency property.
/// </summary>
public static readonly StyledProperty<Color> SubtitleColorProperty = AvaloniaProperty.Register<Plot, Color>(nameof(SubtitleColor), MoreColors.Automatic);
/// <summary>
/// Identifies the <see cref="DefaultFont"/> dependency property.
/// </summary>
public static readonly StyledProperty<string> DefaultFontProperty = AvaloniaProperty.Register<Plot, string>(nameof(DefaultFont), "Segoe UI");
/// <summary>
/// Identifies the <see cref="DefaultFontSize"/> dependency property.
/// </summary>
public static readonly StyledProperty<double> DefaultFontSizeProperty = AvaloniaProperty.Register<Plot, double>(nameof(DefaultFontSize), 12d);
/// <summary>
/// Identifies the <see cref="DefaultColors"/> dependency property.
/// </summary>
public static readonly StyledProperty<IList<Color>> DefaultColorsProperty = AvaloniaProperty.Register<Plot, IList<Color>>(nameof(DefaultColors), new[]
{
Color.FromRgb(0x4E, 0x9A, 0x06),
Color.FromRgb(0xC8, 0x8D, 0x00),
Color.FromRgb(0xCC, 0x00, 0x00),
Color.FromRgb(0x20, 0x4A, 0x87),
Colors.Red,
Colors.Orange,
Colors.Yellow,
Colors.Green,
Colors.Blue,
Colors.Indigo,
Colors.Violet
});
/// <summary>
/// Identifies the <see cref="AxisTierDistance"/> dependency property.
/// </summary>
public static readonly StyledProperty<double> AxisTierDistanceProperty = AvaloniaProperty.Register<Plot, double>(nameof(AxisTierDistance), 4d);
/// <summary>
/// Identifies the <see cref="LegendTextColor"/> dependency property.
/// </summary>
public static readonly StyledProperty<Color> LegendTextColorProperty = AvaloniaProperty.Register<Plot, Color>(nameof(LegendTextColor), MoreColors.Automatic);
/// <summary>
/// Identifies the <see cref="LegendTitle"/> dependency property.
/// </summary>
public static readonly StyledProperty<string> LegendTitleProperty = AvaloniaProperty.Register<Plot, string>(nameof(LegendTitle), null);
/// <summary>
/// Identifies the <see cref="LegendTextColor"/> dependency property.
/// </summary>
public static readonly StyledProperty<Color> LegendTitleColorProperty = AvaloniaProperty.Register<Plot, Color>(nameof(LegendTitleColor), MoreColors.Automatic);
/// <summary>
/// Identifies the <see cref="LegendTitleFont"/> dependency property.
/// </summary>
public static readonly StyledProperty<string> LegendTitleFontProperty = AvaloniaProperty.Register<Plot, string>(nameof(LegendTitleFont), null);
/// <summary>
/// Identifies the <see cref="LegendTitleFontSize"/> dependency property.
/// </summary>
public static readonly StyledProperty<double> LegendTitleFontSizeProperty = AvaloniaProperty.Register<Plot, double>(nameof(LegendTitleFontSize), 12.0);
/// <summary>
/// Identifies the <see cref="LegendTitleFontWeight"/> dependency property.
/// </summary>
public static readonly StyledProperty<FontWeight> LegendTitleFontWeightProperty = AvaloniaProperty.Register<Plot, FontWeight>(nameof(LegendTitleFontWeight), FontWeight.Bold);
/// <summary>
/// Identifies the <see cref="PlotAreaBackground"/> dependency property.
/// </summary>
public static readonly StyledProperty<Brush> PlotAreaBackgroundProperty = AvaloniaProperty.Register<Plot, Brush>(nameof(PlotAreaBackground), null);
/// <summary>
/// Identifies the <see cref="PlotAreaBorderColor"/> dependency property.
/// </summary>
public static readonly StyledProperty<Color> PlotAreaBorderColorProperty = AvaloniaProperty.Register<Plot, Color>(nameof(PlotAreaBorderColor), Colors.Black);
/// <summary>
/// Identifies the <see cref="PlotAreaBorderThickness"/> dependency property.
/// </summary>
public static readonly StyledProperty<Thickness> PlotAreaBorderThicknessProperty = AvaloniaProperty.Register<Plot, Thickness>(nameof(PlotAreaBorderThickness), new Thickness(1.0));
/// <summary>
/// Identifies the <see cref="PlotMargins"/> dependency property.
/// </summary>
public static readonly StyledProperty<Thickness> PlotMarginsProperty = AvaloniaProperty.Register<Plot, Thickness>(nameof(PlotMargins), new Thickness(double.NaN));
/// <summary>
/// Identifies the <see cref="PlotType"/> dependency property.
/// </summary>
public static readonly StyledProperty<PlotType> PlotTypeProperty = AvaloniaProperty.Register<Plot, PlotType>(nameof(PlotType), PlotType.XY);
/// <summary>
/// Identifies the <see cref="SubtitleFontSize"/> dependency property.
/// </summary>
public static readonly StyledProperty<double> SubtitleFontSizeProperty = AvaloniaProperty.Register<Plot, double>(nameof(SubtitleFontSize), 14.0);
/// <summary>
/// Identifies the <see cref="SubtitleFontWeight"/> dependency property.
/// </summary>
public static readonly StyledProperty<FontWeight> SubtitleFontWeightProperty = AvaloniaProperty.Register<Plot, FontWeight>(nameof(SubtitleFontWeight), FontWeight.Normal);
/// <summary>
/// Identifies the <see cref="Subtitle"/> dependency property.
/// </summary>
public static readonly StyledProperty<string> SubtitleProperty = AvaloniaProperty.Register<Plot, string>(nameof(Subtitle), null);
/// <summary>
/// Identifies the <see cref="TextColor"/> dependency property.
/// </summary>
public static readonly StyledProperty<Color> TextColorProperty = AvaloniaProperty.Register<Plot, Color>(nameof(TextColor), Colors.Black);
/// <summary>
/// Identifies the <see cref="TitleHorizontalAlignment"/> dependency property.
/// </summary>
public static readonly StyledProperty<TitleHorizontalAlignment> TitleAlignmentProperty = AvaloniaProperty.Register<Plot, TitleHorizontalAlignment>(nameof(TitleHorizontalAlignment), TitleHorizontalAlignment.CenteredWithinPlotArea);
/// <summary>
/// Identifies the <see cref="TitleFont"/> dependency property.
/// </summary>
public static readonly StyledProperty<string> TitleFontProperty = AvaloniaProperty.Register<Plot, string>(nameof(TitleFont), null);
/// <summary>
/// Identifies the <see cref="TitleFontSize"/> dependency property.
/// </summary>
public static readonly StyledProperty<double> TitleFontSizeProperty = AvaloniaProperty.Register<Plot, double>(nameof(TitleFontSize), 18.0);
/// <summary>
/// Identifies the <see cref="TitleFontWeight"/> dependency property.
/// </summary>
public static readonly StyledProperty<FontWeight> TitleFontWeightProperty = AvaloniaProperty.Register<Plot, FontWeight>(nameof(TitleFontWeight), FontWeight.Bold);
/// <summary>
/// Identifies the <see cref="TitlePadding"/> dependency property.
/// </summary>
public static readonly StyledProperty<double> TitlePaddingProperty = AvaloniaProperty.Register<Plot, double>(nameof(TitlePadding), 6.0);
/// <summary>
/// Identifies the <see cref="Title"/> dependency property.
/// </summary>
public static readonly StyledProperty<string> TitleProperty = AvaloniaProperty.Register<Plot, string>(nameof(Title), null);
/// <summary>
/// Identifies the <see cref="TitleToolTip"/> dependency property.
/// </summary>
public static readonly StyledProperty<string> TitleToolTipProperty = AvaloniaProperty.Register<Plot, string>(nameof(TitleToolTip), null);
/// <summary>
/// Identifies the <see cref="InvalidateFlag"/> dependency property.
/// </summary>
public static readonly StyledProperty<int> InvalidateFlagProperty = AvaloniaProperty.Register<Plot, int>(nameof(InvalidateFlag), 0);
/// <summary>
/// Initializes static members of the <see cref="Plot" /> class.
/// </summary>
static Plot()
{
PaddingProperty.OverrideDefaultValue<Plot>(new Thickness(8));
PaddingProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
CultureProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
IsLegendVisibleProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
LegendBackgroundProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
LegendBorderProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
LegendBorderThicknessProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
LegendFontProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
LegendFontSizeProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
LegendFontWeightProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
LegendItemAlignmentProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
LegendItemOrderProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
LegendItemSpacingProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
LegendLineSpacingProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
LegendMarginProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
LegendMaxHeightProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
LegendMaxWidthProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
LegendOrientationProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
LegendColumnSpacingProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
LegendPaddingProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
LegendPlacementProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
LegendPositionProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
LegendSymbolLengthProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
LegendSymbolMarginProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
LegendSymbolPlacementProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
SelectionColorProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
RenderingDecoratorProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
SubtitleFontProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
TitleColorProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
SubtitleColorProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
DefaultFontProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
DefaultFontSizeProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
DefaultColorsProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
AxisTierDistanceProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
LegendTextColorProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
LegendTitleProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
LegendTitleColorProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
LegendTitleFontProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
LegendTitleFontSizeProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
LegendTitleFontWeightProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
PlotAreaBackgroundProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
PlotAreaBorderColorProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
PlotAreaBorderThicknessProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
PlotMarginsProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
PlotTypeProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
SubtitleFontSizeProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
SubtitleFontWeightProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
SubtitleProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
TextColorProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
TitleAlignmentProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
TitleFontProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
TitleFontSizeProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
TitleFontWeightProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
TitlePaddingProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
TitleProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
TitleToolTipProperty.Changed.AddClassHandler<Plot>(AppearanceChanged);
InvalidateFlagProperty.Changed.AddClassHandler<Plot>((s, e) => s.InvalidateFlagChanged());
}
/// <summary>
/// The annotations.
/// </summary>
private readonly ObservableCollection<Annotation> annotations;
/// <summary>
/// The axes.
/// </summary>
private readonly ObservableCollection<Axis> axes;
/// <summary>
/// The series.
/// </summary>
private readonly ObservableCollection<Series> series;
/// <summary>
/// Gets the axes.
/// </summary>
/// <value>The axes.</value>
public Collection<Axis> Axes
{
get
{
return axes;
}
}
/// <summary>
/// Gets or sets Culture.
/// </summary>
public CultureInfo Culture
{
get
{
return GetValue(CultureProperty);
}
set
{
SetValue(CultureProperty, value);
}
}
/// <summary>
/// Gets or sets a value indicating whether IsLegendVisible.
/// </summary>
public bool IsLegendVisible
{
get
{
return GetValue(IsLegendVisibleProperty);
}
set
{
SetValue(IsLegendVisibleProperty, value);
}
}
/// <summary>
/// Gets or sets LegendBackground.
/// </summary>
public Color LegendBackground
{
get
{
return GetValue(LegendBackgroundProperty);
}
set
{
SetValue(LegendBackgroundProperty, value);
}
}
/// <summary>
/// Gets or sets LegendBorder.
/// </summary>
public Color LegendBorder
{
get
{
return GetValue(LegendBorderProperty);
}
set
{
SetValue(LegendBorderProperty, value);
}
}
/// <summary>
/// Gets or sets LegendBorderThickness.
/// </summary>
public double LegendBorderThickness
{
get
{
return GetValue(LegendBorderThicknessProperty);
}
set
{
SetValue(LegendBorderThicknessProperty, value);
}
}
/// <summary>
/// Gets or sets the spacing between columns of legend items (only for vertical orientation).
/// </summary>
/// <value>The spacing in device independent units.</value>
public double LegendColumnSpacing
{
get
{
return GetValue(LegendColumnSpacingProperty);
}
set
{
SetValue(LegendColumnSpacingProperty, value);
}
}
/// <summary>
/// Gets or sets LegendFont.
/// </summary>
public string LegendFont
{
get
{
return GetValue(LegendFontProperty);
}
set
{
SetValue(LegendFontProperty, value);
}
}
/// <summary>
/// Gets or sets LegendFontSize.
/// </summary>
public double LegendFontSize
{
get
{
return GetValue(LegendFontSizeProperty);
}
set
{
SetValue(LegendFontSizeProperty, value);
}
}
/// <summary>
/// Gets or sets LegendFontWeight.
/// </summary>
public FontWeight LegendFontWeight
{
get
{
return GetValue(LegendFontWeightProperty);
}
set
{
SetValue(LegendFontWeightProperty, value);
}
}
/// <summary>
/// Gets or sets LegendItemAlignment.
/// </summary>
public global::Avalonia.Layout.HorizontalAlignment LegendItemAlignment
{
get
{
return GetValue(LegendItemAlignmentProperty);
}
set
{
SetValue(LegendItemAlignmentProperty, value);
}
}
/// <summary>
/// Gets or sets LegendItemOrder.
/// </summary>
public LegendItemOrder LegendItemOrder
{
get
{
return GetValue(LegendItemOrderProperty);
}
set
{
SetValue(LegendItemOrderProperty, value);
}
}
/// <summary>
/// Gets or sets the horizontal spacing between legend items when the orientation is horizontal.
/// </summary>
/// <value>The horizontal distance between items in device independent units.</value>
public double LegendItemSpacing
{
get
{
return GetValue(LegendItemSpacingProperty);
}
set
{
SetValue(LegendItemSpacingProperty, value);
}
}
/// <summary>
/// Gets or sets the vertical spacing between legend items.
/// </summary>
/// <value>The spacing in device independent units.</value>
public double LegendLineSpacing
{
get
{
return GetValue(LegendLineSpacingProperty);
}
set
{
SetValue(LegendLineSpacingProperty, value);
}
}
/// <summary>
/// Gets or sets the max height of the legend.
/// </summary>
/// <value>The max width of the legends.</value>
public double LegendMaxHeight
{
get
{
return GetValue(LegendMaxHeightProperty);
}
set
{
SetValue(LegendMaxHeightProperty, value);
}
}
/// <summary>
/// Gets or sets the max width of the legend.
/// </summary>
/// <value>The max width of the legends.</value>
public double LegendMaxWidth
{
get
{
return GetValue(LegendMaxWidthProperty);
}
set
{
SetValue(LegendMaxWidthProperty, value);
}
}
/// <summary>
/// Gets or sets LegendMargin.
/// </summary>
public double LegendMargin
{
get
{
return GetValue(LegendMarginProperty);
}
set
{
SetValue(LegendMarginProperty, value);
}
}
/// <summary>
/// Gets or sets LegendOrientation.
/// </summary>
public LegendOrientation LegendOrientation
{
get
{
return GetValue(LegendOrientationProperty);
}
set
{
SetValue(LegendOrientationProperty, value);
}
}
/// <summary>
/// Gets or sets the legend padding.
/// </summary>
public double LegendPadding
{
get
{
return GetValue(LegendPaddingProperty);
}
set
{
SetValue(LegendPaddingProperty, value);
}
}
/// <summary>
/// Gets or sets LegendPlacement.
/// </summary>
public LegendPlacement LegendPlacement
{
get
{
return GetValue(LegendPlacementProperty);
}
set
{
SetValue(LegendPlacementProperty, value);
}
}
/// <summary>
/// Gets or sets the legend position.
/// </summary>
/// <value>The legend position.</value>
public LegendPosition LegendPosition
{
get
{
return GetValue(LegendPositionProperty);
}
set
{
SetValue(LegendPositionProperty, value);
}
}
/// <summary>
/// Gets or sets LegendSymbolLength.
/// </summary>
public double LegendSymbolLength
{
get
{
return GetValue(LegendSymbolLengthProperty);
}
set
{
SetValue(LegendSymbolLengthProperty, value);
}
}
/// <summary>
/// Gets or sets LegendSymbolMargin.
/// </summary>
public double LegendSymbolMargin
{
get
{
return GetValue(LegendSymbolMarginProperty);
}
set
{
SetValue(LegendSymbolMarginProperty, value);
}
}
/// <summary>
/// Gets or sets LegendSymbolPlacement.
/// </summary>
public LegendSymbolPlacement LegendSymbolPlacement
{
get
{
return GetValue(LegendSymbolPlacementProperty);
}
set
{
SetValue(LegendSymbolPlacementProperty, value);
}
}
/// <summary>
/// Gets or sets LegendTitleFont.
/// </summary>
public string LegendTitleFont
{
get
{
return GetValue(LegendTitleFontProperty);
}
set
{
SetValue(LegendTitleFontProperty, value);
}
}
/// <summary>
/// Gets or sets the default font.
/// </summary>
public string DefaultFont
{
get
{
return GetValue(DefaultFontProperty);
}
set
{
SetValue(DefaultFontProperty, value);
}
}
/// <summary>
/// Gets or sets the default font size.
/// </summary>
public double DefaultFontSize
{
get
{
return GetValue(DefaultFontSizeProperty);
}
set
{
SetValue(DefaultFontSizeProperty, value);
}
}
/// <summary>
/// Gets or sets the default colors.
/// </summary>
public IList<Color> DefaultColors
{
get
{
return GetValue(DefaultColorsProperty);
}
set
{
SetValue(DefaultColorsProperty, value);
}
}
/// <summary>
/// Gets or sets the text color of the legends.
/// </summary>
public Color LegendTextColor
{
get
{
return GetValue(LegendTextColorProperty);
}
set
{
SetValue(LegendTextColorProperty, value);
}
}
/// <summary>
/// Gets or sets the legend title.
/// </summary>
public string LegendTitle
{
get
{
return GetValue(LegendTitleProperty);
}
set
{
SetValue(LegendTitleProperty, value);
}
}
/// <summary>
/// Gets or sets color of the legend title.
/// </summary>
public Color LegendTitleColor
{
get
{
return GetValue(LegendTitleColorProperty);
}
set
{
SetValue(LegendTitleColorProperty, value);
}
}
/// <summary>
/// Gets or sets the axis tier distance.
/// </summary>
public double AxisTierDistance
{
get
{
return GetValue(AxisTierDistanceProperty);
}
set
{
SetValue(LegendTitleFontProperty, value);
}
}
/// <summary>
/// Gets or sets the color of selected elements.
/// </summary>
public Color SelectionColor
{
get
{
return GetValue(SelectionColorProperty);
}
set
{
SetValue(LegendTitleFontProperty, value);
}
}
/// <summary>
/// Gets or sets a rendering decorator.
/// </summary>
public Func<IRenderContext, IRenderContext> RenderingDecorator
{
get
{
return GetValue(RenderingDecoratorProperty);
}
set
{
SetValue(RenderingDecoratorProperty, value);
}
}
/// <summary>
/// Gets or sets the font of the subtitles.
/// </summary>
public string SubtitleFont
{
get
{
return GetValue(SubtitleFontProperty);
}
set
{
SetValue(SubtitleFontProperty, value);
}
}
/// <summary>
/// Gets or sets the color of the titles.
/// </summary>
public Color TitleColor
{
get
{
return GetValue(TitleColorProperty);
}
set
{
SetValue(TitleColorProperty, value);
}
}
/// <summary>
/// Gets or sets the font size of the legend titles.
/// </summary>
public double LegendTitleFontSize
{
get
{
return GetValue(LegendTitleFontSizeProperty);
}
set
{
SetValue(LegendTitleFontSizeProperty, value);
}
}
/// <summary>
/// Gets or sets the color of the subtitles.
/// </summary>
public Color SubtitleColor
{
get
{
return GetValue(SubtitleColorProperty);
}
set
{
SetValue(SubtitleColorProperty, value);
}
}
/// <summary>
/// Gets or sets the font weight of the legend titles.
/// </summary>
public FontWeight LegendTitleFontWeight
{
get
{
return GetValue(LegendTitleFontWeightProperty);
}
set
{
SetValue(LegendTitleFontWeightProperty, value);
}
}
/// <summary>
/// Gets or sets the background brush of the Plot area.
/// </summary>
/// <value>The brush.</value>
public Brush PlotAreaBackground
{
get
{
return GetValue(PlotAreaBackgroundProperty);
}
set
{
SetValue(PlotAreaBackgroundProperty, value);
}
}
/// <summary>
/// Gets or sets the color of the Plot area border.
/// </summary>
/// <value>The color of the Plot area border.</value>
public Color PlotAreaBorderColor
{
get
{
return GetValue(PlotAreaBorderColorProperty);
}
set
{
SetValue(PlotAreaBorderColorProperty, value);
}
}
/// <summary>
/// Gets or sets the thickness of the Plot area border.
/// </summary>
/// <value>The thickness of the Plot area border.</value>
public Thickness PlotAreaBorderThickness
{
get
{
return GetValue(PlotAreaBorderThicknessProperty);
}
set
{
SetValue(PlotAreaBorderThicknessProperty, value);
}
}
/// <summary>
/// Gets or sets the Plot margins.
/// </summary>
/// <value>The Plot margins.</value>
public Thickness PlotMargins
{
get
{
return GetValue(PlotMarginsProperty);
}
set
{
SetValue(PlotMarginsProperty, value);
}
}
/// <summary>
/// Gets or sets PlotType.
/// </summary>
public PlotType PlotType
{
get
{
return GetValue(PlotTypeProperty);
}
set
{
SetValue(PlotTypeProperty, value);
}
}
/// <summary>
/// Gets the series.
/// </summary>
/// <value>The series.</value>
[Content]
public Collection<Series> Series
{
get
{
return series;
}
}
/// <summary>
/// Gets or sets the subtitle.
/// </summary>
/// <value>The subtitle.</value>
public string Subtitle
{
get
{
return GetValue(SubtitleProperty);
}
set
{
SetValue(SubtitleProperty, value);
}
}
/// <summary>
/// Gets or sets the font size of the subtitle.
/// </summary>
public double SubtitleFontSize
{
get
{
return GetValue(SubtitleFontSizeProperty);
}
set
{
SetValue(SubtitleFontSizeProperty, value);
}
}
/// <summary>
/// Gets or sets the font weight of the subtitle.
/// </summary>
public FontWeight SubtitleFontWeight
{
get
{
return GetValue(SubtitleFontWeightProperty);
}
set
{
SetValue(SubtitleFontWeightProperty, value);
}
}
/// <summary>
/// Gets or sets text color.
/// </summary>
public Color TextColor
{
get
{
return GetValue(TextColorProperty);
}
set
{
SetValue(TextColorProperty, value);
}
}
/// <summary>
/// Gets or sets the title.
/// </summary>
/// <value>The title.</value>
public string Title
{
get
{
return GetValue(TitleProperty);
}
set
{
SetValue(TitleProperty, value);
}
}
/// <summary>
/// Gets or sets the title tool tip.
/// </summary>
/// <value>The title tool tip.</value>
public string TitleToolTip
{
get
{
return GetValue(TitleToolTipProperty);
}
set
{
SetValue(TitleToolTipProperty, value);
}
}
/// <summary>
/// Gets or sets the horizontal alignment of the title and subtitle.
/// </summary>
/// <value>
/// The alignment.
/// </value>
public TitleHorizontalAlignment TitleHorizontalAlignment
{
get
{
return GetValue(TitleAlignmentProperty);
}
set
{
SetValue(TitleAlignmentProperty, value);
}
}
/// <summary>
/// Gets or sets font of the title.
/// </summary>
public string TitleFont
{
get
{
return GetValue(TitleFontProperty);
}
set
{
SetValue(TitleFontProperty, value);
}
}
/// <summary>
/// Gets or sets font size of the title.
/// </summary>
public double TitleFontSize
{
get
{
return GetValue(TitleFontSizeProperty);
}
set
{
SetValue(TitleFontSizeProperty, value);
}
}
/// <summary>
/// Gets or sets font weight of the title.
/// </summary>
public FontWeight TitleFontWeight
{
get
{
return GetValue(TitleFontWeightProperty);
}
set
{
SetValue(TitleFontWeightProperty, value);
}
}
/// <summary>
/// Gets or sets padding around the title.
/// </summary>
public double TitlePadding
{
get
{
return GetValue(TitlePaddingProperty);
}
set
{
SetValue(TitlePaddingProperty, value);
}
}
/// <summary>
/// Gets or sets the refresh flag (an integer value). When the flag is changed, the Plot will be refreshed.
/// </summary>
/// <value>The refresh value.</value>
public int InvalidateFlag
{
get
{
return GetValue(InvalidateFlagProperty);
}
set
{
SetValue(InvalidateFlagProperty, value);
}
}
/// <summary>
/// Invalidates the Plot control/view when the <see cref="InvalidateFlag" /> property is changed.
/// </summary>
private void InvalidateFlagChanged()
{
InvalidatePlot();
}
}
}
|
6d33455ac57a7c854f11960a258686f563548b29
|
C#
|
keshavsingh4522/ASP.Net-Core-And-Web-API
|
/Attribute_And_Reflection/Reflection_1/Program.cs
| 3.796875
| 4
|
using System;
using System.Reflection;
namespace Reflection_1
{
class Program
{
static void Main(string[] args)
{
#region Type
// same behaviour
//Type T = Type.GetType("Reflection_1.Customer");
//Type T = typeof(Customer);
Customer c1 = new Customer();
Type T = c1.GetType();
#endregion
Console.WriteLine("Full name : {0}", T.FullName);
Console.WriteLine("Just name : {0}", T.Name);
Console.WriteLine("namespace name : {0}", T.Namespace);
Console.WriteLine("\n ------------------ Properties in Customers ------------------");
PropertyInfo[] properties = T.GetProperties();
foreach(PropertyInfo property in properties)
{
Console.WriteLine(property.Name+" : "+property.PropertyType.Name);
}
Console.WriteLine("\n ------------------ Methods in Customers ------------------");
MethodInfo[] methods = T.GetMethods();
foreach(MethodInfo method in methods)
{
Console.WriteLine(method.Name+" : "+method.ReturnType.Name);
}
Console.WriteLine("\n ------------------ Constructor in Customers ------------------");
ConstructorInfo[] constructors = T.GetConstructors();
foreach (ConstructorInfo constructor in constructors)
{
// name does not give more info
// Console.WriteLine(constructor.Name);
Console.WriteLine(constructor.ToString());
}
}
}
class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public Customer(int id, string name)
{
Id = id;
Name = name;
}
public Customer()
{
Id = -1;
Name = string.Empty;
}
public void PrintId()
{
Console.WriteLine("ID = {0}",this.Id);
}
public void PrintName()
{
Console.WriteLine("Name = {0}", this.Name);
}
}
}
|
00c1419f12149247bf5abdc376ae7d4c174461b1
|
C#
|
wf539/CSharpDotNETWebDevsGuide
|
/code_12/jokesService/userAdminImplement.cs
| 2.875
| 3
|
using System;
using System.Data;
using System.Data.SqlClient;
namespace jokesService
{
/// <summary>
/// Implementation class for userAdmin web service.
/// </summary>
/// <remarks>
/// Author: Adrian Turtschi; [email protected]; Sept 2001
/// </remarks>
public class userAdminImplement {
/// <summary>
/// Public class constructor.
/// </summary>
protected internal userAdminImplement() {
}
/// <summary>
/// The createSqlManageUser method sets up the SQL command object
/// for the stored procedure sp_manageUser, which deals with
/// adding, updating, and deleting users and managers
/// </summary>
/// <param name='userName'
/// type='string'
/// desc='name of registered user'>
/// </param>
/// <param name='password'
/// type='string'
/// desc='password of registered user (zero length if N/A)'>
/// </param>
/// <param name='isModerator'
/// type='string'
/// desc='true/false if this user is a moderator'>
/// </param>
/// <param name='action'
/// type='string'
/// desc='the action the SQL stored procedure should take
/// (see the stored procedure definition for allowed action
/// keywords)'>
/// </param>
/// <param name='sqlCommand'
/// type='SqlCommand'
/// desc='a reference to a SQL command object'>
/// </param>
/// <returns>the prepared SQL command object</returns>
protected internal void createSqlManageUser(
string userName, string password,
string isModerator, string action, SqlCommand sqlCommand) {
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.CommandText = "sp_manageUser" ;
SqlParameter argUserName =
new SqlParameter("@@userName", SqlDbType.NVarChar, 20);
argUserName.Value = userName;
sqlCommand.Parameters.Add(argUserName);
SqlParameter argPassword =
new SqlParameter("@@password",SqlDbType.NVarChar, 20);
if(password.Length > 0) {
argPassword.Value = password;
} else {
argPassword.Value = DBNull.Value;
}
sqlCommand.Parameters.Add(argPassword);
SqlParameter argIsModerator =
new SqlParameter("@@isModerator",SqlDbType.Bit);
argIsModerator.Value = bool.Parse(isModerator);
sqlCommand.Parameters.Add(argIsModerator);
SqlParameter argAction =
new SqlParameter("@@action",SqlDbType.NVarChar, 20);
argAction.Value = action;
sqlCommand.Parameters.Add(argAction);
SqlParameter argReturn =
new SqlParameter("@@return",SqlDbType.NVarChar, 20,
ParameterDirection.Output, true, 0, 0, "",
DataRowVersion.Current, "");
sqlCommand.Parameters.Add(argReturn);
}
/// <summary>
/// The createSqlCheckUser method sets up the SQL command object
/// for the stored procedure sp_checkUser, which verifies passed
/// user information with user information in the database
/// </summary>
/// <param name='userName'
/// type='string'
/// desc='name of registered user (zero length if N/A)'>
/// </param>
/// <param name='password'
/// type='string'
/// desc='password of registered user (zero length if N/A)'>
/// </param>
/// <param name='isModerator'
/// type='string'
/// desc='true/false if this user is a moderator
/// (zero length if N/A)'>
/// </param>
/// <param name='sqlCommand'
/// type='SqlCommand'
/// desc='a reference to a SQL command object'>
/// </param>
/// <returns>the prepared SQL command object</returns>
protected internal void createSqlCheckUser(
string userName, string password,
string isModerator, SqlCommand sqlCommand) {
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.CommandText = "sp_checkUser" ;
SqlParameter argUserName =
new SqlParameter("@@userName", SqlDbType.NVarChar, 20);
if(userName.Length > 0) {
argUserName.Value = userName;
} else {
argUserName.Value = DBNull.Value;
}
sqlCommand.Parameters.Add(argUserName);
SqlParameter argPassword =
new SqlParameter("@@password",SqlDbType.NVarChar, 20);
if(password.Length > 0) {
argPassword.Value = password;
} else {
argPassword.Value = DBNull.Value;
}
sqlCommand.Parameters.Add(argPassword);
SqlParameter argIsModerator =
new SqlParameter("@@isModerator",SqlDbType.Bit);
if(isModerator.Length > 0) {
argIsModerator.Value = bool.Parse(isModerator);
} else {
argIsModerator.Value = DBNull.Value;
}
sqlCommand.Parameters.Add(argIsModerator);
SqlParameter argReturn =
new SqlParameter("@@return",SqlDbType.NVarChar, 20,
ParameterDirection.Output, true, 0, 0, "",
DataRowVersion.Current, "");
sqlCommand.Parameters.Add(argReturn);
}
/// <summary>
/// The addUser method adds a new user to the database
/// </summary>
/// <param name='userName'
/// type='string'
/// desc='name of new user'>
/// </param>
/// <param name='password'
/// type='string'
/// desc='password of new user'>
/// </param>
/// <returns>true</returns>
protected internal bool addUser(string userName, string password) {
try {
string retCode;
SqlCommand sqlCommand = new SqlCommand();
createSqlManageUser(
userName, password, "false", "add", sqlCommand);
databaseAccess myDatabase = new databaseAccess();
sqlCommand.Connection = myDatabase.getConnection();
sqlCommand.Connection.Open();
sqlCommand.ExecuteNonQuery();
sqlCommand.Connection.Close();
retCode = sqlCommand.Parameters["@@return"].Value.ToString();
// catch problems within the stored procedure
if (retCode == "S_OK") {
return true;
} else {
throw new jokeException(retCode);
}
// catch problems with the database
} catch (Exception e) {
throw e;
}
}
/// <summary>
/// The addModerator method sets a previously added user to become
/// a moderator
/// </summary>
/// <param name='userName'
/// type='string'
/// desc='name of moderator making the call'>
/// </param>
/// <param name='password'
/// type='string'
/// desc='password of moderator making the call'>
/// </param>
/// <param name='newModerator'
/// type='string'
/// desc='user name of registered user who will become
/// a moderator'>
/// </param>
/// <returns>true</returns>
protected internal bool addModerator(
string userName, string password, string newModerator) {
string retCode;
try {
// check if user is a moderator
SqlCommand sqlCommand = new SqlCommand();
createSqlCheckUser(userName, password, "true", sqlCommand);
databaseAccess myDatabase = new databaseAccess();
sqlCommand.Connection = myDatabase.getConnection();
sqlCommand.Connection.Open();
sqlCommand.ExecuteNonQuery();
retCode = sqlCommand.Parameters["@@return"].Value.ToString();
// catch problems within the stored procedure
if (retCode != "S_OK") {
sqlCommand.Connection.Close();
throw new jokeException(retCode);
}
// make newModerator a moderator
sqlCommand.Parameters.Clear();
createSqlManageUser(
newModerator, "", "true", "modify", sqlCommand);
sqlCommand.ExecuteNonQuery();
sqlCommand.Connection.Close();
retCode = sqlCommand.Parameters["@@return"].Value.ToString();
// catch problems within the stored procedure
if (retCode == "S_OK") {
return true;
} else {
throw new jokeException(retCode);
}
// catch problems with the database
} catch (Exception e) {
throw e;
}
}
/// <summary>
/// The checkUser method checks if a user or moderator is
/// already defined in the database
/// </summary>
/// <param name='userName'
/// type='string'
/// desc='name of user or moderator'>
/// </param>
/// <param name='password'
/// type='string'
/// desc='password of user or moderator'>
/// </param>
/// <param name='isModerator'
/// type='bool'
/// desc='check for moderator status (if false,
/// we do not check)'>
/// </param>
/// <returns>nothing</returns>
protected internal bool checkUser(
string userName, string password, bool isModerator) {
string retCode;
try {
SqlCommand sqlCommand = new SqlCommand();
if(isModerator) {
// check if user is a moderator...
createSqlCheckUser(userName, password, "true", sqlCommand);
} else {
// ... or a registered user
createSqlCheckUser(userName, password, "", sqlCommand);
}
databaseAccess myDatabase = new databaseAccess();
sqlCommand.Connection = myDatabase.getConnection();
sqlCommand.Connection.Open();
sqlCommand.ExecuteNonQuery();
retCode = sqlCommand.Parameters["@@return"].Value.ToString();
// catch problems within the stored procedure
if (retCode == "S_OK") {
return true;
} else {
throw new jokeException(retCode);
}
// catch problems with the database
} catch (Exception e) {
throw e;
}
}
}
}
|
d68cfca5c0d83fd8da7bef11afc9a8c75914d159
|
C#
|
deyantodorov/TelerikAcademy
|
/Database/HW11.EntityFramework/T01.Northwind/DaoClass.cs
| 3.109375
| 3
|
namespace T01.Northwind
{
using System;
public static class DaoClass
{
public static void InsertCustomer(string customerId, string companyName, string city)
{
NorthwindEntities connection = new NorthwindEntities();
using (connection)
{
var newCustomer = new Customer
{
CustomerID = customerId,
CompanyName = companyName,
ContactName = null,
ContactTitle = null,
Address = null,
City = city,
Region = null,
PostalCode = null,
Country = null,
Phone = null,
Fax = null
};
connection.Customers.Add(newCustomer);
connection.SaveChanges();
}
}
public static void DeleteCustomer(string customerId)
{
NorthwindEntities connection = new NorthwindEntities();
using (connection)
{
var customerToRemove = connection.Customers.Find(customerId);
connection.Customers.Remove(customerToRemove);
connection.SaveChanges();
}
}
public static void ModifyCustomer(string customerId, string companyName, string city)
{
NorthwindEntities connection = new NorthwindEntities();
using (connection)
{
var customerToModify = connection.Customers.Find(customerId);
customerToModify.CompanyName = companyName;
customerToModify.City = city;
connection.SaveChanges();
}
}
}
}
|
2be701925350a82ce00e1e0de39c68d53b549388
|
C#
|
HDKnight/WebApplication1
|
/XML格式字符串解析/Program.cs
| 2.84375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace XML格式字符串解析
{
class Program
{
const string xmlStr = "<DETECT_ITEM RuleID='007' Caption='整车装备'>" +
"<RULE name='1' caption='1' LogicalOperator='and'>" +
"<ITEM ID = '1' LogicalOperator='与' KeyWord='cllx' Operator='IN' ComparingValue='B11,B12,B13,B14,B15,B16,B17' DataType='String' />" +
"<ITEM ID = '2' LogicalOperator='与' KeyWord='zzl' Operator='<=' ComparingValue='10000' DataType='Int' />" +
"</RULE>" +
"</DETECT_ITEM>";
static void Main(string[] args)
{
Console.WriteLine(ReWriteXML(xmlStr));
Console.ReadKey();
}
private static string ReWriteXML(string xml)
{
var doc = new XmlDocument();
doc.LoadXml(xml);
var rowNoteList = doc.SelectNodes("/DETECT_ITEM/RULE");
if (rowNoteList != null)
{
foreach (XmlNode rowNode in rowNoteList)
{
var fieldNodeList = rowNode.ChildNodes;
foreach (XmlNode courseNode in fieldNodeList)
{
if (courseNode.Attributes != null)
{
//Console.Write(courseNode.Attributes["ID"].Value);
//Console.Write("\t");
//Console.Write(courseNode.Attributes["LogicalOperator"].Value);
//Console.Write("\t");
//Console.Write(courseNode.Attributes["KeyWord"].Value);
//Console.Write("\t");
//Console.Write(courseNode.Attributes["Operator"].Value);
//Console.Write("\t");
//Console.Write(courseNode.Attributes["ComparingValue"].Value);
//Console.Write("\t");
//Console.Write(courseNode.Attributes["DataType"].Value);
//Console.Write("\r\n");
string str = "\n<!-- " + GetKeyWord(courseNode.Attributes["KeyWord"].Value) + GetOperator(courseNode.Attributes["Operator"].Value) + courseNode.Attributes["ComparingValue"].Value + " -->\n";
string str1 = "<ITEM ID = " + "'" + courseNode.Attributes["ID"].Value + "'";
int index = xml.IndexOf(str1);
xml = xml.Insert(index, str);
}
}
}
}
xml = System.Text.RegularExpressions.Regex.Replace(xml, "<DETECT_ITEM", "");//切割字符串,去掉"<DETECT_ITEM"子字符串
return xml;
}
private static string GetKeyWord(string code)
{
string keyword = "";
switch (code)
{
case "jylb": keyword = "检验类别"; break;
case "cllx": keyword = "车辆类型"; break;
case "zzl": keyword = "总质量"; break;
case "ccdjrq": keyword = "生产日期"; break;
case "ccrq": keyword = "初次登记日期"; break;
case "cwkc": keyword = "整车长度"; break;
case "cwkk": keyword = "整车宽度"; break;
case "cwkg": keyword = "整车高度"; break;
case "IsHaveJSS": keyword = "三轮车是否带驾驶室"; break;
case "SYXZStr": keyword = "使用性质"; break;
case "ZKRS": keyword = "载客人数"; break;
case "UseFulife": keyword = "使用年限"; break;
case "Reareng": keyword = "发动机是否后置(0-否,1-是)"; break;
case "IsHaveHX": keyword = "是否带货箱(0-否,1-是)"; break;
case "IsHaveLB": keyword = "是否带栏板(0-否,1-是)"; break;
case "YWLXID": keyword = "业务类型(0-申请,1-在用)"; break;
case "BrakeFS": keyword = "制动方式(0-液压,1-气压)"; break;
case "Fuel": keyword = "燃油类型(0-汽,1-柴)"; break;
default: keyword = "ERROR"; break;
}
return keyword;
}
private static string GetOperator(String code)
{
string ope = "";
switch (code)
{
case ">": ope = "大于于"; break;
case ">=": ope = "大于等于"; break;
case "=": ope = "等于"; break;
case "<": ope = "小于"; break;
case "<=": ope = "小于等于"; break;
case "!=": ope = "不等于"; break;
case "IN": ope = "有"; break;
case "NOT IN": ope = "没有"; break;
default: ope = "ERROR"; break;
}
return ope;
}
}
}
|
5ba887423f9e5902ad4edc7d76cc3771124d7953
|
C#
|
stefanNaumov/TelerikAcademy
|
/CSharp/Arrays/05.MaxInreasingSequence/MaxIncreasingSeq.cs
| 4.125
| 4
|
using System;
//Write a program that finds the maximal increasing sequence in an array. Example: {3, 2, 3, 4, 2, 2, 4} {2, 3, 4}.
namespace _05.MaxInreasingSequence
{
class MaxIncreasingSeq
{
static void Main()
{
int[] array = new int[] { 3, 2, 3, 4, 2, 2, 4 };
int maxSeqCounter = 0;
int seqStartIndex = 0;
int seqEndIndex = 0;
for (int i = 0; i < array.Length - 1; i++)
{
int currSequenceCounter = 1;
int currElement = array[i];
for (int j = i + 1; j < array.Length; j++)
{
if (array[j] <= currElement)
{
break;
}
currSequenceCounter++;
}
if (currSequenceCounter > maxSeqCounter)
{
maxSeqCounter = currSequenceCounter;
seqStartIndex = i;
seqEndIndex = i + maxSeqCounter - 1;
}
}
Console.Write("The maximal increasing sequence is: ");
for (int i = seqStartIndex; i <= seqEndIndex; i++)
{
Console.Write(array[i] + " ");
}
Console.WriteLine();
}
}
}
|
eabec837d8fde26470f3dac70b64294d5e679e2f
|
C#
|
mygibbs/Chess
|
/ChessLib/ChessLib/ChessBoard.cs
| 3.1875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ChessLib.Behaviours;
using ChessLib.Pieces;
using ChessLib.Enums;
namespace ChessLib
{
/// <summary>
/// The main Chess board.
/// </summary>
/// <remarks>This is also the controller of the game.</remarks>
public class ChessBoard : IEnumerable<Square>
{
/// <summary>
/// All the pieces and their starting locations.
/// </summary>
protected readonly Dictionary<Location, ChessPiece> StartingPieces;
/// <summary>
/// The squares of the Chess board.
/// </summary>
private Square[,] Squares { get; set; }
/// <summary>
/// The color that should move next.
/// </summary>
public ChessColor Turn { get; protected set; }
/// <summary>
/// Whether the game is over.
/// </summary>
public bool GameOver { get; protected set; }
/// <summary>
/// Whether to fire events.
/// </summary>
protected internal bool FireEvents { get; protected set; }
/// <summary>
/// The move history.
/// </summary>
public List<Move> History { get; internal protected set; }
private int _CurrentHistory = 0;
/// <summary>
/// The current position in the move history.
/// </summary>
public int CurrentHistory { get { return this._CurrentHistory; } set { this._CurrentHistory = value; this.PlayHistoryTo(this._CurrentHistory); } }
/// <summary>
/// A function which decides what to promote to when a pawn reaches the end of the Chess board.
/// </summary>
public Func<ChessBoard, PromotionChoise> Promotion { get; set; }
/// <summary>
/// The constructor.
/// </summary>
public ChessBoard() : this(c => PromotionChoise.Queen) { }
/// <summary>
/// The constructor.
/// </summary>
/// <param name="promotion">A function which decides what to promote to when a pawn reaches the end of the Chess board.</param>
public ChessBoard(Func<ChessBoard, PromotionChoise> promotion)
{
this.FireEvents = true;
this.GameOver = false;
this.Promotion = promotion;
this.History = new List<Move>();
this.StartingPieces = new Dictionary<Location, ChessPiece>
{
{new Location(8, 'A'), new Rook(this, ChessColor.Black)},
{new Location(8, 'B'), new Knight(this, ChessColor.Black)},
{new Location(8, 'C'), new Bishop(this, ChessColor.Black)},
{new Location(8, 'D'), new Queen(this, ChessColor.Black)},
{new Location(8, 'E'), new King(this, ChessColor.Black)},
{new Location(8, 'F'), new Bishop(this, ChessColor.Black)},
{new Location(8, 'G'), new Knight(this, ChessColor.Black)},
{new Location(8, 'H'), new Rook(this, ChessColor.Black)},
{new Location(7, 'A'), new Pawn(this, ChessColor.Black)},
{new Location(7, 'B'), new Pawn(this, ChessColor.Black)},
{new Location(7, 'C'), new Pawn(this, ChessColor.Black)},
{new Location(7, 'D'), new Pawn(this, ChessColor.Black)},
{new Location(7, 'E'), new Pawn(this, ChessColor.Black)},
{new Location(7, 'F'), new Pawn(this, ChessColor.Black)},
{new Location(7, 'G'), new Pawn(this, ChessColor.Black)},
{new Location(7, 'H'), new Pawn(this, ChessColor.Black)},
{new Location(1, 'A'), new Rook(this, ChessColor.White)},
{new Location(1, 'B'), new Knight(this, ChessColor.White)},
{new Location(1, 'C'), new Bishop(this, ChessColor.White)},
{new Location(1, 'D'), new Queen(this, ChessColor.White)},
{new Location(1, 'E'), new King(this, ChessColor.White)},
{new Location(1, 'F'), new Bishop(this, ChessColor.White)},
{new Location(1, 'G'), new Knight(this, ChessColor.White)},
{new Location(1, 'H'), new Rook(this, ChessColor.White)},
{new Location(2, 'A'), new Pawn(this, ChessColor.White)},
{new Location(2, 'B'), new Pawn(this, ChessColor.White)},
{new Location(2, 'C'), new Pawn(this, ChessColor.White)},
{new Location(2, 'D'), new Pawn(this, ChessColor.White)},
{new Location(2, 'E'), new Pawn(this, ChessColor.White)},
{new Location(2, 'F'), new Pawn(this, ChessColor.White)},
{new Location(2, 'G'), new Pawn(this, ChessColor.White)},
{new Location(2, 'H'), new Pawn(this, ChessColor.White)},
};
this.Reset(true);
}
/// <summary>
/// Resets the Chess board.
/// </summary>
public void Reset(bool clearHistory = false)
{
this.GameOver = false;
this.Turn = ChessColor.White;
this.Squares = new Square[8, 8];
for (int row = 0; row < this.Squares.GetLength(0); row++)
{
for (int column = 0; column < this.Squares.GetLength(1); column++)
{
Location curLoc = new Location(row + 1, column + 1);
ChessPiece piece = (from p in this.StartingPieces where p.Key == curLoc select p.Value).SingleOrDefault();
Square t = (this.Squares[row, column] == null ? new Square(this, curLoc, (row + column) % 2 == 0 ? ChessColor.Black : ChessColor.White) : this.Squares[row, column]);
t.Piece = piece;
if (piece != null) piece.Reset(t);
this.Squares[row, column] = t;
}
}
if (clearHistory) { this.History.Clear(); this._CurrentHistory = 0; }
if (this.FireEvents) this.NextTurn.IfNotNull(a => a(this));
}
/// <summary>
/// Plays the history from the beginning, the specified amount of moves.
/// </summary>
/// <param name="to">How many moves to play from the beginning.</param>
public void PlayHistoryTo(int to)
{
this.Reset();
this._CurrentHistory = 0;
for (int i = 0; i < Math.Max(Math.Min(to, this.History.Count), 0); i++)
{
Move m = this.History[i];
this.FireEvents = false;
this.Move(this[m.A], this[m.B], false, false);
this.FireEvents = true;
this._CurrentHistory = i + 1;
}
}
/// <summary>
/// Gets the king with the specified color.
/// </summary>
/// <param name="c">The color of the king to find.</param>
/// <returns>The square that the king is on.</returns>
public King GetKing(ChessColor c)
{
return (from s in this
where s.Piece != null && s.Piece.Color == c && s.Piece.GetType() == typeof(King)
select (King)s.Piece).Single();
}
/// <summary>
/// Tell the Chess board that the current turn is over.
/// </summary>
internal protected void TurnOver(bool checkGameOver = true)
{
this.Turn = this.Turn.Opposite();
if (checkGameOver)
{
King blackKing = this.GetKing(ChessColor.Black);
King whiteKing = this.GetKing(ChessColor.White);
if (this.StaleMate)
{
this.GameOver = true;
if (this.FireEvents) this.GameEnded.IfNotNull(a => a(this, ChessWinner.StaleMate));
}
else if (blackKing.CheckMade)
{
this.GameOver = true;
if (this.FireEvents) this.GameEnded.IfNotNull(a => a(this, ChessWinner.White));
}
else if (whiteKing.CheckMade)
{
this.GameOver = true;
if (this.FireEvents) this.GameEnded.IfNotNull(a => a(this, ChessWinner.Black));
}
else
{
if (this.FireEvents) this.NextTurn.IfNotNull(a => a(this));
}
}
}
/// <summary>
/// Moves a Chess piece from A to B.
/// </summary>
/// <param name="a">Square A.</param>
/// <param name="b">Square B.</param>
/// <returns>Whether or not the move was successful.</returns>
internal protected bool Move(Square a, Square b)
{
return this.Move(a, b, true);
}
/// <summary>
/// Moves a Chess piece from A to B.
/// </summary>
/// <param name="a">Square A.</param>
/// <param name="b">Square B.</param>
/// <param name="writeHistory">Whether or not to write the move to the history.</param>
/// <param name="validate">Wether to validate the move.</param>
/// <returns>Whether or not the move was successful.</returns>
protected bool Move(Square a, Square b, bool writeHistory = true, bool validate = true)
{
if (!this.CanMove(a, b, false, validate)) return false;
foreach (Pawn p in from sq in this where sq.Piece != null && sq.Piece.Color == this.Turn && sq.Piece.GetType() == typeof(Pawn) select (Pawn)sq.Piece)
{
p.EnPassantable = false;
}
if (b.Piece.GetType() == typeof(Pawn) && Math.Abs(b.Location.Rank - a.Location.Rank) == 2)
{
((Pawn)b.Piece).EnPassantable = true;
}
if (writeHistory) this.WriteHistory(a.Location, b.Location);
this.TurnOver(validate);
return true;
}
/// <summary>
/// Checks whether the the piece on a can be moved to b.
/// </summary>
/// <param name="a">Square a.</param>
/// <param name="b">Square b.</param>
/// <param name="resetAlways">Whether to reset the board when the check is done.</param>
/// <param name="validate">Whether to validate.</param>
/// <param name="askForPromotion">Whether to ask for promotion.</param>
/// <returns>Whether the piece on a can be move to b.</returns>
protected internal bool CanMove(Square a, Square b, bool resetAlways = false, bool validate = true, bool askForPromotion = true)
{
if (this.GameOver) return false;
if (a.Piece == null) return false;
if (a.Piece.Color != this.Turn) return false;
if (b.Piece != null && b.Piece.Color == a.Piece.Color) return false;
if (validate && !a.Piece.Movement.Move(b)) return false;
King king = null;
if (validate)
{
king = this.GetKing(this.Turn);
if (!Object.ReferenceEquals(a, king.Square) && king.Checked)
{
// Check if move will block check, and that king will not be checked afterwards.
IEnumerable<ChessPiece> threats = king.CheckingPieces;
if (threats.Count() == 1)
{
ChessPiece single = threats.Single();
if (single.Square != b)
{
if (single.Movement.GetType() != typeof(RowMovement)) return false;
RowMovement rm = (RowMovement)single.Movement;
if (rm.AllValidMoves(b).Contains(king.Square)) return false;
}
}
else
{
// Multiple threats.
if (a.Piece != king) return false;
}
}
}
TempPiece[,] backupBoard = null;
if (validate)
{
backupBoard = new TempPiece[8, 8];
foreach (Square s in this)
{
backupBoard[s.Location.Rank - 1, Location.ConvertFile(s.Location.File) - 1] = new TempPiece(s.Piece);
}
}
if (!(a.Piece.GetType() == typeof(Pawn) && (((PawnMovement)a.Piece.Movement).HandlePromotion(b, askForPromotion) || ((PawnMovement)a.Piece.Movement).HandleEnPassant(b))) &&
!(a.Piece.GetType() == typeof(King) && ((KingMovement)a.Piece.Movement).HandleCastling(b)))
{
a.Piece.Square = b;
b.Piece = a.Piece;
a.Piece = null;
b.Piece.MoveCount++;
}
if (validate)
{
bool kingChecked = king.Checked;
if (resetAlways || kingChecked)
{
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
{
TempPiece tp = backupBoard[x, y];
Square s = this.Squares[x, y];
s.Piece = tp.Piece;
if (tp.Piece != null)
{
tp.Piece.Square = s;
tp.Piece.MoveCount = tp.MoveCount;
}
}
}
}
return !kingChecked;
}
else return true;
}
/// <summary>
/// Writes a new move to the history.
/// </summary>
/// <param name="a">From.</param>
/// <param name="b">To.</param>
protected void WriteHistory(Location a, Location b)
{
for (int i = this.History.Count - 1; i >= this.CurrentHistory; i--)
{
this.History.RemoveAt(i);
}
this.History.Add(new Move(a, b));
this._CurrentHistory++;
}
/// <summary>
/// Whether a stalemate has occured.
/// </summary>
public bool StaleMate
{
get
{
if (this.Count(s => s.Piece != null) == 2) return true;
King king = this.GetKing(this.Turn);
if (king.Checked) return false;
foreach (Square square in this.Where(s => s.Piece != null && s.Piece.Color == king.Color))
{
if (square.Piece.TotallyValidMoves.Count() != 0) return false;
}
return true;
}
}
#region Events
/// <summary>
/// An event that is fired when the next player should move.
/// </summary>
public event Action<ChessBoard> NextTurn;
/// <summary>
/// An event that is fired when the game has ended.
/// </summary>
public event Action<ChessBoard, ChessWinner> GameEnded;
#endregion
#region Indexers
/// <summary>
/// Gives access to the squares of the Chess board.
/// </summary>
/// <param name="rank">The rank of the square.</param>
/// <param name="file">The file of the square.</param>
/// <returns>The square at the specified rank and file.</returns>
public Square this[int rank, char file]
{
get
{
return this.Squares[rank - 1, Location.ConvertFile(file) - 1];
}
}
/// <summary>
/// Gives access to the squares of the Chess board.
/// </summary>
/// <param name="rank">The rank of the square.</param>
/// <param name="file">The file of the square.</param>
/// <returns>The square at the specified rank and file.</returns>
public Square this[int rank, int file]
{
get
{
return this.Squares[rank - 1, file - 1];
}
}
/// <summary>
/// Gives access to the squares of the Chess board.
/// </summary>
/// <param name="l">The location of the square.</param>
/// <returns>The square at the specified rank and file.</returns>
public Square this[Location l]
{
get
{
return this[l.Rank, l.File];
}
}
/// <summary>
/// Gives access to the squares of the Chess board.
/// </summary>
/// <param name="l">The location of the square.</param>
/// <returns>The square at the specified rank and file.</returns>
/// <example>A1, D2, H8 ...</example>
public Square this[string l]
{
get
{
return this[Convert.ToInt32(l[1].ToString()), l[0]];
}
}
#endregion
#region Enumerators
/// <see cref="IEnumerable<T>.GetEnumerator()"/>
public IEnumerator<Square> GetEnumerator()
{
for (int rank = 1; rank <= this.Squares.GetLength(0); rank++)
{
for (int file = 1; file <= this.Squares.GetLength(1); file++)
{
yield return this[rank, file];
}
}
}
/// <see cref="System.Collections.IEnumerable.GetEnumerator()"/>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
for (int rank = 1; rank <= this.Squares.GetLength(0); rank++)
{
for (int file = 1; file <= this.Squares.GetLength(1); file++)
{
yield return this[rank, file];
}
}
}
#endregion
#region Import / Export
/// <summary>
/// Imports the specified moves.
/// </summary>
/// <param name="moves">The moves.</param>
/// <param name="tryAll">Whether to try importing all the moves.</param>
/// <returns>Whether all moves could be executed.</returns>
public bool Import(string moves, bool tryAll = false)
{
return this.Import(ChessMoveParser.Parse(moves), tryAll);
}
/// <summary>
/// Imports the specified moves.
/// </summary>
/// <param name="moves">The moves.</param>
/// /// <param name="tryAll">Whether to try importing all the moves.</param>
/// <returns>Whether all moves could be executed.</returns>
public bool Import(Move[] moves, bool tryAll = false)
{
foreach (Move m in moves)
{
if (!this.Move(this[m.A], this[m.B]) && !tryAll) return false;
}
return true;
}
/// <summary>
/// Exports the current move history.
/// </summary>
/// <returns>The move history.</returns>
public string Export()
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < this.CurrentHistory; i++)
{
Move m = this.History[i];
m.A.ToString(sb);
sb.Append(' ');
m.B.ToString(sb);
if (i + 1 < this.CurrentHistory) sb.Append('\n');
}
return sb.ToString();
}
#endregion
}
}
|
e6e5eba12651ae432a7e0caccf1d53101700a1e6
|
C#
|
flipbit/syntax
|
/Source/Syntax.Data/SqlUpdate.cs
| 3.15625
| 3
|
using System.Data;
namespace Syntax.Data
{
/// <summary>
/// Builds an SQL UPDATE statement
/// </summary>
/// <typeparam name="T"></typeparam>
public class SqlUpdate<T> : SqlCommand<T>
{
/// <summary>
/// Initializes a new instance of the <see cref="SqlInsert{T}" /> class.
/// </summary>
/// <param name="target">The target.</param>
/// <param name="connection">The connection.</param>
/// <param name="transaction">The transaction.</param>
public SqlUpdate(T target, IDbConnection connection, IDbTransaction transaction) : base(target, connection, transaction)
{
}
/// <summary>
/// Returns an SQL representation of this command.
/// </summary>
/// <returns></returns>
public override string ToSql()
{
return Dialect.Update(this);
}
}
}
|
f09dc3441a68fe868b15e665e4b166ed48a62338
|
C#
|
sabbir1305/CinemaRestApi
|
/CinemaRestApi/Services/Reservations/ReservationRepo.cs
| 2.703125
| 3
|
using CinemaRestApi.Data;
using CinemaRestApi.Models;
using CinemaRestApi.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CinemaRestApi.Services.Reservations
{
public class ReservationRepo : IReservation
{
private CinemaDbContext _dbContext;
public ReservationRepo(CinemaDbContext dbContext)
{
_dbContext = dbContext;
}
public void Add(Reservation reservation)
{
reservation.ReservationTime = DateTime.Now;
_dbContext.Add(reservation);
}
public void Delete(Reservation reservation)
{
_dbContext.Remove(reservation);
}
public Reservation GetReservation(int id)
{
return _dbContext.Reservations.Find(id);
}
public ReservationDto GetReservationDetail(int id)
{
var data = (from rs in _dbContext.Reservations
join m in _dbContext.Movies on rs.MovieId equals m.Id
join u in _dbContext.Users on rs.UserId equals u.Id
where rs.Id==id
select new ReservationDto
{
Id = rs.Id,
MovieName = m.Name,
ReservationTime = rs.ReservationTime,
UserName = u.Name,
MovieId=m.Id,
Phone=rs.Phone,
Price=rs.Price,
Qty=rs.Qty,
UserId=rs.UserId,
PlayingDate=m.PlayingDate,
PlayingTime=m.PlayingTime
}).FirstOrDefault();
return data;
}
public IList<ReservationSummaryDto> GetReservations()
{
var data = (from rs in _dbContext.Reservations
join m in _dbContext.Movies on rs.MovieId equals m.Id
join u in _dbContext.Users on rs.UserId equals u.Id
select new ReservationSummaryDto
{
Id = rs.Id,
MovieName = m.Name,
ReservationTime = rs.ReservationTime,
UserName = u.Name
}).ToList();
return data;
}
public bool Save()
{
return _dbContext.SaveChanges() >= 0;
}
}
}
|
0becce3f26b0db8e59cc3bf87bb7954a3a672b3a
|
C#
|
angelocuartel/Csharp-Calculator-winform
|
/Calculator/Length.cs
| 2.9375
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Calculator
{
public partial class Length : UserControl
{
public Length()
{
InitializeComponent();
}
private void guna2CircleButton1_Click(object sender, EventArgs e)
{
LabelCurrent.Text += "1";
}
private void guna2CircleButton2_Click(object sender, EventArgs e)
{
LabelCurrent.Text += "2";
}
private void guna2CircleButton3_Click(object sender, EventArgs e)
{
LabelCurrent.Text += "3";
}
private void guna2CircleButton4_Click(object sender, EventArgs e)
{
LabelCurrent.Text += "4";
}
private void guna2CircleButton5_Click(object sender, EventArgs e)
{
LabelCurrent.Text += "5";
}
private void guna2CircleButton6_Click(object sender, EventArgs e)
{
LabelCurrent.Text += "6";
}
private void guna2CircleButton7_Click(object sender, EventArgs e)
{
LabelCurrent.Text += "7";
}
private void guna2CircleButton8_Click(object sender, EventArgs e)
{
LabelCurrent.Text += "8";
}
private void guna2CircleButton9_Click(object sender, EventArgs e)
{
LabelCurrent.Text += "9";
}
private void guna2CircleButton10_Click(object sender, EventArgs e)
{
if (LabelCurrent.Text.Substring(0) != "")
LabelCurrent.Text += "0";
}
private void Converter(string conVal)
{
switch (conVal)
{
case "Kilometre":
this.textBox1.Text = (long.Parse(LabelCurrent.Text) * 1000).ToString()+" m";
this.textBox2.Text = (long.Parse(LabelCurrent.Text) * 100000).ToString() + " cm";
this.textBox3.Text = (long.Parse(LabelCurrent.Text) * 0.621371).ToString() + " mi";
this.textBox4.Text = (long.Parse(LabelCurrent.Text) * 3280.84).ToString() + " ft";
this.textBox5.Text = (long.Parse(LabelCurrent.Text) * 1093.61).ToString() + " yd";
break;
case "Metre":
this.textBox1.Text = (long.Parse(LabelCurrent.Text) / 1000).ToString() + " km";
this.textBox2.Text = (long.Parse(LabelCurrent.Text) * 100).ToString() + " cm";
this.textBox3.Text = (long.Parse(LabelCurrent.Text) / 0.000621371).ToString() + " mi";
this.textBox4.Text = (long.Parse(LabelCurrent.Text) * 3.28084).ToString() + " ft";
this.textBox5.Text = (long.Parse(LabelCurrent.Text) * 1.09361).ToString() + " yd";
break;
case "Centimetre":
this.textBox1.Text = (long.Parse(LabelCurrent.Text) / 100000).ToString() + " km";
this.textBox2.Text = (long.Parse(LabelCurrent.Text) / 100).ToString() + " m";
this.textBox3.Text = (long.Parse(LabelCurrent.Text) / 160934).ToString() + " mi";
this.textBox4.Text = (long.Parse(LabelCurrent.Text) / 30.48).ToString() + " ft";
this.textBox5.Text = (long.Parse(LabelCurrent.Text) / 91.44).ToString() + " yd";
break;
case "Mile":
this.textBox1.Text = (long.Parse(LabelCurrent.Text) * 1.60934).ToString() + " km";
this.textBox2.Text = (long.Parse(LabelCurrent.Text) * 1609.34).ToString() + " m";
this.textBox3.Text = (long.Parse(LabelCurrent.Text) * 160934).ToString() + " cm";
this.textBox4.Text = (long.Parse(LabelCurrent.Text) * 5280).ToString() + " ft";
this.textBox5.Text = (long.Parse(LabelCurrent.Text) * 1760).ToString() + " yd";
break;
case "Foot":
this.textBox1.Text = (long.Parse(LabelCurrent.Text) / 3281).ToString() + " km";
this.textBox2.Text = (long.Parse(LabelCurrent.Text) / 3.281).ToString() + " m";
this.textBox3.Text = (long.Parse(LabelCurrent.Text) * 30.48).ToString() + " cm";
this.textBox4.Text = (long.Parse(LabelCurrent.Text) / 5280).ToString() + " mi";
this.textBox5.Text = (long.Parse(LabelCurrent.Text) / 3).ToString() + " yd";
break;
case "Yard":
this.textBox1.Text = (long.Parse(LabelCurrent.Text) / 1094).ToString() + " km";
this.textBox2.Text = (long.Parse(LabelCurrent.Text) / 1.094).ToString() + " m";
this.textBox3.Text = (long.Parse(LabelCurrent.Text) * 91.44).ToString() + " cm";
this.textBox4.Text = (long.Parse(LabelCurrent.Text) / 1760).ToString() + " mi";
this.textBox5.Text = (long.Parse(LabelCurrent.Text) * 3).ToString() + " ft";
break;
}
}
private void LabelCurrent_Click(object sender, EventArgs e)
{
}
private void LabelCurrent_TextChanged(object sender, EventArgs e)
{
if (LabelCurrent.Text != "")
{
Converter(gunaComboBox1.Text);
}
}
private void guna2CircleButton14_Click(object sender, EventArgs e)
{
if(LabelCurrent.Text != "")
{
LabelCurrent.Text = LabelCurrent.Text.Remove(LabelCurrent.Text.Length-1,1);
}
}
private void gunaComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ClearAll();
}
private void Length_VisibleChanged(object sender, EventArgs e)
{
ClearAll();
gunaComboBox1.Text = "";
}
private void ClearAll()
{
LabelCurrent.Text = "";
textBox1.Text = textBox2.Text = textBox3.Text = textBox4.Text = textBox5.Text = "";
}
private void guna2CircleButton12_Click(object sender, EventArgs e)
{
ClearAll();
}
}
}
|
29182a02c1f7ec31e4f0ec62d18ad29b7e8d6f11
|
C#
|
LeanCabeza/laboratorio2_TP
|
/RECUPERATORIOS TP/TP4-Concesionario/Entidades/ConexioBD.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using Excepciones;
namespace Entidades
{
public static class ConexionBD
{
static SqlConnection conexionBD;
/// <summary>
/// Connection string
/// </summary>
static ConexionBD()
{
conexionBD = new SqlConnection("Data Source = DESKTOP-DCNPJDC\\SQLEXPRESS ; Initial Catalog = Concesionario;Integrated Security=true");
}
/// <summary>
/// Funcion qye sube autos a la bdd
/// </summary>
/// <param name="auxAuto">Objeto auto a subir</param>
public static void SubirAuto(Auto auxAuto)
{
try
{
SqlCommand comando = new SqlCommand();
comando.Connection = conexionBD;
comando.CommandType = CommandType.Text;
comando.CommandText = "INSERT INTO [dbo].[Autos] VALUES (@nombre,@precio,@anio,@kilometraje,@marca,@motor,@caballosDeFuerza) ";
comando.Parameters.Add(new SqlParameter("@nombre", auxAuto.NombreVehiculo));
comando.Parameters.Add(new SqlParameter("@precio", auxAuto.Precio));
comando.Parameters.Add(new SqlParameter("@anio", auxAuto.AnioDeFabricacion));
comando.Parameters.Add(new SqlParameter("@kilometraje", auxAuto.Kilometraje));
comando.Parameters.Add(new SqlParameter("@marca", auxAuto.MarcaAuto));
comando.Parameters.Add(new SqlParameter("@motor", auxAuto.TipoMotor));
comando.Parameters.Add(new SqlParameter("@caballosDeFuerza", auxAuto.CaballosDeFuerza));
if (conexionBD.State != ConnectionState.Open)
{
conexionBD.Open();
}
comando.ExecuteNonQuery();
}
catch (Exception e)
{
throw new ArchivoException("Error al intentar conectar con la base de datos", e);
}
finally
{
conexionBD.Close();
}
}
/// <summary>
/// Funcion que sube motos a la bdd
/// </summary>
/// <param name="auxMoto">Moto a subir a la bdd </param>
public static void SubirMoto(Moto auxMoto)
{
try
{
SqlCommand comando = new SqlCommand();
comando.Connection = conexionBD;
comando.CommandType = CommandType.Text;
comando.CommandText = "INSERT INTO [dbo].[Motos] VALUES (@nombre,@precio,@anio,@kilometraje,@marca,@encendido,@cilindrada) ";
comando.Parameters.Add(new SqlParameter("@nombre", auxMoto.NombreVehiculo));
comando.Parameters.Add(new SqlParameter("@precio", auxMoto.Precio));
comando.Parameters.Add(new SqlParameter("@anio", auxMoto.AnioDeFabricacion));
comando.Parameters.Add(new SqlParameter("@kilometraje", auxMoto.Kilometraje));
comando.Parameters.Add(new SqlParameter("@marca", auxMoto.MarcaMoto));
comando.Parameters.Add(new SqlParameter("@encendido", auxMoto.TipoEncendido));
comando.Parameters.Add(new SqlParameter("@cilindrada", auxMoto.Cilindrada));
if (conexionBD.State != ConnectionState.Open)
{
conexionBD.Open();
}
comando.ExecuteNonQuery();
}
catch (Exception e)
{
throw new ArchivoException("Error al intentar conectar con la base de datos", e);
}
finally
{
conexionBD.Close();
}
}
}
}
|
cea5aaa9c76e32694b5415644221f7b3a663fc66
|
C#
|
benlincoln/Dissertation-Attendance-Automation
|
/API/API/Controllers/EventController.cs
| 2.796875
| 3
|
using API.Models;
using Microsoft.AspNetCore.Mvc;
using Npgsql;
using System;
using System.Collections.Generic;
namespace API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class EventController : ControllerBase
{
// GET api/event
// Get next event and current
[HttpGet]
public List<Event> Get()
{
string classes = Request.Headers["classes"];
// Connection String
string conString = Program.getConString();
using var con = new NpgsqlConnection(conString);
// Connect to the DB
con.Open();
// Will use index 0 as closest event, 1 for if there is a current event to return the next event
List<Event> Events = new List<Event>();
string sql = $"SELECT * FROM events WHERE class in ({classes}) AND (DATE_PART('minute', datetime - LOCALTIMESTAMP)) <= 30" +
" AND (DATE_PART('day', datetime - LOCALTIMESTAMP)) = 0 AND (DATE_PART('hour', datetime - LOCALTIMESTAMP)) = 0";
using var cmd = new NpgsqlCommand(sql, con);
using NpgsqlDataReader reader = cmd.ExecuteReader();
reader.Read();
try
{
DateTime time = (DateTime)reader.GetTimeStamp(4);
Event newEvent = new Event { EventID = reader.GetString(0), LocationID = reader.GetString(1), EventName = reader.GetString(2), Time = time.ToString(), Current = true };
Events.Add(newEvent);
}
// Exception is thrown if there is nothing to read
catch { }
reader.Close();
// Get the next event
cmd.CommandText = $"SELECT * FROM events WHERE class in ({classes}) AND datetime > LOCALTIMESTAMP ORDER BY datetime ASC";
cmd.ExecuteReader();
reader.Read();
try
{
DateTime time = (DateTime)reader.GetTimeStamp(4);
Event newEvent = new Event { EventID = reader.GetString(0), LocationID = reader.GetString(1), EventName = reader.GetString(2), Time = time.ToString(), Current = false };
Events.Add(newEvent);
}
// Exception is thrown if there is nothing to read
catch { }
return Events;
}
// PATCH api/<ValuesController>
// Used to mark students present
[HttpPatch]
public Event Patch()
{
string studentID = Request.Headers["studentID"];
string eventid = "event"+Request.Headers["eventID"];
// Connection String
var conString = Program.getConString();
using var con = new NpgsqlConnection(conString);
con.Open();
// Gets the event's table and marks the student present
string sql = $"UPDATE {eventid} set attended = 'a' WHERE studentno = '{studentID}' ";
using var cmd = new NpgsqlCommand(sql, con);
cmd.ExecuteNonQuery();
return new Event { EventID = eventid };
}
[HttpPatch]
[Route("api/event/update")]
public void MarkAbscent()
{
var conString = Program.getConString();
using var con = new NpgsqlConnection(conString);
con.Open();
// Gets all events in the past day
string sql = $"SELECT eventid FROM events WHERE AND (DATE_PART('day', datetime - LOCALTIMESTAMP)) = 0";
using var cmd = new NpgsqlCommand(sql, con);
using NpgsqlDataReader reader = cmd.ExecuteReader();
reader.Read();
List<string> eventList = new List<string>();
while (reader.Read())
{
eventList.Add(reader.GetString(0));
}
foreach(string currEvent in eventList)
{
string currEventTbl = $"event{currEvent}";
cmd.CommandText = $"UPDATE {currEventTbl} set attended = 'u' WHERE attended = 'null' ";
cmd.ExecuteNonQuery();
}
}
}
}
|
11de6ed38fb4a372838a10d3d3776778922bb535
|
C#
|
zigaosolin/SharpMedia
|
/SharpMedia/Math/Vectorf.cs
| 2.828125
| 3
|
// This file was generated by TemplateEngine from template source 'Vector'
// using template 'Vectorf. Do not modify this file directly, modify it from template source.
// This file constitutes a part of the SharpMedia project, (c) 2007 by the SharpMedia team
// and is licensed for your use under the conditions of the NDA or other legally binding contract
// that you or a legal entity you represent has signed with the SharpMedia team.
// In an event that you have received or obtained this file without such legally binding contract
// in place, you MUST destroy all files and other content to which this lincese applies and
// contact the SharpMedia team for further instructions at the internet mail address:
//
// [email protected]
//
using System;
using System.Collections.Generic;
using System.Text;
using SharpMedia.AspectOriented;
using SharpMedia.Testing;
namespace SharpMedia.Math
{
/// <summary>
/// A general implementation of n-dimensional vector.
/// </summary>
[Serializable]
public sealed class Vectorf : IEquatable<Vectorf>, ICloneable<Vectorf>
{
#region Private Members
private float[] components;
#endregion
#region Properties
//#ifdef Sqrt
/// <summary>
/// The length of vector.
/// </summary>
public float Length
{
get { return MathHelper.Sqrt(this * this); }
}
//#endif
/// <summary>
/// The length of vector squared. It is prefered if you can use Length2 instead od Length.
/// </summary>
public float Length2
{
get { return this * this; }
}
/// <summary>
/// Obtains components.
/// </summary>
public float[] Components
{
get { return components; }
}
/// <summary>
/// The number of dimensions in vector.
/// </summary>
public uint DimensionCount
{
get { return (uint)components.Length; }
}
/// <summary>
/// Indexer on vector.
/// </summary>
/// <param name="index">The index, must be smaller then Length.</param>
/// <returns>The element at that</returns>
public float this[uint index]
{
get { return components[index]; }
set { components[index] = value; }
}
//#ifdef Vector2ClassName
/// <summary>
/// Cast to 2D vector, taking all furher dimensions away.
/// </summary>
public Vector2f Vector2
{
get
{
if (components.Length < 2) throw new ArgumentException("Not castable to vector 2D.");
return new Vector2f(components[0], components[1]);
}
}
//#endif
//#ifdef Vector3ClassName
/// <summary>
/// Cast to 3D vector, taking all furher dimensions away.
/// </summary>
public Vector3f Vector3
{
get
{
if (components.Length < 3) throw new ArgumentException("Not castable to vector 3D.");
return new Vector3f(components[0], components[1], components[2]);
}
}
//#endif
//#ifdef Vector4ClassName
/// <summary>
/// Cast to 4D vector, taking all furher dimensions away.
/// </summary>
public Vector4f Vector4
{
get
{
if (components.Length < 4) throw new ArgumentException("Not castable to vector 4D.");
return new Vector4f(components[0], components[1], components[2], components[3]);
}
}
//#endif
#endregion
#region Operators
/// <summary>
/// The generic vector adition. Vectors must be the same dimension.
/// </summary>
/// <param name="v1">The first vector.</param>
/// <param name="v2">The second vector.</param>
/// <returns>Vectors added.</returns>
public static Vectorf operator +([NotNull] Vectorf v1, [NotNull] Vectorf v2)
{
// Precheck.
if (v1.DimensionCount != v2.DimensionCount)
{
throw new ArithmeticException("The vectors are not compatible in size, one is " +
v1.ToString() + " and the other is " + v2.ToString());
}
// Create result.
uint size = v1.DimensionCount;
Vectorf result = new Vectorf(size);
for (uint i = 0; i < size; ++i)
{
result.components[i] = v1.components[i] + v2.components[i];
}
// Return the result.
return result;
}
/// <summary>
/// The generic vector substraction. Vectors must be the same dimension.
/// </summary>
/// <param name="v1">The first vector.</param>
/// <param name="v2">The second vector.</param>
/// <returns>Vectors added.</returns>
public static Vectorf operator -([NotNull] Vectorf v1, [NotNull] Vectorf v2)
{
// Precheck.
if (v1.DimensionCount != v2.DimensionCount)
{
throw new ArithmeticException("The vectors are not compatible in size, one is " +
v1.ToString() + " and the other is " + v2.ToString());
}
// Create result.
uint size = v1.DimensionCount;
Vectorf result = new Vectorf(size);
for (uint i = 0; i < size; ++i)
{
result.components[i] = v1.components[i] - v2.components[i];
}
// Return the result.
return result;
}
/// <summary>
/// Dot product, defined as a * b = |a| * |b| * cos(phi), where phi is the
/// angle between vectors.
/// </summary>
/// <param name="v1">The first vector.</param>
/// <param name="v2">The second vector.</param>
/// <returns>Scalar result.</returns>
public static float operator *([NotNull] Vectorf v1, [NotNull] Vectorf v2)
{
// Precheck.
if (v1.DimensionCount != v2.DimensionCount)
{
throw new ArithmeticException("The vectors are not compatible in size, one is " +
v1.ToString() + " and the other is " + v2.ToString());
}
// Create result.
uint size = v1.DimensionCount;
float result = 0.0f;
for (uint i = 0; i < size; ++i)
{
result += v1.components[i] * v2.components[i];
}
// Return the result.
return result;
}
/// <summary>
/// Swizzle operation on vector.
/// </summary>
/// <param name="mask">The mask may be any length, but indices must not exceed range.
/// Each element represents the new offset of the element from old vector. The { 0, 2, 1 }
/// means first element is the offset 0 in this vector, second is the offset 2 and last is
/// the offset 1.</param>
/// <returns>Swizzled vector.</returns>
public Vectorf Swizzle([NotNull] uint[] mask)
{
uint size = (uint)components.Length;
float[] array = new float[size];
for (uint x = 0; x < size; x++)
{
uint data = mask[x];
if (data >= size)
{
throw new ArithmeticException("The swizzle offset of mask out of range, vector is "
+ ToString() + " and the mask is " + mask.ToString());
}
array[x] = components[data];
}
return new Vectorf(array);
}
/// <summary>
/// Compares two vectors.
/// </summary>
/// <param name="v1">The first vector.</param>
/// <param name="v2">The second vector.</param>
/// <returns>Are vectors equal.</returns>
public static bool operator ==([NotNull] Vectorf v1, [NotNull] Vectorf v2)
{
uint count = v1.DimensionCount;
if (count != v2.DimensionCount) return false;
for (uint i = 0; i < count; i++)
{
if (v1[i] != v2[i]) return false;
}
return true;
}
/// <summary>
/// Compares two vectors.
/// </summary>
/// <param name="v1">The first vector.</param>
/// <param name="v2">The second vector.</param>
/// <returns>Result of operation.</returns>
public static bool operator !=([NotNull] Vectorf v1, [NotNull] Vectorf v2)
{
return !(v1 == v2);
}
#endregion
#region Overrides
public override bool Equals([NotNull] object obj)
{
if (obj.GetType() == this.GetType()) return this == (Vectorf)obj;
return false;
}
public override string ToString()
{
uint dimensionsCount = DimensionCount;
StringBuilder builder = new StringBuilder("(", (int)dimensionsCount * 2);
for (uint i = 0; i < (dimensionsCount - 1); i++)
{
builder.Append(components[i]);
builder.Append(",");
}
builder.Append(components[dimensionsCount - 1]);
builder.Append(")");
return builder.ToString();
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#endregion
#region Static Members
//#ifdef NearEqual
/// <summary>
/// Near equal.
/// </summary>
public static bool NearEqual([NotNull] Vectorf v1, [NotNull] Vectorf v2)
{
if (v1.DimensionCount != v2.DimensionCount) return false;
for (uint i = 0; i < v1.DimensionCount; i++)
{
if (!MathHelper.NearEqual(v1[i], v2[i])) return false;
}
return true;
}
/// <summary>
/// Near equal test.
/// </summary>
public static bool NearEqual([NotNull] Vectorf v1, [NotNull] Vectorf v2, float eps)
{
if (v1.DimensionCount != v2.DimensionCount) return false;
for (uint i = 0; i < v1.DimensionCount; i++)
{
if (!MathHelper.NearEqual(v1[i], v2[i], eps)) return false;
}
return true;
}
//#endif
#endregion
#region Constructors
/// <summary>
/// Constructor with the vector's dimension. All data is left undefined (set to zero).
/// </summary>
/// <param name="n">The dimension of vector.</param>
public Vectorf(uint n)
{
components = new float[n];
}
/// <summary>
/// Initialisation with actual array.
/// </summary>
/// <param name="array">The array of coefficients. The components are not cloned for
/// performance reasons, so it is possible to change components from outside.</param>
public Vectorf([NotNull] params float[] coef)
{
components = coef;
}
#endregion
#region IEquatable<Vectorf> Members
public bool Equals(Vectorf other)
{
return this == other;
}
#endregion
#region ICloneable<Vectorf> Members
public Vectorf Clone()
{
return new Vectorf(components.Clone() as float[]);
}
#endregion
}
#if SHARPMEDIA_TESTSUITE
/// <summary>
/// A vectord test.
/// </summary>
[TestSuite]
internal class Test_Vectorf
{
protected Vectorf v1 = new Vectorf((float)0, (float)1, (float)2);
protected Vectorf v2 = new Vectorf((float)1, (float)2, (float)3);
[CorrectnessTest]
public void Index()
{
Assert.AreEqual(v1[0], (float)0);
Assert.AreEqual(v1[1], (float)1);
Assert.AreEqual(v1[2], (float)2);
}
[CorrectnessTest]
public void Add() { Assert.AreEqual(v1 + v2, new Vectorf(new float[] { (float)1, (float)3, (float)5 })); }
[CorrectnessTest]
public void Sub() { Assert.AreEqual(v1 - v2, new Vectorf(new float[] { (float)-1, (float)-1, (float)-1 })); }
[CorrectnessTest]
public void Dot() { Assert.AreEqual(v1 * v2, (float)8); }
}
#endif
}
|
5b480df033e5121ad64fa1291709f995a9e0967a
|
C#
|
Bubeee/RoadSigns.VBP
|
/SurfaceHandling/Designs/DesignExpression.cs
| 2.828125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SurfaceHandling.Designs
{
class DesignExpression:IDesign
{
public Func<PixelClass, bool> DesignFunc { get; private set; }
public DesignExpression(Func<PixelClass, bool> ex)
{
if (ex == null)
throw new ArgumentNullException("ex");
DesignFunc = ex;
}
public bool Decide(PixelClass p)
{
return DesignFunc != null && DesignFunc(p);
}
}
}
|
0fd535e04ba1c9abf72d340831095612a12056a5
|
C#
|
wj1s/Refactor15
|
/Refactor/test/LifelineFacts.cs
| 2.59375
| 3
|
using System;
using Refactor.Common;
using Refactor.Model;
using Xunit;
namespace Refactor.test
{
public class LifelineFacts
{
private LifelineSite subject;
public void SetUp()
{
subject = new LifelineSite();
}
[Fact]
public void TestZero()
{
SetUp();
subject.AddReading(new Reading(10, new DateTime(1997, 1, 1)));
subject.AddReading(new Reading(10, new DateTime(1997, 2, 1)));
Assert.Equal(new Dollars(0), subject.Charge());
}
[Fact]
public void Test100()
{
SetUp();
subject.AddReading(new Reading(10, new DateTime(1997, 1, 1)));
subject.AddReading(new Reading(110, new DateTime(1997, 2, 1)));
Assert.Equal(new Dollars(4.84), subject.Charge());
}
[Fact]
public void Test99()
{
SetUp();
subject.AddReading(new Reading(100, new DateTime(1997, 1, 1)));
subject.AddReading(new Reading(199, new DateTime(1997, 2, 1)));
Assert.Equal(new Dollars(4.79), subject.Charge());
}
[Fact]
public void Test101()
{
SetUp();
subject.AddReading(new Reading(1000, new DateTime(1997, 1, 1)));
subject.AddReading(new Reading(1101, new DateTime(1997, 2, 1)));
Assert.Equal(new Dollars(4.91), subject.Charge());
}
[Fact]
public void Test199()
{
SetUp();
subject.AddReading(new Reading(10000, new DateTime(1997, 1, 1)));
subject.AddReading(new Reading(10199, new DateTime(1997, 2, 1)));
Assert.Equal(new Dollars(11.61), subject.Charge());
}
[Fact]
public void Test200()
{
SetUp();
subject.AddReading(new Reading(0, new DateTime(1997, 1, 1)));
subject.AddReading(new Reading(200, new DateTime(1997, 2, 1)));
Assert.Equal(new Dollars(11.68), subject.Charge());
}
[Fact]
public void Test201()
{
SetUp();
subject.AddReading(new Reading(50, new DateTime(1997, 1, 1)));
subject.AddReading(new Reading(251, new DateTime(1997, 2, 1)));
Assert.Equal(new Dollars(11.77), subject.Charge());
}
[Fact]
public void TestMax()
{
SetUp();
subject.AddReading(new Reading(0, new DateTime(1997, 1, 1)));
subject.AddReading(new Reading(int.MaxValue, new DateTime(1997, 2, 1)));
Assert.Equal(new Dollars(1.9730005337E8), subject.Charge());
}
[Fact]
public void TesttNoReadings()
{
SetUp();
Assert.Throws<NullReferenceException>(() => subject.Charge());
}
}
}
|
da53dc4d2db2f4ed792ac540dd410cf1ba88091d
|
C#
|
crazyjackel/enjin-csharp-sdk
|
/EnjinCSharpSDK/Graphql/IVariableHolder.cs
| 2.5625
| 3
|
/* Copyright 2021 Enjin Pte. Ltd.
*
* 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.Collections.Generic;
using JetBrains.Annotations;
namespace Enjin.SDK.Graphql
{
/// <summary>
/// Interface for GraphQL requests to set variables within them.
/// </summary>
/// <typeparam name="T">The implementing type of the interface.</typeparam>
[PublicAPI]
public interface IVariableHolder<out T> : IVariableHolder
{
/// <summary>
/// Sets a variable with the specified key and value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>This object for chaining.</returns>
T SetVariable(string key, object? value);
/// <summary>
/// Determines if a variable exists for the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>Whether the variable exists.</returns>
bool IsSet(string key);
}
/// <summary>
/// Interface for holding variables.
/// </summary>
[PublicAPI]
public interface IVariableHolder
{
/// <summary>
/// Gets the variables this object holds.
/// </summary>
/// <returns>The variables.</returns>
Dictionary<string, object> Variables();
}
}
|
4dae852d32c2bcf291ec23b189a0579a9d95f1e5
|
C#
|
JoelCortezOrtega-bot/TecLab---Proyecto
|
/LabTec/LabTec/ModificarClave.cs
| 2.671875
| 3
|
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 LabTec
{
public partial class FrModificarClave : Form
{
int LocalID;
public FrModificarClave(int ID)
{
InitializeComponent();
LocalID = ID;
}
private void btnGuardar_Click(object sender, EventArgs e)
{
try
{
//Declaramos nuestro objeto de la clase Operaciones
Operaciones.Operaciones op = new Operaciones.Operaciones();
//Variables Auxiliares
string ClaveVieja, ClaveNueva, ClaveRepetida;
//Asignacion de Valores
ClaveVieja = txtClaveActual.Text;
ClaveRepetida = txtClaveNRepetir.Text;
ClaveNueva = txtClaveNueva.Text;
//LLamamos al metodo de la clase Operaciones
op.ModificarClave(LocalID, ClaveNueva, ClaveVieja, ClaveRepetida);
}
catch(FormatException)
{
string mensaje = "Por favor, no ingrese los datos correctos.";
MessageBox.Show(mensaje, "Error de formato", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
//Limpiar los cuadros de texto
txtClaveActual.Clear();
txtClaveNRepetir.Clear();
txtClaveNueva.Clear();
}
}
private void btnAtras_Click(object sender, EventArgs e)
{
//Volver al menu principal
this.Close();
}
}
}
|
759bacc9e5b28bc0ba742a72725bbd7ad2d1e8e9
|
C#
|
KaptenJon/ComponentOne-WinForms-Samples
|
/NetFramework/FlexChart/CS/FlexChart101/Samples/Toggle.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using C1.Win.Chart;
using System.Drawing.Drawing2D;
namespace FlexChart101.Samples
{
public partial class Toggle : UserControl
{
public Toggle()
{
InitializeComponent();
InitializeControls();
SetupChart();
}
void SetupChart()
{
flexChart1.BeginUpdate();
flexChart1.Series.Clear();
// Add 3 data series
var s1 = new Series();
s1.Binding = s1.Name = "March";
flexChart1.Series.Add(s1);
var s2 = new Series();
s2.Binding = s2.Name = "April";
flexChart1.Series.Add(s2);
var s3 = new Series();
s3.Binding = s3.Name = "May";
flexChart1.Series.Add(s3);
// Set x-binding and add data to the chart
flexChart1.BindingX = "Fruit";
flexChart1.DataSource = DataCreator.CreateFruit();
flexChart1.LegendToggle = true;
flexChart1.EndUpdate();
}
private void chb_CheckedChanged(object sender, EventArgs e)
{
var chb = (sender as CheckBox);
if (chb == null) return;
var serie = flexChart1.Series.FirstOrDefault(x => x.Name == chb.Text);
if (serie == null) return;
else serie.Visibility = chb.Checked
? C1.Chart.SeriesVisibility.Visible
: C1.Chart.SeriesVisibility.Legend;
}
private void InitializeControls()
{
#region Init controls
//Set localized text
baseSample1.lblTitle.Text = Localizer.GetItem("toggle", "title");
baseSample1.pDescription.Height = 200;
baseSample1.tbDescription.Rtf = Localizer.GetItem("toggle", "description").MakeRtf();
baseSample1.tbCode.Text = @"//FlexChart LegendToggle property
flexChart1.LegendToggle = true;
//OR you can change visibility manually
serie.Visibility = C1.Chart.SeriesVisibility.Legend;";
flexChart1 = baseSample1.flexChart1;
chbMarch = new CheckBox()
{
Text = "March",
Location = new Point(40, 5),
FlatStyle = FlatStyle.Flat,
Checked = true
};
chbMarch.CheckedChanged += chb_CheckedChanged;
chbApril = new CheckBox()
{
Text = "April",
Location = new Point(chbMarch.Right + 10, 5),
FlatStyle = FlatStyle.Flat,
Checked = true
};
chbApril.CheckedChanged += chb_CheckedChanged;
chbMay = new CheckBox()
{
Text = "May",
Location = new Point(chbApril.Right, 5),
FlatStyle = FlatStyle.Flat,
Checked = true
};
chbMay.CheckedChanged += chb_CheckedChanged;
baseSample1.pControls.Controls.Add(chbMarch);
baseSample1.pControls.Controls.Add(chbApril);
baseSample1.pControls.Controls.Add(chbMay);
#endregion
}
}
}
|
9d465eca4f6f50fb37bb2b45efe0e7d375f87336
|
C#
|
Aptiv-WLL/search-trie
|
/SearchTrieUnitTests/TernarySearchTrieTests/TernaryTrie_RemoveTests.cs
| 3.0625
| 3
|
using System;
using System.Collections.Generic;
using Global.RandomLibraries;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Global.SearchTrie.Tests
{
[TestClass]
public class TrieTests_Remove
{
#region --- Parameters ---
private TernarySearchTrie<char, int> Trie = new TernarySearchTrie<char, int>();
private RandomString rs = new RandomString();
private Random r = new Random();
private int size = Properties.Settings.Default.TestSize;
public TernarySearchTrie<char, int> Fill(int count = -1)
{
if (count == -1) count = size;
TernarySearchTrie<char, int> new_trie = new TernarySearchTrie<char, int>();
for (int i = 0; i < count; i++)
{
new_trie.Add(rs.makeRandString(), i);
}
return new_trie;
}
#endregion
[TestMethod()]
[TestCategory("Removing")]
[TestCategory("TernaryTrie")]
[Description("Verify removal of one item.")]
public void RemoveTest0()
{
Trie = new TernarySearchTrie<char, int>
{
{ "hello", 0 }
};
bool res = Trie.Remove("hello");
Assert.IsTrue(res);
Assert.AreEqual(Trie.Count, 0);
}
[TestMethod()]
[TestCategory("Removing")]
[TestCategory("TernaryTrie")]
[Description("Add and remove on object.")]
public void RemoveTest1()
{
string key = "Hello, world!";
var trie = new TernarySearchTrie<char, int>
{
{ key, 0 }
};
trie.Remove(key);
Assert.AreEqual(trie.Count, 0);
Assert.AreEqual(trie.Search(key).Count, 0);
}
[TestMethod()]
[TestCategory("Removing")]
[TestCategory("TernaryTrie")]
[Description("Verify <size> removals.")]
public void RemoveTest2()
{
Trie = new TernarySearchTrie<char, int>();
var Dict = new Dictionary<IEnumerable<char>, IList<int>>();
int pip = size;
while (pip-- > 0)
{
string key = rs.makeRandString();
IList<int> value = new List<int>{r.Next()};
if (!Dict.ContainsKey(key))
{
Trie.Add(key, value);
Dict.Add(key, value);
}
}
pip = size;
var enu = Dict.GetEnumerator();
while (enu.MoveNext())
{
var pair = enu.Current;
int size_bef = Trie.Count;
Trie.Remove(pair);
Assert.AreEqual(size_bef - 1, Trie.Count);
}
}
[TestMethod()]
[TestCategory("Removing")]
[TestCategory("TernaryTrie")]
[Description("Check ArgumentNullException.")]
public void RemoveTest3()
{
bool thrown = false;
try
{
Trie.Remove(null);
}
catch (ArgumentNullException)
{
thrown = true;
}
Assert.IsTrue(thrown);
}
[TestMethod()]
[TestCategory("Removing")]
[TestCategory("TernaryTrie")]
[Description("Remove 100,000")]
public void RemoveTest4()
{
int count = 10000;
Dictionary<int, string> strs = new Dictionary<int, string>();
for (int i = 0; i < count; i++)
{
string s = rs.makeRandString();
while (strs.ContainsValue(s)) s = rs.makeRandString();
strs.Add(i, s);
}
var trie = new TernarySearchTrie<char, int>();
for (int i = 0; i < count; i++) trie.Add(strs[i], i);
for (int i = 0; i < count; i++)
{
trie.Remove(strs[i]);
Assert.AreEqual(trie.Count, count - 1 - i);
Assert.AreEqual(trie.Search(strs[i]).Count, 0);
}
}
[TestMethod()]
[TestCategory("Removing")]
[TestCategory("TernaryTrie")]
[Description("Verify removal of single elements rather than list of elements in value")]
public void RemoveTest5()
{
Trie = new TernarySearchTrie<char, int>
{
// Part 1
{ "hello", 0 },
{ "hello", 1 }
};
bool res = Trie.Remove("hello", 1);
Assert.IsTrue(res);
Assert.AreEqual(Trie.Count, 1);
KeyValuePair<IEnumerable<char>, int> keyValuePair = new KeyValuePair<IEnumerable<char>, int>("hello", 0);
Assert.IsTrue(Trie.Contains(keyValuePair));
res = Trie.Remove("hello", 2);
Assert.IsFalse(res);
res = Trie.Remove("hello", 0);
Assert.IsTrue(res);
Assert.AreEqual(Trie.Count, 0);
// Part 2
Trie.Add("hello", 0);
Trie.Add("world", 0);
res = Trie.Remove("world", 0);
Assert.IsTrue(res);
Assert.AreEqual(Trie.Count, 1);
res = Trie.Remove("hello", 0);
Assert.IsTrue(res);
Assert.AreEqual(Trie.Count, 0);
}
}
}
|
35069e9342085be883ac57d696e761e73019f220
|
C#
|
SimeonStoykov/SoftUni
|
/C# basics/BGCoder/Telerik 5 December 2013 Evening/Eggcelent/Eggcelent.cs
| 3.328125
| 3
|
using System;
class Eggcelent
{
static void Main()
{
int n = int.Parse(Console.ReadLine());
int firstStars = n - 1;
int innerDots = n + 1;
int outerDots = n + 1;
int width = 3 * n + 1;
int specialFirstRow = 3;
int specialSecondRow = 4;
int downOuterDots = 0;
int downInnerDots = 0;
Console.WriteLine(new String('.', outerDots) + new String('*', firstStars) + new String('.', outerDots));
for (int i = 1; i <= (n-2)/2; i++)
{
outerDots -=2;
Console.WriteLine(new String('.', outerDots) + '*' + new String('.', innerDots) + '*' + new String('.', outerDots));
innerDots += 4;
if (i == (n-2)/2)
{
downOuterDots = outerDots;
downInnerDots = innerDots - 4;
}
}
for (int row = 1; row <= (n-2)/2; row++)
{
Console.WriteLine("." + "*" + new String('.', innerDots) + "*" + ".");
}
for (int row = 1; row <= 2; row++)
{
for (int col = 1; col <= width; col++)
{
if (row == 1)
{
if (col == 1)
{
Console.Write(".");
}
else if (col == 2)
{
Console.Write("*");
}
else if (col == width)
{
Console.Write(".");
}
else if (col == width - 1)
{
Console.Write("*");
}
else if (col == specialFirstRow)
{
Console.Write("@");
specialFirstRow += 2;
}
else
{
Console.Write(".");
}
}
else
{
if (col == 1)
{
Console.Write(".");
}
else if (col == 2)
{
Console.Write("*");
}
else if (col == width)
{
Console.Write(".");
}
else if (col == width - 1)
{
Console.Write("*");
}
else if (col == specialSecondRow)
{
Console.Write("@");
specialSecondRow += 2;
}
else
{
Console.Write(".");
}
}
}
Console.WriteLine();
}
for (int row = 1; row <= (n - 2) / 2; row++)
{
Console.WriteLine("." + "*" + new String('.', innerDots) + "*" + ".");
}
for (int i = 1; i <= (n - 2) / 2; i++)
{
Console.WriteLine(new String('.', downOuterDots) + "*" + new String('.', downInnerDots) + "*" + new String('.', downOuterDots));
downOuterDots += 2;
downInnerDots -= 4;
}
Console.WriteLine(new String('.', n + 1) + new String('*', n - 1) + new String('.', n + 1));
}
}
|
14a04d7f7dd3c2647e3e5b2adb95294aeff5ece9
|
C#
|
MattMarkgraaff/Entelect
|
/src/Entelect/Types/TypeExtensions.cs
| 3.15625
| 3
|
using System;
using Entelect.Extensions;
namespace Entelect.Types
{
/// <summary>
/// Extension methods for working with CLR types
/// </summary>
public class TypeExtensions
{
/// <summary>
/// Takes in a type name string and tries to get the built in system type from that
/// Adapted from http://stackoverflow.com/questions/721870/c-sharp-how-can-i-get-type-from-a-string-representation
/// </summary>
/// <param name="typeName"></param>
/// <returns>Null if type is not recognized</returns>
/// <exception cref="ArgumentNullException"></exception>
public static Type GetTypeFromTypeName(string typeName)
{
if (typeName == null)
{
throw new ArgumentNullException("typeName");
}
var isArray = typeName.IndexOf("[]", StringComparison.OrdinalIgnoreCase) != -1;
var isNullable = typeName.IndexOf("?", StringComparison.OrdinalIgnoreCase) != -1;
var formattedTypeName = FormatTypeName(typeName, isArray, isNullable);
var systemTypeName = ExtractSystemTypeNames(formattedTypeName);
var extractedTypeName = ExtractType(systemTypeName, isArray, isNullable, formattedTypeName);
return Type.GetType(extractedTypeName);
}
private static string ExtractType(string systemTypeName, bool isArray, bool isNullable, string formattedTypeName)
{
var extractedTypeName = systemTypeName;
if (extractedTypeName != null)
{
if(isArray)
{
extractedTypeName = extractedTypeName + "[]";
}
if(isNullable)
{
extractedTypeName = String.Concat("System.Nullable`1[", extractedTypeName, "]");
}
}
else
{
extractedTypeName = formattedTypeName;
}
return extractedTypeName;
}
private static string FormatTypeName(string typeName, bool isArray, bool isNullable)
{
var name = typeName;
if(isArray)
{
name = name.Remove(name.IndexOf("[]", StringComparison.OrdinalIgnoreCase), 2);
}
if(isNullable)
{
name = name.Remove(name.IndexOf("?", StringComparison.OrdinalIgnoreCase), 1);
}
name = name.ToLower();
name = name.ReplaceIgnoreCase("system.", "");
return name;
}
private static string ExtractSystemTypeNames(string typeName)
{
switch(typeName)
{
case "bool":
case "boolean":
return "System.Boolean";
case "byte":
return "System.Byte";
case "char":
return "System.Char";
case "datetime":
return "System.DateTime";
case "datetimeoffset":
return "System.DateTimeOffset";
case "decimal":
return "System.Decimal";
case "double":
return "System.Double";
case "float":
return "System.Single";
case "int16":
case "short":
return "System.Int16";
case "int32":
case "int":
return "System.Int32";
case "int64":
case "long":
return "System.Int64";
case "object":
return "System.Object";
case "sbyte":
return "System.SByte";
case "string":
return "System.String";
case "timespan":
return "System.TimeSpan";
case "uint16":
case "ushort":
return "System.UInt16";
case "uint32":
case "uint":
return "System.UInt32";
case "uint64":
case "ulong":
return "System.UInt64";
default:
return null;
}
}
}
}
|
59e6e752f2a7f956a272e418a1dce87f4a5275e7
|
C#
|
joebir/csharplibrary
|
/0.06_ForLoops/Program.cs
| 3.515625
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _0._06_ForLoops
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i <= 10; i += 2)
{
Console.WriteLine(i);
}
for (int i = 10; i >= 0; i--)
{
switch (i)
{
case 0:
Console.WriteLine("Houston, we have liftoff.");
break;
default:
Console.WriteLine(i);
break;
}
}
Console.ReadLine();
for (int i = 0; i <= 5; i++)
{
Console.WriteLine(i);
}
for (int i = 0; i <= 100; i += 5)
{
Console.WriteLine(i);
}
for (int i = 0; i <= 100; i++)
{
if (i % 3 == 0 && i % 5 == 0)
{
Console.WriteLine("FizzBuzz");
}
else if (i % 3 == 0)
{
Console.WriteLine("Fizz");
}
else if (i % 5 == 0)
{
Console.WriteLine("Buzz");
}
else
{
Console.WriteLine(i);
}
}
int num1 = 0;
int num2 = 1;
int total = 0;
for (int i = 0; i <= 4000000;)
{
i = num1 + num2;
if (i % 2 == 0)
{
total += i;
}
num1 = num2;
num2 = i;
}
Console.WriteLine(total);
total = 0;
for (int i = 0; i < 1000; i++)
{
if (i % 3 == 0 || i % 5 == 0)
{
total += i;
}
}
Console.WriteLine(total);
}
}
}
|
cdf153d86ad722c32a6a7be8395628df8a113fb7
|
C#
|
Dred95/Calculatorofdeath
|
/CalculatorOfDeath/CalculatorOfDeath/Sort/BubbleSort.cs
| 3.375
| 3
|
namespace CalculatorOfDeath.Sort
{
public class BubbleSort : ISort
{
public int[] Sort(int[] mass)
{
int temp;
for (int i = 0; i < mass.Length - 1; i++)
{
for (int j = 0; j < mass.Length - i - 1; j++)
{
if (mass[j] > mass[j + 1])
{
temp = mass[j];
mass[j] = mass[j + 1];
mass[j + 1] = temp;
}
}
}
return mass;
}
}
}
|
145d7f50db84453e4ad627e100ad31ee0b317e2c
|
C#
|
5l1v3r1/CARPARK
|
/CARPARK.Service/Interfaces/ISubscriberService.cs
| 2.640625
| 3
|
using CARPARK.DTO.EntitisDTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CARPARK.Service.Interfaces
{
public interface ISubscriberService
{
/// <summary>
/// Görderilen id ile Abone veri seti döndürülür.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
AboneDTO Subscriber(int id);
/// <summary>
/// Butun Aboneleri getirir.
/// </summary>
/// <returns></returns>
List<AboneDTO> GetAllSubscriber();
/// <summary>
/// Abone ekleme işlemi yapar.
/// </summary>
/// <param name="abone"></param>
/// <param name="uyeID"></param>
/// <param name="aracID"></param>
void Insert(AboneDTO abone,int uyeID, int aracID);
/// <summary>
/// Abone bilgilerini günceller.
/// </summary>
/// <param name="abone"></param>
void Update(AboneDTO abone);
/// <summary>
/// Abone silme durum false yapar.
/// </summary>
/// <param name="abnID"></param>
void Delete(int abnID);
/// <summary>
/// Tum abone ödemelerini liste olarak döndürür.
/// </summary>
/// <returns></returns>
List<AboneOdemeDTO> GetAllSubscriberPayment(int aboneID);
/// <summary>
/// Gelen ID'ye göre ilgili ödeme kaydını döndürür.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
AboneOdemeDTO SubscriberPayment(int id);
/// <summary>
/// Abone ödeme kayıtları ekler.
/// </summary>
/// <param name="odeme"></param>
void SubscriberPaymentInsert(AboneOdemeDTO odeme);
/// <summary>
/// Arac Id'ye göre abone kontrol işlemi yapılıyor. Arac'a ait abone varsa aboneyi yoksa null geri dödürüyor.
/// </summary>
/// <param name="aracId"></param>
/// <returns></returns>
AboneDTO GetSubscriber(int aracId);
/// <summary>
/// Abone Giriş Çıkış işlemini kayıt eder.
/// </summary>
/// <param name="abone"></param>
/// <returns></returns>
bool SubscriberInputOutput(AboneGirisCikisDTO abone);
List<AboneGirisCikisDTO> GetSubscriberAllInputOutput(int abooneId);
}
}
|
8cacb8b7aa40d308e36e3c71e909c3b7b9fa1514
|
C#
|
KorokinYura/TimeLine
|
/Assets/Scripts/HandInstance.cs
| 2.640625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HandInstance : MonoBehaviour
{
public void PlaceCardInHand(GameObject card)
{
card.transform.SetParent(transform);
UpdateCardsLocation();
}
public void UpdateCardsLocation()
{
var cards = LevelController.CardsInHand;
if (cards.Count == 0)
{
return;
}
var cardWidthDelta = Screen.width / cards.Count;
for (int i = 0; i < cards.Count; i++)
{
cards[i].transform.localPosition = new Vector2((cardWidthDelta * i) - (Screen.width / 2) + (cardWidthDelta / 2), -(Screen.height / 2.5f));
}
}
}
|
63274256ec4abd5e41afd03fd796ced33b164356
|
C#
|
jangocheng/BitEx
|
/BitEx.Dapper/Core/KeyAttribute.cs
| 2.984375
| 3
|
using System;
namespace BitEx.Dapper.Core
{
[AttributeUsage(AttributeTargets.Property)]
public class KeyAttribute : Attribute
{
/// <summary>
/// The column name.
/// </summary>
/// <returns>
/// The column name.
/// </returns>
public string Name { get; private set; }
/// <summary>
/// Constructs a new instance of the <seealso cref="KeyAttribute" />.
/// </summary>
/// <param name="primaryKey">The name of the primary key column.</param>
public KeyAttribute(string columnName=null)
{
Name = columnName;
}
}
}
|
b3aecdbacb4ebe30ca36f41ae9373f0af336d0dc
|
C#
|
erinaldo/siscobras
|
/mdlPDF/Xml2PDF/Source/Altsoft/PDFOX/Function.cs
| 2.5625
| 3
|
namespace Altsoft.PDFO
{
using Altsoft.Common;
using System;
using System.Collections;
using System.Reflection;
public abstract class Function : Resource
{
// Methods
static Function()
{
Function.DictKeyName = "Function";
}
internal Function(PDFDirect d) : base(d)
{
this.mDomain = null;
this.mRange = null;
}
internal static Resource Factory(PDFDirect d)
{
if (d.PDFType != PDFObjectType.tPDFDict)
{
goto Label_0061;
}
PDFDict dict1 = ((PDFDict) d);
int num1 = ((PDFInteger) dict1["FunctionType"]).Int32Value;
int num3 = num1;
switch (num3)
{
case 2:
{
goto Label_003C;
}
case 3:
{
goto Label_0043;
}
}
goto Label_004A;
Label_003C:
return new FunctionType2(d);
Label_0043:
return new FunctionType3(d);
Label_004A:
throw new PDFSyntaxException(d, string.Format("Unknown function type: {0}", num1));
Label_0061:
if (d.PDFType != PDFObjectType.tPDFStream)
{
goto Label_00C0;
}
PDFStream stream1 = ((PDFStream) d);
int num2 = ((PDFInteger) stream1.Dict["FunctionType"]).Int32Value;
num3 = num2;
if (num3 != 0)
{
if (num3 == 4)
{
goto Label_00A2;
}
goto Label_00A9;
}
return new FunctionType0(d);
Label_00A2:
return new FunctionType4(d);
Label_00A9:
throw new PDFSyntaxException(d, string.Format("Unknown function type: {0}", num2));
Label_00C0:
throw new PDFSyntaxException(d, "Invalid Function");
}
internal static double InterpolateLin1d(double x, double x0, double x1, double y0, double y1)
{
return ((((x - x0) * (y1 - y0)) / (x1 - x0)) + y0);
}
// Properties
public virtual DoubleMinMaxArray Domain
{
get
{
double[] numArray1;
if (this.mDomain == null)
{
numArray1 = new double[1];
this.mDomain = new DoubleMinMaxArray(new PDFDoubleArray(this.Dict, "Domain", false, numArray1));
}
return this.mDomain;
}
set
{
this.Domain.Set(value);
}
}
public abstract double[] this[double[] args] { get; }
public virtual DoubleMinMaxArray Range
{
get
{
PDFArray array1;
if (this.mRange == null)
{
array1 = ((PDFArray) this.Dict["Range"]);
if (array1 != null)
{
this.mRange = new DoubleMinMaxArray(new PDFDoubleArray(array1, array1.Count));
}
}
return this.mRange;
}
set
{
double[] numArray1;
if (this.Range == null)
{
numArray1 = new double[value.Count];
value.CopyTo(numArray1, 0);
this.mRange = new DoubleMinMaxArray(new PDFDoubleArray(this.Dict, "Range", false, numArray1));
return;
}
this.Range.Set(value);
}
}
public abstract int SubType { get; }
// Fields
internal static readonly string DictKeyName;
private DoubleMinMaxArray mDomain;
private DoubleMinMaxArray mRange;
// Nested Types
public class NamedFunctions
{
// Methods
static NamedFunctions()
{
NamedFunctions._Instance = null;
}
private NamedFunctions()
{
this.funcs = new Hashtable();
this.funcs["Identity"] = "{}";
this.funcs["SimpleDot"] = "{ dup mul exch dup mul add 1 exch sub }";
this.funcs["InvertedSimpleDot"] = "{ dup mul exch dup mul add 1 sub }";
this.funcs["DoubleDot"] = "{ 360 mul sin 2 div exch 360 mul sin 2 div add }";
this.funcs["InvertedDoubleDot"] = "{ 360 mul sin 2 div exch 360 mul sin 2 div add neg }";
this.funcs["CosineDot"] = "{ 180 mul cos exch 180 mul cos add 2 div }";
this.funcs["Double"] = "{ 360 mul sin 2 div exch 2 div 360 mul sin 2 div add }";
this.funcs["InvertedDouble"] = "{ 360 mul sin 2 div exch 2 div 360 mul sin 2 div add neg }";
this.funcs["Line"] = "{ exch pop abs neg }";
this.funcs["LineX"] = "{ pop }";
this.funcs["LineY"] = "{ exch pop }";
this.funcs["Round"] = "{ abs exch abs\t2 copy add 1 le { dup mul exch dup mul add 1 exch sub }\t{ 1 sub dup mul exch 1 sub dup mul add 1 sub } ifelse }";
this.funcs["Ellipse"] = "{ abs exch abs 2 copy 3 mul exch 4 mul add 3 sub dup 0 lt { pop dup mul exch 0.75 div dup mul add 4 div 1 exch sub } { dup 1 gt { pop 1 exch sub dup mul exch 1 exch sub 0.75 div dup mul add 4 div 1 sub } { 0.5 exch sub exch pop exch pop } ifelse } ifelse }";
this.funcs["EllipseA"] = "{ dup mul 0.9 mul exch dup mul add 1 exch sub }";
this.funcs["InvertedEllipseA"] = "{ dup mul 0.9 mul exch dup mul add 1 sub }";
this.funcs["EllipseB"] = "{ dup 5 mul 8 div mul exch dup mul exch add sqrt 1 exch sub }";
this.funcs["EllipseC"] = "{ dup mul exch dup mul 0.9 mul add 1 exch sub }";
this.funcs["InvertedEllipseC"] = "{ dup mul exch dup mul 0.9 mul add 1 sub }";
this.funcs["Square"] = "{ abs exch abs 2 copy lt\t{ exch } if pop neg }";
this.funcs["Cross"] = "{ abs exch abs 2 copy gt { exch } if pop neg }";
this.funcs["Rhombold"] = "{ abs exch abs 0.9 mul add 2 div }";
this.funcs["Diamond"] = "{ abs exch abs 2 copy add 0.75 le { dup mul exch dup mul add 1 exch sub } {2 copy add 1.23 le { 0.85 mul add 1 exch sub } { 1 sub dup mul exch 1 sub dup mul add 1 sub }\tifelse } ifelse }";
}
public static Function Create(string name)
{
double[] numArray1;
if (name == "Identity")
{
numArray1 = new double[2];
numArray1[1] = 1f;
numArray1 = new double[2];
numArray1[1] = 1f;
return FunctionType4.Create(numArray1, numArray1, ((string) NamedFunctions.Instance.funcs[name]));
}
numArray1 = new double[4];
numArray1[1] = 1f;
numArray1[3] = 1f;
numArray1 = new double[2];
numArray1[1] = 1f;
return FunctionType4.Create(numArray1, numArray1, ((string) NamedFunctions.Instance.funcs[name]));
}
// Properties
private static NamedFunctions Instance
{
get
{
if (NamedFunctions._Instance == null)
{
NamedFunctions._Instance = new NamedFunctions();
}
return NamedFunctions._Instance;
}
}
public static ICollection Names
{
get
{
return NamedFunctions.Instance.funcs.Keys;
}
}
// Fields
private static NamedFunctions _Instance;
private Hashtable funcs;
}
}
}
|
fc5fd3bf717434f42b55794abf8c8a79f9703308
|
C#
|
juanDeVicente/SummerSchool
|
/Variables/Program.cs
| 3.90625
| 4
|
using System;
namespace Tipos
{
class Program
{
static void Main(string[] args)
{
int a = 3; //Este tipo de variable es de tipo entero, sin decimales
float b = 3.14f; //Este tipo de variable es decimal con precisión de coma flotante de 32 bits, con decimales y más pequeño que el double
double c = 12348972364.2378d; //Este tipo de variable es decimal con precisión de coma flotante de 64 bits, con decimales.
char letra = 'a'; //Este tipo de variable es un caracter de la tabla ASCII.
string texto = "Esto es un texto"; //Este tipo de variable es un texto.
Console.WriteLine(a + " es de tipo entero!");
Console.WriteLine(b + " es de tipo float!");
Console.WriteLine(c + " es de tipo double!");
Console.WriteLine(letra + " es de tipo char!");
Console.WriteLine(texto + "es de tipo string!");
Console.ReadKey();
}
}
}
|
df3edd829a09cd41550e75479423ab84dd1c46a5
|
C#
|
AAmanzi/Internship-3-Military
|
/military/Program.cs
| 3.390625
| 3
|
using System;
using military.Models;
using military.Enums;
using military.Interfaces;
namespace military
{
class Program
{
static void Main(string[] args)
{
var myTank = new Tank(68000, 70);
var myWarship = new Warship(35000, 80);
var myAmphibian = new Amphibian(23000, 40);
Console.WriteLine("Greetings!\nI see you're in need of " +
"troop transport!\n");
do
{
Console.WriteLine("Please enter the number of soldiers you need " +
"to transport:");
var peopleToTransport = 0;
while (!int.TryParse(Console.ReadLine(), out peopleToTransport))
Console.WriteLine("That is not a valid input, please try again:");
Console.WriteLine("Enter the distance the TANK " +
"needs to overcome in kilometers:");
var distanceTank = 0;
while (!int.TryParse(Console.ReadLine(), out distanceTank))
Console.WriteLine("That is not a valid input, please try again:");
Console.WriteLine("Enter the distance the WARSHIP " +
"needs to overcome in kilometers:");
var distanceWarship = 0;
while (!int.TryParse(Console.ReadLine(), out distanceWarship))
Console.WriteLine("That is not a valid input, please try again:");
var distanceAmphibianByLand = 0;
var distanceAmphibianBySea = 0;
while (true)
{
Console.WriteLine("Enter the distance the AMPHIBIAN " +
"needs to overcome by SEA in kilometers:");
while (!int.TryParse(Console.ReadLine(), out distanceAmphibianBySea))
Console.WriteLine("That is not a valid input, please try again:");
Console.WriteLine("Enter the distance the AMPHIBIAN " +
"needs to overcome by LAND in kilometers:");
while (!int.TryParse(Console.ReadLine(), out distanceAmphibianByLand))
Console.WriteLine("That is not a valid input, please try again:");
if (distanceAmphibianBySea + distanceAmphibianByLand > distanceTank ||
distanceAmphibianBySea + distanceAmphibianByLand > distanceWarship)
{
Console.WriteLine("\n\nThe distance the amphibian has to travel MUST be " +
"shorter than the ones the tank and warship have to cross!\n\n");
}
else
break;
}
var totalDistanceTank = myTank.Move(distanceTank);
var totalDistanceWarship = myWarship.Swim(distanceWarship);
var totalDistanceAmphibian = myAmphibian.Move(distanceAmphibianByLand) +
myAmphibian.Swim(distanceAmphibianBySea);
var totalFuelConsumptionTank = myTank.FuelConsumptionTotal
(totalDistanceTank, peopleToTransport);
var totalFuelConsumptionWarship = myWarship.FuelConsumptionTotal
(totalDistanceWarship, peopleToTransport);
var totalFuelConsumptionAmphibian = myWarship.FuelConsumptionTotal
(totalDistanceAmphibian, peopleToTransport);
var bestTransport = Utility.LeastFuelSpent(totalFuelConsumptionTank,
totalFuelConsumptionWarship, totalFuelConsumptionAmphibian);
Console.WriteLine($"\nThe best option for transport is: {bestTransport}");
switch (bestTransport)
{
case ("Tank"):
Console.WriteLine(myTank.Print(totalDistanceTank, peopleToTransport));
break;
case ("Warship"):
Console.WriteLine(myWarship.Print(totalDistanceWarship, peopleToTransport));
break;
case ("Amphibian"):
Console.WriteLine(myAmphibian.Print(totalDistanceAmphibian, peopleToTransport));
break;
}
Console.WriteLine("\nWould you like to make another shipment?");
Console.WriteLine(" ___________________________");
Console.WriteLine("| |");
Console.WriteLine("|Press Y for Yes |");
Console.WriteLine("|Press anything else for No |");
Console.WriteLine("|___________________________|");
}
while (Console.ReadKey().Key == ConsoleKey.Y);
}
}
}
|
1fe03d4c4eda5459f464d716f1f588d8afa8afeb
|
C#
|
wndtanaka/DIP_SQL
|
/Assets/Scripts/Timer.cs
| 2.59375
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
// countdown timer fore resending another email
public class Timer : MonoBehaviour
{
#region MyRegion
public static float resendTimer = 60;
public Button resendButton;
public Text timeText;
#endregion
void Update()
{
// set timeText text accordingly
timeText.text = "Please wait " + resendTimer.ToString("F0") + " second(s) before sending another code";
// if resendTimer is zero or lower then, resendButton will be enabled to used.
if (resendTimer <= 0)
{
// set resendButton interactable
resendButton.interactable = true;
// disable resendButton EventTrigger component
resendButton.GetComponent<EventTrigger>().enabled = true;
// disable timeText
timeText.enabled = false;
// return
return;
}
// if resendTimer is zero or lower then, resendButton will be unabled to used.
if (resendTimer > 0)
{
// resendButton not interactable
resendButton.interactable = false;
// if resendButton.interactable is false
if (resendButton.interactable == false)
{
// disable resendButton EventTrigger component
resendButton.GetComponent<EventTrigger>().enabled = false;
}
// enabled timeText
timeText.enabled = true;
}
// counting down the resendTimer
resendTimer -= Time.deltaTime;
}
}
|
fb4d1ce24f69f6e287dfeb2a98dd88c866653ff9
|
C#
|
JasFreaq/RPG-Project
|
/Assets/Scripts/Inventories/RandomDropper.cs
| 2.640625
| 3
|
using System.Collections;
using System.Collections.Generic;
using GameDevTV.Inventories;
using UnityEngine;
using UnityEngine.AI;
namespace RPG.Inventory
{
public class RandomDropper : ItemDropper
{
//Config Data
[Tooltip("How far the pickups are scattered from the dropper.")]
[SerializeField] [Range(1,5)] float _scatterDistance = 1;
//Constants
const int _Attempts = 25;
protected override Vector3 GetDropLocation()
{
for (int i = 0; i < _Attempts; i++)
{
Vector3 randomPoint = transform.position + Random.insideUnitSphere * _scatterDistance;
NavMeshHit hit;
if (NavMesh.SamplePosition(randomPoint, out hit, 0.1f, NavMesh.AllAreas))
{
return hit.position;
}
}
Debug.LogWarning(this.name + " is probably not on a NavMesh");
return transform.position;
}
}
}
|
d5804f86e38a33d8798fb2d4b0fe55fe1b84c553
|
C#
|
Zamazi/FFTRPG
|
/FF TRPG Database Management Service/FF TRPG Database Management Service/DatabaseManagementService.cs
| 3.078125
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using FF_TRPG_ClassLibrary;
namespace FF_TRPG_Database_Management_Service
{
/// <summary>
/// Basic database class for TRPG
/// </summary>
public class TRPG_Database
{
private string filepath; //bath to database file
private int magiccategorystartindex;
private int magiccategorynextindex;
private FileStream filestream;
public void OpenConnection()
{
filestream = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
/*
* opens connection to a database.
*
* If _filepath is a database file, then do not create a new database.
*
* Else, create database tables.
* For now, we will assume that only magic is contained in the database.
* Items in database are bracketed by <trpg_item> </trpg_item>
* database key is contained immedately after <trpg_key=#####>
*
* key numbers are seperated by database categories, ie magic, skills, monsters, ect.
*
* index in the database refers to the number at which the
*/
}
public void CreateNewDatabase(string DatabaseName)
{
using (StreamWriter _streamwriter = new StreamWriter("..\\..\\TestData\\" + DatabaseName + ".TDB"))
{
filepath = ((FileStream)(_streamwriter.BaseStream)).Name;
}
Magic test = new Magic();
WriteMagicToDabase(test);
}
public void WriteMagicToDabase(Magic MagicToWrite)
{
using (StreamWriter _streamwriter = new StreamWriter(filepath))
{
_streamwriter.WriteLine(MagicToWrite.ReturnTextOutput());
}
}
public void OpenConnection(string FilepathIn)
{
filepath = FilepathIn;
OpenConnection();
}
}
}
|
733b382aef95d353ac2bbcfed71194e6c853f08d
|
C#
|
Rene-Sackers/MakeTopmost
|
/src/MakeTopmost/Services/Application.cs
| 3.109375
| 3
|
using System;
using System.Linq;
using MakeTopmost.Extensions;
using MakeTopmost.Models;
namespace MakeTopmost.Services
{
public class Application
{
public void Process(Options options)
{
if (options.WindowHandle.HasValue)
{
ToggleWindowTopmost(options.WindowHandle.Value);
return;
}
QueryForTargetWindow();
}
private static void QueryForTargetWindow()
{
Console.WriteLine("Choose a window:");
var windows = Native.GetOpenedWindows()
.Where(w => !string.IsNullOrWhiteSpace(w.Title))
.OrderBy(w => w.Title)
.ToArray();
for (var i = 0; i < windows.Length; i++)
{
var windowInfo = windows[i];
var processName = (windowInfo.Process.ProcessName + ".exe").TakeMaxLength(13);
var windowTitle = windowInfo.Title.TakeMaxLength(50);
Console.WriteLine($"[{i}]\t- {processName}\t\t-\t{windowTitle}");
}
Console.Write("ID: ");
int chosenHandleId;
while (!int.TryParse(Console.ReadLine(), out chosenHandleId) || chosenHandleId < 0 || chosenHandleId >= windows.Length)
continue;
var chosenWindowHandle = windows[chosenHandleId].Handle;
ToggleWindowTopmost(chosenWindowHandle);
}
private static void ToggleWindowTopmost(IntPtr chosenWindowHandle)
{
Native.ToggleWindowTopmost(chosenWindowHandle, !Native.IsWindowTopmost(chosenWindowHandle));
}
}
}
|
50fa552bfb26c6b060fe15946f2e9432fdf2d7d5
|
C#
|
hahaking119/coaltrans
|
/COMM/Util/DataUtility.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using CoalTrans.Model;
using System.Collections;
using System.Reflection;
using System.Data.SqlClient;
namespace CoalTrans.Util
{
public class DataUtility
{
/// <summary>
/// תΪresultobject
/// </summary>
/// <param name="dtSource">Դ</param>
/// <param name="filter">datatableɸѡ</param>
/// <param name="sorter">datatable</param>
/// <param name="pageIndex">ҳʼ</param>
/// <param name="pageSize">ÿҳ¼0Ϊҳ</param>
/// <returns>ResultObject</returns>
public static ResultObject ConvertToResultObject(DataTable dtSource,string filter,string sorter,int pageIndex,int pageSize)
{
ResultObject RO = new ResultObject();
if (dtSource == null || dtSource.Rows.Count == 0)
{
RO["records"] = 0;
return null;
}
DataRow[] row = dtSource.Select(filter, sorter);
int recordCount = row.Length;
int start = pageIndex * pageSize;
ArrayList list = new ArrayList();
int endIndex = start + pageSize;
//ҳ״̬endindexΪ¼
if (pageSize == 0)
{
endIndex = recordCount;
}
if (endIndex > recordCount)
endIndex = recordCount;
for (int i = start; i < endIndex; i++)
{
IDictionary dict = new SortedList();
foreach(DataColumn column in dtSource.Columns)
{
dict[column.ColumnName] = row[i][column.ColumnName];
}
list.Add(dict);
}
RO["records"] = recordCount;
RO.Rows = list;
return RO;
}
public static ResultObject ConvertToResultObject(DataTable dtSource, int pageIndex, int pageSize)
{
return ConvertToResultObject(dtSource, string.Empty, string.Empty, pageIndex, pageSize);
}
public static ResultObject ConvertToResultObject(DataTable dtSource)
{
return ConvertToResultObject(dtSource, string.Empty, string.Empty, 0, 0);
}
public static ResultObject ConvertToResultObject(DataTable dtSource, string filter, string sorter)
{
return ConvertToResultObject(dtSource, filter, sorter, 0, 0);
}
/// <summary>
/// תΪresultobject
/// </summary>
/// <param name="List">Դ</param>
/// <returns>ResultObject</returns>
public static ResultObject ConvertToResultObject(IList listobj)
{
ResultObject RO = new ResultObject();
if (listobj == null || listobj.Count == 0)
{
RO["records"] = 0;
return null;
}
ArrayList list = new ArrayList();
for (int i = 0; i < listobj.Count; i++)
{
IDictionary dict = new SortedList();
PropertyInfo[] properties = listobj[i].GetType().GetProperties();
foreach (PropertyInfo p in properties)
{
dict[p.Name] = p.GetValue(listobj[i], null);
}
list.Add(dict);
}
RO["records"] = listobj.Count;
RO.Rows = list;
return RO;
}
#region used for building partial sql to access database.
/// <summary>
/// زΪNULLб
/// </summary>
/// <param name="model"></param>
/// <returns>dictionaryĬϷcount=0dic</returns>
public static Dictionary<string, object> GetModelProperties(object model)
{
Dictionary<string, object> properties = new Dictionary<string, object>();
//Ҫӵֶκֵ
foreach (PropertyInfo p in model.GetType().GetProperties())
{
object value = p.GetValue(model, null);
string key = p.Name;
if (value != null)
{
properties.Add(p.Name, value);
}
}
return properties;
}
/// <summary>
/// Ӽ¼sql
/// </summary>
/// <param name="model">ΪNullбGetModelProperties(object model)ķֵ</param>
/// <param name="tableName"></param>
/// <param name="sql">sql</param>
/// <returns>ز</returns>
private static SqlParameter[] BuildAddSql(Dictionary<string, object> model, string tableName, ref string sql)
{
SqlParameter[] reval = null;
StringBuilder strSql = new StringBuilder();
if (model.Count > 0)
{
strSql.Append(string.Format("INSERT INTO {0}(", tableName));
string fileds = string.Empty;
string paraValue = string.Empty;
reval = new SqlParameter[model.Count];
int i = 0;
foreach (KeyValuePair<string, object> keyValue in model)
{
if (i == model.Count - 1)
{
fileds += keyValue.Key + ")";
paraValue += "@" + keyValue.Key + ")";
}
else
{
fileds += keyValue.Key + ",";
paraValue += "@" + keyValue.Key + ",";
}
reval[i] = new SqlParameter("@" + keyValue.Key, keyValue.Value);
i++;
}
strSql.Append(fileds);
strSql.Append(" VALUES (");
strSql.Append(paraValue);
}
sql = strSql.ToString();
return reval;
}
/// <summary>
/// Ӽ¼sql
/// </summary>
/// <param name="model">ΪNullбGetModelProperties(object model)ķֵ</param>
/// <param name="tableName"></param>
/// <param name="sql">sql</param>
/// <returns>ز</returns>
private static SqlParameter[] BuildUpdateSql(Dictionary<string, object> model, string tableName, string where, ref string sql)
{
SqlParameter[] reval = null;
StringBuilder strSql = new StringBuilder();
if (model.Count > 0)
{
strSql.Append(string.Format("UPDATE {0} SET ", tableName));
string fileds = string.Empty;
string paraValue = string.Empty;
reval = new SqlParameter[model.Count];
int i = 0;
foreach (KeyValuePair<string, object> keyValue in model)
{
if (i == model.Count - 1)
{
strSql.Append(keyValue.Key + "=@" + keyValue.Key);
}
else
{
strSql.Append(keyValue.Key + "=@" + keyValue.Key + ",");
}
reval[i] = new SqlParameter("@" + keyValue.Key, keyValue.Value);
i++;
}
if (!string.IsNullOrEmpty(where))
{
strSql.Append(" WHERE " + where);
}
}
sql = strSql.ToString();
return reval;
}
private static void BuildSelectSql(Dictionary<string, object> model, string tableName, string where, ref string sql)
{
// SqlParameter[] reval = null;
StringBuilder strSql = new StringBuilder();
if (model.Count > 0)
{
strSql.Append("SELECT ");
string fileds = string.Empty;
int i = 0;
foreach (KeyValuePair<string, object> keyValue in model)
{
if (i == model.Count - 1)
{
fileds += keyValue.Key + " ";
}
else
{
fileds += keyValue.Key + ",";
}
i++;
}
strSql.Append(fileds);
strSql.Append(string.Format("FROM {0}", tableName));
if (!string.IsNullOrEmpty(where))
{
strSql.Append(" WHERE " + where);
}
}
sql = strSql.ToString();
}
public static SqlParameter[] BuildAdd(object model, string tableName, ref string sql)
{
SqlParameter[] parameters = null;
Dictionary<string, object> properties = GetModelProperties(model);
if (properties.Count > 0)
{
parameters = BuildAddSql(properties, tableName, ref sql);
}
return parameters;
}
public static SqlParameter[] BuildUpdate(object model, string tableName, string where, ref string sql)
{
SqlParameter[] parameters = null;
Dictionary<string, object> properties = GetModelProperties(model);
if (properties.Count > 0)
{
parameters = BuildUpdateSql(properties, tableName, where, ref sql);
}
return parameters;
}
public static void BuildSelect(object model, string tableName, string where, ref string sql)
{
Dictionary<string, object> properties = GetModelProperties(model);
if (properties.Count > 0)
{
BuildSelectSql(properties, tableName, where, ref sql);
}
}
public static string BuildSelect(string[] selectFields, string tableName, string where)
{
string sql = string.Empty;
if (selectFields.Length > 0)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("SELECT ");
string fileds = string.Empty;
int i = 0;
foreach (string keyValue in selectFields)
{
if (i == selectFields.Length - 1)
{
fileds += keyValue + " ";
}
else
{
fileds += keyValue + ",";
}
i++;
}
strSql.Append(fileds);
strSql.Append(string.Format("FROM {0}", tableName));
if (!string.IsNullOrEmpty(where))
{
strSql.Append(" WHERE " + where);
}
sql = strSql.ToString();
}
return sql;
}
/// <summary>
/// ȽҪѯʵеǷͬ(ToLower)ضӦʵеб
/// </summary>
/// <param name="inputFileds"></param>
/// <param name="model">Ӧʵ</param>
/// <returns>ʵб</returns>
public static List<string> CompareInputFileds(string[] inputFileds, object model)
{
PropertyInfo[] ps = model.GetType().GetProperties();
//ݿͬ
List<string> columns = new List<string>();
foreach (string filed in inputFileds)
{
foreach (PropertyInfo p in model.GetType().GetProperties())
{
if (p.Name.ToLower() == filed.ToLower())
{
columns.Add(p.Name);
}
}
}
return columns;
}
#endregion
}
}
|
1941c3410599dda8352798b9aacf19da71d36e82
|
C#
|
MrSliddes/GameDevAI
|
/BehaviourTreeExample/Assets/Scripts/Tymon Scripts/TAB Behavior Tree/VariableType.cs
| 2.84375
| 3
|
using UnityEngine;
namespace TAB.BehaviorTree
{
/// <summary>
/// This class is used to pass trough a value and be able to change that value later in a different script. This stuff is apperently not possible? cannot use Instantiate(VeriableType<T>)
/// </summary>
/// <typeparam name="T">The type of the variable</typeparam>
[CreateAssetMenu(fileName = "VariableType_", menuName = "TAB/BehaviorTree/VariableType")]
public class VariableType<T> : BaseScriptableObject
{
//Old value, New value
public System.Action<T, T> OnValueChanged;
[SerializeField] private T value;
public T Value
{
get { return value; }
set
{
OnValueChanged?.Invoke(this.value, value);
this.value = value;
}
}
}
}
|
fa7116945f5076f3978a352696ad14edbfaa547c
|
C#
|
bellatesla/Helpful-Scripts-and-Extensions
|
/Unity Extentions and Misc/MathB.cs
| 3.046875
| 3
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public static class MathB
{
public enum Shapes
{
HalfCircle = 0,
Circle = 1,
}
public static Vector3[] CircleOfPositions(float radius, int amount)
{
Vector3[] objectPositions = new Vector3[amount];
for (int i = 0; i < amount; i++)
{
//Circle Shape
float angle = i * Mathf.PI * 2f / amount;
Vector3 position = new Vector3(Mathf.Cos(angle), 0, Mathf.Sin(angle)) * radius;
objectPositions[i] = position;
}
return objectPositions;
}
public static List<GameObject> CircleOfGameObjects(GameObject pf,float radius, int amount,bool fullCircle)
{
List<GameObject> objects = new List<GameObject>(amount);
for (int i = 0; i < amount; i++)
{
//Circle Shape
float n = fullCircle ? 2 : 1;//2=full circle 1=half circle
float angle = i * Mathf.PI * n / amount;
Vector3 position = new Vector3(Mathf.Cos(angle), 0, Mathf.Sin(angle)) * radius;
var obj = Object.Instantiate(pf, position, Quaternion.identity) as GameObject;
objects.Add(obj);
}
return objects;
}
//public static List<GameObject> CircleOfGameObjects(GameObject pf, float radius, int amount, Shapes shape)
//{
// List<GameObject> objects = new List<GameObject>(amount);
// Vector3 position=Vector3.zero;
// for (int i = 0; i < amount; i++)
// {
// float angle = 0;
// switch (shape)
// {
// case (Shapes.Circle):
// angle = i * Mathf.PI * 2 / amount;
// position = new Vector3(Mathf.Cos(angle), 0, Mathf.Sin(angle)) * radius;
// break ;
// case (Shapes.HalfCircle):
// angle = i * Mathf.PI * 1 / amount;
// position = new Vector3(Mathf.Cos(angle), 0, Mathf.Sin(angle)) * radius;
// break;
// }
// var obj = Object.Instantiate(pf, position, Quaternion.identity) as GameObject;
// objects.Add(obj);
// }
// return objects;
//}
}
|
0544485ee49a913c77e76141835966928a5eccfe
|
C#
|
truong2307/dotnet5-rpg
|
/Services/CharacterService/CharacterService.cs
| 2.8125
| 3
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using dotnet5_rpg.Dtos.Character;
using dotnet5_rpg.Models;
using System;
using dotnet5_rpg.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http;
using System.Security.Claims;
namespace dotnet5_rpg.Services.CharacterService
{
public class CharacterService : ICharacterService
{
private readonly IMapper _mapper;
private readonly DataContext _context;
private readonly IHttpContextAccessor _httpContextAccessor;
public CharacterService(IMapper mapper
, DataContext context
, IHttpContextAccessor httpContextAccessor)
{
_mapper = mapper;
_context = context;
_httpContextAccessor = httpContextAccessor;
}
public int GetUserId() => int.Parse(_httpContextAccessor.HttpContext.User
.FindFirstValue(ClaimTypes.NameIdentifier));
public string GetUserRole() => _httpContextAccessor.HttpContext.User
.FindFirstValue(ClaimTypes.Role);
public async Task<ServiceResponse<List<GetCharacterDto>>> GetAllCharacters()
{
var serviceResponse = new ServiceResponse<List<GetCharacterDto>>();
var dbCharacters = GetUserRole().Equals("Admin") ?
await _context.Characters.ToListAsync() :
await _context.Characters
.Include(c => c.Weapon)
.Include(c => c.Skills)
.Where(c => c.User.Id == GetUserId()).ToListAsync();
if (dbCharacters.Count != 0)
{
serviceResponse.Data = dbCharacters.Select(c => _mapper.Map<GetCharacterDto>(c)).ToList();
}
else
{
serviceResponse.Success = false;
serviceResponse.Message = "Character not found";
}
return serviceResponse;
}
public async Task<ServiceResponse<GetCharacterDto>> GetCharacterById(int id)
{
var serviceResponse = new ServiceResponse<GetCharacterDto>();
var dbCharacter = GetUserRole().Equals("Admin") ?
await _context.Characters.FirstOrDefaultAsync(c => c.Id == id) :
await _context.Characters
.Include(c => c.Weapon)
.Include(c => c.Skills)
.FirstOrDefaultAsync(c => c.Id == id && c.User.Id == GetUserId());
if (dbCharacter != null)
{
serviceResponse.Data = _mapper.Map<GetCharacterDto>(dbCharacter);
}
else
{
serviceResponse.Success = false;
serviceResponse.Message = "Character not found";
}
return serviceResponse;
}
public async Task<ServiceResponse<List<GetCharacterDto>>> AddCharacter(AddCharacterDto character)
{
var serviceResponse = new ServiceResponse<List<GetCharacterDto>>();
Character characterNew = _mapper.Map<Character>(character);
characterNew.User = await _context.Users
.FirstOrDefaultAsync(u => u.Id == GetUserId());
await _context.Characters.AddAsync(characterNew);
await _context.SaveChangesAsync();
serviceResponse.Data = await _context.Characters
.Where(c => c.User.Id == GetUserId())
.Select(c => _mapper.Map<GetCharacterDto>(c))
.ToListAsync();
return serviceResponse;
}
public async Task<ServiceResponse<GetCharacterDto>> UpdateCharacter(UpdateCharacterDto updateCharacter)
{
var serviceResponse = new ServiceResponse<GetCharacterDto>();
try
{
var obj = await _context.Characters
.Include(c => c.Weapon)
.Include(c => c.Skills)
.Include(c => c.User)
.FirstOrDefaultAsync(c => c.Id == updateCharacter.Id);
if (obj.User.Id == GetUserId())
{
obj.Name = updateCharacter.Name;
obj.HitPoints = updateCharacter.HitPoints;
obj.Strength = updateCharacter.Strength;
obj.Defense = updateCharacter.Defense;
obj.Intelligence = updateCharacter.Intelligence;
obj.Class = obj.Class;
await _context.SaveChangesAsync();
serviceResponse.Data = _mapper.Map<GetCharacterDto>(obj);
}
else
{
serviceResponse.Success= false;
serviceResponse.Message = "Character not found.";
}
}
catch (Exception ex)
{
serviceResponse.Success = false;
serviceResponse.Message = ex.Message;
}
return serviceResponse;
}
public async Task<ServiceResponse<List<GetCharacterDto>>> DeleteCharacter(int id)
{
var serviceResponse = new ServiceResponse<List<GetCharacterDto>>();
try
{
var obj = await _context.Characters
.Include(c => c.Weapon)
.Include(c => c.Skills)
.FirstOrDefaultAsync(c => c.Id == id && c.User.Id == GetUserId());
if (obj != null)
{
_context.Remove(obj);
await _context.SaveChangesAsync();
serviceResponse.Data = await _context.Characters
.Where(c => c.User.Id == GetUserId())
.Select(c => _mapper.Map<GetCharacterDto>(c)).ToListAsync();
}
else
{
serviceResponse.Success = false;
serviceResponse.Message = "Character not found";
}
}
catch (Exception ex)
{
serviceResponse.Success = false;
serviceResponse.Message = ex.Message;
}
return serviceResponse;
}
public async Task<ServiceResponse<GetCharacterDto>> AddCharacterSkill(AddCharacterSkillDto addCharacterSkill)
{
var serviceResponse = new ServiceResponse<GetCharacterDto>();
try
{
var characterInDb = await _context.Characters
.Include(c => c.Weapon)
.Include(c => c.Skills)
.FirstOrDefaultAsync(c => c.Id == addCharacterSkill.CharacterId && c.User.Id == GetUserId());
if(characterInDb == null)
{
serviceResponse.Success = false;
serviceResponse.Message = "Character not found.";
return serviceResponse;
}
var skill = await _context.Skills.FirstOrDefaultAsync(c => c.Id == addCharacterSkill.SkillId);
if(skill == null)
{
serviceResponse.Success = false;
serviceResponse.Message = "Skill not found.";
}
characterInDb.Skills.Add(skill);
await _context.SaveChangesAsync();
serviceResponse.Data = _mapper.Map<GetCharacterDto>(characterInDb);
}
catch(Exception ex)
{
serviceResponse.Success = false;
serviceResponse.Message = ex.Message;
}
return serviceResponse;
}
}
}
|
55eb5940de993c841dc4e404fbcac7802e823711
|
C#
|
bncamp/DBTestStresser
|
/DBTestStresser/Model/ExampleStore/Product.cs
| 2.875
| 3
|
using DBTestStresser.Util;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace DBTestStresser.Model {
public class Product : ExampleStore.ModelExampleStore {
public int Id { get; set; }
public Brand Brand { get; set; }
public string Name { get; set; }
public double Price { get; set; }
public int Stock { get; set; }
public static Product GenerateRandom(int maxBrandId, int id=-1) {
Product p = new Product();
p.Id = id;
p.Name = RandomDB.GenerateRandomString(15);
p.Price = (double) RandomDB.GenerateRandomInt(0, 500);
p.Stock = RandomDB.GenerateRandomInt(0, 15);
int brand_id = RandomDB.GenerateRandomInt(0, maxBrandId);
p.Brand = Brand.GenerateRandom(brand_id);
return p;
}
public JsonDocument ToJSON() {
string content = JsonConvert.SerializeObject(this);
Console.WriteLine(content);
var json = JsonDocument.Parse(content);
return json;
}
public string ToCypherJsonString() {
// Avoid serializing Brand in graph
string json = "{" + String.Format("Id:{0},Name:\"{1}\",Price:{2},Stock:{3}",
Id,Name,Price,Stock) + "}";
return json;
}
public override string ToString() {
return String.Format("{0}:{1},{2},{3}({4})",Id,Brand,Name,Price,Stock);
}
}
}
|
9df22e5786745cb5fef5228f586ee88e89d22aba
|
C#
|
shahabsharafi/SimpleERP
|
/Libraries/SimpleERP.Libraries.Infrastructure/Entities/CollectionResult.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace SimpleERP.Libraries.Infrastructure.Entities
{
public interface ICollectionResult<TData>
{
IEnumerable<TData> Rows { get; }
long RowCount { get; }
}
public class CollectionResult<TData>: ICollectionResult<TData>
{
private IEnumerable<TData> _rows;
private long _rowCount;
public CollectionResult(IEnumerable<TData> rows, long rowCount)
{
this._rows = rows;
this._rowCount = rowCount;
}
public IEnumerable<TData> Rows => this._rows;
public long RowCount => this._rowCount;
}
}
|
c15bca70278c9878071a555e1fe15a27685e971c
|
C#
|
duy81020/Excercise05
|
/Excercise5A/Excercise5A/Program.cs
| 3.59375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Excercise5A
{
class Program
{
static void Main(string[] args)
{
Print_a_2_z_v1();
while(true )
{
char c = Console.ReadKey().KeyChar;
Console.WriteLine(Char2Code(c));
}
}
public static void Print_a_2_z_v1()
{
char[] az = Enumerable.Range('a', 'z' - 'a' + 1).Select(i => (Char)i).ToArray();
foreach (var c in az)
{
Console.WriteLine(c);
}
}
public static int Char2Code(char c)
{
return (int)c;
}
public static bool IsUpper(char c)
{
return false;
}
public static bool IsLower(char c)
{
return false;
}
public static char ToUpper(char c)
{
return c;
}
}
}
|
751b61dde6dbecfa8de61d2e923075b20d14185e
|
C#
|
bubdm/EsriJSON.NET
|
/EsriJSON.NET/JsonLayerContainer.cs
| 2.96875
| 3
|
using System.Collections.Generic;
using Newtonsoft.Json;
namespace EsriJSON.NET
{
/// <summary>
/// Represents a container for layers, which can be serialized to EsriJSON
/// </summary>
public class JsonLayerContainer
{
// TODO: add extent property!
/// <summary>
/// Layers container
/// </summary>
[JsonProperty("layers")]
public Dictionary<string, JsonLayer> Layers { get; private set; }
/// <summary>
/// Creates a new Layer Container, ready to be serialized to EsriJSON
/// </summary>
public JsonLayerContainer()
{
this.Layers = new Dictionary<string, JsonLayer>();
}
/// <summary>
/// Adds a Layer to the container. ID will be set to FeatureSet.DisplayFieldName value!
/// </summary>
/// <param name="layer">Layer to be added</param>
public void AddLayer(JsonLayer layer)
{
this.AddLayer(layer.LayerDefinition.Name, layer);
}
/// <summary>
/// Adds a Layer to the container
/// </summary>
/// <param name="id">ID of the Layer.</param>
/// <param name="layer">Layer to be added</param>
public void AddLayer(string id, JsonLayer layer)
{
this.Layers.Add(id, layer);
}
/// <summary>
/// Returns the JSON text representing this object
/// </summary>
/// <returns></returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this);
}
}
}
|
f0ec42ba86e9976e927f64c0c1223ce98de37710
|
C#
|
alaudo/MerchantsGuideToGalaxy
|
/Guide/Universal/RomanExtensions.cs
| 3.640625
| 4
|
using System;
namespace Guide.Universal
{
/// <summary>
/// Container for Roman enum extensions (to allow fluent interface syntax)
/// </summary>
public static class RomanExtensions
{
/// <summary>
/// If the string is the valid Roman digit
/// </summary>
/// <param name="test">string to test</param>
/// <returns></returns>
public static bool IsRoman(this string test)
{
return Enum.IsDefined(typeof (Roman), test);
}
/// <summary>
/// Converts string to Roman if possible
/// </summary>
public static Roman ToRoman(this string test)
{
return (Roman) Enum.Parse(typeof (Roman), test);
}
/// <summary>
/// Converts Roman digit to its integer value
/// </summary>
public static int ToInteger(this Roman digit)
{
return (int) digit;
}
/// <summary>
/// If the Roman digit can be repeated
/// </summary>
public static bool IsRepeatable(this Roman digit)
{
return (digit == Roman.I)
|| (digit == Roman.X)
|| (digit == Roman.C)
|| (digit == Roman.M);
}
public static bool CanPrecede(this Roman left, Roman right)
{
return
(left == Roman.I && right == Roman.V)
|| (left == Roman.I && right == Roman.X)
|| (left == Roman.X && right == Roman.L)
|| (left == Roman.X && right == Roman.C)
|| (left == Roman.C && right == Roman.D)
|| (left == Roman.C && right == Roman.M);
}
}
}
|
516c11077b5ba50cbf5b44e1d8f56a9b36da30bb
|
C#
|
phillsteele/MeterReadingDemo
|
/src/Services/MeterCsvLineParser.cs
| 3.015625
| 3
|
using MeterReader.Model;
using System;
namespace MeterReader.Services
{
public class MeterCsvLineParser : IMeterCsvLineParser
{
private readonly IMeterCsvValidator _meterCsvValidator;
public MeterCsvLineParser(IMeterCsvValidator meterCsvValidator) => _meterCsvValidator = meterCsvValidator;
public bool TryParseMeterLine(string csvMeterLine, out MeterReading successfulReading)
{
successfulReading = new MeterReading();
// Make an assumption that the order of the headers is: AccountId,MeterReadingDateTime,MeterReadValue
// Additional code would be required if that assumption could not be relied upon. We would need
// to determine the position of each header and process accordingly.
string[] tokens = csvMeterLine.Split(',');
// We expect exactly 3 entries
if (tokens.Length != 3)
return false;
if (!_meterCsvValidator.TryParseAccountId(tokens[0], out int accountId))
return false;
// Seconds token must be a valid date time
if (!_meterCsvValidator.TryParseMeterReadingDateTime(tokens[1], out DateTime meterReadingDateTime))
return false;
// Last token must be a string in the format of NNNNN
if (!_meterCsvValidator.TryParseMeterReading(tokens[2], out string meterReading))
return false;
successfulReading.AccountId = accountId;
successfulReading.MeterReadingDateTime = meterReadingDateTime;
successfulReading.MeterReadValue = meterReading;
return true;
}
}
}
|
88a409abac6a9539442596d2a64df5f82f7bb401
|
C#
|
MrPerekrestov/LaboratoryBookWindowsPublic
|
/LaboratoryBook/SelectColumnsWIndow/SelectColumnsCommandImplementation.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace LaboratoryBook.SelectColumnsWindow
{
public partial class SelectColumnsWindow : Window
{
//remove command implementation
public void RemoveCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if ((LvSelectedColumns?.SelectedItems?.Count > 0))
{
e.CanExecute = true;
}
else
{
e.CanExecute = false;
}
}
public void RemoveCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
var selectedItems = new List<object>();
foreach (var selectedItem in LvSelectedColumns.SelectedItems)
{
selectedItems.Add(selectedItem);
}
foreach (var selectedItem in selectedItems)
{
LvSelectedColumns.Items.Remove(selectedItem);
}
CanApply = true;
}
//add command implementation
public void AddCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if ((LvAllColumns?.SelectedItems?.Count > 0))
{
e.CanExecute = true;
}
else
{
e.CanExecute = false;
}
}
public void AddCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
var selectedItems = new List<string>();
foreach (var selectedItem in LvAllColumns.SelectedItems)
{
selectedItems.Add((string)selectedItem);
}
var existingItems = new List<string>();
foreach (var item in LvSelectedColumns.Items)
{
existingItems.Add((string)item);
}
foreach (var selectedItem in selectedItems)
{
if (!existingItems.Contains(selectedItem))
{
LvSelectedColumns.Items.Add(selectedItem);
}
else continue;
}
CanApply = true;
}
//apply command implementation
public void ApplyCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (CanApply)
{
e.CanExecute = true;
}
else
{
e.CanExecute = false;
}
}
public void ApplyCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
bool columnIsVisible = false;
foreach (var column in DataGrid.Columns)
{
foreach(var selectedColumn in LvSelectedColumns.Items)
{
if ((string)column.Header ==(string)selectedColumn)
{
column.Visibility = Visibility.Visible;
columnIsVisible = true;
break;
}
}
if (!columnIsVisible)
{
column.Visibility = Visibility.Collapsed;
}
columnIsVisible = false;
}
CanApply = false;
}
//Close command implementation
public void CloseCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
public void CloseCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
this.Close();
}
}
}
|
11e9fc343535a1bbd70dc1dd0fbf44808a9dcc35
|
C#
|
paulofrederico84/sances
|
/ProjetoSancesWebAPI/Controllers/ProdutoController.cs
| 2.6875
| 3
|
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using ProjetoSancesWebAPI.Data;
using ProjetoSancesWebAPI.Models;
namespace ProjetoSancesWebAPI.Controllers
{
[ApiController]
[Route("[controller]")]
public class ProdutoController : ControllerBase
{
private readonly IRepository _repository;
public ProdutoController(IRepository repository)
{
_repository = repository;
}
[HttpGet]
public async Task<IActionResult> GetAction()
{
try
{
var result = await _repository.GetAllProdutoAsync(false);
return Ok(result);
}
catch (Exception ex)
{
return BadRequest($"Erro: {ex.Message}");
}
}
[HttpGet("produtoId={produtoId}")]
public async Task<IActionResult> Get(int produtoId)
{
try
{
var result = await _repository.GetProdutoAsyncById(produtoId, false);
return Ok(result);
}
catch (Exception ex)
{
return BadRequest($"Erro: {ex.Message}");
}
}
[HttpGet("descricao={descricao}")]
public async Task<IActionResult> Get(string descricao)
{
try
{
var result = await _repository.GetProdutoAsyncByDescricao(descricao);
return Ok(result);
}
catch (Exception ex)
{
return BadRequest($"Erro: {ex.Message}");
}
}
[HttpPost]
public async Task<IActionResult> Post(Produto produto)
{
try
{
_repository.Add(produto);
if (await _repository.SaveChangesAsync())
{
return Ok(produto);
}
}
catch (Exception ex)
{
return BadRequest($"Erro: {ex.Message}");
}
return BadRequest();
}
[HttpPut("produtoId={produtoId}")]
public async Task<IActionResult> Put(int produtoId, Produto produto)
{
try
{
var pedidoCadastrado = await _repository.GetProdutoAsyncById(produtoId, false);
if (pedidoCadastrado == null)
{
return NotFound();
}
_repository.Update(produto);
if (await _repository.SaveChangesAsync())
{
return Ok(produto);
}
}
catch (Exception ex)
{
return BadRequest($"Erro: {ex.Message}");
}
return BadRequest();
}
[HttpDelete("produtoId={produtoId}")]
public async Task<IActionResult> delete(int produtoId)
{
try
{
var produto = await _repository.GetProdutoAsyncById(produtoId, false);
if (produto == null)
{
return NotFound();
}
_repository.Delete(produto);
if (await _repository.SaveChangesAsync())
{
return Ok("Deletado");
}
}
catch (Exception ex)
{
return BadRequest($"Erro: {ex.Message}");
}
return BadRequest();
}
}
}
|
b9a981a8b9ac311032f46350550d0fb4551b6052
|
C#
|
just-me-/dafny-language-server
|
/Source/DafnyLanguageServer/WorkspaceManager/Workspace.cs
| 2.90625
| 3
|
using DafnyLanguageServer.Commons;
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
using System;
using System.Collections.Concurrent;
namespace DafnyLanguageServer.WorkspaceManager
{
/// <summary>
/// This <c>WorkspaceManager</c> buffers for every Dafny file a valid intermediate version.
/// The structure is key-value-based <c>URI, FileRepository</c>.
/// This buffer is needed to have always a valid intermediate file version to provide features like <c>AutoCompletion</c>
/// even if the current file state would not be valid Dafny code (eg the user is typing a new line in his Dafny source file.)
/// </summary>
public class Workspace : IWorkspace
{
private readonly ConcurrentDictionary<Uri, IFileRepository> _files = new ConcurrentDictionary<Uri, IFileRepository>();
/// <summary>
/// Requests the fileRepository to apply updates and store it in the buffer.
/// </summary>
/// <typeparam name="T">string or Container with TextDocumentContentChangeEvent</typeparam>
/// <param name="documentPath">URI to the document</param>
/// <param name="changes">Update Information, either just the new complete sourcecode or TextDocumentChangeEvent-Container</param>
/// <returns></returns>
public IFileRepository UpdateFile<T>(Uri documentPath, T changes)
{
IFileRepository fileRepository = GetOrCreateFileRepositoryInWorkspace(documentPath);
if (typeof(T) == typeof(string)) //Sync Kind Full
{
var text = changes as string;
fileRepository.UpdateFile(text);
}
else if (typeof(T) == typeof(Container<TextDocumentContentChangeEvent>)) //Sync Kind Incremental
{
var changes1 = changes as Container<TextDocumentContentChangeEvent>;
fileRepository.UpdateFile(changes1);
}
else
{
throw new TypeAccessException(Resources.ExceptionMessages.unexpected_file_type);
}
_files.AddOrUpdate(documentPath, fileRepository, (k, v) => fileRepository);
return fileRepository;
}
/// <summary>
/// Retreives a fileRepository from the buffer. If it doesn't exist, it will be created.
/// </summary>
/// <param name="documentPath">URI to the file.</param>
/// <returns>FileRepository</returns>
private IFileRepository GetOrCreateFileRepositoryInWorkspace(Uri documentPath)
{
return _files.TryGetValue(documentPath, out var bufferedFile)
? bufferedFile
: new FileRepository(new PhysicalFile
{
Uri = documentPath,
Filepath = documentPath.LocalPath,
Sourcecode = string.Empty
});
}
public IFileRepository GetFileRepository(Uri documentPath)
{
return GetOrCreateFileRepositoryInWorkspace(documentPath);
}
public IFileRepository GetFileRepository(string documentPath)
{
return GetFileRepository(new Uri(documentPath));
}
public ConcurrentDictionary<Uri, IFileRepository> GetAllFiles()
{
return _files;
}
}
}
|
49ddb992f382ce77e46924b64bd06a5645f30b9e
|
C#
|
edurdias/architecture
|
/foundation/Foundation.Data/DataContextWrapper.cs
| 2.9375
| 3
|
using System;
using System.Configuration;
using System.Data.Entity;
namespace AdventureWorks.Foundation.Data
{
public class DataContextWrapper : IDataContext
{
public DataContextWrapper()
{
var contextTypeName = ConfigurationManager.AppSettings["DataContext:Type"];
var contextType = Type.GetType(contextTypeName);
if (contextType == null)
throw new Exception(string.Format("Cannot find DbContext type {0}", contextTypeName));
InternalContext = (DbContext) Activator.CreateInstance(contextType);
}
public DataContextWrapper(DbContext context)
{
InternalContext = context;
}
public DbContext InternalContext { get; set; }
public IDataSet<T> Set<T>() where T : class
{
return new DataSetWrapper<T>(InternalContext.Set<T>());
}
public void SaveChanges()
{
InternalContext.SaveChanges();
}
public void MarkAsModified(object entity)
{
InternalContext.Entry(entity).State = EntityState.Modified;
}
}
}
|
30522df6b9719bbd85bca224929f8b8a053a0fee
|
C#
|
greck2908/DataStructures
|
/C#/Leetcode/Array/TaskScheduler.cs
| 3.3125
| 3
|
using System;
namespace LeetcodeSolutions.Array
{
// Leetcode 621 - https://leetcode.com/problems/task-scheduler/
public class TaskScheduler
{
//public static void Main(string[] args)
//{
// TaskScheduler s = new TaskScheduler();
// char[] c1 = { 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'E', 'E', 'F', 'F', 'G', 'G' };
// Console.WriteLine(s.LeastInterval(c1, 3)); //13
// char[] c2 = { 'A', 'C', 'C', 'C', 'E', 'E', 'E' };
// Console.WriteLine(s.LeastInterval(c2, 2)); //8
// char[] c3 = {};
// Console.WriteLine(s.LeastInterval(c3, 2)); //23
// Console.ReadKey();
//}
// Ref: https://leetcode.com/problems/task-scheduler/discuss/104500/Java-O(n)-time-O(1)-space-1-pass-no-sorting-solution-with-detailed-explanation
// Submission Detail: https://leetcode.com/submissions/detail/208333877/
// Tx = O(n)
// Sx = O(1)
public int LeastIntervalUnderstandable(char[] tasks, int n)
{
int[] taskFreq = new int[26];
int maxFreq = 0, maxFreqCount = 0;
foreach (char task in tasks)
{
int index = task - 'A';
taskFreq[index]++;
if (maxFreq == taskFreq[index])
{
maxFreqCount++;
}
else if (maxFreq < taskFreq[index])
{ // Found a new max task frequency
maxFreq = taskFreq[index];
maxFreqCount = 1;
}
}
int totalMaxFreq = maxFreq - 1; // last task may not need additional idle n slots
int remainingTasksCount = n - (maxFreqCount - 1);
int emptySlots = totalMaxFreq * remainingTasksCount;
int availableSlots = tasks.Length - maxFreq * maxFreqCount;
int idleSlots = System.Math.Max(0, emptySlots - availableSlots);
return tasks.Length + idleSlots;
}
// Solution 2 :
// Tx = O(1) although it is Math.Max(O(26log26),O(10000)) as input array length is in the range [1...10000]
// Sx = O(1)
// Explanation - http://www.cnblogs.com/grandyang/p/7098764.html
// Solution - https://leetcode.com/problems/task-scheduler/discuss/104496/concise-Java-Solution-O(N)-time-O(26)-space
// Submission - https://leetcode.com/submissions/detail/140296542/
public int LeastInterval(char[] tasks, int n)
{
int[] frequencies = new int[26];
foreach (char c in tasks)
frequencies[c - 'A']++;
System.Array.Sort(frequencies);
int i = 25;
while (i >= 0 && frequencies[i] == frequencies[25])
i--;
return System.Math.Max(tasks.Length, (frequencies[25] - 1) * (n + 1) + 25 - i);
}
}
}
|