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
}
}
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 71