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
|
|---|---|---|---|---|---|---|
73cad8650f8cd8d0bec731e6552f84b9a9048216
|
C#
|
CrazyPandaLimited/SimplePromises
|
/Runtime/PandaTasks/WaitWhilePandaTask.cs
| 2.84375
| 3
|
using System;
using System.Threading;
namespace CrazyPanda.UnityCore.PandaTasks
{
class WaitWhilePandaTask : PandaTask
{
private readonly Func< bool > _condition;
private static readonly SendOrPostCallback _tickCallback = new SendOrPostCallback(Tick);
public WaitWhilePandaTask( Func< bool > condition, CancellationToken cancellationToken )
{
_condition = condition;
if( cancellationToken.CanBeCanceled )
{
cancellationToken.Register( TryCancel );
}
Tick( this );
}
private static void Tick( object t )
{
// this function will post itself to current SynchronizationContext while _condition is true
// UnitySynchronizationContext will process posted tasks each frame so this is equivalent to Update()
var task = t as WaitWhilePandaTask;
if( task.Status == PandaTaskStatus.Pending )
{
bool willWait = false;
try
{
willWait = task._condition();
}
catch( Exception ex )
{
task.Reject( ex );
return;
}
if( !willWait )
task.Resolve();
else
SynchronizationContext.Current.Post( _tickCallback, task );
}
}
}
}
|
8585c74ce403fa2b711ddbf32cb507c5a4b400b9
|
C#
|
jeason0813/RuiJi.Net
|
/RuiJi.Net.Core/Compile/FileProviderBase.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RuiJi.Net.Core.Compile
{
/// <summary>
/// file provider base class
/// </summary>
public abstract class FileProviderBase : IProvider
{
/// <summary>
/// functions dictionary
/// </summary>
public Dictionary<string, string> Functions { get; protected set; }
public FileProviderBase()
{
Functions = Load();
}
/// <summary>
/// load function abstract method
/// </summary>
/// <returns>functions dictionary</returns>
public abstract Dictionary<string, string> Load();
/// <summary>
/// get function code by function name
/// </summary>
/// <param name="name">function name</param>
/// <returns>function code</returns>
public virtual string GetFunc(string name)
{
if (!Functions.Keys.Contains(name))
return "";
return Functions[name];
}
}
}
|
483591559403e83dec15202cb05d5b617617afe6
|
C#
|
mhartzell/LearnWithCode
|
/DesignPatterns/Structural/Bridge/IGamer.cs
| 3.21875
| 3
|
namespace PMasta.LearnWithCode.DesignPatterns.Structural.Bridge
{
/// <summary>
/// Defines a generic video game player.
/// </summary>
/// <remarks>
/// In the Bridge pattern, this interface takes on the role of the Abstraction. We have a generic game-playin' human,
/// who may like to play games on a variety of platforms. The methods on this class would in reality likely be on
/// some kind of service, but for this trivial example, the gamer abstraction itself provides informtion requested of it.
/// </remarks>
public interface IGamer
{
/// <summary>
/// Retrieves the gamer's name.
/// </summary>
/// <returns>A <see cref="String>"/>.</returns>
string GetName();
/// <summary>
/// Retrieves the gamer's account score.
/// </summary>
/// <returns>An <see cref="Int32"/>.</returns>
int GetScore();
}
}
|
d11c9782b0abf3322ae7805549302bde25b78c2f
|
C#
|
gastonmancini/codility-training-tasks
|
/src/CodilityTrainingTasks/Tests/Lesson9-MaximumSliceProblem/MaxDoubleSliceSumTests.cs
| 2.65625
| 3
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TrainingTasks;
namespace Tests
{
[TestClass]
public class MaxDoubleSliceSumTests
{
private MaxDoubleSliceSum _maxDoubleSliceSum;
[TestInitialize]
public void Initialize()
{
_maxDoubleSliceSum = new MaxDoubleSliceSum();
}
[TestMethod]
public void MaxDoubleSliceSum_Example_Test()
{
var A = new int[8];
A[0] = 3;
A[1] = 2;
A[2] = 6;
A[3] = -1;
A[4] = 4;
A[5] = 5;
A[6] = -1;
A[7] = 2;
Test(A, 17);
}
private void Test(int[] A, int expectedResult)
{
var result = _maxDoubleSliceSum.solution(A);
Assert.AreEqual(expectedResult, result);
}
}
}
|
2c5a73d759b35b84a75a0616a4109e510795e23b
|
C#
|
baddazi/Realizace-kognitivn-hry-s-podporou-pro-eyetracker
|
/Hra/Kořenová složka projektu hry/Arkanoid/Assets/Prefab/Brick/Scripts/brickGray.cs
| 2.53125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/**
*Trida slouzi pro sedive cihlicky se tremi zivoty
*
* @autor David Zaruba
*
*
*/
public class brickGray : MonoBehaviour
{
private int life = 2;
[SerializeField] Sprite demage;
[SerializeField] Sprite smallDemage;
private GameObject BonusManager;
private int[] positionField = new int[2];
public int[] PositionField
{
get => positionField;
set => positionField = value;
}
public GameObject BonusManager1
{
get => BonusManager;
set => BonusManager = value;
}
/**
*
*Funkce je spoustena pri kolizi. Ubere jeden zivot cihlicce a pokud je 0 zivotu, zajisti jeji zniceni, a take o zniceni informuje.
*
*/
void OnCollisionEnter2D(Collision2D col)
{
if (life == 0)
{
BonusManager.GetComponent<BonusManager>().brickDestroyed(positionField);
Destroy(gameObject);
}
else
{
if (life == 2)
GetComponent<SpriteRenderer>().sprite = smallDemage;
else
GetComponent<SpriteRenderer>().sprite = demage;
}
life--;
}
}
|
68129c30453e4e4207c703b2d039d8f4fadfe77c
|
C#
|
softwarefiche/Fiche
|
/Fiche/Extensions/BooleanExtensions.cs
| 3.296875
| 3
|
namespace Fiche.Extensions
{
public static class BooleanExtensions
{
/// <summary>
/// Short-hand for the ternary conditional operator '?:'
/// <para>
/// <code>
/// condition ? trueResult : falseResult
/// </code>
/// </para>
/// </summary>
public static T If<T>(this bool condition, T trueResult, T falseResult)
=> condition ? trueResult : falseResult;
/// <summary>
/// Short-hand for the ternary conditional operator '?:'; except for allowing incompatible types. Could be useful for non-generic collections conditional manipulation.
/// <para>
/// <code>
/// condition ? trueResult : falseResult
/// </code>
/// </para>
/// </summary>
public static object If(this bool condition, object trueResult, object falseResult)
=> condition.If<object>(trueResult, falseResult);
}
}
|
88e7cf72f0aebb120a470342f14455ad4c2efd7b
|
C#
|
DexterHarvey/Portfolio
|
/Portfolio/C#/Windows Forms/CPRG200_Lab4/CPRG200_Lab4/Form1.cs
| 3.09375
| 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 CPRG200_Lab4
{
public partial class Form1 : Form
{
//create a new instance of the buisiness layer, the only layer the form communicates with
BuisinessLayer bl = new BuisinessLayer();
public Form1()
{
InitializeComponent();
}
//method to populate form with data from order object
public void PopulateTextBoxes(Order1 order)
{
orderIDTextBox.Text = Convert.ToString(order.OrderID);
string orderDate = $"{order.OrderDate:yyyy-MM-dd}";
customerIDTextBox.Text = Convert.ToString(order.CustomerID);
string reqDate = $"{order.RequiredDate:yyyy-MM-dd}";
string shipDate = $"{order.ShippedDate:yyyy-MM-dd}";
txtOrderDate.Text = orderDate;
txtReqDate.Text = reqDate;
txtShipDate.Text = shipDate;
}
//methods used to convert text box strings to datatime objects
public DateTime GetOrderDateTime()
{
DateTime orderDateTime = Convert.ToDateTime(txtOrderDate.Text);
return orderDateTime;
}
public DateTime GetRequiredDateTime()
{
DateTime reqDateTime = Convert.ToDateTime(txtReqDate.Text);
return reqDateTime;
}
//method to use data in form to construct an order object (allows nulls in shipdate)
public Order1 CreateOrderFromForm(DateTime? shipDate)
{
int orderID = Convert.ToInt32(orderIDTextBox.Text);
DateTime orderDate = Convert.ToDateTime(txtOrderDate.Text);
string customerID = customerIDTextBox.Text;
DateTime reqDate = Convert.ToDateTime(txtReqDate.Text);
var newOrder = new Order1
{
OrderID = orderID,
OrderDate = orderDate,
CustomerID = customerID,
RequiredDate = reqDate,
ShippedDate = shipDate
};
return newOrder;
}
private void Form1_Load(object sender, EventArgs e)
{
//uses method to find first order in db by OrderID asc
int firstOrderId = bl.GetFirstOrderID();
//builds object from first order
Order1 order = bl.GetOrderByID(firstOrderId);
//fills form with data of order object
PopulateTextBoxes(order);
//creates an order details data table based on the orderId and uses it to populate datagridview
dataGridView1.DataSource = bl.CreateDataTable(Convert.ToInt32(orderIDTextBox.Text));
}
private void btnOrderNext_Click(object sender, EventArgs e)
{
int orderId = Convert.ToInt32(orderIDTextBox.Text);
//uses method to get next order in table and builds order object
Order1 order = bl.GetNextOrder(orderId);
PopulateTextBoxes(order);
dataGridView1.DataSource = bl.CreateDataTable(Convert.ToInt32(orderIDTextBox.Text));
}
private void btnGetById_Click(object sender, EventArgs e)
{
string orderIdString = txtGetById.Text;
//checks if the order field is empty, if not does the following:
if (!bl.ValidateIsNull(orderIdString))
{
//checks if the entered data is a valid data type (intager)
if (bl.ValidateOrderIdFormat(txtGetById.Text))
{
int orderId = Convert.ToInt32(txtGetById.Text);
//checks if information entered in orderId field matches an orderId in the database
if (bl.ValidateOrderExists(orderId))
{
//if orderId is valid, uses methods to retrieve order and populate relevant data fields
Order1 order = bl.GetOrderByID(orderId);
PopulateTextBoxes(order);
dataGridView1.DataSource = bl.CreateDataTable(Convert.ToInt32(orderIDTextBox.Text));
}
//if order id is invalid, prompts user to reenter data
else
{
txtGetById.Text = "";
txtGetById.Focus();
MessageBox.Show("Please enter a valid order Id");
}
}
else
{
//entered data was not an intager
MessageBox.Show("Please enter a whole number");
}
}
//orderid field was left empty
else
{
txtGetById.Text = "";
txtGetById.Focus();
MessageBox.Show("Please enter an order Id");
}
}
//method to update db with new ship date
private void btnUpdate_Click(object sender, EventArgs e)
{
//checks if the ship date field is empty
if (bl.ValidateIsNull(txtShipDate.Text))
{
//if ship date field is empty, constructs an order object with a null ship date
Order1 updatedOrder = CreateOrderFromForm(bl.ConvertDateToNull());
//attempts to update database with new order object
if (bl.UpdateShippedDate(updatedOrder))
{
//if update is successful
MessageBox.Show("Order updated successfully with null date");
}
else
{
//if update is unsuccessful, this indicated a concurrency error has occurred. data refreshes with changed info and user is informed
bl.RefreshDataBase();
Order1 newOrder = bl.GetOrderByID(Convert.ToInt32(orderIDTextBox.Text));
PopulateTextBoxes(newOrder);
MessageBox.Show("Concurrency Error: Data has been altered or deleted");
}
}
//if the ship date field is not empty, checks if it is a valid datetime
else if (bl.ValidateDateTimeEntryFormat(txtShipDate.Text))
{
//if the date is entered in a valid format, it is checked to make sure it is in the valid range (after order date but before required date)
if (bl.ValidateDateTimeEntryDate(Convert.ToDateTime(txtShipDate.Text), GetOrderDateTime(), GetRequiredDateTime()))
{
//if date is in acceptable range, order object is built from form and an attempt is made to update the database with it
Order1 updatedOrder = CreateOrderFromForm(Convert.ToDateTime(txtShipDate.Text));
if (bl.UpdateShippedDate(updatedOrder))
{
MessageBox.Show("Order updated successfully with valid date");
}
//if update is unsuccessful, this indicated a concurrency error has occurred. data refreshes with changed info and user is informed
else
{
bl.RefreshDataBase();
Order1 newOrder = bl.GetOrderByID(Convert.ToInt32(orderIDTextBox.Text));
PopulateTextBoxes(newOrder);
MessageBox.Show("Concurrency Error: Data has been altered or deleted");
}
}
//date failed range validation
else
{
txtShipDate.Text = "";
txtShipDate.Focus();
MessageBox.Show("Please enter a valid date that is after the order date and before the required date");
}
}
//date failed format validation
else
{
txtShipDate.Text = "";
txtShipDate.Focus();
MessageBox.Show("Please enter a valid date in the form yyyy-mm-dd");
}
}
private void btnPrev_Click(object sender, EventArgs e)
{
int orderId = Convert.ToInt32(orderIDTextBox.Text);
Order1 order = bl.GetPreviousOrder(orderId);
PopulateTextBoxes(order);
dataGridView1.DataSource = bl.CreateDataTable(Convert.ToInt32(orderIDTextBox.Text));
}
private void btnLast_Click(object sender, EventArgs e)
{
Order1 order = bl.GetLastOrder();
PopulateTextBoxes(order);
dataGridView1.DataSource = bl.CreateDataTable(Convert.ToInt32(orderIDTextBox.Text));
}
private void btnFirst_Click(object sender, EventArgs e)
{
Order1 order = bl.GetFirstOrder();
PopulateTextBoxes(order);
dataGridView1.DataSource = bl.CreateDataTable(Convert.ToInt32(orderIDTextBox.Text));
}
//formats cells that represent currency to display in an appropriate way
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.RowIndex < 0)
{
return;
}
var orderTotalColumn = dataGridView1.Columns[e.ColumnIndex];
if (orderTotalColumn.Name == "OrderTotal" && e.Value != null)
{
var value = (decimal)e.Value;
// Display only two digits of decimals without rounding
var twoDigitsValue = Math.Truncate(value * 100) / 100;
e.Value = twoDigitsValue.ToString("C2");
}
var unitPriceColumn = dataGridView1.Columns[e.ColumnIndex];
if (unitPriceColumn.Name == "UnitPrice" && e.Value != null)
{
var value = (decimal)e.Value;
// Display only two digits of decimals without rounding
var twoDigitsValue = Math.Truncate(value * 100) / 100;
e.Value = twoDigitsValue.ToString("C2");
}
}
}
}
|
7174c88762bad1ba788670aa00e8892679df2592
|
C#
|
pabitrad/Othello
|
/Othello.Logic/Classes/GameManager.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Othello;
using Othello.Logic.Classes.Players;
using Othello.Logic.Common;
using Othello.Logic.Interfaces;
namespace Othello.Logic.Classes
{
public class GameManager:IGameManager
{
#region Implementation of IGameManager
public IBoard Board { get; set; }
public IPlayer WhitePlayer { get; set; }
public IPlayer BlackPlayer { get; set; }
public IPlayer CurrentPlayerAtTurn { get; set; }
public bool GameStarted { get; set; }
private IMove _lastMove = null;
public int BlackAvailableMoves
{
get;
set;
}
public IMove LastMove
{
get
{
return _lastMove;
}
}
public int WhiteAvailableMoves { get; set; }
public void StartGame()
{
ResetGame();
GameStarted = true;
CurrentPlayerAtTurn = BlackPlayer;
}
public void ResetGame()
{
Board.ConfigureNewGame(false);
GameStarted = false;
IsPlaying = false;
IsEndGame = false;
}
public bool IsPlaying { get; set; }
public bool IsEndGame { get; set; }
private bool HasPlayerPassed { get; set; }
public void MoveNext()
{
if (IsEndGame || IsPlaying || !GameStarted)
return;
IsPlaying = true;
var nextMove = CurrentPlayerAtTurn.GetNextMove(Board);
if (nextMove == null) //if can't move
{
IsPlaying = false;
return;
}
if (nextMove.IsPassMove && HasPlayerPassed) //finish case
{
IsEndGame = true;
var whites = Board.WhitePoints.Count;
var blacks = Board.BlackPoints.Count;
var gameFinishedEventArgs = new GameFinishedEventArgs {WhiteCount = whites, BlackCount = blacks};
if (whites - blacks != 0)
gameFinishedEventArgs.WhiteWins = whites - blacks > 0;
RaiseGameFinished(gameFinishedEventArgs);
GameStarted = false;
IsPlaying = false;
return;
}
HasPlayerPassed = nextMove.IsPassMove;
MakeMove(nextMove);
IsPlaying = false;
}
private void MakeMove(IMove nextMove)
{
Board.MakeMove(nextMove);
_lastMove = nextMove;
//CurrentPlayerAtTurn = CurrentPlayerAtTurn == WhitePlayer ? BlackPlayer : WhitePlayer;
if (CurrentPlayerAtTurn == WhitePlayer)
{
if (BlackAvailableMoves > 0)
{
CurrentPlayerAtTurn = BlackPlayer;
}
}
else if (CurrentPlayerAtTurn == BlackPlayer)
{
if (WhiteAvailableMoves > 0)
{
CurrentPlayerAtTurn = WhitePlayer;
}
}
RaiseMoveDone(new MoveEventArgs(nextMove));
}
public void UndoLastMove() {
if (_lastMove == null || _lastMove.IsPassMove)
{
return;
}
Board.UnDoMove(_lastMove);
PlayerKind lastPlayerKind = _lastMove.Player.PlayerKind;
var previosPlayer = CurrentPlayerAtTurn;
if (lastPlayerKind == PlayerKind.White)
{
CurrentPlayerAtTurn = WhitePlayer;
}
else if (lastPlayerKind == PlayerKind.Black)
{
CurrentPlayerAtTurn = BlackPlayer;
}
else
{
throw new InvalidOperationException(string.Format("Unknown PlayerKind: {0}", lastPlayerKind));
}
if (previosPlayer != null)
{
previosPlayer.CancelNextMove();
}
RaiseMoveDone(new MoveEventArgs(_lastMove, true));
_lastMove = null;
}
#region MoveDone
public event EventHandler<MoveEventArgs> MoveDone;
private void RaiseMoveDone(MoveEventArgs e)
{
EventHandler<MoveEventArgs> handler = MoveDone;
if (handler != null) handler(this, e);
}
#endregion
#region GameFinished
public event EventHandler<GameFinishedEventArgs> GameFinished;
private void RaiseGameFinished(GameFinishedEventArgs e)
{
EventHandler<GameFinishedEventArgs> handler = GameFinished;
if (handler != null) handler(this, e);
}
#endregion
#endregion
}
}
|
8aed03c76c13acb2a6cab99c64f2e5933eca9515
|
C#
|
IELBHJY/C--projects
|
/02_out and ref/_方法的递归/Program.cs
| 3.359375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _方法的递归
{
class Program
{
//方法的递归:就是方法自己调用自己。
public static int i = 0;//静态变量实现全局变量的作用
public static void TellStory()
{
Console.WriteLine("从前有个山");
i++;
if (i >= 10)
{
return;
}
TellStory();
}
static void Main(string[] args)
{
TellStory();
Console.ReadKey();
}
}
}
|
cf3e5b38490bc463ab5fc677afbec4b0323c3bbb
|
C#
|
armohamm/design-patterns
|
/structural/Decorator/Program.cs
| 3.125
| 3
|
using System;
using System.Collections.Generic;
namespace Decorator
{
class Program
{
static void Main(string[] args)
{
Honda car = new Honda();
Console.WriteLine("Honda base price is: {0}", car.Price);
SpecialOffer offer = new SpecialOffer(car);
offer.DiscountPercentage = 25;
offer.Offer = "25% discount";
Console.WriteLine("{1} @ Diwali Special Offer and price is : {0}", offer.Price, offer.Offer);
Console.ReadKey();
}
}
}
|
b5560f92653e29b5d96a18063c0a3716002580af
|
C#
|
DimitarStoyanovVictory/JavaSciprt-Advanced
|
/ExamTasks/Problem-2-Infestation/Infestation-Stoyanov/Infestation/Tank.cs
| 2.734375
| 3
|
using System.Collections.Generic;
namespace Infestation
{
public class Tank : Unit
{
private ICollection<ISupplement> supplements;
public Tank(string id)
: base(id, UnitClassification.Mechanical, 20, 25, 25)
{
}
public ICollection<ISupplement> Supplements
{
get
{
if (this.supplements == null)
{
this.supplements = new List<ISupplement>();
}
return this.supplements;
}
private set
{
this.supplements = value;
}
}
}
}
|
fd6fcb67fd2858a49894e39dc01d17d90999384c
|
C#
|
fse-accreditation/app-service
|
/eStockMarket/CompaniesAPI/DBContexts/CompanyContext.cs
| 2.671875
| 3
|
using CompaniesAPI.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CompaniesAPI.DBContexts
{
public class CompanyDBContext : DbContext
{
public CompanyDBContext(DbContextOptions<CompanyDBContext> options) : base(options)
{
Database.EnsureCreated();
}
public DbSet<Company> Companies { get; set; }
public DbSet<Stock> Stocks { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Stock>()
.HasOne<Company>(s => s.Company)
.WithMany(g => g.Stocks)
.HasForeignKey(s => s.CompanyCode)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Company>().HasData(new Company {
CompanyCode = "Code1",
CompanyName = "ABC",
CompanyCEO = "XYZ",
CompanyTurnOver = 100,
Website = "website1"
});
modelBuilder.Entity<Stock>().HasData(
new Stock {
StockId = 101,
StockDateTime = DateTime.Now,
StockPrice = 100.89m,
CompanyCode = "Code1"
});
}
}
}
|
14398774ccbcd69f3067a2f7e5e00a5a167e350a
|
C#
|
servirtium/servirtium-dotnet
|
/Servirtium.Core/InteractionCounter.cs
| 2.90625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace Servirtium.Core
{
public class InteractionCounter
{
private long _currentInteraction = -1;
public int Bump()
{
return (int)Interlocked.Increment(ref _currentInteraction);
}
public int Get()
{
return (int)Interlocked.Read(ref _currentInteraction);
}
public void Reset()
{
Interlocked.Exchange(ref _currentInteraction, -1);
}
}
}
|
510a8dc00e419ef1fe2d8e17c4657bd25e0d26f3
|
C#
|
shendongnian/download4
|
/first_version_download2/254210-20228102-52359575-2.cs
| 2.765625
| 3
|
//establish initial query
var queryBase = (from a in db.Jobs where a.StatusId == 7 select a);
//instead of running the search against all of the entities, I first take the ones that are possible candidates, this is done through checking if they have any of the search terms under any of their columns. This is the one and only query that will be run against the database
if (search.Count > 0)
{
nquery = nquery.Where(job => search.All(y => (job.Title.ToLower() + " " + job.FullDescription.ToLower() + " " + job.Company.Name.ToLower() + " " + job.NormalLocation.ToLower() + " " + job.MainCategory.Name.ToLower() + " " + job.JobType.Type.ToLower()).Contains(y))); // + " " + job.Location.ToLower() + " " + job.MainCategory.Name.ToLower() + " " + job.JobType.Type.ToLower().Contains(y)));
}
//run the query and grab a list of baseJobs
List<Job> baseJobs = nquery.ToList<Job>();
//A list of SearchResult object (these object act as a container for job ids and their search values
List<SearchResult> baseResult = new List<SearchResult>();
//from here on Jim's algorithm comes to play where it assigns points depending on where the search term is located and added to a list of id/value pair list
foreach (var a in baseJobs)
{
foreach (var item in search)
{
var itemLower = item.ToLower();
if (a.Company.Name.ToLower().Contains(itemLower))
baseResult.Add(new SearchResult { ID = a.ID, Value = 5 });
if (a.Title.ToLower().Contains(itemLower))
baseResult.Add(new SearchResult { ID = a.ID, Value = 3 });
if (a.FullDescription.ToLower().Contains(itemLower))
baseResult.Add(new SearchResult { ID = a.ID, Value = 2 });
}
}
List<SearchResult> result = baseResult.GroupBy(x => x.ID).Select(p => new SearchResult() { ID = p.First().ID, Value = p.Sum(i => i.Value) }).OrderByDescending(a => a.Value).ToList<SearchResult>();
//the data generated through the id/value pair list are then used to reorder the initial jobs.
var NewQuery = (from id in result join jbs in baseJobs on id.ID equals jbs.ID select jbs).AsQueryable();
|
914130729c3c526abda7e0ed39fb96ccdfc31579
|
C#
|
sshnet/SSH.NET
|
/src/Renci.SshNet/ForwardedPort.cs
| 2.71875
| 3
|
using System;
using Renci.SshNet.Common;
namespace Renci.SshNet
{
/// <summary>
/// Base class for port forwarding functionality.
/// </summary>
public abstract class ForwardedPort : IForwardedPort
{
/// <summary>
/// Gets or sets the session.
/// </summary>
/// <value>
/// The session.
/// </value>
internal ISession Session { get; set; }
/// <summary>
/// The <see cref="Closing"/> event occurs as the forwarded port is being stopped.
/// </summary>
internal event EventHandler Closing;
/// <summary>
/// The <see cref="IForwardedPort.Closing"/> event occurs as the forwarded port is being stopped.
/// </summary>
event EventHandler IForwardedPort.Closing
{
add { Closing += value; }
remove { Closing -= value; }
}
/// <summary>
/// Gets a value indicating whether port forwarding is started.
/// </summary>
/// <value>
/// <c>true</c> if port forwarding is started; otherwise, <c>false</c>.
/// </value>
public abstract bool IsStarted { get; }
/// <summary>
/// Occurs when an exception is thrown.
/// </summary>
public event EventHandler<ExceptionEventArgs> Exception;
/// <summary>
/// Occurs when a port forwarding request is received.
/// </summary>
public event EventHandler<PortForwardEventArgs> RequestReceived;
/// <summary>
/// Starts port forwarding.
/// </summary>
public virtual void Start()
{
CheckDisposed();
if (IsStarted)
{
throw new InvalidOperationException("Forwarded port is already started.");
}
if (Session is null)
{
throw new InvalidOperationException("Forwarded port is not added to a client.");
}
if (!Session.IsConnected)
{
throw new SshConnectionException("Client not connected.");
}
Session.ErrorOccured += Session_ErrorOccured;
StartPort();
}
/// <summary>
/// Stops port forwarding.
/// </summary>
public virtual void Stop()
{
if (IsStarted)
{
StopPort(Session.ConnectionInfo.Timeout);
}
}
/// <summary>
/// Starts port forwarding.
/// </summary>
protected abstract void StartPort();
/// <summary>
/// Stops port forwarding, and waits for the specified timeout until all pending
/// requests are processed.
/// </summary>
/// <param name="timeout">The maximum amount of time to wait for pending requests to finish processing.</param>
protected virtual void StopPort(TimeSpan timeout)
{
RaiseClosing();
var session = Session;
if (session != null)
{
session.ErrorOccured -= Session_ErrorOccured;
}
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
var session = Session;
if (session != null)
{
StopPort(session.ConnectionInfo.Timeout);
Session = null;
}
}
}
/// <summary>
/// Ensures the current instance is not disposed.
/// </summary>
/// <exception cref="ObjectDisposedException">The current instance is disposed.</exception>
protected abstract void CheckDisposed();
/// <summary>
/// Raises <see cref="Exception"/> event.
/// </summary>
/// <param name="exception">The exception.</param>
protected void RaiseExceptionEvent(Exception exception)
{
Exception?.Invoke(this, new ExceptionEventArgs(exception));
}
/// <summary>
/// Raises <see cref="RequestReceived"/> event.
/// </summary>
/// <param name="host">Request originator host.</param>
/// <param name="port">Request originator port.</param>
protected void RaiseRequestReceived(string host, uint port)
{
RequestReceived?.Invoke(this, new PortForwardEventArgs(host, port));
}
/// <summary>
/// Raises the <see cref="IForwardedPort.Closing"/> event.
/// </summary>
private void RaiseClosing()
{
Closing?.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// Handles session ErrorOccured event.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="ExceptionEventArgs"/> instance containing the event data.</param>
private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
{
RaiseExceptionEvent(e.Exception);
}
}
}
|
734197b1a764f09f6695fb9a4798cffcf101312d
|
C#
|
ludekvesely/4IT449-block-breaker
|
/vesl00_4IT449_semestralka/DataObjects/HighscoreDO.cs
| 2.921875
| 3
|
using System;
using System.Text;
using System.Data.SqlClient;
using vesl00_4IT449_semestralka;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using vesl00_4IT449_semestralka.Models;
namespace vesl00_4IT449_semestralka.DataObjects
{
// Hoghscore - nicks and points pairs
class HighscoreDO
{
public int Score { get; set; }
public string Nick { get; set; }
// Get top scores
public static List<HighscoreDO> GetHighscores()
{
using (HighscoreEntities context =
new HighscoreEntities())
{
return context.Highscores
.Select(x => new HighscoreDO()
{
Nick = x.Nick,
Score = x.Score
})
.OrderByDescending(x => x.Score)
.Take(10)
.ToList();
}
}
// Add new score
public static void Store(string Nick, int Score)
{
using (HighscoreEntities context =
new HighscoreEntities())
{
Highscore newItem = new Highscore();
newItem.Nick = Nick;
newItem.Score = Score;
context.Highscores.Add(newItem);
context.SaveChanges();
}
}
}
}
|
632112f485478f7111f9874f6d02682c8f7e46d3
|
C#
|
BagautdinovRen/UdpApp
|
/Udp_client/Udp_client/Program.cs
| 2.953125
| 3
|
using System;
using System.IO;
using System.Net;
using System.Diagnostics;
using System.Net.Sockets;
using System.Text;
using System.Xml.Serialization;
public class UdpFileClient
{
// Детали файла
[Serializable]
public class FileDetails
{
public string FILETYPE = "";
public long FILESIZE = 0;
}
private static FileDetails fileDet;
// Поля, связанные с UdpClient
private static int localPort = 5002;
private static UdpClient receivingUdpClient = new UdpClient(localPort);
private static IPEndPoint RemoteIpEndPoint = null;
private static FileStream fs;
private static byte[] receiveBytes = new byte[0];
[STAThread]
static void Main(string[] args)
{
// Получаем информацию о файле
GetFileDetails();
// Подтверждаем получение
SendResponse();
}
private static void GetFileDetails()
{
try
{
Console.WriteLine("-----------*******Ожидание информации о файле от сервера*******-----------");
// Получаем информацию о файле
receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
Console.WriteLine("----Информация о файле получена!");
XmlSerializer fileSerializer = new XmlSerializer(typeof(FileDetails));
MemoryStream stream1 = new MemoryStream();
// Считываем информацию о файле
stream1.Write(receiveBytes, 0, receiveBytes.Length);
stream1.Position = 0;
// Вызываем метод Deserialize
fileDet = (FileDetails)fileSerializer.Deserialize(stream1);
Console.WriteLine("Получен файл типа ." + fileDet.FILETYPE +
" имеющий размер " + fileDet.FILESIZE.ToString() + " байт");
}
catch (Exception eR)
{
Console.WriteLine(eR.ToString());
}
}
private static void SendResponse()
{
Console.WriteLine("Скачать файл?");
string response = Console.ReadLine();
byte[] bytes = Encoding.Unicode.GetBytes(response);
try
{
// Отправляем ответ серверу
receivingUdpClient.Send(bytes, bytes.Length, RemoteIpEndPoint);
}
catch (Exception e)
{
Console.WriteLine("Возникла ошибка при отправке подтвержения: " + e.Message);
return;
}
if (response.ToLower() == "да")
{
// Получаем файл
ReceiveFile();
return;
}
Console.WriteLine("Скачивание файла отменено");
Console.ReadLine();
}
public static void ReceiveFile()
{
try
{
Console.WriteLine("-----------*******Ожидайте получение файла*******-----------");
fs = new FileStream("temp." + fileDet.FILETYPE, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
Console.WriteLine("Скачивание файла запущено!");
while (true)
{
receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
// theendfile - последняя датаграмма
if (Encoding.Unicode.GetString(receiveBytes) == "theendfile")
{
break;
}
// Записываем полученную датаграмму в файл
fs.Write(receiveBytes, 0, receiveBytes.Length);
}
Console.WriteLine("----Файл сохранен...");
Console.WriteLine("-------Открытие файла------");
// Открываем файл связанный с ним программой
Process.Start(fs.Name);
}
catch (Exception eR)
{
Console.WriteLine(eR.ToString());
}
finally
{
fs.Close();
receivingUdpClient.Close();
Console.Read();
}
}
}
|
36d2e0a1d68a8cd9f82a556a81dfb1876a85bbf2
|
C#
|
Roman-Port/RaptorSDR
|
/Plugins/RomanPort.AudioOPUS/server/OGG/OggEncoder.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace RomanPort.AudioOPUS.OGG
{
public class OggEncoder
{
public OggEncoder()
{
//Generate random serial number
serialNumber = new Random().Next();
}
private int serialNumber = 0;
private int sequenceNumber = 0;
private static uint[] TABLE = new uint[]
{
0x00000000, 0xB71DC104, 0x6E3B8209, 0xD926430D, 0xDC760413, 0x6B6BC517,
0xB24D861A, 0x0550471E, 0xB8ED0826, 0x0FF0C922, 0xD6D68A2F, 0x61CB4B2B,
0x649B0C35, 0xD386CD31, 0x0AA08E3C, 0xBDBD4F38, 0x70DB114C, 0xC7C6D048,
0x1EE09345, 0xA9FD5241, 0xACAD155F, 0x1BB0D45B, 0xC2969756, 0x758B5652,
0xC836196A, 0x7F2BD86E, 0xA60D9B63, 0x11105A67, 0x14401D79, 0xA35DDC7D,
0x7A7B9F70, 0xCD665E74, 0xE0B62398, 0x57ABE29C, 0x8E8DA191, 0x39906095,
0x3CC0278B, 0x8BDDE68F, 0x52FBA582, 0xE5E66486, 0x585B2BBE, 0xEF46EABA,
0x3660A9B7, 0x817D68B3, 0x842D2FAD, 0x3330EEA9, 0xEA16ADA4, 0x5D0B6CA0,
0x906D32D4, 0x2770F3D0, 0xFE56B0DD, 0x494B71D9, 0x4C1B36C7, 0xFB06F7C3,
0x2220B4CE, 0x953D75CA, 0x28803AF2, 0x9F9DFBF6, 0x46BBB8FB, 0xF1A679FF,
0xF4F63EE1, 0x43EBFFE5, 0x9ACDBCE8, 0x2DD07DEC, 0x77708634, 0xC06D4730,
0x194B043D, 0xAE56C539, 0xAB068227, 0x1C1B4323, 0xC53D002E, 0x7220C12A,
0xCF9D8E12, 0x78804F16, 0xA1A60C1B, 0x16BBCD1F, 0x13EB8A01, 0xA4F64B05,
0x7DD00808, 0xCACDC90C, 0x07AB9778, 0xB0B6567C, 0x69901571, 0xDE8DD475,
0xDBDD936B, 0x6CC0526F, 0xB5E61162, 0x02FBD066, 0xBF469F5E, 0x085B5E5A,
0xD17D1D57, 0x6660DC53, 0x63309B4D, 0xD42D5A49, 0x0D0B1944, 0xBA16D840,
0x97C6A5AC, 0x20DB64A8, 0xF9FD27A5, 0x4EE0E6A1, 0x4BB0A1BF, 0xFCAD60BB,
0x258B23B6, 0x9296E2B2, 0x2F2BAD8A, 0x98366C8E, 0x41102F83, 0xF60DEE87,
0xF35DA999, 0x4440689D, 0x9D662B90, 0x2A7BEA94, 0xE71DB4E0, 0x500075E4,
0x892636E9, 0x3E3BF7ED, 0x3B6BB0F3, 0x8C7671F7, 0x555032FA, 0xE24DF3FE,
0x5FF0BCC6, 0xE8ED7DC2, 0x31CB3ECF, 0x86D6FFCB, 0x8386B8D5, 0x349B79D1,
0xEDBD3ADC, 0x5AA0FBD8, 0xEEE00C69, 0x59FDCD6D, 0x80DB8E60, 0x37C64F64,
0x3296087A, 0x858BC97E, 0x5CAD8A73, 0xEBB04B77, 0x560D044F, 0xE110C54B,
0x38368646, 0x8F2B4742, 0x8A7B005C, 0x3D66C158, 0xE4408255, 0x535D4351,
0x9E3B1D25, 0x2926DC21, 0xF0009F2C, 0x471D5E28, 0x424D1936, 0xF550D832,
0x2C769B3F, 0x9B6B5A3B, 0x26D61503, 0x91CBD407, 0x48ED970A, 0xFFF0560E,
0xFAA01110, 0x4DBDD014, 0x949B9319, 0x2386521D, 0x0E562FF1, 0xB94BEEF5,
0x606DADF8, 0xD7706CFC, 0xD2202BE2, 0x653DEAE6, 0xBC1BA9EB, 0x0B0668EF,
0xB6BB27D7, 0x01A6E6D3, 0xD880A5DE, 0x6F9D64DA, 0x6ACD23C4, 0xDDD0E2C0,
0x04F6A1CD, 0xB3EB60C9, 0x7E8D3EBD, 0xC990FFB9, 0x10B6BCB4, 0xA7AB7DB0,
0xA2FB3AAE, 0x15E6FBAA, 0xCCC0B8A7, 0x7BDD79A3, 0xC660369B, 0x717DF79F,
0xA85BB492, 0x1F467596, 0x1A163288, 0xAD0BF38C, 0x742DB081, 0xC3307185,
0x99908A5D, 0x2E8D4B59, 0xF7AB0854, 0x40B6C950, 0x45E68E4E, 0xF2FB4F4A,
0x2BDD0C47, 0x9CC0CD43, 0x217D827B, 0x9660437F, 0x4F460072, 0xF85BC176,
0xFD0B8668, 0x4A16476C, 0x93300461, 0x242DC565, 0xE94B9B11, 0x5E565A15,
0x87701918, 0x306DD81C, 0x353D9F02, 0x82205E06, 0x5B061D0B, 0xEC1BDC0F,
0x51A69337, 0xE6BB5233, 0x3F9D113E, 0x8880D03A, 0x8DD09724, 0x3ACD5620,
0xE3EB152D, 0x54F6D429, 0x7926A9C5, 0xCE3B68C1, 0x171D2BCC, 0xA000EAC8,
0xA550ADD6, 0x124D6CD2, 0xCB6B2FDF, 0x7C76EEDB, 0xC1CBA1E3, 0x76D660E7,
0xAFF023EA, 0x18EDE2EE, 0x1DBDA5F0, 0xAAA064F4, 0x738627F9, 0xC49BE6FD,
0x09FDB889, 0xBEE0798D, 0x67C63A80, 0xD0DBFB84, 0xD58BBC9A, 0x62967D9E,
0xBBB03E93, 0x0CADFF97, 0xB110B0AF, 0x060D71AB, 0xDF2B32A6, 0x6836F3A2,
0x6D66B4BC, 0xDA7B75B8, 0x035D36B5, 0xB440F7B1, 0x00000001
};
public int WriteOggFrame(byte[] buffer, byte[] data, int dataLen, long granulePos, byte flag)
{
//Prepare
int used = 0;
//Capture pattern, "OggS"
buffer[used++] = (byte)'O';
buffer[used++] = (byte)'g';
buffer[used++] = (byte)'g';
buffer[used++] = (byte)'S';
//Version
buffer[used++] = 0x00;
//Flag
buffer[used++] = flag;
//Granule position
BitConverter.GetBytes(granulePos).CopyTo(buffer, used);
used += 8;
//Bitstream sequence number
BitConverter.GetBytes(serialNumber).CopyTo(buffer, used);
used += 4;
//Page sequence number
BitConverter.GetBytes(sequenceNumber++).CopyTo(buffer, used);
used += 4;
//CRC, which we'll set later
int crcPos = used;
buffer[used++] = 0;
buffer[used++] = 0;
buffer[used++] = 0;
buffer[used++] = 0;
//Write page segments
int segmentsCountLoc = used++;
int segmentsCount = 0;
for (int i = dataLen; i >= 0; i -= 255)
{
buffer[used++] = (byte)Math.Min(255, i);
segmentsCount++;
}
buffer[segmentsCountLoc] = (byte)segmentsCount;
//Copy data
Array.Copy(data, 0, buffer, used, dataLen);
used += dataLen;
//Calculate CRC
uint crc = 0;
for (int i = 0; i < used; i++)
crc = TABLE[(crc & 0xff) ^ buffer[i]] ^ (crc >> 8);
byte[] crcBytes = BitConverter.GetBytes(crc);
Array.Reverse(crcBytes);
crcBytes.CopyTo(buffer, crcPos);
return used;
}
public static byte[] CreateOpusHeader(byte channelCount, ushort preSkip, int sampleRate, ushort outputGain)
{
byte[] header = new byte[19];
//Magic
header[0] = (byte)'O';
header[1] = (byte)'p';
header[2] = (byte)'u';
header[3] = (byte)'s';
header[4] = (byte)'H';
header[5] = (byte)'e';
header[6] = (byte)'a';
header[7] = (byte)'d';
//Version
header[8] = 0x01;
//Channels
header[9] = channelCount;
//Pre-skip
BitConverter.GetBytes(preSkip).CopyTo(header, 10);
//Sample rate
BitConverter.GetBytes(sampleRate).CopyTo(header, 12);
//Gain
BitConverter.GetBytes(outputGain).CopyTo(header, 16);
//Channel map
header[18] = 0x00;
return header;
}
public static byte[] CreateOpusTags(string vendor, Dictionary<string, string> comments)
{
//Calculate length
int len = 16 + Encoding.UTF8.GetByteCount(vendor);
foreach (var c in comments)
len += Encoding.UTF8.GetByteCount(c.Key) + 1 + Encoding.UTF8.GetByteCount(c.Value);
//Create buffer
byte[] buffer = new byte[len];
int offset = 0;
//Write magic
buffer[offset++] = (byte)'O';
buffer[offset++] = (byte)'p';
buffer[offset++] = (byte)'u';
buffer[offset++] = (byte)'s';
buffer[offset++] = (byte)'T';
buffer[offset++] = (byte)'a';
buffer[offset++] = (byte)'g';
buffer[offset++] = (byte)'s';
//Write vendor string
len = Encoding.UTF8.GetBytes(vendor, 0, vendor.Length, buffer, offset + 4);
BitConverter.GetBytes(len).CopyTo(buffer, offset);
offset += len + 4;
//Write comment count
BitConverter.GetBytes(comments.Count).CopyTo(buffer, offset);
offset += 4;
//Write comments
foreach (var c in comments)
{
//Write text
len = Encoding.UTF8.GetBytes(c.Key, 0, c.Key.Length, buffer, offset + 4);
len += Encoding.UTF8.GetBytes("=", 0, 1, buffer, offset + 4 + len);
len += Encoding.UTF8.GetBytes(c.Value, 0, c.Value.Length, buffer, offset + 4 + len);
//Write length
BitConverter.GetBytes(len).CopyTo(buffer, offset);
offset += len + 4;
}
return buffer;
}
}
}
|
8d6c9b8a7787f3e95a0022b112739982caea54c3
|
C#
|
metrowave/UnityFramework
|
/Framework/LocalisationSystem/LocalisedTextMesh.cs
| 2.671875
| 3
|
using UnityEngine;
namespace Framework
{
namespace LocalisationSystem
{
[ExecuteInEditMode()]
[RequireComponent(typeof(TextMesh))]
public class LocalisedTextMesh : MonoBehaviour
{
#region Public Data
public LocalisedStringRef _text;
#endregion
#region Private Data
private TextMesh _textMesh;
#endregion
#region MonoBehaviour
void Awake()
{
_textMesh = GetComponent<TextMesh>();
RefreshText();
}
void Update()
{
RefreshText();
}
#endregion
#region Private Methods
public void RefreshText()
{
string text = _text.GetLocalisedString();
if (_textMesh.text != text)
{
_textMesh.text = text;
}
}
#endregion
}
}
}
|
eac21280a45dc595fd3d7bb5aae55843a4827284
|
C#
|
Shakkozu/ComissionGenerator
|
/ClassLibrary/DataModels/ClientMVCModel.cs
| 2.796875
| 3
|
using ExpressiveAnnotations.Attributes;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
using System.Web.Mvc;
namespace ClassLibrary.DataModels
{
public class ClientMVCModel
{
public int Id { get; set; }
[Display(Name = "Email Address")]
[EmailAddress]
[Required]
public string EmailAddress { get; set; }
[Required]
[StringLength(30, MinimumLength = 2)]
public string Street { get; set; }
[Required]
[StringLength(60, MinimumLength = 2)]
public string City { get; set; }
[Required]
[Display(Name = "Postal Code")]
[RegularExpression(@"\d{2}[\s\-]?\d{3}$", ErrorMessage = "Invalid postal code, valid format:\n ##-###")]
public string PostalCode { get; set; }
[Display(Name = "Contact Number")]
[Required]
[RegularExpression(@"^(\+\d{2})?\s?\d{3}[\s\-]?\d{3}[\s\-]?\d{3}$", ErrorMessage = "Invalid phone number, valid format:\n ###-###-###")]
public string PhoneNumber { get; set; }
[RequiredIf("Company == true", ErrorMessage = "\"NIP\" field is required, when \"Company\" option is checked")]
[AssertThat(@"IsRegexMatch(NIP, '^\\d{3}[\\-\\s]?\\d{3}[\\-\\s]?\\d{2}[\\-\\s]?\\d{2}$')", ErrorMessage = "Invalid NIP number, valid format:\n ###-###-##-##")]
public string NIP { get; set; } = "";
[RequiredIf("Company == false", ErrorMessage = "\"Name\" field is required, when \"Company\" option is not checked" )]
[StringLength(60, MinimumLength = 2)]
public string Name { get; set; }
[RequiredIf("Company == false", ErrorMessage = "\"Last Name\" field is required, when \"Company\" option is not checked")]
[StringLength(60, MinimumLength = 3)]
public string LastName { get; set; }
[RequiredIf("Company == true", ErrorMessage = "\"Company Name\" field is required, because \"Company\" option is checked" )]
[Display(Name = "Company Name")]
public string CompanyName { get; set; } = "";
public bool Company { get; set; } = false;
[Display(Name = "Full Name")]
public string FullName { get
{
if(CompanyName != null && CompanyName.Length > 0 && NIP != null && NIPModel.Validate(NIP))
{
return $"\"{ CompanyName }\" { Name } { LastName }";
}
else
{
return $"{ Name } { LastName }";
}
} }
}
}
|
e1172f1e46962a41ca012999c81cbfb078c87150
|
C#
|
mrmacsi/ASP.NET-SignalR-Chatroom
|
/BL/ChatProcess.cs
| 2.828125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using myChat.Models.DB;
namespace myChat.BL
{ //uygulama için iş mantıklarını sağlayan katman
public class ChatProcess
{
chatDBEntities e = new chatDBEntities();
//üyelik alındığında kullanıcı verı tabanına kaydedilir
public string createUser(User user)
{
int kullaniciSayisi = ((from x in e.User
where x.username == user.username
select x).ToList<User>()).Count;
if (kullaniciSayisi > 0)
{
return "var";
}
else
{
e.User.Add(user);
e.SaveChanges();
return "eklendi";
}
}
//kullanıcı listesi döndürür
public List<User> userListGetir()
{
List<User> userlistemiz = ((from x in e.User
select x).ToList<User>());
return userlistemiz;
}
//chat veritabanına eklendi
public string grupchatKaydet(GroupChat chat)
{
chat.time = DateTime.Now;
e.GroupChat.Add(chat);
return "yorum eklendi";
}
//mevcut grupların listesini verir
public List<Group> groupListGetir()
{
List<Group> grouplistemiz = ((from x in e.Group
select x).ToList<Group>());
return grouplistemiz;
}
//üyrlik kontrolü. varsa 1den büyük
public int loginCheck(string username,string password)
{
int kullaniciSayisi = ((from x in e.User
where x.username == username && x.password==password
select x).ToList<User>()).Count;
return kullaniciSayisi;
}
}
}
|
fbb8340f4b624939dce53726776473bc5206163b
|
C#
|
zeWizard/LinqToLdap
|
/LinqToLdap/Collections/OriginalValuesCollection.cs
| 2.9375
| 3
|
/*
* LINQ to LDAP
* http://linqtoldap.codeplex.com/
*
* Copyright Alan Hatter (C) 2010-2014
*
* This project is subject to licensing restrictions. Visit http://linqtoldap.codeplex.com/license for more information.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace LinqToLdap.Collections
{
/// <summary>
/// Represents a collection
/// </summary>
[Serializable]
public class OriginalValuesCollection : Collection<SerializableKeyValuePair<string, object>>
{
/// <summary>
/// Default constructor
/// </summary>
public OriginalValuesCollection() : base(new List<SerializableKeyValuePair<string, object>>()){}
/// <summary>
/// Constructor that takes list of values.
/// </summary>
/// <param name="values"></param>
public OriginalValuesCollection(IList<SerializableKeyValuePair<string, object>> values) : base(values) { }
/// <summary>
/// Case insensitive key accessor for the value.
/// </summary>
/// <param name="key">The property name</param>
/// <returns></returns>
public object this[String key]
{
get
{
return this.Where(kvp => kvp.Key.Equals(key, StringComparison.OrdinalIgnoreCase))
.Select(kvp => kvp.Value)
.FirstOrDefault();
}
}
}
}
|
1ec171ae8c63c440458c221b0984bf1fce41e3a0
|
C#
|
charlie-a-maxwell/CardGame
|
/CardGame/CardGame/CardGame/CardClass.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Storage;
using System.Xml.Serialization;
namespace CardGame
{
public class MoveLocation
{
public MoveLocation()
{
x = 0;
y = 0;
modifier = 0;
}
public MoveLocation(int mod)
{
x = 0;
y = 0;
modifier = mod;
}
public int x;
public int y;
public int modifier;
public override string ToString()
{
return modifier.ToString();
}
}
public class CardType
{
public string typeName;
public string textureName;
public Texture2D texture;
public Texture2D textureLarge;
[XmlIgnore]
private PlayerTurn _player;
[XmlIgnore]
private bool turnSet = false;
[XmlIgnore]
public PlayerTurn player
{
get
{
if (!turnSet)
{
if (typeName[typeName.Length - 1] == 'A')
_player = PlayerTurn.Player1;
else
_player = PlayerTurn.Player2;
turnSet = true;
}
return _player;
}
}
[XmlIgnore]
private int[,] moveOptions;
[XmlIgnore]
public int numberOfMoves = 0;
public int weight = 0;
public string moveString
{
get
{
string data = "";
for (int i = 0; i < moveOptions.GetLength(0); i++)
{
for (int j = 0; j < moveOptions.GetLength(1); j++)
{
data += moveOptions[i, j] + ",";
}
data = data.TrimEnd(',');
data += "|";
}
data = data.TrimEnd('|');
return data;
}
set
{
string data = value;
string[] rows = data.Split('|');
moveOptions = new int[rows.Length, rows[0].Split(',').Length];
int i= 0, j=0;
foreach (string col in rows)
{
foreach (string item in col.Split(','))
moveOptions[i, j++] = Convert.ToInt32(item);
j = 0;
i++;
}
}
}
[XmlIgnore]
private MoveLocation[,] _moves = null;
[XmlIgnore]
public MoveLocation[,] moves
{
get
{
if (_moves == null)
{
int[,] tempMoves;
if (player == PlayerTurn.Player1)
{
tempMoves = moveOptions;
}
else
{
tempMoves = new int[moveOptions.GetLength(0), moveOptions.GetLength(1)];
for (int i = 0; i < tempMoves.GetLength(0); i++)
{
for (int j = 0; j < tempMoves.GetLength(1); j++)
{
tempMoves[tempMoves.GetLength(0) - i - 1, j] = moveOptions[i, j];
}
}
}
_moves = ParseIntMoves(tempMoves);
}
return _moves;
}
}
public CardType()
{
}
public CardType(string name, string texName)
{
typeName = name;
textureName = texName;
moveOptions = new int[5, 5];
}
public CardType(string name, string texName, int[,] move)
{
typeName = name;
textureName = texName;
moveOptions = new int[5, 5];
SetMove(move);
}
public int GetStat()
{
return moveOptions[2,2];
}
public void SetMove(int[,] move)
{
if (move.GetLength(0) == moveOptions.GetLength(0) && move.GetLength(1) == moveOptions.GetLength(1))
{
moveOptions = (int[,])move.Clone();
}
}
public int[,] GetMove()
{
return moveOptions;
}
public void LoadTexture(ContentManager cm)
{
if (textureName != null && textureName.Length > 0 && texture == null)
{
texture = cm.Load<Texture2D>(textureName);
textureLarge = cm.Load<Texture2D>(textureName+"L");
}
}
private MoveLocation[,] ParseIntMoves(int[,] m)
{
MoveLocation[,] temp = new MoveLocation[m.GetLength(0), m.GetLength(1)];
for (int i = 0; i < temp.GetLength(0); i++)
{
for (int j = 0; j < temp.GetLength(1); j++)
{
if (m[i, j] == -999)
temp[i, j] = null;
else
{
int tempX = -1;
int tempY = -1;
int locX = 0;
int locY = 0;
int dist = int.MaxValue;
int tempDist = 0;
int midX = temp.GetLength(0) / 2;
int midY = temp.GetLength(1) / 2;
temp[i, j] = new MoveLocation(m[i, j]);
for (int k = 0; k < 9; k++)
{
locX = (k % 3) - 1;
locY = (int)(k / 3) - 1;
if ((locX + i >= 0 && locX + i < temp.GetLength(0)) && (locY + j >= 0 && locY + j < temp.GetLength(1)) && (m[locX + i, locY + j] != -999))
{
tempDist = (((locX + i) - midX) * ((locX + i) - midX)) + (((locY + j) - midY) * ((locY + j) -midY));
if (tempDist < dist)
{
tempX = locX + i;
tempY = locY + j;
dist = tempDist;
}
}
}
numberOfMoves++;
if (tempX != -1 && tempY != -1)
{
temp[i, j].x = tempX;
temp[i, j].y = tempY;
}
}
}
}
return temp;
}
}
public class CardClass
{
CardType type;
public const int cardWidth = 50;
public const int cardHeight = 75;
public PlayerTurn player
{
get
{
return type.player;
}
}
Vector2 loc;
Vector2 oldLoc;
Vector2 movingLoc;
static Color outlineColor = Color.Yellow;
static Texture2D circleTex = null;
private bool placed = false;
private bool moving = false;
public bool Selected = false;
public static void SetCircleText(Texture2D tex)
{
circleTex = tex;
}
public CardClass(CardType t)
{
type = t;
loc = new Vector2(-1, -1);
oldLoc = new Vector2(-1, -1);
movingLoc = new Vector2(-1, -1);
}
public CardClass(CardType t, PlayerTurn pt)
{
type = t;
loc = new Vector2(-1, -1);
oldLoc = new Vector2(-1, -1);
}
public void SetMoving(Vector2 v)
{
movingLoc = v;
moving = true;
}
public Vector2 GetMovingLoc()
{
return movingLoc;
}
public void EndMoving()
{
moving = false;
}
public void Render(SpriteBatch sb)
{
Render(sb, 0);
}
public void Render(SpriteBatch sb, int space)
{
Vector2 curLoc = loc;
if (moving)
{
curLoc = movingLoc;
}
SpriteEffects effect = SpriteEffects.None;
Color textColor = (player == PlayerTurn.Player1 ? Color.Black : Color.DarkRed);
if (placed && player == PlayerTurn.Player2)
effect = SpriteEffects.FlipVertically;
if (type.texture != null)
sb.Draw(type.texture, new Rectangle((int)curLoc.X, (int)curLoc.Y, cardWidth, cardHeight), null, Color.White, 0.0f, new Vector2(0, 0), effect, 0.5f);
sb.Draw(circleTex, curLoc + new Vector2((cardWidth / 2.0f) - 15, (player == PlayerTurn.Player1 || !placed ? cardHeight - 30 : 0)), null, Color.White, 0.0f, new Vector2(0, 0), 0.18f, SpriteEffects.None, 0.0f);
Screen.DrawText(sb, type.GetStat().ToString(), curLoc + new Vector2((cardWidth / 2.0f) - 9, (player == PlayerTurn.Player1 || !placed ? cardHeight - 30 : 0) + 4), textColor, 1.0f, effect);
if (Selected)
{
// Incoming Magic numbers!
int originX = 30;
int originY = 30;
// TEST OF NEW AND IMPROVED TEXTURE LARGES!
int width = cardWidth * 3;
int height = cardHeight * 3;
int xMargin = 5;
int yMargin = 5;
//int[,] cardMove = type.GetMove(); //GetMove();
Vector2 origin = new Vector2();
Vector2 hor = new Vector2(CardClass.cardWidth, 0);
Vector2 ver = new Vector2(0, CardClass.cardHeight);
//int stat = type.GetStat();
if (type.textureLarge != null)
sb.Draw(type.textureLarge, new Rectangle(originX, originX, width, height), null, Color.White, 0.0f, new Vector2(0, 0), SpriteEffects.None, 0.5f);
if (oldLoc.X != -1 && oldLoc.Y != -1)
{
Color border = outlineColor;
for (int i = 0; i < type.moves.GetLength(0); i++)
{
for (int j = 0; j < type.moves.GetLength(1); j++)
{
if (type.moves[i, j] != null)
{
origin = new Vector2((int)loc.X + (cardWidth + space) * (j - 2), (int)loc.Y + (cardHeight + space) * (i - 2));
if (origin == oldLoc)
border = Color.DarkRed;
else
border = outlineColor;
Screen.DrawLine(sb, origin, origin + hor, border, 0.9f);
Screen.DrawLine(sb, origin, origin + ver, border, 0.9f);
Screen.DrawLine(sb, origin + ver, origin + ver + hor, border, 0.9f);
Screen.DrawLine(sb, origin + hor, origin + hor + ver, border, 0.9f);
}
}
}
}
}
}
public CardType GetCardType()
{
return type;
}
public void LoadTexture(ContentManager cm)
{
type.LoadTexture(cm);
if (circleTex == null)
circleTex = cm.Load<Texture2D>("Circle");
}
public void SetLocation(Vector2 l, bool updateLoc)
{
if (updateLoc)
{
oldLoc = loc;
placed = true;
}
loc = l;
}
public Vector2 GetPrevLocation()
{
return oldLoc;
}
public Vector2 GetLoc()
{
return loc;
}
public bool Intersect(Vector2 point)
{
if (point.X > loc.X && point.Y > loc.Y && point.X < loc.X + cardWidth && point.Y < loc.Y + cardHeight)
return true;
return false;
}
public MoveLocation[,] GetMove()
{
return type.moves;
}
}
public class Hand
{
List<CardClass> hand;
PlayerTurn owner;
Vector2 renderLoc;
public Hand(PlayerTurn player)
{
hand = new List<CardClass>();
owner = player;
renderLoc = new Vector2(0, 0);
}
public void SetRenderLoc(Vector2 loc)
{
renderLoc = loc;
}
public bool AddCard(CardClass card)
{
if (card != null && card.player == owner)
{
Vector2 offset = new Vector2(CardClass.cardWidth, 0);
if (owner == PlayerTurn.Player1)
card.SetLocation(renderLoc + offset*hand.Count, false);
else
card.SetLocation(renderLoc - offset * hand.Count, false);
hand.Add(card);
return true;
}
return false;
}
public int Count
{
get
{
return hand.Count;
}
}
public bool RemoveCard(CardClass card)
{
bool found = false;
Vector2 offset = new Vector2(CardClass.cardWidth, 0);
int count = 0;
foreach (CardClass cc in hand)
{
if (cc == card && !found)
{
found = true;
count--;
}
else if (found)
{
if (owner == PlayerTurn.Player1)
cc.SetLocation(renderLoc + offset * count, false);
else
cc.SetLocation(renderLoc - offset * count, false);
}
count++;
}
return hand.Remove(card);
}
public CardClass SelectCard(int i)
{
if (i >= 0 && i < hand.Count)
{
return hand[i];
}
return null;
}
public CardClass SelectCard(Vector2 pos)
{
CardClass found = null;
foreach (CardClass card in hand)
{
if (card.Intersect(pos))
{
found = card;
break;
}
}
return found;
}
public CardClass GetSelectedCard()
{
CardClass found = null;
foreach (CardClass card in hand)
{
if (card.Selected)
{
found = card;
break;
}
}
return found;
}
public void Render(SpriteBatch sb)
{
Render(sb, renderLoc, null);
}
public void Render(SpriteBatch sb, CardClass selectedCard)
{
Render(sb, renderLoc, selectedCard);
}
public void Render(SpriteBatch sb, Vector2 origin, CardClass selectedCard)
{
CardClass card;
for (int i = 0; i < hand.Count; i++ )
{
card = hand[i];
card.Render(sb);
}
}
public void Clear()
{
hand.Clear();
}
public List<CardClass> GetCardList()
{
return hand;
}
}
public class Deck
{
Stack<CardClass> deck;
PlayerTurn owner;
static Random rand = new Random();
Vector2 renderLoc;
Texture2D deckTex;
public Deck(PlayerTurn player)
{
deck = new Stack<CardClass>();
owner = player;
}
public void SetTexure(Texture2D tex)
{
deckTex = tex;
}
public void SetLoc(Vector2 v)
{
renderLoc = v;
}
public CardClass GetTopCard()
{
if (deck.Count > 0)
return deck.Pop();
return null;
}
public void ShuffleCurrentDeck()
{
CardClass[] deckArray = deck.ToArray();
int first, second;
int length = deckArray.Length;
CardClass temp;
for (int i = 0; i < 30; i++)
{
first = rand.Next(length);
second = rand.Next(length);
temp = deckArray[first];
deckArray[first] = deckArray[second];
deckArray[second] = temp;
}
deck = new Stack<CardClass>(deckArray);
}
public void Render(SpriteBatch sb)
{
if (deckTex != null && deck.Count > 0)
sb.Draw(deckTex, new Rectangle((int)renderLoc.X, (int)renderLoc.Y, CardClass.cardWidth, CardClass.cardHeight), Color.White);
}
public bool Intersect(Vector2 point)
{
if (point.X > renderLoc.X && point.Y > renderLoc.Y && point.X < renderLoc.X + CardClass.cardWidth && point.Y < renderLoc.Y + CardClass.cardHeight)
return true;
return false;
}
public bool AddCard(CardClass card)
{
if (card.player == owner)
{
deck.Push(card);
return true;
}
return false;
}
public void SendToGraveYard()
{
}
public void ClearDeck()
{
deck.Clear();
}
}
}
|
33bf659695984a3a8bf1e6c1137f403c4241e910
|
C#
|
DeveshVagal/C-Sharp-Projects
|
/BSCITATTENDENCE/loginapprovalandstaffupdate.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
namespace BSCITATTENDENCE
{
public partial class loginapprovalandstaffupdate : Form
{
string conn = System.Configuration.ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
public loginapprovalandstaffupdate()
{
InitializeComponent();
}
private void loginapprovalandstaffupdate_Load(object sender, EventArgs e)
{
label13.Text = LoginPage.passingText;
SqlConnection con = new SqlConnection(conn);
con.Open();
SqlCommand cmd1 = new SqlCommand("select Name from LOGIN", con);
SqlDataReader reader;
reader = cmd1.ExecuteReader();
DataTable dt1 = new DataTable();
dt1.Columns.Add("Name", typeof(string));
dt1.Load(reader);
comboBox3.DisplayMember = "Name";
comboBox3.DataSource = dt1;
con.Close();
}
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
string id = comboBox3.SelectedValue.ToString();
button1.Visible = true;
button2.Visible = true;
SqlConnection con = new SqlConnection(conn);
string query = "select * from LOGIN where Name = '" + comboBox3.Text + "' ";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dbr;
try
{
con.Open();
dbr = cmd.ExecuteReader();
while (dbr.Read())
{
string username = (string)dbr["USERNAME"].ToString();
string password = (string)dbr["PASSWORD"].ToString();
string gender = (string)dbr["Gender"].ToString();
string contactnumber = (string)dbr["ContactNumber"].ToString();
string email = (string)dbr["EmailId"].ToString();
string doj = (string)dbr["DateOfJoining"].ToString();
string address = (string)dbr["Address"].ToString();
string qualification = (string)dbr["Qualification"].ToString();
string status = (string)dbr["Status"].ToString();
string pastexp = (string)dbr["PastExperiences"].ToString();
string classcourse = (string)dbr["CurrentClassCourse"].ToString();
textBox1.Text = username;
textBox2.Text = password;
textBox3.Text = password;
comboBox4.Text = gender;
textBox5.Text = contactnumber;
textBox6.Text = email;
dateTimePicker1.Text = doj;
textBox7.Text = address;
textBox8.Text = qualification;
comboBox2.Text = status;
textBox9.Text = pastexp;
comboBox1.Text = classcourse;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
private void button2_Click(object sender, EventArgs e)
{
if (textBox2.Text == textBox3.Text)
{
SqlConnection con = new SqlConnection(conn);
con.Open();
SqlCommand cmd = new SqlCommand("UPDATE LOGIN SET USERNAME ='"+textBox1.Text+"', PASSWORD ='"+textBox3.Text+"', Gender='"+comboBox4.Text+"', ContactNumber ='"+textBox5.Text+"', EmailId ='"+textBox6.Text+"', DateOfJoining='"+dateTimePicker1.Text+"', Address ='"+textBox7.Text+"', Qualification ='"+textBox8.Text+"', PastExperiences ='"+textBox9.Text+"', CurrentClassCourse ='"+comboBox1.Text+"', Status ='"+comboBox2.Text+"' WHERE Name='"+comboBox3.Text+"'", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Details Updated Successfully");
AdminSection admin = new AdminSection();
admin.Show();
this.Hide();
con.Close();
Clear();
}
else
{
MessageBox.Show("Password Does not Match..");
Clear();
}
}
private void Clear()
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox5.Text = "";
textBox6.Text = "";
textBox7.Text = "";
textBox8.Text = "";
textBox9.Text = "";
comboBox1.SelectedIndex = -1;
comboBox2.SelectedIndex = -1;
error();
}
private void textBox5_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
private void textBox6_Validating(object sender, CancelEventArgs e)
{
if (textBox6.Text == string.Empty)
{
errorProvider1.SetError(textBox6, "Please Enter the Email Address of the Staff.");
}
else
{
errorProvider1.SetError(textBox6, "");
}
Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
Match match = regex.Match(textBox6.Text);
if (match.Success)
errorProvider1.SetError(textBox6, "");
else
errorProvider1.SetError(textBox6, "Please Enter a Valid Email Address");
}
private void textBox5_Validated(object sender, EventArgs e)
{
}
private void textBox5_Validating(object sender, CancelEventArgs e)
{
if (textBox5.Text == string.Empty)
{
errorProvider1.SetError(textBox5, "Please Enter the Contact Number of the Staff.");
}
else
{
errorProvider1.SetError(textBox5, "");
}
}
private void textBox7_Validating(object sender, CancelEventArgs e)
{
if (textBox7.Text == string.Empty)
{
errorProvider1.SetError(textBox7, "Please Enter the Address of the Staff.");
}
else
{
errorProvider1.SetError(textBox7, "");
}
}
private void textBox8_Validating(object sender, CancelEventArgs e)
{
if (textBox8.Text == string.Empty)
{
errorProvider1.SetError(textBox8, "Please Enter the Qualification of the Staff.");
}
else
{
errorProvider1.SetError(textBox8, "");
}
}
private void textBox9_Validating(object sender, CancelEventArgs e)
{
if (textBox9.Text == string.Empty)
{
errorProvider1.SetError(textBox9, "Please Enter the Past Experiences of the Staff.");
}
else
{
errorProvider1.SetError(textBox9, "");
}
}
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text == string.Empty)
{
errorProvider1.SetError(textBox1, "Please Enter the Username.");
}
else
{
errorProvider1.SetError(textBox1, "");
}
}
private void textBox2_Validating(object sender, CancelEventArgs e)
{
if (textBox2.Text == string.Empty)
{
errorProvider1.SetError(textBox2, "Please Enter the Password.");
}
else
{
errorProvider1.SetError(textBox2, "");
}
}
private void textBox3_Validating(object sender, CancelEventArgs e)
{
if (textBox3.Text == string.Empty)
{
errorProvider1.SetError(textBox3, "Please Confirm the Password");
}
else
{
errorProvider1.SetError(textBox3, "");
}
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
if (textBox5.Text != "")
{
button1.Visible = true;
button2.Visible = true;
}
else
{
button1.Visible = false;
button2.Visible = false;
}
if (textBox5.Text == "")
{
errorProvider1.SetError(textBox5, "Please Enter the Contact Number of the Staff.");
}
else
{
errorProvider1.SetError(textBox5, "");
}
}
private void textBox6_TextChanged(object sender, EventArgs e)
{
if (textBox6.Text != "")
{
button1.Visible = true;
button2.Visible = true;
}
else
{
button1.Visible = false;
button2.Visible = false;
}
if (textBox6.Text == "")
{
errorProvider1.SetError(textBox6, "Please Enter the Email Address of the Staff.");
}
else
{
errorProvider1.SetError(textBox6, "");
}
}
private void textBox7_TextChanged(object sender, EventArgs e)
{
if (textBox7.Text != "")
{
button1.Visible = true;
button2.Visible = true;
}
else
{
button1.Visible = false;
button2.Visible = false;
}
if (textBox7.Text == "")
{
errorProvider1.SetError(textBox7, "Please Enter the Address of the Staff.");
}
else
{
errorProvider1.SetError(textBox7, "");
}
}
private void textBox8_TextChanged(object sender, EventArgs e)
{
if (textBox8.Text != "")
{
button1.Visible = true;
button2.Visible = true;
}
else
{
button1.Visible = false;
button2.Visible = false;
}
if (textBox8.Text == "")
{
errorProvider1.SetError(textBox8, "Please Enter the Qualification of the Staff.");
}
else
{
errorProvider1.SetError(textBox8, "");
}
}
private void textBox9_TextChanged(object sender, EventArgs e)
{
if (textBox9.Text != "")
{
button1.Visible = true;
button2.Visible = true;
}
else
{
button1.Visible = false;
button2.Visible = false;
}
if (textBox9.Text == "")
{
errorProvider1.SetError(textBox9, "Please Enter the Past Expereinces of the Staff.");
}
else
{
errorProvider1.SetError(textBox9, "");
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
button1.Visible = true;
button2.Visible = true;
}
else
{
button1.Visible = false;
button2.Visible = false;
}
if (textBox1.Text == "")
{
errorProvider1.SetError(textBox1, "Please Enter the Username.");
}
else
{
errorProvider1.SetError(textBox1, "");
}
SqlConnection con = new SqlConnection(conn);
SqlDataAdapter sda = new SqlDataAdapter("Select count(*) From LOGIN Where USERNAME = '" + textBox1.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (int.Parse(dt.Rows[0][0].ToString()) == 0)
{
label12.Text = textBox1.Text + " Available";
this.label12.ForeColor = System.Drawing.Color.Green;
if (textBox1.Text == "")
{
label12.Text = "";
}
}
else
{
label12.Text = textBox1.Text + " not Available";
this.label12.ForeColor = System.Drawing.Color.Red;
if (textBox1.Text == "")
{
label12.Text = "";
}
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
if (textBox2.Text != "")
{
button1.Visible = true;
button2.Visible = true;
}
else
{
button1.Visible = false;
button2.Visible = false;
}
if (textBox2.Text == "")
{
errorProvider1.SetError(textBox2, "Please Enter the Password");
}
else
{
errorProvider1.SetError(textBox2, "");
}
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
if (textBox3.Text != "")
{
button1.Visible = true;
button2.Visible = true;
}
else
{
button1.Visible = false;
button2.Visible = false;
}
if (textBox3.Text == "")
{
errorProvider1.SetError(textBox3, "Please Confirm the password");
}
else
{
errorProvider1.SetError(textBox3, "");
}
}
private void error()
{
errorProvider1.SetError(textBox5, "Please Enter the Contact Number of the Staff.");
errorProvider1.SetError(textBox6, "Please Enter the Email Address of the Staff.");
errorProvider1.SetError(textBox7, "Please Enter the Address of the Staff.");
errorProvider1.SetError(textBox8, "Please Enter the Qualification of the Staff.");
errorProvider1.SetError(textBox9, "Please Enter the Past Experiences of the Staff.");
errorProvider1.SetError(comboBox1, "Please Enter the Current ClassCourse of the Staff.");
errorProvider1.SetError(textBox1, "Please Enter the Username.");
errorProvider1.SetError(textBox2, "Please Enter the Password.");
errorProvider1.SetError(textBox3, "Please Confirm the Password");
}
private void loginapprovalandstaffupdate_FormClosed(object sender, FormClosedEventArgs e)
{
AdminSection admin = new AdminSection();
admin.Show();
this.Hide();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("Delete from LOGIN WHERE Name='" + comboBox3.Text + "'", con);
cmd.CommandType = CommandType.Text;
try
{
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Details Deleted Successfully");
AdminSection admin = new AdminSection();
admin.Show();
this.Hide();
Clear();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void comboBox4_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox2.SelectedItem == "ADMIN")
{
textBox2.PasswordChar = '\0';
textBox3.PasswordChar = '\0';
}
else
{
textBox2.PasswordChar = '*';
textBox3.PasswordChar = '*';
}
}
private void comboBox4_TextChanged(object sender, EventArgs e)
{
if (comboBox4.Text != "")
{
button1.Visible = true;
button2.Visible = true;
}
else
{
button1.Visible = false;
button2.Visible = false;
}
}
private void comboBox3_TextChanged(object sender, EventArgs e)
{
if (comboBox3.Text != "")
{
button1.Visible = true;
button2.Visible = true;
}
else
{
button1.Visible = false;
button2.Visible = false;
}
}
private void comboBox2_TextChanged(object sender, EventArgs e)
{
if (comboBox2.Text != "")
{
button1.Visible = true;
button2.Visible = true;
}
else
{
button1.Visible = false;
button2.Visible = false;
}
}
private void comboBox1_TextChanged(object sender, EventArgs e)
{
if (comboBox1.Text != "")
{
button1.Visible = true;
button2.Visible = true;
}
else
{
button1.Visible = false;
button2.Visible = false;
}
}
}
}
|
da6da68dd0f78bf45ed8f723c39ff4bfae211575
|
C#
|
r-petrov/OOP-Course
|
/Homeworks-and-exercises/InheritanceAndAbstraction/InheritanceAndAbstraction/Program.cs
| 3.5
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using InheritanceAndAbstraction;
namespace HumanStudentAndWorker
{
class Program
{
static void Main(string[] args)
{
//List<Student> students = new List<Student>();
//for (int i = 0; i < 10; i++)
//{
// bool isStudentIncorrect = true;
// while (isStudentIncorrect)
// {
// try
// {
// Student student = new Student(Console.ReadLine(), Console.ReadLine(), Console.ReadLine());
// students.Add(student);
// isStudentIncorrect = false;
// }
// catch (ArgumentNullException)
// {
// Console.Error.WriteLine("Student's first name, last name and faculty number are mandatory");
// }
// catch (ArgumentException aex)
// {
// Console.Error.WriteLine("{0}", aex.Message);
// }
// }
//}
//List<Worker> workers = new List<Worker>();
//for (int i = 0; i < 10; i++)
//{
// bool isWorkerIncorrect = true;
// while (isWorkerIncorrect)
// {
// try
// {
// Worker worker = new Worker(Console.ReadLine(), Console.ReadLine(),
// decimal.Parse(Console.ReadLine()), int.Parse(Console.ReadLine()));
// workers.Add(worker);
// isWorkerIncorrect = false;
// }
// catch (ArgumentNullException)
// {
// Console.Error.WriteLine("Worker's first name and last name are mandatory");
// }
// catch (ArgumentOutOfRangeException)
// {
// Console.Error.WriteLine("Week salary and work hours per day cannot have negative values");
// }
// }
//}
//create and sort the students
try
{
List<Student> students = new List<Student>()
{
new Student( "Pesho", "Peshev", "123456asdf"),
new Student( "Ivaila", "Ivanova", "546786asdf"),
new Student( "Emilia", "Todorova", "088546asdf"),
new Student( "Angelina", "Ivanova", "456987asdv"),
new Student( "Teodor", "Timonov", "456789ascb"),
new Student( "Virgil", "Malushev", "455468asfc"),
new Student( "Angel", "Tomov", "321564zxcv"),
new Student( "Krum", "Asparuhov", "123456asdf"),
new Student( "Boyan", "Simeonov", "123456zxas"),
new Student( "Ognyan", "Iskrov", "123456lore"),
};
var sortedStudents = students.OrderBy(student => student.FacultyNumber);
foreach (var student in sortedStudents)
{
Console.WriteLine(student.ToString());
}
}
catch (ArgumentNullException)
{
Console.Error.WriteLine("Student's first name, last name and faculty number are mandatory");
}
catch (ArgumentException aex)
{
Console.Error.WriteLine("{0}", aex.Message);
}
//create and sort the workers
try
{
List<Worker> workers = new List<Worker>()
{
new Worker("Raya", "Petrova", 250m, 8),
new Worker("Beloslava", "Licheva", 225.8m, 8),
new Worker("Petar", "Ivanov", 321m, 9),
new Worker("Belin", "Trifonov", 225m, 8),
new Worker("Rosica", "Belova", 221.25m, 8),
new Worker("Elmir", "Nenkov", 215m, 7),
new Worker("Raya", "Dimitrova", 255m, 9),
new Worker("Polina", "Filova", 250m, 9),
new Worker("Apostol", "Krumov", 250m, 7),
new Worker("Boyan", "Simeonov", 250m, 6),
};
var sortedWorkers =
from worker in workers
orderby worker.MoneyPerHour() descending
select worker;
Console.WriteLine();
foreach (var worker in sortedWorkers)
{
Console.WriteLine(worker.ToString());
}
}
catch (ArgumentNullException)
{
Console.Error.WriteLine("Worker's first name and last name are mandatory");
}
catch (ArgumentOutOfRangeException)
{
Console.Error.WriteLine("Week salary and work hours per day cannot have negative values");
}
List<Human> people = new List<Human>()
{
new Student( "Pesho", "Peshev", "123456asdf"),
new Student( "Ivaila", "Ivanova", "546786asdf"),
new Student( "Emilia", "Todorova", "088546asdf"),
new Student( "Angelina", "Ivanova", "456987asdv"),
new Student( "Teodor", "Timonov", "456789ascb"),
new Student( "Virgil", "Malushev", "455468asfc"),
new Student( "Angel", "Tomov", "321564zxcv"),
new Student( "Krum", "Asparuhov", "123456asdf"),
new Student( "Boyan", "Simeonov", "123456zxas"),
new Student( "Ognyan", "Iskrov", "123456lore"),
new Worker("Raya", "Petrova", 250m, 8),
new Worker("Beloslava", "Licheva", 225.8m, 8),
new Worker("Petar", "Ivanov", 321m, 9),
new Worker("Belin", "Trifonov", 225m, 8),
new Worker("Rosica", "Belova", 221.25m, 8),
new Worker("Elmir", "Nenkov", 215m, 7),
new Worker("Raya", "Dimitrova", 255m, 9),
new Worker("Polina", "Filova", 250m, 9),
new Worker("Apostol", "Krumov", 250m, 7),
new Worker("Boyan", "Simeonov", 250m, 6),
};
var sortedPeople = people.OrderBy(human => human.FirstName).ThenBy(human => human.LastName);
foreach (var human in sortedPeople)
{
Console.WriteLine(human.ToString());
}
}
}
}
|
55a736bb11e9eaec3c9eeda034790138870713b5
|
C#
|
kraftvaerk/OCPI
|
/src/v2_1_1/Shared/Response.cs
| 2.96875
| 3
|
using System;
using System.ComponentModel.DataAnnotations;
namespace OCPI.DTO.v2_1_1.Shared
{
/// <summary>
/// When a request cannot be accepted, an HTTP error response code is expected including a JSON object that contains more details. HTTP status codes are described on w3.org.
/// </summary>
/// <typeparam name="T">Array or Object or String</typeparam>
public class Response<T>
{
/// <summary>
/// Contains the actual response data object or list of objects from each request,
/// depending on the cardinality of the response data, this is an array (card. * or +), or a single object (card. 1 or ?)
/// </summary>
public T data { get; set; }
/// <summary>
/// Response code, as listed in Status Codes, indicates how the request was handled.
/// To avoid confusion with HTTP codes, at least four digits are used.
/// 1xxx -- Success
/// 2xxx -- Client errors – The data sent by the client can not be processed by the server
/// 3xxx -- Server errors – The server encountered an internal error
/// </summary>
public int status_code { get; set; }
/// <summary>
/// An optional status message which may help when debugging.
/// </summary>
public string status_message { get; set; }
/// <summary>
/// The time this message was generated.
/// </summary>
[Required]
public DateTime timestamp { get; set; }
}
}
|
f9d63fd9572622bf0d8460b9efc92087a043ab40
|
C#
|
BorislavDimitrov/C-Sharp-Basics
|
/ConditionalStatementsAdvanced/MoreExercises/TruckDriver/Program.cs
| 3.484375
| 3
|
using System;
namespace TruckDriver
{
class Program
{
static void Main(string[] args)
{
string season = Console.ReadLine();
double kilometersMonthly = double.Parse(Console.ReadLine());
double priceForKm = 0.0;
if (kilometersMonthly <= 5000)
{
if (season == "Spring" || season == "Autumn")
{
priceForKm = 0.75;
}
else if (season == "Summer")
{
priceForKm = 0.90;
}
else if (season == "Winter")
{
priceForKm = 1.05;
}
}
else if (kilometersMonthly > 5000 && kilometersMonthly <= 10000)
{
if (season == "Spring" || season == "Autumn")
{
priceForKm = 0.95;
}
else if (season == "Summer")
{
priceForKm = 1.10;
}
else if (season == "Winter")
{
priceForKm = 1.25;
}
}
else if (kilometersMonthly > 10000 && kilometersMonthly <= 20000)
{
priceForKm = 1.45;
}
double money = priceForKm * kilometersMonthly * 4;
double profit = money - (money * 10 / 100);
Console.WriteLine($"{profit:F2}");
}
}
}
|
6a2ab6eb4e87b12dc64aa2b801c2521f718a4365
|
C#
|
greck2908/DataStructures
|
/C#/Leetcode/BinaryTree/ZigZagBinaryTreeTraversal.cs
| 3.421875
| 3
|
using LeetcodeSolutions.DataStructures;
using System.Collections.Generic;
namespace LeetcodeSolutions.BinaryTree
{
// Leetcode 103 - https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal
// Submission Detail - https://leetcode.com/submissions/detail/123636957/
// Use 2 Stacks
public class ZigZagBinaryTreeTraversal
{
// Tx: O(n) { n: n is the number of nodes in the binary tree}
// Sx: O(n) { n: n is the number of nodes in the binary tree}
public static IList<IList<int>> ZigzagLevelOrder(BinaryTreeNode root)
{
IList<IList<int>> outerList = new List<IList<int>>();
Stack<BinaryTreeNode> stack1 = new Stack<BinaryTreeNode>();
Stack<BinaryTreeNode> stack2 = new Stack<BinaryTreeNode>();
if(root != null)
stack1.Push(root);
while (stack1.Count != 0 || stack2.Count != 0)
{
IList<int> innerList1 = new List<int>();
while (stack1.Count != 0)
{
BinaryTreeNode node = stack1.Pop();
innerList1.Add(node.Val);
if (node.Left != null)
stack2.Push(node.Left);
if (node.Right != null)
stack2.Push(node.Right);
}
IList<int> innerList2 = new List<int>();
while (stack2.Count != 0)
{
BinaryTreeNode node = stack2.Pop();
innerList2.Add(node.Val);
if (node.Right != null)
stack1.Push(node.Right);
if (node.Left != null)
stack1.Push(node.Left);
}
if (innerList1.Count > 0)
outerList.Add(innerList1);
if (innerList2.Count > 0)
outerList.Add(innerList2);
}
return outerList;
}
}
}
|
c7a99c0886c0c66eb33a85d96153ae63eb91a0b0
|
C#
|
vitaliy-novik/HttpFundamentals
|
/WebCrawler/Crawler.cs
| 2.890625
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using WebCrawler.UriFilters;
namespace WebCrawler
{
public class Crawler
{
private string url;
private int depth;
private string extensions;
private HttpClient client;
private HtmlParser parser;
private Verbose verbose;
private Uri baseUri;
private ExtensionFilter extensionFilter;
private VerboseFilter verboseFilter;
public event Action<Stream, string, string> OnRespose = (stream, url, statusCode) => { };
public Crawler(string url)
{
this.baseUri = UriFactory.Create(url);
client = new HttpClient { BaseAddress = this.baseUri };
}
public Crawler(string url, int depth, Verbose verbose, string extensions) : this(url)
{
this.url = url;
this.depth = depth;
this.verbose = verbose;
this.extensions = extensions;
this.extensionFilter = new ExtensionFilter(extensions);
this.verboseFilter = new VerboseFilter(verbose, baseUri);
}
public void Start()
{
List<Uri> pages = new List<Uri>() { this.baseUri };
for (int curDepth = 0; curDepth <= this.depth; curDepth++)
{
pages = this.DownloadDepth(this.baseUri, pages);
}
}
public List<Uri> DownloadDepth(Uri currentUri, List<Uri> links)
{
List<Uri> newDepthLinks = new List<Uri>();
foreach (var link in links)
{
Uri uri = UriFactory.Create(currentUri, link);
newDepthLinks.AddRange(this.GetPage(uri));
}
return newDepthLinks;
}
public List<Uri> GetPage(Uri uri)
{
if (!this.verboseFilter.IsValid(uri))
{
return new List<Uri>();
}
HttpResponseMessage response = client.GetAsync(uri).Result;
parser = new HtmlParser(response.Content.ReadAsStringAsync().Result);
List<Uri> files = parser.GetStylesheets().Union(parser.GetScripts()).Union(parser.GetImages()).Select(l => UriFactory.Create(this.baseUri, l)).ToList();
OnRespose(response.Content.ReadAsStreamAsync().Result, uri.AbsolutePath.Replace(this.baseUri.AbsolutePath, string.Empty), response.StatusCode.ToString());
List<Uri> links = parser.GetLinks().Select(link => UriFactory.Create(this.baseUri, link)).Where(u => this.verboseFilter.IsValid(u)).ToList();
foreach (var file in files)
{
GetFile(file);
}
return links;
}
public void GetFileAsync(string path)
{
client.GetAsync(path).ContinueWith(
(requestTask) =>
{
HttpResponseMessage response = requestTask.Result;
response.EnsureSuccessStatusCode();
response.Content.ReadAsStreamAsync().ContinueWith((readtask) =>
{
this.OnRespose(readtask.Result, path, response.StatusCode.ToString());
});
});
}
public void GetFile(Uri path)
{
if (!this.extensionFilter.IsValid(path))
{
return;
}
string fileName = path.AbsolutePath.Replace(this.baseUri.AbsolutePath, string.Empty);
HttpResponseMessage response = client.GetAsync(path).Result;
if (!response.StatusCode.Equals(HttpStatusCode.OK))
{
return;
}
this.OnRespose(response.Content.ReadAsStreamAsync().Result, fileName, response.StatusCode.ToString());
}
public static bool ValidateUrl(string url)
{
try
{
UriBuilder uriBuilder = new UriBuilder(url);
return true;
}
catch (FormatException)
{
return false;
}
}
bool IsAbsoluteUrl(string url)
{
Uri result;
return Uri.TryCreate(url, UriKind.Absolute, out result);
}
}
}
|
40f815489a85d3e2b24104cf7e266d8457bc7c9d
|
C#
|
presidentjimstevens/JSIL
|
/Tests/SpecialTestCases/OuterThisDelegateNew.cs
| 3.765625
| 4
|
using System;
public class MyClass {
public Action<int> GetPrintNumber () {
return this.PrintNumber;
}
public void PrintNumber (int x) {
Console.WriteLine("MyClass.PrintNumber({0})", x);
}
}
public static class Program {
public static void Main (string[] args) {
var instance = new MyClass();
Action<int> a = PrintNumber;
Action<int> b = instance.GetPrintNumber();
a(1);
b(2);
}
public static void PrintNumber (int x) {
Console.WriteLine("PrintNumber({0})", x);
}
}
|
404bc9b94908d969ddb6cdd65a84806abb5a4bc0
|
C#
|
fengzhbo/ToolsTest
|
/ToolsTest.Console/Program.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
namespace ToolsTest.ConsoleTest
{
class Program
{
static void Main(string[] args)
{
AssemblyName an = new AssemblyName("TestEmit");
AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.RunAndSave);
ModuleBuilder mb = ab.DefineDynamicModule("TestEmitModule", "TestEmit.exe");
TypeBuilder tb = mb.DefineType("TestEmitClass", TypeAttributes.Public);
MethodBuilder methodBuilder = tb.DefineMethod("SayHelloMethod",
MethodAttributes.Public | MethodAttributes.Static, null, null);
ILGenerator ilGenerator = methodBuilder.GetILGenerator();
ilGenerator.Emit(OpCodes.Ldstr, "hello,first emit!");
ilGenerator.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(String) }));
ilGenerator.Emit(OpCodes.Call, typeof(Console).GetMethod("ReadLine"));
ilGenerator.Emit(OpCodes.Pop);
ilGenerator.Emit(OpCodes.Ret);
Type emitType = tb.CreateType();
ab.SetEntryPoint(emitType.GetMethod("SayHelloMethod"));
ab.Save("TestEmit.exe");
Console.WriteLine("hello,the first emit test class has been generated for you.");
Console.ReadLine();
}
}
}
|
b9efa1e9371c38e581521ac1eebb4776a692cf7f
|
C#
|
AndreevNikita/netcoro
|
/NetCoro/NetCoro/Awaitable.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace NetCoro {
public enum AwaitableType {
AsyncTask, WaitHandle, Delay, DoNothing, Interrupt, InterruptAll
}
public enum TaskExceptionBehaviour {
Default, Nothing, ThrowInCoro
}
public class Awaitable {
public static Awaitable DoNothingAwaitable => new Awaitable(AwaitableType.DoNothing);
public static Awaitable InterruptCurrentAwaitable => new Awaitable(AwaitableType.Interrupt);
public static Awaitable InterruptAllAwaitable => new Awaitable(AwaitableType.InterruptAll);
public readonly AwaitableType Type;
public bool IsAsyncTask => Type == AwaitableType.AsyncTask;
public bool IsDoNothing => Type == AwaitableType.DoNothing;
public bool IsInterruptTask => Type == AwaitableType.Interrupt;
public bool IsInterruptAllTask => Type == AwaitableType.InterruptAll;
public bool IsDelayTask => Type == AwaitableType.Delay;
public bool IsWaitHandle => Type == AwaitableType.WaitHandle;
public virtual bool IsFinished => true;
public virtual bool IsSuccess => true;
public Awaitable(AwaitableType type) {
this.Type = type;
}
public virtual void Assert(TaskExceptionBehaviour defaultBehaviour) {
if(!IsSuccess) {
switch(defaultBehaviour) {
case TaskExceptionBehaviour.Default:
case TaskExceptionBehaviour.Nothing:
return;
case TaskExceptionBehaviour.ThrowInCoro:
throw new AwaitableExecuteException("UnknownException");
}
}
}
public virtual void Start() { }
//Returns true if interrupted immidiately
public virtual bool OnInterruptStart() => false;
private bool isCached = false;
public void Cache<T>(ICollection<T> cacheCollection) {
if(isCached)
return;
AddToCache(cacheCollection);
isCached = true;
}
protected virtual void AddToCache<T>(ICollection<T> cacheCollection) { }
public void Uncache<T>(ICollection<T> cacheCollection) {
if(!isCached)
return;
RemoveFromCache(cacheCollection);
isCached = false;
}
protected virtual void RemoveFromCache<T>(ICollection<T> cacheCollection) { }
}
public class AwaitableTask : Awaitable {
public readonly Task Task;
public readonly TaskExceptionBehaviour TaskExceptionBehaviour;
public override bool IsFinished => Task.IsCompleted || Task.IsFaulted || Task.IsCanceled;
public override bool IsSuccess => !Task.IsFaulted;
public AwaitableTask(Task task, TaskExceptionBehaviour taskExceptionBehaviour = TaskExceptionBehaviour.Default) : base(AwaitableType.AsyncTask) {
Task = task;
TaskExceptionBehaviour = taskExceptionBehaviour;
}
public override void Start() {
if(Task.Status == TaskStatus.Created)
Task.Start();
}
public override void Assert(TaskExceptionBehaviour defaultBehaviour) {
TaskExceptionBehaviour exceptionBehaviour = TaskExceptionBehaviour != TaskExceptionBehaviour.Default ? TaskExceptionBehaviour : defaultBehaviour;
if(!IsSuccess) {
switch(exceptionBehaviour) {
case TaskExceptionBehaviour.Default:
case TaskExceptionBehaviour.Nothing:
return;
case TaskExceptionBehaviour.ThrowInCoro:
throw new TaskExecuteException(Task);
}
}
}
protected override void AddToCache<T>(ICollection<T> cacheCollection) => ((ICollection<Task>)cacheCollection).Add(Task);
protected override void RemoveFromCache<T>(ICollection<T> cacheCollection) => ((ICollection<Task>)cacheCollection).Remove(Task);
}
public class WaitHandleAwaitable : Awaitable {
public readonly WaitHandle WaitHandle;
private bool isInterrupted = false;
public override bool IsFinished => isInterrupted || taskCompletionSource.Task.IsCompleted; //Doesn't block a thread
private RegisteredWaitHandle registredWaitHandle;
private TaskCompletionSource<bool> taskCompletionSource;
public WaitHandleAwaitable(WaitHandle waitHandle) : base(AwaitableType.WaitHandle) {
WaitHandle = waitHandle;
taskCompletionSource = new TaskCompletionSource<bool>();
taskCompletionSource.Task.ContinueWith(UnregisterWaitHandleDelegate);
registredWaitHandle = ThreadPool.RegisterWaitForSingleObject(waitHandle, WaitHandleCallback, null, -1, true);
}
private void WaitHandleCallback(object state, bool timedOut) {
taskCompletionSource.SetResult(true);
}
private void UnregisterWaitHandleDelegate(Task _) {
registredWaitHandle.Unregister(null);
}
public override bool OnInterruptStart() {
UnregisterWaitHandleDelegate(taskCompletionSource.Task);
isInterrupted = true;
return true;
}
protected override void AddToCache<T>(ICollection<T> cacheCollection) => ((ICollection<Task>)cacheCollection).Add(taskCompletionSource.Task);
protected override void RemoveFromCache<T>(ICollection<T> cacheCollection) => ((ICollection<Task>)cacheCollection).Remove(taskCompletionSource.Task);
}
public class DelayAwaitable : Awaitable {
public DateTime CooldownTime { get; private set;}
private bool isInterrupted = false;
public override bool IsFinished => isInterrupted || CooldownTime <= DateTime.Now;
public DelayAwaitable(DateTime cooldownTime) : base(AwaitableType.Delay) {
CooldownTime = cooldownTime;
}
public static DelayAwaitable MakeSleep(TimeSpan sleepTime) => new DelayAwaitable(DateTime.Now + sleepTime);
public override bool OnInterruptStart() { isInterrupted = true; return true; }
}
public class AwaitableExecuteException : Exception {
public AwaitableExecuteException(string message) : base(message) { }
}
public class TaskExecuteException : AwaitableExecuteException {
public readonly Exception CausedByException;
public readonly Task Task;
public TaskExecuteException(Task task) : base(task.Exception.Message) {
CausedByException = task.Exception;
Task = task;
}
}
}
|
579df942f40ef4d2454779fc3a4cf298ddfb7138
|
C#
|
OJ13/Arquitetura-Base
|
/Back/1 - DDD/DDD/Helpers/PasswordHelper.cs
| 3.25
| 3
|
using System;
using System.Security.Cryptography;
using System.Text;
namespace DDD.Helpers
{
public static class PasswordHelper
{
public static string RandomPassword()
{
StringBuilder builder = new StringBuilder();
builder.Append(RandomString(1, false));
builder.Append(RandomString(4, true));
builder.Append(RandomSpecialCharacters(1));
builder.Append(RandomNumber(1000, 9999));
return builder.ToString();
}
private static int RandomNumber(int min, int max)
{
return RandomNumberGenerator.GetInt32(min, max);
}
private static string RandomString(int size, bool lowerCase)
{
StringBuilder builder = new StringBuilder();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * RandomDouble() + 65)));
builder.Append(ch);
}
if (lowerCase)
return builder.ToString().ToLower();
return builder.ToString();
}
private static string RandomSpecialCharacters(int size)
{
string validChars = "._$*#@";
char[] chars = new char[size];
for (int i = 0; i < size; i++)
{
chars[i] = validChars[RandomNumberGenerator.GetInt32(0, validChars.Length)];
}
return new string(chars);
}
private static double RandomDouble()
{
var rng = new RNGCryptoServiceProvider();
var bytes = new byte[8];
rng.GetBytes(bytes);
var ul = BitConverter.ToUInt64(bytes, 0) / (1 << 11);
return ul / (double)(1UL << 53);
}
}
}
|
941603e6befc9fbcdf3e947b4020b3c91eecb955
|
C#
|
jaykang920/x2net
|
/src/xpiler/CommentAwareXmlHandler.cs
| 2.703125
| 3
|
// Copyright (c) 2017-2019 Jae-jun Kang
// See the file LICENSE for details.
using System;
using System.Xml;
namespace x2net.xpiler
{
class CommentAwareXmlHandler : Handler
{
public bool Handle(string path, out Unit unit)
{
unit = null;
var xml = new XmlDocument();
try
{
xml.Load(path);
}
catch (Exception e)
{
Console.Error.WriteLine(e);
return false;
}
var rootElem = xml.DocumentElement;
if (rootElem.Name != "x2")
{
// Not a valid x2 document.
return true;
}
unit = new Unit {
Namespace = rootElem.GetAttribute("namespace")
};
var node = rootElem.FirstChild;
for ( ; node != null; node = node.NextSibling)
{
if (node.NodeType == XmlNodeType.Element)
{
var elem = (XmlElement)node;
switch (elem.Name)
{
case "references":
if (ParseReferences(unit, elem) == false)
{
return false;
}
break;
case "definitions":
if (ParseDefinitions(unit, elem) == false)
{
return false;
}
break;
default:
break;
}
}
}
return true;
}
private bool ParseReferences(Unit unit, XmlElement elem)
{
var node = elem.FirstChild;
for (; node != null; node = node.NextSibling)
{
if (node.NodeType == XmlNodeType.Element)
{
var child = (XmlElement)node;
switch (child.Name)
{
case "namespace":
if (ParseReference(unit, child) == false)
{
return false;
}
break;
default:
break;
}
}
}
return true;
}
private bool ParseDefinitions(Unit unit, XmlElement elem)
{
string comment = null;
var node = elem.FirstChild;
for (; node != null; node = node.NextSibling)
{
if (node.NodeType != XmlNodeType.Element)
{
if (node.NodeType == XmlNodeType.Comment)
{
comment = node.Value.Trim();
}
else
{
comment = null;
}
continue;
}
var child = (XmlElement)node;
switch (child.Name)
{
case "consts":
if (ParseConsts(unit, child, comment) == false)
{
return false;
}
break;
case "cell":
case "event":
if (ParseCell(unit, child, comment) == false)
{
return false;
}
break;
default:
break;
}
comment = null;
}
return true;
}
private bool ParseReference(Unit unit, XmlElement elem)
{
var target = elem.GetAttribute("target");
if (String.IsNullOrEmpty(target))
{
return false;
}
Reference reference = new Reference {
Target = target
};
unit.References.Add(reference);
return true;
}
private bool ParseConsts(Unit unit, XmlElement elem, string comment)
{
var name = elem.GetAttribute("name");
var type = elem.GetAttribute("type");
if (String.IsNullOrEmpty(name))
{
return false;
}
if (String.IsNullOrEmpty(type))
{
type = "int32"; // default type
}
var def = new ConstsDef {
Name = name,
Type = type,
Comment = comment
};
string subComment = null;
var node = elem.FirstChild;
for ( ; node != null; node = node.NextSibling)
{
if (node.NodeType != XmlNodeType.Element)
{
if (node.NodeType == XmlNodeType.Comment)
{
subComment = node.Value.Trim();
}
else
{
subComment = null;
}
continue;
}
var child = (XmlElement)node;
if (child.IsEmpty)
{
continue;
}
switch (child.Name)
{
case "const":
if (ParseConstant(def, child, subComment) == false)
{
return false;
}
break;
default:
break;
}
subComment = null;
}
unit.Definitions.Add(def);
return true;
}
private bool ParseConstant(ConstsDef def, XmlElement elem, string comment)
{
var name = elem.GetAttribute("name");
if (String.IsNullOrEmpty(name))
{
return false;
}
var element = new ConstsDef.Constant {
Name = name,
Value = elem.InnerText.Trim(),
Comment = comment
};
def.Constants.Add(element);
return true;
}
private bool ParseCell(Unit unit, XmlElement elem, string comment)
{
var name = elem.GetAttribute("name");
if (String.IsNullOrEmpty(name))
{
return false;
}
var isEvent = (elem.Name == "event");
var id = elem.GetAttribute("id");
if (isEvent && String.IsNullOrEmpty(id))
{
return false;
}
CellDef def = (isEvent ? new EventDef() : new CellDef());
def.Name = name;
if (isEvent)
{
((EventDef)def).Id = id;
}
def.Base = elem.GetAttribute("base");
var local = elem.GetAttribute("local");
if (!String.IsNullOrEmpty(local) && local.EndsWith("rue"))
{
def.IsLocal = true;
}
var asIs = elem.GetAttribute("asIs");
if (!String.IsNullOrEmpty(asIs) && asIs.EndsWith("rue"))
{
def.AsIs = true;
}
def.Comment = comment;
string subComment = null;
var node = elem.FirstChild;
for ( ; node != null; node = node.NextSibling)
{
if (node.NodeType != XmlNodeType.Element)
{
if (node.NodeType == XmlNodeType.Comment)
{
subComment = node.Value.Trim();
}
else
{
subComment = null;
}
continue;
}
var child = (XmlElement)node;
switch (child.Name)
{
case "property":
if (ParseCellProperty(def, child, subComment) == false)
{
return false;
}
break;
default:
break;
}
subComment = null;
}
unit.Definitions.Add(def);
return true;
}
private bool ParseCellProperty(CellDef def, XmlElement elem, string comment)
{
var name = elem.GetAttribute("name");
var type = elem.GetAttribute("type");
if (String.IsNullOrEmpty(name))
{
return false;
}
if (String.IsNullOrEmpty(type))
{
return false;
}
var property = new CellDef.Property {
Name = name,
DefaultValue = elem.InnerText.Trim(),
Comment = comment
};
def.Properties.Add(property);
property.TypeSpec = Types.Parse(type);
if (property.TypeSpec == null)
{
return false;
}
return true;
}
}
}
|
829ecfe046eda86b5fc7cf31cc83c96e9c944681
|
C#
|
ValentinDosh/patterns-3
|
/StudentsAbstractFactory/StudentsAbstractFactory/Program.cs
| 3.15625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentsAbstractFactory
{
class Program
{
static void Main(string[] args)
{
// Отличник
Student student1 = new Student(new GoodStudentFactory());
student1.DisplayInfo();
student1.Do();
Console.WriteLine();
// средний
Student student2 = new Student(new NormalStudentFactory());
student2.DisplayInfo();
student2.Do();
Console.WriteLine();
// Отсталый
Student student3 = new Student(new BadStudentFactory());
student3.DisplayInfo();
student3.Do();
Console.WriteLine();
// Иностранец
Student student4= new Student(new ForeignStudentFactory());
student4.DisplayInfo();
student4.Do();
Console.WriteLine();
Console.ReadLine();
}
}
}
|
4459bc1b01b176dea47c38a59a98895920701695
|
C#
|
mdmn07C5/BB3D_scripts
|
/Level/WinLevel.cs
| 2.875
| 3
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// Handles losing the level, attached to anything that allows player to win game
/// </summary>
public class WinLevel : MonoBehaviour
{
#region Unity Inspector Fields
[Tooltip("An int variable to the amount of current stars in the current level")]
[SerializeField]
private IntVariable currentStar;
[Tooltip("An int variable to the amount of max stars in the current level")]
[SerializeField]
private IntVariable maxStar;
[Tooltip("When level is won, this event will be raised")]
[SerializeField]
private GameEvent onLevelWin;
#endregion
private static bool gameWon;
/// <summary>
/// Tries to win the game by comparing the amount of current stars/collectables with the max amount
/// </summary>
public void TryWinGame()
{
if (AllStarsPickedUp() && gameWon == false)
{
gameWon = true;
onLevelWin.Raise();
}
}
/// <summary>
/// Resets collectable/stars
/// </summary>
public void Reset_Callback()
{
gameWon = false;
currentStar.SetValue(0);
maxStar.SetValue(0);
}
private bool AllStarsPickedUp()
{
return currentStar.GetValue() == maxStar.GetValue();
}
}
|
e6b5a97998a59061a216856bd081c4e78cfd727c
|
C#
|
frankbsd/CLRViaCSharp
|
/Chapter27/CancellationTokenTest.cs
| 3.34375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Chapter27
{
class CancellationTokenTest
{
public static void TestTaskReturn2()
{
CancellationTokenSource cts = new CancellationTokenSource();
Task<int> t = Task.Run(() => Sum2(cts.Token, 10000), cts.Token);
cts.Cancel();
try
{
Console.WriteLine("The sum is {0}",t.Result);
}
catch (AggregateException ex)
{
ex.Handle(e => e is OperationCanceledException);
Console.WriteLine("Sum was canceled");
}
}
public static void TestTaskReturn()
{
Task<int> t = new Task<int>(n => Sum((int)n), 100000);
t.Start();
t.Wait();
Console.WriteLine("The sum is {0}",t.Result);
}
public static void Go()
{
CancellationTokenSource cts = new CancellationTokenSource();
ThreadPool.QueueUserWorkItem(o => Count(cts.Token, 100));
ThreadPool.QueueUserWorkItem(t => Count(cts.Token, 200));
cts.Token.Register(Cancel);
cts.Token.Register(Cancel2);
Console.WriteLine("Hit any key to cancel the operation");
Console.ReadKey();
cts.Cancel();
}
private static void Count(CancellationToken token, int countTo)
{
for (int i = 0; i < countTo; i++)
{
if (token.IsCancellationRequested)
{
Console.WriteLine("Count is cancelled");
break;
}
Console.WriteLine(i);
Thread.Sleep(200);
}
Console.WriteLine("Count is done");
}
private static void Cancel()
{
Console.WriteLine(" Cancel()被调用");
Console.WriteLine("线程ID={0}被取消了", Thread.CurrentThread.ManagedThreadId);
}
private static void Cancel2()
{
Console.WriteLine("Cancel2()被调用");
Console.WriteLine("线程ID={0}被取消了", Thread.CurrentThread.ManagedThreadId);
}
public static int Sum(int n)
{
int sum = 0;
for (; n > 0; n--)
checked
{
sum += n;
}
return sum;
}
public static int Sum2(CancellationToken ct,int n)
{
int sum = 0;
for (; n > 0; n--)
{
ct.ThrowIfCancellationRequested();
checked
{
sum += n;
}
}
return sum;
}
}
}
|
d4402db6b720a34a9bae83819961958495898ca5
|
C#
|
maxstralin/csharp-to-js
|
/src/Core/Services/AssemblyTypeResolver.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using CSharpToJs.Core.Attributes;
using CSharpToJs.Core.Interfaces;
namespace CSharpToJs.Core.Services
{
/// <inheritdoc />
public class AssemblyTypeResolver : IAssemblyTypeResolver
{
private readonly Assembly assembly;
private readonly string ns;
private readonly IEnumerable<string> excludedNamespaces;
/// <summary>
/// Used to get types to be serialized in an assembly
/// </summary>
/// <param name="assembly">Assembly to look in</param>
/// <param name="ns">Namespace for the types</param>
/// <param name="excludedNamespaces">Namespaces to exclude</param>
public AssemblyTypeResolver(Assembly assembly, string ns, IEnumerable<string> excludedNamespaces)
{
this.assembly = assembly;
this.ns = ns;
this.excludedNamespaces = excludedNamespaces ?? Enumerable.Empty<string>();
}
/// <inheritdoc />
public IEnumerable<Type> Resolve()
{
return assembly.GetExportedTypes().Where(a =>
!a.ContainsGenericParameters && !a.IsInterface && !a.IsEnum && !Attribute.IsDefined(a, typeof(JsIgnoreAttribute)) && a.Namespace.StartsWith(ns) &&
!excludedNamespaces.Contains(a.Namespace));
}
}
}
|
0cf9ab76408caf3727d858e4bf6753b1a827fa1d
|
C#
|
tianmao888sdo/KTLuaFramework
|
/Assets/core/Assemblies/Kernel.core/Attributes/AttributeVariable.cs
| 2.71875
| 3
|
using System;
namespace Kernel.core
{
public class AttributeVariable
{
private readonly int key;
private AttributeValue value;
public AttributeVariable(int key, AttributeValue value)
{
this.key = key;
this.value = value;
}
public int Key => key;
public AttributeValue Value
{
get
{
return value;
}
set
{
this.value = value;
}
}
public void Add(AttributeModifyType attributeModifyType, double v)
{
value.Add(attributeModifyType, v);
}
public void Set(AttributeModifyType attributeModifyType, double v)
{
value.Set(attributeModifyType, v);
}
public void Add(AttributeVariable v)
{
if(v.key == key)
{
value.Add(v.value);
}
}
public void Sub(AttributeVariable v)
{
if(v.key == key)
{
value.Sub(v.value);
}
}
public void Set(AttributeVariable v)
{
if(v.key == key)
{
value.Set(v.value);
}
}
public AttributeVariable Multiple(int count)
{
value.Multiple(count);
return this;
}
}
}
|
88125bc61c285a8cdb3358fd4e1daa4f4f87824b
|
C#
|
210215-USF-NET/Angeleen_Abesamis-P0
|
/BeautyStore/BeautyStoreAppUI/BeautyStoreMenu.cs
| 3.078125
| 3
|
using System;
using BeautyStore.BeautyStoreModels;
using BeautyStoreBL;
using Serilog;
using System.Collections.Generic;
namespace BeautyStoreAppUI
{
public class BeautyStoreMenu : IBeautyStoreMenu
{
private IBeautyStoreBL _repo;
public BeautyStoreMenu(IBeautyStoreBL repo)
{
_repo = repo;
}
public void Start()
{
Log.Logger = new LoggerConfiguration().WriteTo.File("../Logs/UILogs.json").CreateLogger();
IBeautyStoreMenu menu;
Boolean stay = true;
do
{
Console.WriteLine("Welcome to Perfume Candy!");
Console.WriteLine("Please choose an option: ");
Console.WriteLine("[0] Register");
Console.WriteLine("[1] Login");
Console.WriteLine("[2] Manager Login");
Console.WriteLine("[3] Exit");
string customerInput = Console.ReadLine();
switch (customerInput)
{
case "0":
_repo.AddCustomer(newAccount());
List<Customer> customerList = _repo.GetCustomers();
foreach(Customer cust in customerList)
{
Console.WriteLine(cust.ToString());
}
Console.WriteLine("Your account has been successfully added!");
break;
case "1":
Console.WriteLine("Please enter your name:");
string strname = Console.ReadLine();
Customer findCustomer = _repo.GetCustomerByName(strname);
if(findCustomer == null)
{
Console.WriteLine("Sorry, no customer has been found. Please try again!");
} else
{
Console.WriteLine($"Welcome, {findCustomer.CustomerName}!");
menu = new CustomerMenu(_repo, findCustomer);
menu.Start();//else if ( findCustomer.CustomerName.Equals("Angeleen")) //Stretch goal: use DB for this
}break;
case "2":
Console.WriteLine("Please enter your name:");
string managerName = Console.ReadLine();
if(managerName.Equals("Angeleen")) {
menu = new Admin(_repo);
menu.Start();
}
break;
case "3":
stay = false;
Console.WriteLine("Thank you for shopping with us!");
break;
default:
Console.WriteLine("Invalid option. Please try again.");
break;
}
} while (stay);
}
public Customer newAccount()
{
Customer newCustomer = new Customer();
//Register a new customer.
Console.WriteLine("Please enter your name:");
newCustomer.CustomerName = Console.ReadLine();
Console.WriteLine("Please enter your phone number:");
newCustomer.PhoneNumber = Console.ReadLine();
Console.WriteLine("Please enter your email address:");
newCustomer.EmailAddress = Console.ReadLine();
Console.WriteLine("Please enter your home address:");
newCustomer.HomeAddress = Console.ReadLine();
Console.WriteLine("Please enter your billing address:");
newCustomer.BillingAddress = Console.ReadLine();
return newCustomer;
}
}
}
|
4b47290b51db9ed9f1f532d6fb320b0bfaf64060
|
C#
|
Yaksh36/Algorithms-II
|
/Network/Vertex.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Network
{
public class Vertex<T> where T:IComparable<T>
{
public T Data { get; set; }
public LinkedList<Tuple<Vertex<T>, int>> Edges = new LinkedList<Tuple<Vertex<T>, int>>();
public Vertex() { }
public Vertex(T data)
{
Data = data;
}
}
}
|
af4a63e64dc7fbf0931ef64e03adfa5839aa7431
|
C#
|
pkmitl205/OBJECT_ORIENTED_PROGRAMMING
|
/Car/Car/Program.cs
| 3.09375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Car
{
class Program
{
static void Main(string[] args)
{
Car _car = new Car();
_car.FrontLeft = new Door();
_car.FrontRight = new Door();
_car.RearLeft = new Door();
_car.RearRight = new Door();
Console.ReadKey();
}
}
public class Car
{
// composition #1 Engine -> create class Engine inside class Car
public class Engine
{
public int hoursePower;
}
// composition #2 Battery -> create class Battery inside class Batterty
public class Batterty
{
public int voltage;
}
// create reference of composition components
protected Engine _engine;
protected Batterty _battery;
public Car()
{
_engine = new Engine();
_battery = new Batterty();
}
// aggregation #3 Door -> create class Door outside class Car
public Door FrontRight;
public Door FrontLeft;
public Door RearRight;
public Door RearLeft;
internal object _door;
}
public class Door
{
public int position;
public static int _position;
public Door()
{
_position++;
position = _position;
}
}
}
|
77fba693e00e33c649337512b38257ca2410d027
|
C#
|
exercism/csharp
|
/exercises/practice/robot-simulator/.meta/Example.cs
| 3.609375
| 4
|
using System;
public enum Direction
{
North,
East,
South,
West
}
public class RobotSimulator
{
public RobotSimulator(Direction bearing, int x, int y)
{
Direction = bearing;
X = x;
Y = y;
}
public Direction Direction { get; private set; }
public int X { get; private set; }
public int Y { get; private set; }
public void Move(string instructions)
{
foreach (var instruction in instructions)
{
Move(instruction);
}
}
private void Move(char code)
{
switch (code)
{
case 'L':
TurnLeft();
break;
case 'R':
TurnRight();
break;
case 'A':
Advance();
break;
default:
throw new ArgumentOutOfRangeException("Invalid instruction");
}
}
private void TurnLeft()
{
switch (Direction)
{
case Direction.North:
Direction = Direction.West;
break;
case Direction.East:
Direction = Direction.North;
break;
case Direction.South:
Direction = Direction.East;
break;
case Direction.West:
Direction = Direction.South;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
private void TurnRight()
{
switch (Direction)
{
case Direction.North:
Direction = Direction.East;
break;
case Direction.East:
Direction = Direction.South;
break;
case Direction.South:
Direction = Direction.West;
break;
case Direction.West:
Direction = Direction.North;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
private void Advance()
{
switch (Direction)
{
case Direction.North:
Y++;
break;
case Direction.East:
X++;
break;
case Direction.South:
Y--;
break;
case Direction.West:
X--;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
|
d0d5dd5236033fa21135ae521f5df2342314128a
|
C#
|
dystudio/SuperRocket
|
/SuperRocket/src/SuperRocket.Framework/Bus/Configurators/ResponseConfigurator.cs
| 2.859375
| 3
|
using System;
namespace SuperRocket.Framework.Bus.Configurators
{
/// <summary>
/// 响应配置。
/// </summary>
public class ResponseConfigurator
{
private readonly IBus _bus;
private readonly MessageBase _message;
/// <summary>
/// 初始化一个新的响应配置。
/// </summary>
/// <param name="bus">总线。</param>
/// <param name="message">请求消息。</param>
/// <exception cref="ArgumentNullException"><paramref name="bus"/> 或 <paramref name="message"/> 为 null。</exception>
public ResponseConfigurator(IBus bus, MessageBase message)
{
if (bus == null)
throw new ArgumentNullException("bus");
if (message == null)
throw new ArgumentNullException("message");
_bus = bus;
_message = message;
}
/// <summary>
/// 提交一个响应给请求消息。
/// </summary>
/// <param name="configuration">响应消息配置。</param>
/// <exception cref="ArgumentNullException"><paramref name="configuration"/> 为null。</exception>
public void Post(Action<ResponseMessage> configuration)
{
if (configuration == null)
throw new ArgumentNullException("configuration");
var message = new ResponseMessage(_message.Id);
configuration(message);
_bus.Publish(message);
}
}
/// <summary>
/// 响应配置扩展。
/// </summary>
public static class ResponseConfiguratorExtensions
{
/// <summary>
/// 提交一个结果给请求消息。
/// </summary>
/// <param name="responseConfigurator">响应配置。</param>
/// <param name="result">结果。</param>
/// <exception cref="ArgumentNullException"><paramref name="responseConfigurator"/> 为null。</exception>
public static void Post(this ResponseConfigurator responseConfigurator, object result)
{
if (responseConfigurator == null)
throw new ArgumentNullException("responseConfigurator");
responseConfigurator.Post(message => message.Result = result);
}
/// <summary>
/// 提交一个结果给请求消息。
/// </summary>
/// <param name="responseConfigurator">响应配置。</param>
/// <param name="result">结果。</param>
/// <param name="exception">响应异常。</param>
/// <exception cref="ArgumentNullException"><paramref name="responseConfigurator"/> 为null。</exception>
public static void Post(this ResponseConfigurator responseConfigurator, object result, Exception exception)
{
if (responseConfigurator == null)
throw new ArgumentNullException("responseConfigurator");
responseConfigurator.Post(message =>
{
message.Result = result;
message.Exception = exception;
});
}
}
}
|
d25f565edacf15c993d1e69d7192239af796909f
|
C#
|
kwonganding/Util
|
/src/Util.Datas/Dapper/Oracle/OracleDialect.cs
| 2.71875
| 3
|
using Util.Datas.Sql.Builders.Core;
namespace Util.Datas.Dapper.Oracle {
/// <summary>
/// Oracle方言
/// </summary>
public class OracleDialect : DialectBase {
/// <summary>
/// 起始转义标识符
/// </summary>
public override string OpeningIdentifier => "\"";
/// <summary>
/// 结束转义标识符
/// </summary>
public override string ClosingIdentifier => "\"";
/// <summary>
/// 获取安全名称
/// </summary>
/// <param name="name">名称</param>
protected override string GetSafeName( string name ) {
return $"\"{name}\"";
}
/// <summary>
/// 获取参数前缀
/// </summary>
public override string GetPrefix() {
return ":";
}
/// <summary>
/// Select子句是否支持As关键字
/// </summary>
public override bool SupportSelectAs() {
return false;
}
/// <summary>
/// 创建参数名
/// </summary>
/// <param name="paramIndex">参数索引</param>
public override string GenerateName( int paramIndex ) {
return $"{GetPrefix()}p_{paramIndex}";
}
/// <summary>
/// 获取参数名
/// </summary>
/// <param name="paramName">参数名</param>
public override string GetParamName( string paramName ) {
if ( paramName.StartsWith( ":" ) )
return paramName.TrimStart( ':' );
return paramName;
}
/// <summary>
/// 获取参数值
/// </summary>
/// <param name="paramValue">参数值</param>
public override object GetParamValue( object paramValue ) {
if( paramValue == null )
return "";
switch( paramValue.GetType().Name.ToLower() ) {
case "boolean":
return Helpers.Convert.ToBool( paramValue ) ? 1 : 0;
case "int16":
case "int32":
case "int64":
case "single":
case "double":
case "decimal":
return paramValue.SafeString();
default:
return $"{paramValue}";
}
}
}
}
|
1c7de529bc43a73c81b15f8681648d810e3b1fb3
|
C#
|
aaronmcooke/Mono-Framework
|
/Parameters/FrequencyParameter.cs
| 3
| 3
|
// <copyright file="FrequencyParameter.cs" company="GoatDogGames">
// Copyright @ 2011 All Rights Reserved. </copyright>
// <author>Aaron M. Cooke</author>
// <email>aaron.m.cooke@gmail.com</email>
using System;
namespace GoatDogGames
{
public class FrequencyParameter : ParameterBase
{
#region Fields
private delegate DateTime FromDateDelegate();
private delegate DateTime ThruDateDelegate();
private FromDateDelegate fromDateMethod;
private ThruDateDelegate thruDateMethod;
private DateTime referenceDate;
#endregion
#region Properties
public override Type Type
{
get { return typeof(FrequencyParameter); }
}
public override string Text
{
get
{
return base.Text;
}
set
{
if (value != null)
{
text = value;
}
else
{
text = string.Empty;
}
fromDateMethod = GetFromDateMethod();
thruDateMethod = GetThruDateMethod();
}
}
public DateTime FromDate
{
get { return fromDateMethod(); }
}
public DateTime ThruDate
{
get { return thruDateMethod(); }
}
public TimeSpan ReportingPeriod
{
get { return ThruDate.Subtract(FromDate); }
}
#endregion
#region Constructors
public FrequencyParameter()
{
SetDefaults();
SetFrequencyParameterDefaults();
}
public FrequencyParameter(DateTime referenceDatePassed)
{
SetDefaults();
SetFrequencyParameterDefaults();
SetReferenceDateFromDateTimePassed(referenceDatePassed);
}
public FrequencyParameter(string referenceDatePassed)
{
SetDefaults();
SetFrequencyParameterDefaults();
SetReferenceDateFromStringPassed(referenceDatePassed);
}
#endregion
#region Constructor Methods
private void SetFrequencyParameterDefaults()
{
referenceDate = DateTime.Now;
fromDateMethod = GetFromDateMethod();
thruDateMethod = GetThruDateMethod();
}
private void SetReferenceDateFromDateTimePassed(DateTime referenceDatePassed)
{
if (referenceDatePassed != null)
{
referenceDate = referenceDatePassed;
}
else
{
FormattingError newError = new FormattingError(FormattingErrorTypes.Null);
errors.Add(newError);
}
}
private void SetReferenceDateFromStringPassed(string referenceDatePassed)
{
if (referenceDatePassed == null)
{
FormattingError newError = new FormattingError(FormattingErrorTypes.Null);
errors.Add(newError);
}
else if (referenceDatePassed.Length == 0)
{
FormattingError newError = new FormattingError(FormattingErrorTypes.Empty);
errors.Add(newError);
}
else if (!DateIsValid(referenceDatePassed))
{
FormattingError newError = new FormattingError(FormattingErrorTypes.FailedParse);
errors.Add(newError);
}
}
#endregion
#region Delegate Assignment Methods
private FromDateDelegate GetFromDateMethod()
{
FromDateDelegate currentMethod = null;
switch (Text.ToUpper())
{
case "PMTD":
currentMethod = GetLastMonth;
break;
case "CMTD":
currentMethod = GetThisMonth;
break;
case "MNTH":
currentMethod = GetLastMonth;
break;
case "YSTR":
currentMethod = GetYesterday;
break;
case "CMTH":
currentMethod = GetThisMonth;
break;
case "CYR":
currentMethod = GetThisYear;
break;
case "PYR":
currentMethod = GetLastYear;
break;
default:
currentMethod = GetToday;
break;
}
return currentMethod;
}
private ThruDateDelegate GetThruDateMethod()
{
ThruDateDelegate currentMethod = null;
switch (Text.ToUpper())
{
case "PMTD":
currentMethod = GetTomorrow;
break;
case "CMTD":
currentMethod = GetTomorrow;
break;
case "MNTH":
currentMethod = GetThisMonth;
break;
case "YSTR":
currentMethod = GetToday;
break;
case "CMTH":
currentMethod = GetNextMonth;
break;
case "CYR":
currentMethod = GetNextYear;
break;
case "PYR":
currentMethod = GetThisYear;
break;
default:
currentMethod = GetTomorrow;
break;
}
return currentMethod;
}
#endregion
#region Date Computation Methods
private DateTime GetTomorrow()
{
TimeSpan spanToAdd = new TimeSpan(1, 0, 0, 0);
DateTime dateResult = DateTime.MaxValue;
if (DateAddWontExceedMaxDate(referenceDate, spanToAdd))
{
dateResult = new DateTime(referenceDate.Year, referenceDate.Month, referenceDate.Day, 0, 0, 0);
dateResult = dateResult.Add(spanToAdd);
}
else
{
FrequencyError newError = new FrequencyError(FrequencyErrorTypes.ResultGreaterThanDateMax);
errors.Add(newError);
}
return dateResult;
}
private DateTime GetToday()
{
return new DateTime(referenceDate.Year, referenceDate.Month, referenceDate.Day, 0, 0, 0);
}
private DateTime GetYesterday()
{
TimeSpan spanToSubtract = new TimeSpan(1, 0, 0, 0);
DateTime dateResult = DateTime.MinValue;
if (DateSubtractWontBeLessThanMinDate(referenceDate, spanToSubtract))
{
dateResult = new DateTime(referenceDate.Year, referenceDate.Month, referenceDate.Day, 0, 0, 0);
dateResult = dateResult.Subtract(spanToSubtract);
}
else
{
FrequencyError newError = new FrequencyError(FrequencyErrorTypes.ResultLessThanDateMin);
errors.Add(newError);
}
return dateResult;
}
private DateTime GetThisMonth()
{
return new DateTime(referenceDate.Year, referenceDate.Month, 1, 0, 0, 0);
}
private DateTime GetLastMonth()
{
int priorMonth = referenceDate.Month - 1;
int yearOfPriorMonth = referenceDate.Year;
if (priorMonth == 0)
{
priorMonth = 12;
yearOfPriorMonth -= 1;
}
DateTime resultDate = DateTime.MinValue;
if (YearNotLessThanMinimumYear(yearOfPriorMonth))
{
resultDate = new DateTime(yearOfPriorMonth, priorMonth, 1, 0, 0, 0);
}
else
{
FrequencyError newError = new FrequencyError(FrequencyErrorTypes.ResultLessThanDateMin);
errors.Add(newError);
}
return resultDate;
}
private DateTime GetNextMonth()
{
DateTime resultDate = DateTime.MaxValue;
if ((referenceDate.Month != 12) || (YearNotGreaterThanMaximumYear(referenceDate.Year + 1)))
{
DateTime nextMonth = GetThisMonth();
nextMonth = nextMonth.Add(new TimeSpan(27, 0, 0, 0));
int monthOfPriorDate = nextMonth.Month;
int monthOfCurrentDate = monthOfPriorDate;
while (monthOfCurrentDate == monthOfPriorDate)
{
nextMonth = nextMonth.Add(new TimeSpan(1, 0, 0, 0));
monthOfCurrentDate = nextMonth.Month;
}
resultDate = new DateTime(nextMonth.Year, nextMonth.Month, nextMonth.Day, 0, 0, 0);
}
else
{
FrequencyError newError = new FrequencyError(FrequencyErrorTypes.ResultGreaterThanDateMax);
errors.Add(newError);
}
return resultDate;
}
private DateTime GetThisYear()
{
return new DateTime(referenceDate.Year, 1, 1, 0, 0, 0);
}
private DateTime GetNextYear()
{
DateTime resultDate = DateTime.MaxValue;
if (YearNotGreaterThanMaximumYear(referenceDate.Year + 1))
{
resultDate = new DateTime(referenceDate.Year + 1, 1, 1, 0, 0, 0);
}
else
{
FrequencyError newError = new FrequencyError(FrequencyErrorTypes.ResultGreaterThanDateMax);
errors.Add(newError);
}
return resultDate;
}
private DateTime GetLastYear()
{
DateTime resultDate = DateTime.MinValue;
if (YearNotLessThanMinimumYear(referenceDate.Year - 1))
{
resultDate = new DateTime(referenceDate.Year - 1, 1, 1, 0, 0, 0);
}
else
{
FrequencyError newError = new FrequencyError(FrequencyErrorTypes.ResultLessThanDateMin);
errors.Add(newError);
}
return resultDate;
}
#endregion
#region Validation Methods
private bool DateIsValid(string dateToCheck)
{
bool checkResult = true;
if (!DateTime.TryParse(dateToCheck, out referenceDate))
{
referenceDate = DateTime.Now;
checkResult = false;
}
return checkResult;
}
private bool DateAddWontExceedMaxDate(DateTime datePassed, TimeSpan amountToBeAdded)
{
bool checkResult = true;
DateTime safeDate = DateTime.MaxValue.Subtract(amountToBeAdded);
if (datePassed.CompareTo(safeDate) == 1)
{
checkResult = false;
}
return checkResult;
}
private bool DateSubtractWontBeLessThanMinDate(DateTime datePassed, TimeSpan amountToBeSubtracted)
{
bool checkResult = true;
DateTime safeDate = DateTime.MinValue.Add(amountToBeSubtracted);
if (datePassed.CompareTo(safeDate) == -1)
{
checkResult = false;
}
return checkResult;
}
private bool YearNotLessThanMinimumYear(int yearPassed)
{
bool resultCheck = true;
if (yearPassed < DateTime.MinValue.Year)
{
resultCheck = false;
}
return resultCheck;
}
private bool YearNotGreaterThanMaximumYear(int yearPassed)
{
bool resultCheck = true;
if (yearPassed > DateTime.MaxValue.Year)
{
resultCheck = false;
}
return resultCheck;
}
#endregion
}
}
|
06bf096c756dd12889c4eba29245eea40c50a846
|
C#
|
pep4eto1211/SimpleCompiler
|
/SimpleCompiler.Compiler/CodeCompiler.cs
| 2.53125
| 3
|
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SimpleCompiler.Compiler
{
public class CodeCompiler
{
#region Constants
private const string _COMPILER_VERSION = "v3.5";
#endregion
#region Public methods
public static void CompileCode(string[] referenceAssemblies, string resultBinaryLocation, string code, bool includeDebugInformation, out List<string> compileErrors)
{
compileErrors = new List<string>();
var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", _COMPILER_VERSION } });
var parameters = new CompilerParameters(referenceAssemblies, resultBinaryLocation, includeDebugInformation);
parameters.GenerateExecutable = true;
CompilerResults results = csc.CompileAssemblyFromSource(parameters, code);
compileErrors = results.Errors.Cast<CompilerError>().Select(e => e.ErrorText).ToList();
}
#endregion
}
}
|
b5d1c2c16e56a5704243be351ee4f56ea6244145
|
C#
|
nassarao/AnalyzeProperty
|
/PropertyAnalyzerLib/Property.cs
| 3.265625
| 3
|
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
namespace PropertyAnalyzerLib
{
public class Property
{
public string PropertyType { get; set; }
public Address Address { get; set; }
public double PropertyTax { get; set; }
public int UnitCount { get; set; }
public Property(Address address, string propertyType)
{
Address = address;
PropertyType = propertyType;
if (PropertyType == PropertyTypes.SINGLE_FAMILY)
UnitCount = 1;
else if (PropertyType == PropertyTypes.DUPLEX)
UnitCount = 2;
else if (PropertyType == PropertyTypes.TRIPLEX)
UnitCount = 3;
else if (PropertyType == PropertyTypes.QUADPLEX)
UnitCount = 4;
}
override
public string ToString()
{
return String.Format("Property Details|Address: {0}|Property Type: {1}|Unit Count: {2}|Property Tax:{3}",
Address.ToString(), PropertyType, UnitCount, PropertyTax);
}
}
public class Address
{
public string StreetNumber { get; set; }
public string StreetName { get; set; }
public string City { get; set; }
public string Zip { get; set; }
public string State { get; set; }
public Address(string streetNum, string streetName, string city, string zip, string state)
{
StreetNumber = streetNum;
StreetName = streetName;
City = city;
Zip = zip;
State = state;
}
override
public string ToString()
{
return String.Format("{0} {1} {2} {3} {4}", StreetNumber, StreetName, City, State, Zip);
}
}
public static class PropertyTypes
{
public static string SINGLE_FAMILY = "Single Family";
public static string DUPLEX = "Duplex";
public static string TRIPLEX = "Triplex";
public static string QUADPLEX = "Quadplex";
public static string APARTMNET_BUILDING = "Apartment building";
}
}
|
6d67f5d6c2e098b5274b52261b5643ae009b6551
|
C#
|
bippity/Sign-Editor
|
/Sign_Editor/FileTools.cs
| 2.953125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using TShockAPI;
namespace Sign_Editor
{
public static class FileTools
{
private static string workpath = Path.Combine(TShock.SavePath, "Sign Editor");
public static string DirPath
{
get { return workpath; }
}
public static bool CheckDir(string path)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
return false;
}
return true;
}
public static string Load(string filename)
{
var path = Path.Combine(workpath, filename);
if (!CheckDir(workpath) || !File.Exists(path))
{
return null;
}
return File.ReadAllText(path);
}
public static bool Save(string filename, string text)
{
try
{
var path = Path.Combine(workpath, filename);
CheckDir(workpath);
File.WriteAllText(path, text);
}
catch (Exception ex)
{
TShock.Log.ConsoleError(ex.ToString());
return false;
}
return true;
}
public static List<string> ListFiles()
{
var list = new List<string>();
var files = Directory.EnumerateFiles(workpath).ToList();
FileInfo info;
foreach (var file in files)
{
info = new FileInfo(file);
if (info.Extension == ".txt")
list.Add(info.Name);
}
return list;
}
}
}
|
49144a12240fe0ab16fcf07f9b917051713e9eb0
|
C#
|
zhoulk/LeeCode
|
/Test00819.cs
| 3.265625
| 3
|
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
public class Test00819 : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Debug.Log(MostCommonWord("Bob hit a ball, the hit BALL flew far after it was hit.", new string[] { "hit" }));
}
// 给定一个段落(paragraph) 和一个禁用单词列表(banned)。返回出现次数最多,同时不在禁用列表中的单词。
//题目保证至少有一个词不在禁用列表中,而且答案唯一。
//禁用列表中的单词用小写字母表示,不含标点符号。段落中的单词不区分大小写。答案都是小写字母。
//示例:
//输入:
//paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
//banned = ["hit"]
// 输出: "ball"
//解释:
//"hit" 出现了3次,但它是一个禁用的单词。
//"ball" 出现了2次(同时没有其他单词出现2次),所以它是段落里出现次数最多的,且不在禁用列表中的单词。
//注意,所有这些单词在段落里不区分大小写,标点符号需要忽略(即使是紧挨着单词也忽略, 比如 "ball,"),
//"hit"不是最终的答案,虽然它出现次数更多,但它在禁用单词列表中。
//提示:
//1 <= 段落长度 <= 1000
//0 <= 禁用单词个数 <= 100
//1 <= 禁用单词长度 <= 10
//答案是唯一的, 且都是小写字母(即使在 paragraph 里是大写的,即使是一些特定的名词,答案都是小写的。)
//paragraph 只包含字母、空格和下列标点符号!?',;.
//不存在没有连字符或者带有连字符的单词。
//单词里只包含字母,不会出现省略号或者其他标点符号。
public string MostCommonWord(string paragraph, string[] banned)
{
paragraph += ".";
Dictionary<string, int> count = new Dictionary<string, int>();
HashSet<string> hs = new HashSet<string>();
foreach(var s in banned)
{
hs.Add(s);
}
int ansfreq = 0;
string ans = "";
StringBuilder word = new StringBuilder();
foreach(var c in paragraph.ToCharArray())
{
if (isChar(c))
{
word.Append(c);
}
else if(word.Length > 0)
{
string finalword = word.ToString().ToLower();
if (!hs.Contains(finalword))
{
if (count.ContainsKey(finalword))
{
count[finalword]++;
}
else
{
count.Add(finalword, 1);
}
if (count[finalword] > ansfreq)
{
ans = finalword;
ansfreq = count[finalword];
}
}
word.Clear();
}
}
return ans;
}
bool isChar(char c)
{
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
}
|
5b039d7f4459872f696f0906ab72223ece43d662
|
C#
|
zsjzhang/testgit
|
/Vcyber.BLMS.Common/AppServiceLocator.cs
| 2.59375
| 3
|
// <copyright file="AppServiceLocator.cs" company="Microsoft">
// © Vcyber - All rights reserved.
// </copyright>
using System;
using System.Collections.Generic;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
namespace Vcyber.BLMS.Common
{
/// <summary>
/// An implementation of a Service Locator for use in CMS applications.
/// </summary>
public class AppServiceLocator
{
#region Private Variables
/// <summary>
/// A UnityContainer object for managing service instances.
/// </summary>
private IUnityContainer container;
#endregion
#region Constructors
/// <summary>
/// Initializes static members of the <see cref="AppServiceLocator" /> class.
/// </summary>
static AppServiceLocator()
{
Instance = new AppServiceLocator();
}
/// <summary>
/// Initializes a new instance of the <see cref="AppServiceLocator"/> class.
/// </summary>
public AppServiceLocator()
: this(new UnityContainer())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AppServiceLocator"/> class.
/// </summary>
/// <param name="container">A UnityContainer to be used for managing service instances</param>
public AppServiceLocator(IUnityContainer container)
{
this.container = container;
// Load the default container configuration
this.container.LoadConfiguration();
}
#endregion
/// <summary>
/// Gets an instance of AppServiceLocator
/// </summary>
public static AppServiceLocator Instance { get; private set; }
#region Public Methods
/// <summary>
/// Indicates whether a type has been registered.
/// </summary>
/// <typeparam name="T">Type to check</typeparam>
/// <returns>True if the type has been registered.</returns>
public bool IsRegistered<T>()
{
return this.container.IsRegistered<T>();
}
/// <summary>
/// Register a Type and resolve an instance.
/// </summary>
/// <typeparam name="TFrom">Interface Type</typeparam>
/// <typeparam name="TTo">Implementation Type</typeparam>
public void RegisterType<TFrom, TTo>() where TTo : TFrom
{
this.container.RegisterType<TFrom, TTo>();
}
/// <summary>
/// Register a Type and resolve an instance.
/// </summary>
/// <typeparam name="TFrom">Interface Type</typeparam>
/// <typeparam name="TTo">Implementation Type</typeparam>
/// <param name="injectionMembers">Array of injection members</param>
public void RegisterType<TFrom, TTo>(params InjectionMember[] injectionMembers) where TTo : TFrom
{
this.container.RegisterType<TFrom, TTo>(injectionMembers);
}
/// <summary>
/// Register a Type and resolve an instance.
/// </summary>
/// <typeparam name="TFrom">Interface Type</typeparam>
/// <typeparam name="TTo">Implementation Type</typeparam>
/// <param name="name">The name of the item to register.</param>
/// <param name="injectionMembers">Array of injection members</param>
public void RegisterType<TFrom, TTo>(string name, params InjectionMember[] injectionMembers) where TTo : TFrom
{
this.container.RegisterType<TFrom, TTo>(name, injectionMembers);
}
/// <summary>
/// Register an instance of a Type
/// </summary>
/// <typeparam name="TInterface">Type to be registered</typeparam>
/// <param name="instance">Instance to be registered.</param>
public void RegisterInstance<TInterface>(TInterface instance)
{
this.container.RegisterInstance<TInterface>(instance);
}
/// <summary>
/// Register an instance of a Type
/// </summary>
/// <typeparam name="TInterface">Type to be registered</typeparam>
/// <param name="name">The name of the item to register.</param>
/// <param name="instance">Instance to be registered.</param>
public void RegisterInstance<TInterface>(string name, TInterface instance)
{
this.container.RegisterInstance<TInterface>(name, instance);
}
/// <summary>
/// Retrieve an instance of the requested service.
/// </summary>
/// <typeparam name="T">Type of instance requested.</typeparam>
/// <returns>A resolved instance of the requested service.</returns>
public T GetInstance<T>()
{
return this.container.Resolve<T>();
}
/// <summary>
/// Retrieve an instance of the requested service.
/// </summary>
/// <typeparam name="T">Type of instance requested.</typeparam>
/// <param name="key">Name of the specific instance of registered service requested. May be null.</param>
/// <returns>A resolved instance of the requested service.</returns>
public T GetInstance<T>(string key)
{
return this.container.Resolve<T>(key);
}
/// <summary>
/// Tries to get an Instance and returns false when not found rather than throw an exception
/// </summary>
/// <typeparam name="T">The type of Instance to get</typeparam>
/// <param name="key">The key of the Instace to get</param>
/// <param name="result">The result to assign the Instance to</param>
/// <returns>A true if the get succeeds, otherwise false</returns>
public bool TryGetInstance<T>(string key, out T result)
{
result = default(T);
try
{
result = this.container.Resolve<T>(key);
}
catch
{
return false;
}
return true;
}
/// <summary>
/// Retrieve an instance of the requested service.
/// </summary>
/// <param name="serviceType">Type of instance requested.</param>
/// <returns>A resolved instance of the requested service.</returns>
public object GetInstance(Type serviceType)
{
return this.container.Resolve(serviceType);
}
/// <summary>
/// Retrieve an instance of the requested service.
/// </summary>
/// <param name="serviceType">Type of instance requested.</param>
/// <param name="key">Name of the specific instance of registered service requested. May be null.</param>
/// <returns>A resolved instance of the requested service.</returns>
public object GetInstance(Type serviceType, string key)
{
return this.container.Resolve(serviceType, key);
}
/// <summary>
/// Retrieves all instances of the requested service.
/// </summary>
/// <typeparam name="T">Type of the service requested.</typeparam>
/// <returns>A collection of all the resolved instances of the requested service.</returns>
public IEnumerable<T> GetAllInstances<T>()
{
return this.container.ResolveAll<T>();
}
/// <summary>
/// Retrieves all instances of the requested service.
/// </summary>
/// <param name="serviceType">Type of the service requested.</param>
/// <returns>A collection of all the resolved instances of the requested service.</returns>
public IEnumerable<object> GetAllInstances(Type serviceType)
{
return this.container.ResolveAll(serviceType);
}
#endregion
}
}
|
a3b4f46f9166bfb62b78f931d8b8a955b1970dbb
|
C#
|
UtahC/Accounting-csharp-wpf
|
/Accounting/Item.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Accounting
{
public class Item
{
public Item()
{
}
public Item(DateTime time, string cusName, string itemName, int count, int weight, int price, string note)
{
this.time = time;
this.cusName = cusName;
this.itemName = itemName;
this.count = count;
this.weight = weight;
this.price = price;
this.note = note;
}
public Item(int id, DateTime time, string cusName, string itemName, int count, int weight, int price, string note) {
this.id = id;
this.time = time;
this.cusName = cusName;
this.itemName = itemName;
this.count = count;
this.weight = weight;
this.price = price;
this.note = note;
}
public int id { get; set; }
public DateTime time { get; set; }
public string cusName { get; set; }
public string itemName { get; set; }
public int count { get; set; }
public int weight { get; set; }
public int price { get; set; }
public string note { get; set; }
}
}
|
2459ba052793ef42b63e1a7b9fa60e1ed7fc9372
|
C#
|
HelWord/DataGridView-Extension
|
/SuperGridControlExtension.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using System.Drawing;
using System.ComponentModel;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using DevComponents.SuperGrid;
using DevComponents.DotNetBar.SuperGrid;
namespace GeneralAutoTestUI
{
public static class SuperGridControlExtension
{
public static void GenerateColumnFromClass(this SuperGridControl ctl, Type target)
{
/*****************************反射生成各列*******************************************/
/* 根据类的属性/属性/属性生成SuperGridControl的列 */
/* 列名为属性的Description Attribute */
/* 是否显示为列根据属性的Browsable Attribute */
/* 根据类的属性/属性/属性生成SuperGridControl的列 */
/*****************************反射生成各列*******************************************/
if (ctl == null || target == null)
return;
ctl.PrimaryGrid.Columns.Clear();
PropertyInfo[] classPropertyInfo;
classPropertyInfo = target.GetProperties(BindingFlags.Public | BindingFlags.Instance);//获得属性名
if (classPropertyInfo == null || classPropertyInfo.Length < 1)
return;
string catKey = "";
for (int i = 0; i < classPropertyInfo.Length; i++)
{
object[] objs = classPropertyInfo[i].GetCustomAttributes(typeof(DescriptionAttribute), true);
object[] objs1 = classPropertyInfo[i].GetCustomAttributes(typeof(BrowsableAttribute), true); //根据BrowsableAttribute判断是否显示为列
bool visible = true;
if (objs != null && objs.Length > 0)
{
if (objs1 != null && objs1.Length > 0) visible = ((BrowsableAttribute)objs1[0]).Browsable;
if (visible)
{
catKey = ((DescriptionAttribute)objs[0]).Description;
if (string.IsNullOrEmpty(catKey))
catKey = string.Format("列{0}", i + 1); //设置默认列名
GridColumn col = new GridColumn(catKey);
col.DataPropertyName = classPropertyInfo[i].Name; //设置绑定的信号属性
col.ColumnSortMode = ColumnSortMode.None; //禁止排序
col.ResizeMode = ColumnResizeMode.None; //禁止用户调整宽度
col.CellStyles.Default.Alignment = DevComponents.DotNetBar.SuperGrid.Style.Alignment.MiddleCenter; //单元格内容居中显示
ctl.PrimaryGrid.Columns.Add(col);
}
}
}
}
public static void GenerateColumnFromClassWithDefaultEditor(this SuperGridControl ctl, Type target, int readonlyCol = 0)
{
if (ctl == null || target == null)
return;
ctl.PrimaryGrid.Columns.Clear();
PropertyInfo[] classPropertyInfo;
classPropertyInfo = target.GetProperties(BindingFlags.Public | BindingFlags.Instance);//获得属性名
if (classPropertyInfo == null || classPropertyInfo.Length < 1)
return;
string catKey = "";
string editorType = "";
for (int i = 0; i < classPropertyInfo.Length; i++)
{
Type t = classPropertyInfo[i].PropertyType; // t will be System.String
editorType = t.ToString();
object[] objs = classPropertyInfo[i].GetCustomAttributes(typeof(DescriptionAttribute), true);
if (objs != null && objs.Length > 0)
{
catKey = ((DescriptionAttribute)objs[0]).Description;
if (string.IsNullOrEmpty(catKey))
catKey = string.Format("列{0}", i + 1);
//continue;
GridColumn col = new GridColumn(catKey);
if (i == readonlyCol)
col.ReadOnly = true;
col.DataPropertyName = classPropertyInfo[i].Name;
if (editorType == "System.Boolean")
col.EditorType = typeof(GridCheckBoxXEditControl);
else if (editorType == "System.Int32")
col.EditorType = typeof(GridNumericUpDownEditControl);
else if (editorType == "System.Single")
col.EditorType = typeof(GridDoubleInputEditControl);
else
col.EditorType = typeof(GridTextBoxXEditControl);
ctl.PrimaryGrid.Columns.Add(col);
}
}
}
public static void FullScreenGridControlInWidth(this SuperGridControl ctl)
{
/**************************计算公式**********************************************/
/* 单元格宽度 = (总可用宽度)/ 列数 */
/******************************计算公式******************************************/
if (ctl == null || ctl.PrimaryGrid.Columns.Count <= 0)
return;
int count = ctl.PrimaryGrid.Columns.Count;
int totalWidth = 0; //可使用的宽度
if (ctl.VScrollBarVisible)
totalWidth = ctl.Width - System.Windows.Forms.SystemInformation.VerticalScrollBarWidth;
else
totalWidth = ctl.Width;
if (ctl.PrimaryGrid.ShowRowHeaders)
totalWidth = totalWidth - ctl.PrimaryGrid.RowHeaderWidth;
int widthUnit = totalWidth / count;
for (int i = 0; i < count - 1; i++)
{
ctl.PrimaryGrid.Columns[i].Width = widthUnit;
}
ctl.PrimaryGrid.Columns[count - 1].Width = totalWidth - (count - 1) * widthUnit; //最后一列占据剩余的宽度
}
public static void SaveDataToFile(this SuperGridControl ctl, string filePath)
{
if (string.IsNullOrEmpty(filePath))
return;
if (ctl == null || ctl.PrimaryGrid.Rows.Count < 1)
return;
string dir = Path.GetDirectoryName(filePath);
if (string.IsNullOrEmpty(dir))
return;
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
ctl.PrimaryGrid.SelectAll();
ctl.PrimaryGrid.CopySelectedCellsToClipboard(true);
string str = Clipboard.GetText(TextDataFormat.Text);
File.AppendAllText(filePath, str);
}
public static void SetRowBackColor(this SuperGridControl ctrl, int row)
{
if (ctrl == null || ctrl.PrimaryGrid.Rows.Count < 1 || row > ctrl.PrimaryGrid.Rows.Count)
return;
int count = ctrl.PrimaryGrid.Rows.Count;
if (row < 0)
{
for (int i = 0; i < count; i++)
{
GridRow currentRow = ctrl.PrimaryGrid.Rows[i] as GridRow;
currentRow.CellStyles.Default.Background.Color1 = Color.White;
currentRow.CellStyles.Default.Background.Color2 = Color.White;
}
}
else if (row < ctrl.PrimaryGrid.Rows.Count)
{
for (int i = 0; i <= row; i++)
{
GridRow currentRow = ctrl.PrimaryGrid.Rows[i] as GridRow;
if (i < row)
{
currentRow.CellStyles.Default.Background.Color1 = Color.LightGray;
currentRow.CellStyles.Default.Background.Color2 = Color.LightGray;
}
else
{
currentRow.CellStyles.Default.Background.Color1 = Color.Green;
currentRow.CellStyles.Default.Background.Color2 = Color.Green;
}
}
}
else
{
for (int i = 0; i <= row - 1; i++)
{
GridRow currentRow = ctrl.PrimaryGrid.Rows[i] as GridRow;
currentRow.CellStyles.Default.Background.Color1 = Color.LightGray;
currentRow.CellStyles.Default.Background.Color2 = Color.LightGray;
}
}
}
/// <summary>
/// 设置单元格字体颜色
/// <para>可用于设置执行结果是否成功的指示</para>
/// </summary>
/// <param name="ctl">SuperGridControl</param>
/// <param name="row">行</param>
/// <param name="col">列</param>
/// <param name="color">颜色</param>
public static void SetCellForeColor(this SuperGridControl ctl, int row, int col, System.Drawing.Color color)
{
if (ctl == null || ctl.PrimaryGrid.Columns.Count < 1 || ctl.PrimaryGrid.Rows.Count < 1)
return;
if (row >= ctl.PrimaryGrid.Rows.Count || col >= ctl.PrimaryGrid.Columns.Count)
return;
GridRow targetRow = ctl.PrimaryGrid.Rows[row] as GridRow;
targetRow.Cells[col].CellStyles.Default.TextColor = color;
}
/// <summary>
/// 设置单元格背景色
/// <para>可用于设置执行结果是否成功的指示</para>
/// </summary>
/// <param name="ctl">SuperGridControl</param>
/// <param name="row">行</param>
/// <param name="col">列</param>
/// <param name="color">颜色</param>
public static void SetCellBackColor(this SuperGridControl ctl, int row, int col, System.Drawing.Color color)
{
if (ctl == null || ctl.PrimaryGrid.Columns.Count < 1 || ctl.PrimaryGrid.Rows.Count < 1)
return;
if (row >= ctl.PrimaryGrid.Rows.Count || col >= ctl.PrimaryGrid.Columns.Count)
return;
GridRow targetRow = ctl.PrimaryGrid.Rows[row] as GridRow;
targetRow.Cells[col].CellStyles.Default.Background.Color1 = color;
targetRow.Cells[col].CellStyles.Default.Background.Color2 = color;
}
public static void SetRowHeight(this SuperGridControl ctl, int rowHeight, int font)
{
if (ctl == null || ctl.PrimaryGrid.Columns.Count <= 0)
return;
for (int i = 0; i < ctl.PrimaryGrid.Columns.Count; i++)
{
ctl.PrimaryGrid.Columns[i].CellStyles.Default.Font = new System.Drawing.Font("Times New Roman", font);
}
ctl.PrimaryGrid.MinRowHeight = rowHeight;
}
}
}
|
62198987ccbd9269f0ac4f330cdebfba27522eac
|
C#
|
kpanova/clio
|
/clio/Package/NuGet/NugetPackagesProvider.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using Clio.Common;
namespace Clio.Project.NuGet
{
#region Class: NugetPackagesProvider
public class NugetPackagesProvider : INugetPackagesProvider
{
#region Fields: Private
private readonly INugetExecutor _nugetExecutor;
#endregion
#region Constructors: Public
public NugetPackagesProvider(INugetExecutor nugetExecutor)
{
nugetExecutor.CheckArgumentNull(nameof(nugetExecutor));
_nugetExecutor = nugetExecutor;
}
#endregion
#region Methods: Private
private string CorrectNugetSourceUrlForLinux(string nugetSourceUrl)
{
if (nugetSourceUrl.EndsWith('/'))
{
return nugetSourceUrl;
}
return $"{nugetSourceUrl}/";
}
private NugetPackage ParsePackage(string packageWithVersionDescription) {
string[] packageItems = packageWithVersionDescription
.Trim(' ')
.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (packageItems.Length != 2) {
throw new ArgumentException(
$"Wrong format for the package with version: '{packageWithVersionDescription}'. " +
"The format of the package with version must be: <NamePackage> <VersionPackage>");
}
string packageName = packageItems[0].Trim(' ');
PackageVersion packageVersion = PackageVersion.ParseVersion(packageItems[1].Trim(' '));
return new NugetPackage(packageName, packageVersion);
}
private IEnumerable<NugetPackage> ParsePackages(string packagesDescription) {
return packagesDescription
.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
.Select(ParsePackage);
}
private NugetPackage GetLastVersionNugetPackage(string packageName, IEnumerable<NugetPackage> nugetPackages) {
return nugetPackages
.Where(pkg => pkg.Name == packageName)
.OrderByDescending(pkg => pkg.Version)
.FirstOrDefault();
}
private NugetPackage GetLastStableVersionNugetPackage(string packageName,
IEnumerable<NugetPackage> nugetPackages) {
return nugetPackages
.Where(pkg => pkg.Name == packageName)
.OrderByDescending(pkg => pkg.Version)
.FirstOrDefault(pkg => pkg.Version.IsStable);
}
#endregion
#region Methods: Public
public IEnumerable<NugetPackage> GetPackages(string nugetSourceUrl) {
nugetSourceUrl.CheckArgumentNullOrWhiteSpace(nameof(nugetSourceUrl));
nugetSourceUrl = CorrectNugetSourceUrlForLinux(nugetSourceUrl);
string getlistCommand = $"list -AllVersions -PreRelease -Source {nugetSourceUrl}";
string packagesDescription = _nugetExecutor.Execute(getlistCommand, true);
return ParsePackages(packagesDescription);
}
public LastVersionNugetPackages GetLastVersionPackages(string packageName, IEnumerable<NugetPackage> nugetPackages) {
packageName.CheckArgumentNullOrWhiteSpace(nameof(packageName));
nugetPackages.CheckArgumentNull(nameof(nugetPackages));
NugetPackage last = GetLastVersionNugetPackage(packageName, nugetPackages);
NugetPackage stable = GetLastStableVersionNugetPackage(packageName, nugetPackages);
return last == null ? null : new LastVersionNugetPackages(last, stable);
}
public LastVersionNugetPackages GetLastVersionPackages(string packageName, string nugetSourceUrl) {
packageName.CheckArgumentNullOrWhiteSpace(nameof(packageName));
nugetSourceUrl.CheckArgumentNullOrWhiteSpace(nameof(nugetSourceUrl));
nugetSourceUrl = CorrectNugetSourceUrlForLinux(nugetSourceUrl);
IEnumerable<NugetPackage> nugetPackages = GetPackages(nugetSourceUrl);
return GetLastVersionPackages(packageName, nugetPackages);
}
#endregion
}
#endregion
}
|
376793c3cbdeee00196b3860e7705e8c7e4f1324
|
C#
|
enata/PhonemeLattice
|
/PhonemeLattice.Lattice/Builder/WordDivision.cs
| 2.609375
| 3
|
namespace PhonemeLattice.Lattice.Builder
{
internal sealed class WordDivision
{
private readonly int _middlePartLength;
private readonly int _middlePartStart;
private readonly LatticeNode _postfix;
private readonly LatticeNode _prefix;
public WordDivision(LatticeNode prefix, LatticeNode postfix, int middlePartLength, int middlePartStart)
{
_prefix = prefix;
_postfix = postfix;
_middlePartLength = middlePartLength;
_middlePartStart = middlePartStart;
}
public LatticeNode Prefix
{
get { return _prefix; }
}
public LatticeNode Postfix
{
get { return _postfix; }
}
public int MiddlePartLength
{
get { return _middlePartLength; }
}
public int MiddlePartStart
{
get { return _middlePartStart; }
}
}
}
|
20547f96943fbc6a8d32593296a751ebb17b3b08
|
C#
|
pnarimani/quick-find
|
/FindableSODrawer.cs
| 2.546875
| 3
|
using Sirenix.OdinInspector.Editor;
using Sirenix.Utilities;
using Sirenix.Utilities.Editor;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace QuickFind
{
public class FindableSODrawer<T> : OdinValueDrawer<T> where T : ScriptableObject
{
protected override void DrawPropertyLayout(GUIContent label)
{
Rect position = EditorGUILayout.GetControlRect();
Rect fieldRect = position.SubXMax(25);
ValueEntry.SmartValue = (T) SirenixEditorFields.UnityObjectField(fieldRect,
label,
ValueEntry.SmartValue,
typeof(T),
false);
var buttonRect = new Rect(fieldRect.xMax, fieldRect.y, 25, fieldRect.height);
if (GUI.Button(buttonRect, "F"))
{
var guids = AssetDatabase.FindAssets($"t:{typeof(T)}");
if (guids.Length == 0)
{
Debug.LogWarning("Could not find instance of type " + typeof(T));
return;
}
string labelText = label?.text;
if (labelText == null)
{
labelText = Property.Parent.Label.text;
}
if (labelText == null)
{
ValueEntry.SmartValue = AssetDatabase.LoadAssetAtPath<T>(AssetDatabase.GUIDToAssetPath(guids[0]));
}
else
{
// Split label text into words
string[] words = labelText.SplitPascalCase().Split(' ', '-', '_');
(string path, string name)[] names = guids
.Select(guid => (AssetDatabase.GUIDToAssetPath(guid)))
.Select(path => (path, Path.GetFileName(path)))
.ToArray();
string mostSimilarPath = GetMostSimilarTo(words, names);
ValueEntry.SmartValue = AssetDatabase.LoadAssetAtPath<T>(mostSimilarPath);
}
}
}
private string GetMostSimilarTo(string[] words, (string path, string name)[] names)
{
string chosen = null;
int bestScore = int.MinValue;
foreach ((string path, string name) in names)
{
// Calculate score on a word basis and add them all together
int currentScore = words.Sum(x => GetScore(name, x));
if (currentScore > bestScore)
{
chosen = path;
bestScore = currentScore;
}
}
return chosen;
}
private int GetScore(string source, string other)
{
const int sameCaseCharScore = 2;
const int sameCharScore = 1;
int score = 0;
for (int i = 0; i < Math.Min(source.Length, other.Length); i++)
{
char sChar = source[i];
char otherChar = other[i];
if (sChar == otherChar)
{
score += sameCaseCharScore;
continue;
}
if (char.ToLower(sChar) == char.ToLower(otherChar))
{
score += sameCharScore;
}
}
return score;
}
}
}
|
07795593b91a9715bfb2e4f97698d4b1f0ed39bb
|
C#
|
alaminut/design-patterns-course
|
/Mediator/Exercise/Mediator.cs
| 3.140625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Mediator.Exercise
{
public class Mediator
{
private readonly Dictionary<string, Participant> _participants = new Dictionary<string, Participant>();
public string Register(Participant p)
{
var id = Guid.NewGuid().ToString("N");
if (_participants.ContainsKey(id))
{
_participants[id] = p;
}
else
{
_participants.Add(id, p);
}
return id;
}
public void AnnounceValue(string clientId, int value)
{
foreach (var p in _participants.Where(kvp => kvp.Key != clientId).Select(kvp => kvp.Value))
{
p.ReceiveValue(value);
}
}
}
}
|
c0073de23a8384e0901be74aa874ff42149af03a
|
C#
|
delapiero/csharp-design-patterns
|
/Kompozyt/Multiczasteczka.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Kompozyt
{
public class Multiczasteczka : ObiektWieloczasteczkowy
{
private IList<ObiektWieloczasteczkowy> czasteczka;
public Multiczasteczka()
{
czasteczka = new List<ObiektWieloczasteczkowy>();
}
public void przesuniecie(Wektor3d _v)
{
foreach (ObiektWieloczasteczkowy o in czasteczka)
{
o.przesuniecie(_v);
}
}
public double Masa
{
get
{
double sumaMasy = 0;
foreach (ObiektWieloczasteczkowy o in czasteczka)
sumaMasy += o.Masa;
return sumaMasy;
}
}
public int Zlozonosc
{
get
{
int zlozonosc = 0;
foreach (ObiektWieloczasteczkowy o in czasteczka)
zlozonosc += o.Zlozonosc;
return zlozonosc;
}
}
public Wektor3d SrodekMasy
{
get
{
Wektor3d _v = new Wektor3d(0, 0, 0);
double sumaMasy = 0;
foreach (ObiektWieloczasteczkowy o in czasteczka)
{
Wektor3d c = o.SrodekMasy;
_v.x += c.x * o.Masa;
_v.y += c.y * o.Masa;
_v.z += c.z * o.Masa;
sumaMasy += o.Masa;
}
_v.x /= sumaMasy;
_v.y /= sumaMasy;
_v.z /= sumaMasy;
return _v;
}
}
public Wektor3d SrodekGeometryczny
{
get
{
Wektor3d _v = new Wektor3d(0, 0, 0);
int iloscCzastek = 0;
foreach (ObiektWieloczasteczkowy o in czasteczka)
{
Wektor3d c = o.SrodekGeometryczny;
iloscCzastek += o.Zlozonosc;
_v.x += c.x;
_v.y += c.y;
_v.z += c.z;
}
_v.x /= iloscCzastek;
_v.y /= iloscCzastek;
_v.z /= iloscCzastek;
return _v;
}
}
public void dodaj(ObiektWieloczasteczkowy o)
{
czasteczka.Add(o);
}
public void usun(ObiektWieloczasteczkowy o)
{
czasteczka.Remove(o);
}
public override string ToString()
{
string wynik = "";
foreach (ObiektWieloczasteczkowy o in czasteczka)
{
wynik += o.ToString();
}
return wynik;
}
}
}
|
4dd439b02e9fa712d6e439bcafbd07d26efdda0c
|
C#
|
alanoudalhamid/VR-TicTacToe
|
/vrnd-tic-tac-toe-starter-project-v1.1.0/Tic-Tac-Toe/Assets/Scripts/PlayerPiece.cs
| 2.515625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerPiece : MonoBehaviour {
public bool hasBeenPlayed = false;
Vector3 OriginalLocation;
Vector3 SelectedLocation;
// Use this for initialization
void Start () {}
// Update is called once per frame
void Update () {}
public void inPlay() {
OriginalLocation = this.transform.position;
SelectedLocation = new Vector3(OriginalLocation.x, OriginalLocation.y + 0.3f, OriginalLocation.z);
this.transform.position = SelectedLocation;
//StartCoroutine(SmoothMove(SelectedLocation));
GetComponent<Collider>().enabled = false;
}
public void PlayPiece(GameObject GridPlate) {
hasBeenPlayed = true;
GridPlate.GetComponent<Collider>().enabled = false;
SelectedLocation = new Vector3(GridPlate.transform.position.x, GridPlate.transform.position.y, GridPlate.transform.position.z);
//this.transform.position = new Vector3(GridPlate.transform.position.x, GridPlate.transform.position.y + 0.3f, GridPlate.transform.position.z);
this.transform.position = SelectedLocation;
//StartCoroutine(SmoothMove(SelectedLocation));
//Tell our GameLogic script to occupy the game board array at the right location with a player piece
}
/*public void SmoothMove(Vector3 toLocation)
{
/* float closeEnough = 0.01f;
float distance = (this.transform.position - toLocation).magnitude;
WaitForEndOfFrame wait = new WaitForEndOfFrame();/////////
while (distance >= closeEnough)
{
transform.position = Vector3.Slerp(this.transform.position, toLocation, 0.1f);
yield return wait;
distance = (this.transform.position - toLocation).magnitude;
}
this.transform.position = toLocation;
}*/
}
|
3236dea03205bb8bc53d342723ec25f6d57cc152
|
C#
|
HellGoesOn/PizzaSimulator
|
/PizzaSimulator/Content/Entities/EntityManager.cs
| 2.65625
| 3
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using PizzaSimulator.Content.Components;
using PizzaSimulator.Content.Enums;
using PizzaSimulator.Helpers;
using System.Collections.Generic;
namespace PizzaSimulator.Content.Entities
{
public class EntityManager : Singleton<EntityManager>
{
public void SetDeltaTime(GameTime gameTime)
{
DeltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
}
public void Update()
{
foreach (Entity e in Entities)
{
e.Highlighted = false;
if (e.MyCollider.Hitbox.Contains(InputManager.MouseScreenPosition))
e.Highlighted = true;
}
foreach (Entity e in EntitiesToRemove)
Entities.Remove(e);
EntitiesToRemove.Clear();
}
public static void CreateEntity(EntityType entity, Vector2 position)
{
switch(entity)
{
case EntityType.Customer:
Customer.SpawnCustomer(position);
break;
case EntityType.Worker:
Worker.SpawnWorker(position);
break;
case EntityType.Pudge:
Pudge.SpawnPudge(position);
break;
}
}
public static void KillEntity(Entity e)
{
Entity entityRef = null;
foreach(Entity entity in Instance.Entities)
if (entity == e)
entityRef = entity;
Instance.EntitiesToRemove.Add(entityRef);
}
public float DeltaTime { get; private set; }
public List<Entity> Entities { get; } = new List<Entity>();
public HashSet<Entity> EntitiesToRemove { get; } = new HashSet<Entity>();
}
}
|
bc97c513ae060c4239e49436ae1441b8db5d4fa8
|
C#
|
switchspan/DukeSharp
|
/Duke/Duke.Test/Cleaners/DigitsOnlyCleanerTest.cs
| 3.421875
| 3
|
using System;
using Duke.Cleaners;
using NUnit.Framework;
namespace Duke.Test
{
[TestFixture]
public class DigitsOnlyCleanerTest
{
#region Setup/Teardown
[SetUp]
public void Init()
{
// Setup code goes here...
_cleaner = new DigitsOnlyCleaner();
}
[TearDown]
public void Cleanup()
{
// TearDown code goes here...
_cleaner = null;
}
#endregion
private DigitsOnlyCleaner _cleaner;
[Test]
public void Clean_AlphanumericString_ReturnsOnlyDigits()
{
const string valueToClean = "Abc12321hds";
string actual = _cleaner.Clean(valueToClean);
Console.WriteLine(String.Format("Alphanumeric Digits clean result = {0}", actual));
Assert.AreEqual("12321", actual);
}
[Test]
public void Clean_NoDigitsInString_ReturnsEmptyString()
{
const string valueToClean = "alsdkfjLSKJFSHDFSD";
string actual = _cleaner.Clean(valueToClean);
Console.WriteLine(String.Format("Only Alpha Digits clean result = {0}", actual));
Assert.IsEmpty(actual);
}
}
}
|
ec6ac009acf50bcdaad60bd2717289ce47fdb243
|
C#
|
MRTSoft/an_iv_ia
|
/LaboratorIA08/Interfata/MainForm.cs
| 2.828125
| 3
|
/**************************************************************************
* *
* Copyright: (c) 2016-2017, Florin Leon *
* E-mail: florin.leon@tuiasi.ro *
* Website: http://florinleon.byethost24.com/lab_ia.htm *
* Description: Game playing. Minimax algorithm *
* (Artificial Intelligence lab 8) *
* *
* This code and information is provided "as is" without warranty of *
* any kind, either expressed or implied, including but not limited *
* to the implied warranties of merchantability or fitness for a *
* particular purpose. You are free to use this source code in your *
* applications as long as the original copyright notice is included. *
* *
**************************************************************************/
using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace SimpleCheckers
{
public partial class MainForm : Form
{
private Board _board;
private int _selected; // indexul piesei selectate
private PlayerType _currentPlayer; // om sau calculator
private Bitmap _boardImage;
public MainForm()
{
InitializeComponent();
try
{
_boardImage = (Bitmap)Image.FromFile("board.png");
}
catch
{
MessageBox.Show("Nu se poate incarca board.png");
Environment.Exit(1);
}
_board = new Board();
_currentPlayer = PlayerType.None;
_selected = -1; // nicio piesa selectata
this.ClientSize = new System.Drawing.Size(927, 600);
this.pictureBoxBoard.Size = new System.Drawing.Size(500, 500);
pictureBoxBoard.Refresh();
}
private void pictureBoxBoard_Paint(object sender, PaintEventArgs e)
{
Bitmap board = new Bitmap(_boardImage);
e.Graphics.DrawImage(board, 0, 0);
if (_board == null)
return;
int dy = 500 - 125 + 12;
SolidBrush transparentRed = new SolidBrush(Color.FromArgb(192, 255, 0, 0));
SolidBrush transparentGreen = new SolidBrush(Color.FromArgb(192, 0, 128, 0));
SolidBrush transparentYellow = new SolidBrush(Color.FromArgb(192, 255, 255, 0));
foreach (Piece p in _board.Pieces)
{
SolidBrush brush = transparentRed;
if (p.Player == PlayerType.Human)
{
if (p.Id == _selected)
brush = transparentYellow;
else
brush = transparentGreen;
}
e.Graphics.FillEllipse(brush, 12 + p.X * 125, dy - p.Y * 125, 100, 100);
}
}
private void pictureBoxBoard_MouseUp(object sender, MouseEventArgs e)
{
if (_currentPlayer != PlayerType.Human)
return;
int mouseX = e.X / 125;
int mouseY = 3 - e.Y / 125;
if (_selected == -1)
{
foreach (Piece p in _board.Pieces.Where(a => a.Player == PlayerType.Human))
{
if (p.X == mouseX && p.Y == mouseY)
{
_selected = p.Id;
pictureBoxBoard.Refresh();
break;
}
}
}
else
{
Piece selectedPiece = _board.Pieces[_selected];
if (selectedPiece.X == mouseX && selectedPiece.Y == mouseY)
{
_selected = -1;
pictureBoxBoard.Refresh();
}
else
{
Move m = new Move(_selected, mouseX, mouseY);
if (selectedPiece.IsValidMove(_board, m))
{
_selected = -1;
Board b = _board.MakeMove(m);
AnimateTransition(_board, b);
_board = b;
pictureBoxBoard.Refresh();
_currentPlayer = PlayerType.Computer;
CheckFinish();
if (_currentPlayer == PlayerType.Computer) // jocul nu s-a terminat
ComputerMove();
}
}
}
}
private void ComputerMove()
{
Board nextBoard = Minimax.FindNextBoard(_board);
AnimateTransition(_board, nextBoard);
_board = nextBoard;
pictureBoxBoard.Refresh();
_currentPlayer = PlayerType.Human;
CheckFinish();
}
private void CheckFinish()
{
bool end; PlayerType winner;
_board.CheckFinish(out end, out winner);
if (end)
{
if (winner == PlayerType.Computer)
{
MessageBox.Show("Calculatorul a castigat!");
_currentPlayer = PlayerType.None;
}
else if (winner == PlayerType.Human)
{
MessageBox.Show("Ai castigat!");
_currentPlayer = PlayerType.None;
}
}
}
private void AnimateTransition(Board b1, Board b2)
{
Bitmap board = new Bitmap(_boardImage);
int dy = 500 - 125 + 12;
SolidBrush transparentRed = new SolidBrush(Color.FromArgb(192, 255, 0, 0));
SolidBrush transparentGreen = new SolidBrush(Color.FromArgb(192, 0, 128, 0));
Bitmap final = new Bitmap(500, 500);
Graphics g = Graphics.FromImage(final);
int noSteps = 50;
for (int j = 1; j < noSteps; j++)
{
g.DrawImage(board, 0, 0);
for (int i = 0; i < b1.Pieces.Count; i++)
{
double avx = (j * b2.Pieces[i].X + (noSteps - j) * b1.Pieces[i].X) / (double)noSteps;
double avy = (j * b2.Pieces[i].Y + (noSteps - j) * b1.Pieces[i].Y) / (double)noSteps;
SolidBrush brush = transparentRed;
if (b1.Pieces[i].Player == PlayerType.Human)
brush = transparentGreen;
g.FillEllipse(brush, (int)(12 + avx * 125), (int)(dy - avy * 125), 100, 100);
}
Graphics pbg = pictureBoxBoard.CreateGraphics();
pbg.DrawImage(final, 0, 0);
}
}
private void jocNouToolStripMenuItem_Click(object sender, System.EventArgs e)
{
_board = new Board();
_currentPlayer = PlayerType.Computer;
ComputerMove();
}
private void despreToolStripMenuItem_Click(object sender, EventArgs e)
{
const string copyright =
"Algoritmul minimax\r\n" +
"Inteligenta artificiala, Laboratorul 8\r\n" +
"(c)2016-2017 Florin Leon\r\n" +
"http://florinleon.byethost24.com/lab_ia.htm";
MessageBox.Show(copyright, "Despre jocul Dame simple");
}
private void iesireToolStripMenuItem_Click(object sender, System.EventArgs e)
{
Environment.Exit(0);
}
}
}
|
f35bc70c2b6b33d8dbd761d096311a8e160e2c0c
|
C#
|
sonicpro/MSSpeech
|
/helloworld/helloworld/Program.cs
| 2.953125
| 3
|
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;
using System;
using System.Threading.Tasks;
namespace helloworld
{
class Program
{
static void Main(string[] args)
{
RecognizeSpeechAsync().Wait();
Console.WriteLine("Please press <Return> to continue.");
Console.ReadLine();
}
public static async Task RecognizeSpeechAsync()
{
var config = SpeechConfig.FromSubscription("f36e26ed19334a5381b09bd28425ff49", "northeurope");
using (var recognizer = new SpeechRecognizer(config, AudioConfig.FromDefaultMicrophoneInput()))
{
Console.WriteLine("Say something...");
var result = await recognizer.RecognizeOnceAsync();
if (result.Reason == ResultReason.RecognizedSpeech)
{
Console.WriteLine($"We recognized: {result.Text}");
}
else if (result.Reason == ResultReason.NoMatch)
{
Console.WriteLine($"NOMATCH: Speech could not be recognized.");
}
else if (result.Reason == ResultReason.Canceled)
{
var cancellation = CancellationDetails.FromResult(result);
Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");
if (cancellation.Reason == CancellationReason.Error)
{
Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
Console.WriteLine($"CANCELED: ErrorDetails={cancellation.ErrorDetails}");
Console.WriteLine($"CANCELED: Did you update the subscription info?");
}
}
}
}
}
}
|
e52ce554a758be2dc6ce5b6d4928444230aa8e42
|
C#
|
vjpudelski/Interfaces
|
/Interfaces/Models/Wizard.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Interfaces.Models
{
class Wizard : ISpellCaster
{
public bool Prepare(Spell spellToPrepare)
{
bool spellPrepared = false;
// code for the wizard to prepare the spell to be casted
return spellPrepared;
}
public bool Cast(Spell spellToCast)
{
bool spellCasted = false;
// code to cast the spell
return spellCasted;
}
}
}
|
1038d0f5a7004c66a9c7fe8c6b0e3ca81efd9c5b
|
C#
|
dayluke/udp-server
|
/Server.cs
| 3.234375
| 3
|
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Linq;
namespace UDPServer
{
class Server
{
UdpClient server;
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);
Dictionary<string, Action<object[]>> functionDict = new Dictionary<string, Action<object[]>>();
List<Player> players = new List<Player>();
public Server(int listenPort)
{
server = new UdpClient(listenPort);
functionDict["Print"] = x => Print(x.ToString());
functionDict["PlayerJoined"] = x => PlayerJoined(x);
functionDict["PlayerLeft"] = x => PlayerLeft(x);
// functionDict["PlayerJoined"] = new Action<object>(PlayerJoined);
Console.WriteLine("Server initialised");
}
public void ReceiveData()
{
try
{
while (true)
{
byte[] bytes = server.Receive(ref endPoint);
string data = Encoding.ASCII.GetString(bytes);
Console.WriteLine(String.Format("Server received broadcast from: {0}:{1}", endPoint.Address.ToString(), endPoint.Port.ToString()));
object[] info = data.Split(" -> ");
string command = info[0].ToString();
List<object> t = info.ToList();
t.RemoveAt(0);
info = t.ToArray();
Console.WriteLine(" Command: {0}", command);
Console.WriteLine(" Parameters: [{0}]", string.Join(", ", info));
Console.WriteLine(" Info Length: {0}", info.Length);
// functionDict[command].DynamicInvoke(info[0]);
functionDict[command](info);
}
}
catch (SocketException e)
{
Console.WriteLine(e);
}
finally
{
server.Close();
}
}
public void PlayerJoined(object[] args)
{
string playerName = args[0].ToString();
PlayerType playerType;
if (Enum.TryParse(args[1].ToString(), out playerType)) Console.WriteLine("Enum successfully parsed.");
players.Add(new Player(playerName, playerType));
Console.WriteLine("{0} joined the lobby as an {1}", playerName, playerType);
Console.WriteLine("There are now {0} players in the lobby.", players.Count);
}
public void PlayerLeft(object[] args)
{
string playerName = args[0].ToString();
players.Remove(players.Single(player => player.username == playerName));
Console.WriteLine("Player {0} has left the lobby. There are now {1} players in the lobby.", playerName, players.Count);
}
public void Print(string str)
{
Console.WriteLine("Server received: " + str);
}
}
}
|
330e4355f5a299a5c09d28b36c07ebae4f0f172f
|
C#
|
vmedvedovskiy/fullstack.net-example
|
/Fullstack.NET.Services/Authentication/Tokens/TokenProvider.cs
| 2.640625
| 3
|
using System;
using System.Security.Cryptography;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Runtime.Serialization;
using Microsoft.Extensions.Options;
namespace Fullstack.NET.Services.Authentication.Tokens
{
public class TokenProvider : ITokenProvider, IDisposable
{
private const bool DoOAEPPadding = false;
private readonly RSACryptoServiceProvider cryptoAlgorithm
= new RSACryptoServiceProvider();
private readonly DataContractJsonSerializer serializer
= new DataContractJsonSerializer(typeof(TokenData));
public TokenProvider(IOptions<TokenOptions> opts)
=> this.cryptoAlgorithm.ImportParameters(this.FromOptions(opts.Value));
public string Get(UserModel user)
{
using (var stream = new MemoryStream())
{
var tokenData = new TokenData
{
TodayEpochSeconds = DateTime.Today.ToFileTimeUtc(),
Username = user.Username
};
serializer.WriteObject(stream, tokenData);
var encryptedToken = this.cryptoAlgorithm.Encrypt(
stream.ToArray(),
DoOAEPPadding);
return Convert.ToBase64String(encryptedToken);
}
}
public bool IsValid(string token)
{
var decryptedToken = this.cryptoAlgorithm.Decrypt(
Convert.FromBase64String(token),
DoOAEPPadding);
using (var stream = new MemoryStream(decryptedToken))
{
var deserializedData = (TokenData)serializer.ReadObject(stream);
return deserializedData.TodayEpochSeconds == DateTime.Today.ToFileTimeUtc();
}
}
public void Dispose() => this.cryptoAlgorithm?.Dispose();
private RSAParameters FromOptions(TokenOptions opts)
{
return new RSAParameters
{
D = Convert.FromBase64String(opts.D),
DP = Convert.FromBase64String(opts.DP),
DQ = Convert.FromBase64String(opts.DQ),
Exponent = Convert.FromBase64String(opts.Exponent),
InverseQ = Convert.FromBase64String(opts.InverseQ),
Modulus = Convert.FromBase64String(opts.Modulus),
P = Convert.FromBase64String(opts.P),
Q = Convert.FromBase64String(opts.Q)
};
}
[DataContract]
private class TokenData
{
[DataMember]
public string Username { get; set; }
[DataMember]
public long TodayEpochSeconds { get; set; }
}
}
}
|
484c4943ed90c802031fedb0d9e0a07c78c45170
|
C#
|
sv99/EVOK
|
/xjplc/xjplc/Permutation.cs
| 3.078125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace xjplc
{
public class Permutation
{
public RichTextBox t1;
public int count = 0;
public List<List<int>> patternLstInt;
public List<List<string>> patternLstStr;
public void AllPermutation(char[] s, int n)
{
for (int i = n; i < s.Length; i++)
{
if (n != s.Length - 1)
{
int tn = n + 1;
if (i != n)
{
char tempch = s[n];
s[n] = s[i];
s[i] = tempch;
AllPermutation(s, tn);
s[i] = s[n];
s[n] = tempch;
}
else
{
AllPermutation(s, tn);
}
}
else
{
count++;
string str = new string(s);
if (t1 != null) t1.AppendText(str+"\r\n");
List<int> intL = new List<int>();
List<string> strL = new List<string>();
foreach ( char c in s)
{
int id=0;
if (int.TryParse(c.ToString(),out id))
{
if (patternLstInt != null)
{
intL.Add(id);
}
}
if (patternLstStr!=null)
strL.Add(c.ToString());
}
if (patternLstInt != null)
{
patternLstInt.Add(intL);
}
if (patternLstStr != null)
{
patternLstStr.Add(strL);
}
}
}
}
}
}
|
3abfba13d664cbd5fe799c6287be699821adf7b8
|
C#
|
Flash0ver/F0.Wpf
|
/source/production/F0.Wpf/Windows/Data/LogicalNegationConverter.cs
| 2.75
| 3
|
using System;
using System.Globalization;
using System.Windows.Data;
namespace F0.Windows.Data
{
public sealed class LogicalNegationConverter : IValueConverter
{
public LogicalNegationConverter()
{
}
object? IValueConverter.Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
return Negate(value);
}
object? IValueConverter.ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
{
return Negate(value);
}
private static object? Negate(object? value)
{
if (value is null)
{
return value;
}
else if (value is bool boolean)
{
return !boolean;
}
else
{
string message = $"{nameof(LogicalNegationConverter)} cannot convert from {value.GetType().FullName}.";
throw new NotSupportedException(message);
}
}
}
}
|
f086f4f68792520eb874017233272917e14fc3c1
|
C#
|
SubnauticaNitrox/Harmony
|
/Harmony/HarmonyInstance.cs
| 2.671875
| 3
|
using Harmony.Tools;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
namespace Harmony
{
/// <summary>A Harmony instance</summary>
public class HarmonyInstance
{
readonly string id;
/// <summary>The unique identifier</summary>
public string Id => id;
/// <summary>Set to true before instantiating Harmony to debug Harmony</summary>
public static bool DEBUG = false;
private static bool selfPatchingDone = false;
HarmonyInstance(string id)
{
if (DEBUG)
{
var assembly = typeof(HarmonyInstance).Assembly;
var version = assembly.GetName().Version;
var location = assembly.Location;
if (location == null || location == "") location = new Uri(assembly.CodeBase).LocalPath;
FileLog.Log("### Harmony id=" + id + ", version=" + version + ", location=" + location);
var callingMethod = GetOutsideCaller();
var callingAssembly = callingMethod.DeclaringType.Assembly;
location = callingAssembly.Location;
if (location == null || location == "") location = new Uri(callingAssembly.CodeBase).LocalPath;
FileLog.Log("### Started from " + callingMethod.FullDescription() + ", location " + location);
FileLog.Log("### At " + DateTime.Now.ToString("yyyy-MM-dd hh.mm.ss"));
}
this.id = id;
if (!selfPatchingDone)
{
selfPatchingDone = true;
SelfPatching.PatchOldHarmonyMethods();
}
}
public Patches IsPatched(MethodBase method)
{
return PatchProcessor.IsPatched(method);
}
/// <summary>Creates a new Harmony instance</summary>
/// <param name="id">A unique identifier</param>
/// <returns>A Harmony instance</returns>
///
public static HarmonyInstance Create(string id)
{
if (id == null) throw new Exception("id cannot be null");
return new HarmonyInstance(id);
}
private MethodBase GetOutsideCaller()
{
var trace = new StackTrace(true);
foreach (var frame in trace.GetFrames())
{
var method = frame.GetMethod();
if (method.DeclaringType.Namespace != typeof(HarmonyInstance).Namespace)
return method;
}
throw new Exception("Unexpected end of stack trace");
}
/// <summary>Searches current assembly for Harmony annotations and uses them to create patches</summary>
///
public void PatchAll()
{
var method = new StackTrace().GetFrame(1).GetMethod();
var assembly = method.ReflectedType.Assembly;
PatchAll(assembly);
}
/// <summary>Searches an assembly for Harmony annotations and uses them to create patches</summary>
/// <param name="assembly">The assembly</param>
///
public void PatchAll(Assembly assembly)
{
assembly.GetTypes().Do(type =>
{
var parentMethodInfos = type.GetHarmonyMethods();
if (parentMethodInfos != null && parentMethodInfos.Count() > 0)
{
var info = HarmonyMethod.Merge(parentMethodInfos);
var processor = new PatchProcessor(this, type, info);
processor.Patch();
}
});
}
/// <summary>Creates patches by manually specifying the methods</summary>
/// <param name="original">The original method</param>
/// <param name="prefix">An optional prefix method wrapped in a HarmonyMethod object</param>
/// <param name="postfix">An optional postfix method wrapped in a HarmonyMethod object</param>
/// <param name="transpiler">An optional transpiler method wrapped in a HarmonyMethod object</param>
/// <returns>The dynamic method that was created to patch the original method</returns>
///
public DynamicMethod Patch(MethodBase original, HarmonyMethod prefix = null, HarmonyMethod postfix = null, HarmonyMethod transpiler = null)
{
var processor = new PatchProcessor(this, new List<MethodBase> { original }, prefix, postfix, transpiler);
return processor.Patch().FirstOrDefault();
}
/// <summary>Unpatches methods</summary>
/// <param name="harmonyID">The optional Harmony ID to restrict unpatching to a specific instance</param>
///
public void UnpatchAll(string harmonyID = null)
{
bool IDCheck(Patch patchInfo) => harmonyID == null || patchInfo.owner == harmonyID;
var originals = GetPatchedMethods().ToList();
foreach (var original in originals)
{
var info = GetPatchInfo(original);
info.Prefixes.DoIf(IDCheck, patchInfo => Unpatch(original, patchInfo.patch));
info.Postfixes.DoIf(IDCheck, patchInfo => Unpatch(original, patchInfo.patch));
info.Transpilers.DoIf(IDCheck, patchInfo => Unpatch(original, patchInfo.patch));
}
}
/// <summary>Unpatches a method</summary>
/// <param name="original">The original method</param>
/// <param name="type">The patch type</param>
/// <param name="harmonyID">The optional Harmony ID to restrict unpatching to a specific instance</param>
///
public void Unpatch(MethodBase original, HarmonyPatchType type, string harmonyID = null)
{
var processor = new PatchProcessor(this, new List<MethodBase> { original });
processor.Unpatch(type, harmonyID);
}
/// <summary>Unpatches a method</summary>
/// <param name="original">The original method</param>
/// <param name="patch">The patch method to remove</param>
///
public void Unpatch(MethodBase original, MethodInfo patch)
{
var processor = new PatchProcessor(this, new List<MethodBase> { original });
processor.Unpatch(patch);
}
/// <summary>Test for patches from a specific Harmony ID</summary>
/// <param name="harmonyID">The Harmony ID</param>
/// <returns>True if patches for this ID exist</returns>
///
public bool HasAnyPatches(string harmonyID)
{
return GetPatchedMethods()
.Select(original => GetPatchInfo(original))
.Any(info => info.Owners.Contains(harmonyID));
}
/// <summary>Gets patch information for a given original method</summary>
/// <param name="method">The original method</param>
/// <returns>The patch information</returns>
///
public Patches GetPatchInfo(MethodBase method)
{
return PatchProcessor.GetPatchInfo(method);
}
/// <summary>Gets a patched methods</summary>
/// <returns>An enumeration of original methods</returns>
///
public IEnumerable<MethodBase> GetPatchedMethods()
{
return HarmonySharedState.GetPatchedMethods();
}
/// <summary>Gets current version information</summary>
/// <param name="currentVersion">[out] The current Harmony version</param>
/// <returns>A dictionary containing assembly versions keyed by Harmony version</returns>
///
public Dictionary<string, Version> VersionInfo(out Version currentVersion)
{
currentVersion = typeof(HarmonyInstance).Assembly.GetName().Version;
var assemblies = new Dictionary<string, Assembly>();
GetPatchedMethods().Do(method =>
{
var info = HarmonySharedState.GetPatchInfo(method);
info.prefixes.Do(fix => assemblies[fix.owner] = fix.patch.DeclaringType.Assembly);
info.postfixes.Do(fix => assemblies[fix.owner] = fix.patch.DeclaringType.Assembly);
info.transpilers.Do(fix => assemblies[fix.owner] = fix.patch.DeclaringType.Assembly);
});
var result = new Dictionary<string, Version>();
assemblies.Do(info =>
{
var assemblyName = info.Value.GetReferencedAssemblies().FirstOrDefault(a => a.FullName.StartsWith("0Harmony, Version"));
if (assemblyName != null)
result[info.Key] = assemblyName.Version;
});
return result;
}
}
}
|
97768ae8577a6c4609100b4c88887691575494ff
|
C#
|
YessyEckley/BackEnd_ObjectOrientedPrograming_CSharp
|
/BackEnd_ObjectOrientedPrograming_CSharp/Week8_Functions/Samples/ReferenceMath/ReferenceMath.cs
| 2.953125
| 3
|
// ReferenceMath.cs
namespace BackEnd_ObjectOrientedPrograming_CSharp.Week8_Functions.Samples.ReferenceMath
{
public class ReferenceMath
{
public static void Calculate(int x, int y, ref int sum, ref int prod)
{
sum = x + y;
prod = x * y;
}
}
}
|
4abf90ee4d6204132cca0a7eb6f815f1a3512755
|
C#
|
GrandBarbier/Surrounded_By_DarkGit
|
/Assets/Scripts/Gears/LevelManager.cs
| 2.515625
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class LevelManager
{
public static Action preLoadingScene;
public static IEnumerator FadeDuration(Image image, Color start, Color end, float duration, bool setActiveFalse = true, Action onComplete = null)
{
image.gameObject.SetActive(true);
image.color = start;
for (float t = 0f; t < duration; t += Time.deltaTime)
{
float normalizedTime = t/duration;
if (image)
{
image.color = Color.Lerp(start, end, normalizedTime);
}
else
{
break;
}
yield return null;
}
if (image)
{
image.color = end;
if (setActiveFalse)
{
image.gameObject.SetActive(false);
}
onComplete?.Invoke();
}
}
public static void LoadScene(int index)
{
preLoadingScene?.Invoke();
preLoadingScene = null;
Time.timeScale = 1f;
SceneManager.LoadScene(index);
Gears.gears.StartCoroutine(FadeDuration(Gears.gears.menuManager.blackPanel, start: new Color(r: 0f, g: 0f, b: 0f, a: 1f), end: new Color(r: 0f, g: 0f, b: 0f, a: 0f), duration: 2f));
}
public static IEnumerator LoadAsyncScene(int sceneIndex)
{
preLoadingScene?.Invoke();
preLoadingScene = null;
//Load new scene and display loading screen
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(sceneIndex);
Gears.gears.StartCoroutine(FadeDuration(Gears.gears.menuManager.blackPanel, start: new Color(r: 0f, g: 0f, b: 0f, a: 0f),
end: new Color(r: 0f, g: 0f, b: 0f, a: 1f), duration: 0.5f));
Gears.gears.menuManager.loadScreen.SetActive(true);
// Wait until the asynchronous scene fully loads
while (!asyncLoad.isDone)
{
Gears.gears.menuManager.loadBarScaler.transform.localScale = new Vector3(asyncLoad.progress, Gears.gears.menuManager.loadBarScaler.transform.localScale.y,
Gears.gears.menuManager.loadBarScaler.transform.localScale.z);
yield return null;
}
}
}
|
7419a2036d3f01a5f2b32b594785eefac728f2f4
|
C#
|
unityai/unityai-core
|
/UnityAI.Core/Fuzzy/FuzzyObjects/FuzzyOperator.cs
| 2.90625
| 3
|
//-------------------------------------------------------------------
// (c) Copyright 2009 UnityAI Core Team
// Developed For: UnityAI
// License: Artistic License 2.0
//
// Description: FuzzyOperator
// From Constructing Intelligent Agents using Java
//
// Authors: SMcCarthy
//-------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
namespace UnityAI.Core.Fuzzy
{
[Serializable]
public class FuzzyOperator
{
#region Constructors
/// <summary>
/// Create a Fuzzy Operator
/// </summary>
private FuzzyOperator()
{
}
#endregion
#region Methods
/// <summary>
/// Assign the Rhs to the Lhs
/// </summary>
/// <param name="lhs"></param>
/// <param name="rhs"></param>
internal static void Assign(FuzzyRuleVariable lhs, FuzzySet rhs)
{
lhs.SetFuzzyValue(rhs);
}
/// <summary>
/// Assign the Rhs Fuzzy to the Lhs with a truth value
/// </summary>
/// <param name="lhs"></param>
/// <param name="rhs"></param>
/// <param name="truthValue"></param>
internal static void Assign(FuzzyRuleVariable lhs, FuzzySet rhs, double truthValue)
{
//This is correlation with a truth value.
((ContinuousFuzzyRuleVariable)lhs).SetFuzzyValue(rhs, truthValue);
}
/// <summary>
/// Determines the Membership
/// </summary>
/// <param name="lhs"></param>
/// <param name="rhs"></param>
/// <returns></returns>
internal static double Compare(FuzzyRuleVariable lhs, FuzzySet rhs)
{
// Take crisp value and look up membership
return (rhs.Membership(lhs.GetNumericValue()));
}
#endregion
}
}
|
9f0c8f3b92194c7a5860c9ecf43d1ff5d21dfe1b
|
C#
|
reddude256/Reflex-TrackParser
|
/ReflexTrackParser/Program.cs
| 2.6875
| 3
|
using Newtonsoft.Json;
using System;
using System.Linq;
using TrackManagement;
namespace ReflexTrackParser
{
class Program
{
static void Main(string[] args)
{
try
{
//Console.WriteLine("Fetching tracks from reflex central...");
//ReflexCentralParser parser = new ReflexCentralParser();
//var tracks = parser.ParseTracks();
//Console.WriteLine("Fetching tracks from our databse...");
//var existingTrackNames = HttpUtility.Get<string[]>("https://spptqssmj8.execute-api.us-east-1.amazonaws.com/test/tracknames");
//Console.WriteLine("Filtering out existing tracks...");
//var newTracks = tracks.Where(t => existingTrackNames.Any(e => e == t.TrackName) == false).ToArray();
//foreach (var track in newTracks)
//{
// Console.WriteLine(string.Format("Processing {0}...", track.TrackName));
// HttpUtility.Post("https://spptqssmj8.execute-api.us-east-1.amazonaws.com/test/uploadtrack", track);
//}
//Console.WriteLine("Processing Complete!");
//Test
//ReflexCentralParser parser = new ReflexCentralParser();
//var track = parser.ParseTrack(string.Format("http://reflex-central.com/track_profile.php?track_id={0}", 382));
//bool success = HttpUtility.Post("https://spptqssmj8.execute-api.us-east-1.amazonaws.com/test/uploadtracksqs", track);
var js = JsonConvert.DeserializeObject<JsonInt>("{\"TrackId\":51}");
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
|
a83a7f35a26864eef79c9db2acbd5695f975a19d
|
C#
|
gwmyers/hep-fun-sim
|
/Assets/Scripts/PartonDistributionFunction.cs
| 2.65625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// A class to manage PDF related probability calculations
/// </summary>
public class PartonDistributionFunction
{
protected double centerOfMassEnergy = 13.0;
protected WeightTable partonNumberWeightTable = new WeightTable();
protected WeightTable flavorWeightTable = new WeightTable();
// placeholeder probabilities:
public static Dictionary<string, int> X_a = new Dictionary<string, int>()
{
{"g", 50000},
{"u", 20000},
{"d", 20000},
{"s", 900},
{"c", 100},
{"b", 15},
{"t", 1}
};
/// <summary>
/// Default constructor
/// </summary>
public PartonDistributionFunction()
{
// initialize number of partons weight table:
partonNumberWeightTable.addEntry(8, 100);
partonNumberWeightTable.addEntry(9, 100);
partonNumberWeightTable.addEntry(10, 100);
partonNumberWeightTable.addEntry(11, 100);
partonNumberWeightTable.addEntry(12, 100);
// initialize flavor weight table:
foreach (KeyValuePair<string, int> kvp in X_a)
{
flavorWeightTable.addEntry(StandardModelDefs.particleID[kvp.Key], kvp.Value);
}
}
/// <summary>
/// return a list of partons inside a proton at the time of collision
/// </summary>
/// <returns> an integer list of parton IDs to instantiate </returns>
public List<int> generatePartonContent()
{
List<int> partonComposition = new List<int>();
int nPartons = partonNumberWeightTable.getRandomID();
for (int iParton = 0; iParton < nPartons; iParton++)
{
partonComposition.Add(flavorWeightTable.getRandomID());
}
return partonComposition;
}
}
|
45774a5fdc57547e25737b6ae8d6d77d13457412
|
C#
|
dhamotharang/PILLARSALT-APPLICATION
|
/PILLARSALT KIOSK/AppCodes/ThermalPrinterClass.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using ThermalDotNet;
namespace PILLARSALT_KIOSK.AppCodes
{
public class ThermalPrinterClass
{
public ThermalPrinterClass()
{
//SetupPrinter();
}
public void TestReceipt(ThermalPrinter printer)
{
Dictionary<string, int> ItemList = new Dictionary<string, int>(100);
printer.SetLineSpacing(0);
printer.SetAlignCenter();
printer.WriteLine("MY SHOP",
(byte)ThermalPrinter.PrintingStyle.DoubleHeight
+ (byte)ThermalPrinter.PrintingStyle.DoubleWidth);
printer.WriteLine("My address, CITY");
printer.LineFeed();
printer.LineFeed();
//ItemList.Add("Item #1", 8990);
//ItemList.Add("Item #2 goes here", 2000);
//ItemList.Add("Item #3", 1490);
//ItemList.Add("Item number four", 490);
//ItemList.Add("Item #5 is cheap", 245);
//ItemList.Add("Item #6", 2990);
//ItemList.Add("The seventh item", 790);
//int total = 0;
//foreach (KeyValuePair<string, int> item in ItemList)
//{
// CashRegister(printer, item.Key, item.Value);
// total += item.Value;
//}
// printer.HorizontalLine(32);
// double dTotal = Convert.ToDouble(total) / 100;
// double VAT = 10.0;
// printer.WriteLine(String.Format("{0:0.00}", (dTotal)).PadLeft(32));
// printer.WriteLine("VAT 10,0%" + String.Format("{0:0.00}", (dTotal * VAT / 100)).PadLeft(23));
// printer.WriteLine(String.Format("$ {0:0.00}", dTotal * VAT / 100 + dTotal).PadLeft(16),
// ThermalPrinter.PrintingStyle.DoubleWidth);
// printer.LineFeed();
// printer.WriteLine("CASH" + String.Format("{0:0.00}", (double)total / 100).PadLeft(28));
// printer.LineFeed();
// printer.LineFeed();
// printer.SetAlignCenter();
// printer.WriteLine("Have a good day.", ThermalPrinter.PrintingStyle.Bold);
// printer.LineFeed();
// printer.SetAlignLeft();
// printer.WriteLine("Seller : Bob");
// printer.WriteLine("09-28-2011 10:53 02331 509");
// printer.LineFeed();
// printer.LineFeed();
// printer.LineFeed();
//}
//static void TestBarcode(ThermalPrinter printer)
//{
// ThermalPrinter.BarcodeType myType = ThermalPrinter.BarcodeType.ean13;
// string myData = "3350030103392";
// printer.WriteLine(myType.ToString() + ", data: " + myData);
// printer.SetLargeBarcode(true);
// printer.LineFeed();
// printer.PrintBarcode(myType, myData);
// printer.SetLargeBarcode(false);
// printer.LineFeed();
// printer.PrintBarcode(myType, myData);
}
static void TestImage(ThermalPrinter printer)
{
printer.WriteLine("Test image:");
Bitmap img = new Bitmap("../../../mono-logo.png");
printer.LineFeed();
printer.PrintImage(img);
printer.LineFeed();
printer.WriteLine("Image OK");
}
// public static void Main(string[] args)
// {
// string printerPortName = "/dev/tty.usbserial-A600dP3F";
//
// //Serial port init
// SerialPort printerPort = new SerialPort(printerPortName, 9600);
//
// if (printerPort != null)
// {
// Console.WriteLine("Port ok");
// if (printerPort.IsOpen)
// {
// printerPort.Close();
// }
// }
//
// Console.WriteLine("Opening port");
//
// try
// {
// printerPort.Open();
// }
// catch
// {
// Console.WriteLine("I/O error");
// Environment.Exit(0);
// }
//
// //Printer init
// ThermalPrinter printer = new ThermalPrinter(printerPort, 2, 180, 2);
// printer.WakeUp();
// Console.WriteLine(printer.ToString());
//
// TestReceipt(printer);
//
// //System.Threading.Thread.Sleep(5000);
// //printer.SetBarcodeLeftSpace(25);
// //TestBarcode(printer);
//
// //System.Threading.Thread.Sleep(5000);
// //TestImage(printer);
//
// //System.Threading.Thread.Sleep(5000);
//
// printer.WriteLineSleepTimeMs = 200;
// printer.WriteLine("Default style");
// printer.WriteLine("PrintingStyle.Bold", ThermalPrinter.PrintingStyle.Bold);
// printer.WriteLine("PrintingStyle.DeleteLine", ThermalPrinter.PrintingStyle.DeleteLine);
// printer.WriteLine("PrintingStyle.DoubleHeight", ThermalPrinter.PrintingStyle.DoubleHeight);
// printer.WriteLine("PrintingStyle.DoubleWidth", ThermalPrinter.PrintingStyle.DoubleWidth);
// printer.WriteLine("PrintingStyle.Reverse", ThermalPrinter.PrintingStyle.Reverse);
// printer.WriteLine("PrintingStyle.Underline", ThermalPrinter.PrintingStyle.Underline);
// printer.WriteLine("PrintingStyle.Updown", ThermalPrinter.PrintingStyle.Updown);
// printer.WriteLine("PrintingStyle.ThickUnderline", ThermalPrinter.PrintingStyle.ThickUnderline);
// printer.SetAlignCenter();
// printer.WriteLine("BIG TEXT!", ((byte)ThermalPrinter.PrintingStyle.Bold +
// (byte)ThermalPrinter.PrintingStyle.DoubleHeight +
// (byte)ThermalPrinter.PrintingStyle.DoubleWidth));
// printer.SetAlignLeft();
// printer.WriteLine("Default style again");
//
// printer.LineFeed(3);
// printer.Sleep();
// Console.WriteLine("Printer is now offline.");
// printerPort.Close();
// }
static void CashRegister(ThermalPrinter printer, string item, int price)
{
printer.Reset();
printer.Indent(0);
if (item.Length > 24)
{
item = item.Substring(0, 23) + ".";
}
printer.WriteToBuffer(item.ToUpper());
printer.Indent(25);
string sPrice = String.Format("{0:0.00}", (double)price / 100);
sPrice = sPrice.PadLeft(7);
printer.WriteLine(sPrice);
printer.Reset();
}
}
}
|
553877391070c5bf3710356366494d13b57d51c1
|
C#
|
CrypToolProject/CrypTool-2
|
/LibSource/SharpPcap/CaptureDeviceList.cs
| 2.671875
| 3
|
/*
This file is part of SharpPcap.
SharpPcap is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SharpPcap is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with SharpPcap. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Copyright 2011 Chris Morgan <chmorgan@gmail.com>
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Text;
namespace SharpPcap
{
/// <summary>
/// List of available capture devices
/// </summary>
public class CaptureDeviceList : ReadOnlyCollection<ICaptureDevice>
{
private static CaptureDeviceList instance;
private WinPcap.WinPcapDeviceList winPcapDeviceList;
private LibPcap.LibPcapLiveDeviceList libPcapDeviceList;
/// <summary>
/// Method to retrieve this classes singleton instance
/// </summary>
public static CaptureDeviceList Instance
{
get
{
if (instance == null)
{
instance = new CaptureDeviceList();
}
return instance;
}
}
/// <summary>
/// Caution: Use the singlton instance unless you know why you need to call this.
/// One use is for multiple filters on the same physical device. To apply multiple
/// filters open the same physical device multiple times, one for each
/// filter by calling this routine and picking the same device out of each list.
/// </summary>
/// <returns>
/// A <see cref="CaptureDeviceList"/>
/// </returns>
public static CaptureDeviceList New()
{
CaptureDeviceList newCaptureDevice = new CaptureDeviceList();
// windows
if ((Environment.OSVersion.Platform == PlatformID.Win32NT) ||
(Environment.OSVersion.Platform == PlatformID.Win32Windows))
{
newCaptureDevice.winPcapDeviceList = WinPcap.WinPcapDeviceList.New();
}
else // not windows
{
newCaptureDevice.libPcapDeviceList = LibPcap.LibPcapLiveDeviceList.New();
}
// refresh the device list to flush the original devices and pull the
// new ones into the newCaptureDevice
newCaptureDevice.Refresh();
return newCaptureDevice;
}
/// <summary>
/// Represents a strongly typed, read-only list of PcapDevices.
/// </summary>
private CaptureDeviceList()
: base(new List<ICaptureDevice>())
{
// windows
if ((Environment.OSVersion.Platform == PlatformID.Win32NT) ||
(Environment.OSVersion.Platform == PlatformID.Win32Windows))
{
winPcapDeviceList = WinPcap.WinPcapDeviceList.Instance;
}
else // not windows
{
libPcapDeviceList = LibPcap.LibPcapLiveDeviceList.Instance;
}
Refresh();
}
/// <summary>
/// Retrieve a list of the current devices
/// </summary>
/// <returns>
/// A <see cref="List<ICaptureDevice>"/>
/// </returns>
private List<ICaptureDevice> GetDevices()
{
List<ICaptureDevice> deviceList = new List<ICaptureDevice>();
// windows
if ((Environment.OSVersion.Platform == PlatformID.Win32NT) ||
(Environment.OSVersion.Platform == PlatformID.Win32Windows))
{
WinPcap.WinPcapDeviceList dl = winPcapDeviceList;
foreach (WinPcap.WinPcapDevice c in dl)
{
deviceList.Add(c);
}
}
else // not windows
{
LibPcap.LibPcapLiveDeviceList dl = libPcapDeviceList;
foreach (LibPcap.LibPcapLiveDevice c in dl)
{
deviceList.Add(c);
}
}
return deviceList;
}
/// <summary>
/// Refresh the device list
/// </summary>
public void Refresh()
{
lock (this)
{
// clear out any items we might have
base.Items.Clear();
// windows
if ((Environment.OSVersion.Platform == PlatformID.Win32NT) ||
(Environment.OSVersion.Platform == PlatformID.Win32Windows))
{
winPcapDeviceList.Refresh();
foreach (WinPcap.WinPcapDevice i in winPcapDeviceList)
{
base.Items.Add(i);
}
}
else // not windows
{
libPcapDeviceList.Refresh();
foreach (LibPcap.LibPcapLiveDevice i in libPcapDeviceList)
{
base.Items.Add(i);
}
}
}
}
#region Device Indexers
/// <param name="Name">The name or description of the pcap interface to get.</param>
public ICaptureDevice this[string Name]
{
get
{
// lock to prevent issues with multi-threaded access
// with other methods
lock (this)
{
// windows
if ((Environment.OSVersion.Platform == PlatformID.Win32NT) ||
(Environment.OSVersion.Platform == PlatformID.Win32Windows))
{
return winPcapDeviceList[Name];
}
else // not windows
{
return libPcapDeviceList[Name];
}
}
}
}
#endregion
}
}
|
f3e00acea651e679b3bd9eaf9aa74fdbaba1b9be
|
C#
|
jaelys/UACHelper
|
/UACHelper/AdminPromptType.cs
| 2.65625
| 3
|
namespace UACHelper
{
/// <summary>
/// AAM behaviors regarding administrators
/// </summary>
public enum AdminPromptType : uint
{
/// <summary>
/// Allows the Consent Admin to perform an operation that requires elevation without consent or credentials
/// </summary>
AllowAll = 0,
/// <summary>
/// Prompts the Consent Admin to enter his or her user name and password (or another valid admin) when an operation
/// requires elevation of privilege. This operation occurs on the secure desktop.
/// </summary>
DimmedPromptWithPasswordConfirmation = 1,
/// <summary>
/// Prompts the administrator in Admin Approval Mode to select either "Permit" or "Deny" an operation that requires
/// elevation of privilege. This operation occurs on the secure desktop.
/// </summary>
DimmedPrompt = 2,
/// <summary>
/// Prompts the Consent Admin to enter his or her user name and password (or another valid admin) when an operation
/// requires elevation of privilege.
/// </summary>
PromptWithPasswordConfirmation = 3,
/// <summary>
/// Prompts the administrator in Admin Approval Mode to select either "Permit" or "Deny" an operation that requires
/// elevation of privilege.
/// </summary>
Prompt = 4,
/// <summary>
/// Prompts the administrator in Admin Approval Mode to select either "Permit" or "Deny" an operation that requires
/// elevation of privilege for any non-Windows binaries. This operation occurs on the secure desktop.
/// </summary>
DimmedPromptForNonWindowsBinaries = 5
}
}
|
3f908d4832e3de818ef8199d81299ad8ef30d4b9
|
C#
|
15827068711/CSharpHomework
|
/Homework3/Homework3/Program.cs
| 3.609375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace homework3
{
public abstract class BaseProdImag//定义一个抽象图形基类
{
public abstract void draw();//创建图形
public abstract double S();//求图形的面积
public void erase()//删除图形
{
Console.WriteLine("擦除图形");
}
}
public class Circle : BaseProdImag//创建圆形
{
double radius;
public void GetInfor1(double[] Infor)//获取圆周的半径
{
radius = Infor[0];
}
public override void draw()//重写创建函数
{
}
public override double S()
{
double res = radius * radius * 3.14;
return res;
}
}
public class Rect : BaseProdImag//创建矩形
{
double length, width;
public void GetInfor2(double[] Infor)
{
length = Infor[0];
width = Infor[1];
}
public override void draw()
{
}
public override double S()
{
double res = length * width;
return res;
}
}
public class Square : BaseProdImag//创建正方形
{
double sidesL;
public void GetInfor3(double[] Infor)
{
sidesL = Infor[0];
}
public override void draw()
{
}
public override double S()
{
double res = sidesL * sidesL;
return res;
}
}
public class Triang : BaseProdImag//创建三角形
{
double side1, side2, side3;
public void GetInfor4(double[] Infor)
{
side1 = Infor[0];
side2 = Infor[1];
side3 = Infor[2];
}
public override void draw()
{
}
public override double S()
{
if (side1 + side2 > side3 && side1 + side3 > side2 && side2 + side3 > side1)
{
double p = (side1 + side2 + side3) / 2;
double e = Math.Sqrt(p * (p - side1) * (p - side2) * (p - side3));
return e;
}
else
{
Console.WriteLine("不存在该三角形");
return 0;
}
}
}
public class ImagFactory//工厂类,用来生产图形
{
public static BaseProdImag CreateImag(string imagname, double[] Infor)
{
switch (imagname)
{
case "circle":
return new Circle();
case "rectangle":
return new Rect();
case "square":
return new Square();
case "Triangle":
return new Triang();
default:
return new Rect();
}
}
}
class Program
{
static void Main(string[] args)
{
BaseProdImag image = ImagFactory.CreateImag("circle", new double[1] { 3 });
image.draw();
image.S();
}
}
}
|
0290cbae211701197c55cf9ffb88d93280d4d4ac
|
C#
|
fr830/BookMobile
|
/BookClientModal/BookClient/ViewModels/SignupPageViewModel.cs
| 2.84375
| 3
|
using BookClient.Models;
using BookClient.Validators;
using FluentValidation;
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
namespace BookClient.ViewModels
{
// Fluent Validation With MVVM In Xamarin Forms Application
// https://www.c-sharpcorner.com/article/fluent-validation-with-mvvm-in-xamarin-forms-application/
public class SignUpPageViewModel : ObservableObject
{
public User User { get; set; }
private string _username;
private string _password;
private string _confirmPassword;
private string _email;
private string _color = "Green";
private Command _signUpCommand;
private readonly IValidator _validator;
public SignUpPageViewModel()
{
_validator = new UserValidator();
}
public string UserName
{
get { return _username; }
set { SetProperty(ref _username, value); }
}
public string Password
{
get { return _password; }
set { SetProperty(ref _password, value); }
}
public string ConfirmPassword
{
get { return _confirmPassword; }
set { SetProperty(ref _confirmPassword, value); }
}
public string Email
{
get { return _email; }
set { SetProperty(ref _email, value); }
}
public string Color
{
get { return _color; }
set { SetProperty(ref _color, value); }
}
public Command SignUpCommand
{
get
{
return _signUpCommand ?? (_signUpCommand = new Command(ExecuteSignUpCommand));
}
}
protected void ExecuteSignUpCommand()
{
this.User = new User
{
UserName = _username,
Password = _password,
ConfirmPassword = _confirmPassword,
Email = _email
};
var validationResult = _validator.Validate(this.User);
if (validationResult.IsValid)
{
this.ValidationMessage = "Validation Success!!";
this.Color = "Green";
}
else
{
this.ValidationMessage = string.Empty;
foreach (var error in validationResult.Errors)
{
this.ValidationMessage += error.ErrorMessage + "\n";
this.Color = "Red";
}
App.Current.MainPage.DisplayAlert("FluentValidation: ", this.ValidationMessage, "Ok");
}
}
}
}
|
9d4f229559ad04c76da89c1604071aeeff0ed909
|
C#
|
thebravoman/software_engineering_2015
|
/VhodnoNivo/Lubomir_Kiprov/Lubomir_Kiprov_{10}/Program.cs
| 3.421875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Problem_10
{
class Program
{
static void Main(string[] args)
{
int x;
do
{
Console.WriteLine("Type number >= 0 or number < 10");
x = int.Parse(Console.ReadLine());
} while (x < 0 || x > 9);
ulong[] arr = new ulong[10];
ulong fibonaci_number1 = 1, fibonaci_number2 = 1, sum = 0, i = 0;
do
{
sum = fibonaci_number1 + fibonaci_number2;
fibonaci_number1 = fibonaci_number2;
fibonaci_number2 = sum;
if (sum % Convert.ToUInt64(x) == 0 )
{
arr[i] = sum;
i++;
}
} while (i < Convert.ToUInt64(arr.Length));
Console.WriteLine();
for (int j = 0; j < arr.Length; j++)
{
Console.WriteLine(arr[j]);
}
}
}
}
|
a3a2bbd459459aa544c636c5298c26442343f539
|
C#
|
Docente2018/PROGRAMMER
|
/LuisOchoa/Ejercicio_1/Ejercicio_1/Clase_Animal.cs
| 3.21875
| 3
|
using System;
namespace Ejercicio_1
{
public class Clase_Animal
{
static void Main(string[] args)
{
Accion animal = new Accion();
animal.nace();
animal.rugir();
}
}
public class Animal
{
public void nace()
{
Console.WriteLine("Ha nacido un animal");
Console.ReadKey();
}
public void rugir()
{
Console.WriteLine("Hace algun ruido");
Console.ReadKey();
}
}
public class Accion : Animal
{ }
}
|
8bca64848e7757929aac5f3daf7c86aa06333f02
|
C#
|
fenixrtr7/TutoC-
|
/Assets/TutoSuv/Scripts/Dictionary/Main2.cs
| 2.9375
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Main2 : MonoBehaviour
{
public Dictionary<string, int> people = new Dictionary<string, int>();
public Dictionary<int, string> books = new Dictionary<int, string>();
// Start is called before the first frame update
void Start()
{
people.Add("Jon", 26);
people.Add("kil", 28);
people.Add("Jum", 21);
people.Add("hu", 39);
int kilAge = people["kil"];
Debug.Log("kil age: " + kilAge);
books.Add(1, "ghdsfghdsggfdsgjhghjdghjdsgfgdhs");
books.Add(2, "jkdkjfhdskjfhsjdk zzz");
//Debug.Log(books[2]);
foreach (KeyValuePair<int, string> book in books)
{
Debug.Log("Book: " + book.Value);
}
// Other form
foreach (var book in books.Values)
{
Debug.Log("Book: " + book);
}
}
// Update is called once per frame
void Update()
{
}
}
|
c7c690586a2f3b9c21538f2d6e023c98866a64c9
|
C#
|
xavierdelacruz/LeetCodeProblemsSolved
|
/9 - Palindrome Number.cs
| 3.765625
| 4
|
public class Solution {
public bool IsPalindrome(int x) {
// These are all numbers that end with a 0, other than 0 itself
if (x % 10 == 0 && x != 0) {
return false;
}
// negative numbers are automatically not palindromes
if (x < 0) {
return false;
}
// Storage (can be an int array too, but takes O(n) space)
var reversed = 0;
// The loop condition ensures that if the reverse string is bigger than what x currently is, then it ends.
// As we remove digits, it reduces the value of x. When we get to the midpoint, we stop.
while (x > reversed) {
// This gets the first digit, bumps up the current reversed number, and adds that digit
// This works similar to StringBuilder append.
var firstDigit = x % 10;
reversed *= 10;
reversed += firstDigit;
// Update x to the next digit;
x = x/10;
}
// if it is odd, we need to check reversed / 10 == x,
// since it will take the middle digit for odd-digit numbers
// Otherwise, we can simply check x == reversed for even-digit numbers
return x == reversed || x == reversed/10;
}
}
|
7c57d6829f4237a2764f87f28e05075b224fb157
|
C#
|
Mungert69/VoyagerWebService
|
/CodeWorksVoyWeb/Bussiness Logic/Utils/FactoryUtils.cs
| 2.65625
| 3
|
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace CodeWorksVoyWebService.Bussiness_Logic.Bussiness_Objects
{
public class FactoryUtils
{
public static List<T> CheckCache<T>(ref IMemoryCache cache, DbContext context, List<T> chkObj, string objName) where T : class {
cache.TryGetValue(objName, out chkObj);
if (chkObj == null)
{
cache.CreateEntry(objName);
context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
chkObj = context.Set<T>().ToList();
cache.Set(objName, chkObj);
}
return chkObj;
}
public static T CheckCacheNoWrite<T>(ref IMemoryCache cache, T chkObj, string objName) where T : class
{
cache.TryGetValue(objName, out chkObj);
if (chkObj != null)
{
return chkObj;
}
return null;
}
public static T CheckCache<T>(ref IMemoryCache cache, T chkObj, string objName) where T : class
{
cache.TryGetValue(objName, out chkObj);
if (chkObj == null)
{
cache.CreateEntry(objName);
chkObj = Activator.CreateInstance<T>();
cache.Set(objName, chkObj);
}
return chkObj;
}
public static void WriteCache<T>(ref IMemoryCache cache, T chkObj, string objName) where T : class
{
cache.Set(objName, chkObj);
}
}
}
|
9b9e4b5213c567eb414defd6931efe452585db10
|
C#
|
fccoul/Projects-VS-2013
|
/Projects/WebAPI_2013/ConsApp_Customer/Program.cs
| 3.25
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace ConsApp_Customer
{
class Program
{
static HttpClient client = new HttpClient();
static void ShowProduct(Product product)
{
Console.WriteLine("Name: {0}\tPrice: {1}\tCategory: {2}\tQuantite: {3}", product.Name, product.Price, product.Category,product.Quantite);
}
#region CRUD
static async Task<Uri> CreateProductAsync(Product product)
{
//The PostAsJsonAsync method serializes an object to JSON and then sends the JSON payload in a POST request
HttpResponseMessage response = await client.PostAsJsonAsync("products", product);
response.EnsureSuccessStatusCode();
// return URI of the created resource.
return response.Headers.Location;
}
static async Task<Product> GetProductAsync(string path)
{
Product product = null;
HttpResponseMessage response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
//ReadAsAsync to deserialize the JSON
//La méthode ReadAsync est asynchrone car le corps de réponse peut être arbitrairement grand.
product = await response.Content.ReadAsAsync<Product>();
}
return product;
}
static async Task<Product> UpdateProductAsync(Product product)
{
HttpResponseMessage response = await client.PutAsJsonAsync(string.Format("products/{0}",product.Id), product);
response.EnsureSuccessStatusCode();//Throws an exception if the IsSuccessStatusCode property for the HTTP response is false.
// Deserialize the updated product from the response body.
product = await response.Content.ReadAsAsync<Product>();
return product;
}
static async Task<HttpStatusCode> DeleteProductAsync(string id)
{
HttpResponseMessage response = await client.DeleteAsync(string.Format("products/{0}",id));
return response.StatusCode;
}
#endregion
static void Main(string[] args)
{
RunAsync().Wait();
}
static async Task RunAsync()
{
client.BaseAddress = new Uri("http://localhost:51653/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
Product product = new Product();
// Create a new product
product = new Product { Name = "Gizmo", Price = 100, Category = "Widgets",Quantite=75 };
var url = await CreateProductAsync(product);
Console.WriteLine("Created at {0}",url);
// Get the product
product = await GetProductAsync(url.PathAndQuery);
// product = await GetProductAsync("http://localhost:51653/api/products/2");
ShowProduct(product);
// Update the product
Console.WriteLine("Updating price...");
product.Price = 80;
await UpdateProductAsync(product);
// Get the updated product
product = await GetProductAsync(url.PathAndQuery);
ShowProduct(product);
// Delete the product
var statusCode = await DeleteProductAsync(product.Id);
Console.WriteLine("Deleted (HTTP Status = {0})",statusCode);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
}
}
|
395f5eb0ebecdefbe16b16ee4026082ba89ba03e
|
C#
|
IamAbhii/MITT-System
|
/MITT-System-V1/Models/IdentityModels.cs
| 2.515625
| 3
|
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Collections.Generic;
using System;
namespace MITT_System_V1.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit https://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
public bool? IsOnVisa { get; set; }
public DateTime DOB { get; set; }
public Persontype? Type { get; set; }
public virtual ICollection<ApplicationUserCourse> Curses { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class ApplicationUserCourse
{
public int Id { get; set; }
public int ApplicationUserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
public int CourseId { get; set; }
public Course Course { get; set; }
public DateTime DateOfJoin { get; set; }
}
public enum Persontype
{
Admin,
Teacher,
Student,
}
public class Course
{
public int CourseId { get; set; }
public string CourseName { get; set; }
public int Capacity { get; set; }
public int Credits { get; set; }
public virtual ICollection<ApplicationUserCourse> ApplicationUsers { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<Course> Courses { get; set; }
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
}
|
fa1b68b9f2b8b62b0015ecc5d4a0235231b0cbdb
|
C#
|
anvesh9597/EcommerceSystem_MVC
|
/MVC_ecommerce_system/Ecommerce.DataAccessLayer/AdminDAL.cs
| 2.671875
| 3
|
using Ecommerce.System.Ecommerce.Entities;
using Ecommerce.System.Ecommerce.Contracts.DALContracts;
using System;
using System.Collections.Generic;
using System.Text;
using Ecommerce.System.Ecommerce.Exceptions;
namespace Ecommerce.System.Ecommerce.DataAccessLayer
{
public class AdminDAL:AdminDALBase
{
/// <summary>
/// Gets admin based on AdminID.
/// </summary>
/// <param name="searchAdminID">Represents AdminID to search.</param>
/// <returns>Returns Admin object.</returns>
public override Admin GetAdminByAdminIDDAL(Guid searchAdminID)
{
Admin matchingAdmin = null;
try
{
//Find Admin based on searchAdminID
matchingAdmin = AdminDALBase.adminList.Find(
(item) => { return item.AdminID == searchAdminID; }
);
}
catch (AdminNotFoundException)
{
throw new AdminNotFoundException("admin was not found!");
}
return matchingAdmin;
}
/// <summary>
/// Gets admin based on Email and Password.
/// </summary>
/// <param name="email">Represents Admin's Email Address.</param>
/// <param name="password">Represents Admin's Password.</param>
/// <returns>Returns Admin object.</returns>
public override Admin GetAdminByEmailAndPasswordDAL(string email, string password)
{
Admin matchingAdmin = null;
try
{
//Find Admin based on Email and Password
matchingAdmin = adminList.Find(
(item) => { return item.Email.Equals(email) && item.Password.Equals(password); }
);
}
catch (AdminNotFoundException)
{
throw new AdminNotFoundException("admin was not found!");
}
return matchingAdmin;
}
//update admin details
public override bool UpdateAdminDAL(Admin updateAdmin)
{
bool adminUpdated = false;
try
{
//Find Admin based on AdminID
Admin matchingAdmin = GetAdminByAdminIDDAL(updateAdmin.AdminID);
if (matchingAdmin != null)
{
//Update admin details
matchingAdmin.AdminName = updateAdmin.AdminName;
matchingAdmin.Email = updateAdmin.Email;
matchingAdmin.LastModifiedDateTime = DateTime.Now;
adminUpdated = true;
}
}
catch (AdminNotFoundException)
{
throw new AdminNotFoundException("admin was not found!");
}
return adminUpdated;
}
public override bool UpdateAdminForgotPasswordDAL(string email)
{
bool passwordUpdated = false;
Admin matchingAdmin = null;
try
{
matchingAdmin = adminList.Find(
(item) => { return item.Email.Equals(email); }
);
passwordUpdated = UpdateAdminPasswordDAL(matchingAdmin);
}
catch (AdminNotFoundException)
{
throw new AdminNotFoundException("admin was not found!");
}
return passwordUpdated;
}
//update admin password
public override bool UpdateAdminPasswordDAL(Admin updateAdmin)
{
bool adminUpdated = false;
try
{
//Find Admin based on AdminID
Admin matchingAdmin = GetAdminByAdminIDDAL(updateAdmin.AdminID);
//Update admin password
for (int i = 0; i < adminList.Count; i++)
{
if(adminList[i].AdminID == matchingAdmin.AdminID)
{
matchingAdmin.Password = updateAdmin.Password;
matchingAdmin.LastModifiedDateTime = DateTime.Now;
}
}
adminUpdated = true;
}
catch (AdminNotFoundException)
{
throw new AdminNotFoundException("admin was not found!");
}
return adminUpdated;
}
}
}
|
92c7fdbe5f27853f97a6bcdef3a77fda513dbeb0
|
C#
|
yong7743/arcgis-runtime-samples-dotnet
|
/src/Forms/Shared/Converters/ItemToImageSourceConverter.cs
| 2.578125
| 3
|
using Esri.ArcGISRuntime;
using Esri.ArcGISRuntime.Portal;
using System;
using System.Globalization;
using Xamarin.Forms;
namespace Forms.Converters
{
class ItemToImageSourceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Item mapItem = value as Item;
if (mapItem != null)
{
if (mapItem.ThumbnailUri != null)
{
// Sometimes image URIs have a . appended to them...
return ImageSource.FromUri(new Uri(mapItem.ThumbnailUri.OriginalString.TrimEnd('.')));
}
if (mapItem.Thumbnail != null &&
mapItem.Thumbnail.LoadStatus == LoadStatus.Loaded &&
mapItem.Thumbnail.Width > 0)
{
return ImageSource.FromStream(() => mapItem.Thumbnail.GetEncodedBufferAsync().Result);
}
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
|
7b4729e715ae512873df117c9d029d1d2aa7dcdc
|
C#
|
thyjukki/Rebelion
|
/Assets/Scripts/Menu/CharacterInfo.cs
| 2.546875
| 3
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class CharacterInfo : MonoBehaviour {
public Text CharacterName;
public Text CharacterAttributes;
public Text AtributeValues;
public Text CharacterClass;
private GameObject currentCharacter;
public void SetCharacterInfo()
{
currentCharacter = GameObject.Find("Player");
Atributes atributes = GameObject.FindObjectOfType<Atributes>();//currentCharacter.GetComponent<Atributes>();
//TODO(FIXME)
string atrbiuteText = string.Empty;
string valueText = string.Empty;
if (atributes.Strenght > 0)
{
atrbiuteText = atrbiuteText + "Strenght:";
valueText = valueText + atributes.Strenght.ToString() + "/";
if (atributes.GetExtraStrenght() > 0)
{
valueText = valueText + "<color=green>+" + atributes.GetExtraStrenght().ToString() + "</color>";
}
else if (atributes.GetExtraStrenght() < 0)
{
valueText = valueText + "<color=red>" + atributes.GetExtraStrenght().ToString() + "</color>";
}
else
{
valueText = valueText + "0";
}
atrbiuteText = atrbiuteText + "\n";
valueText = valueText + "\n";
}
if (atributes.Dexterity > 0)
{
atrbiuteText = atrbiuteText + "Dexterity:";
valueText = valueText + atributes.Dexterity.ToString() + "/";
if (atributes.GetExtraDexterity() > 0)
{
valueText = valueText + "<color=green>+" + atributes.GetExtraDexterity().ToString() + "</color>";
}
else if (atributes.GetExtraDexterity() < 0)
{
valueText = valueText + "<color=red>" + atributes.GetExtraDexterity().ToString() + "</color>";
}
else
{
valueText = valueText + "0";
}
atrbiuteText = atrbiuteText + "\n";
valueText = valueText + "\n";
}
if (atributes.Intelligent > 0)
{
atrbiuteText = atrbiuteText + "Intelligent:";
valueText = valueText + atributes.Intelligent.ToString() + "/";
if (atributes.GetExtraIntelligent() > 0)
{
valueText = valueText + "<color=green>+" + atributes.GetExtraIntelligent().ToString() + "</color>";
}
else if (atributes.GetExtraIntelligent() < 0)
{
valueText = valueText + "<color=red>" + atributes.GetExtraIntelligent().ToString() + "</color>";
}
else
{
valueText = valueText + "0";
}
atrbiuteText = atrbiuteText + "\n";
valueText = valueText + "\n";
}
if (atributes.Magic > 0)
{
atrbiuteText = atrbiuteText + "Magic:";
valueText = valueText + atributes.Magic.ToString() + "/";
if (atributes.GetExtraMagic() > 0)
{
valueText = valueText + "<color=green>+" + atributes.GetExtraMagic().ToString() + "</color>";
}
else if (atributes.GetExtraMagic() < 0)
{
valueText = valueText + "<color=red>" + atributes.GetExtraMagic().ToString() + "</color>";
}
else
{
valueText = valueText + "0";
}
atrbiuteText = atrbiuteText + "\n";
valueText = valueText + "\n";
}
string className = "Lvl " + atributes.Level.ToString() + " " + atributes.CharClass.ToString();
AtributeValues.text = valueText;
CharacterAttributes.text = atrbiuteText;
CharacterName.text = currentCharacter.name;
CharacterClass.text = className;
}
}
|
b0275002b1eac1f8cbe4bf875b03d34e84c8da60
|
C#
|
bzzitsme/Programming-Principles
|
/1st Attestation/Lab1 Everything/Lab1Student/Lab1Student/Program.cs
| 3.53125
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lab1Student
{
class Student
{
public string name, surname;
public double gpa;
public Student()
{
name = "FIT";
surname = "KBTU";
gpa = 4;
}
public Student(string a, string b)
{
name = a;
surname = b;
gpa = 3.47;
}
public Student(string a, string b, double c)
{
name = a;
surname = b;
gpa = c;
}
public override string ToString()
{
return name + " " + surname + " " + gpa;
}
}
class Program
{
static void Main(string[] args)
{
Student a = new Student();
Console.WriteLine(a);
Student b = new Student("Timka", "Dyussyumbayev");
Console.WriteLine(b);
Student c = new Student(Console.ReadLine(), Console.ReadLine(), double.Parse(Console.ReadLine()));
Console.WriteLine(c);
Console.ReadKey();
}
}
}
|
23df46d4f602d7697d94a1b402464cf07c684add
|
C#
|
srgul/Genel-.net-tekrar-
|
/Metotlar/Program.cs
| 2.84375
| 3
|
using System;
namespace Metotlar
{
class Program
{
static void Main(string[] args)
{
Urun elma = new Urun();
elma.Adi = "Amasya";
elma.Aciklama = "Amasyadan gelen elma";
elma.Fiyat = 200;
elma.Id = 1;
Urun urun2 = new Urun();
urun2.Adi = "Karpuz";
urun2.Aciklama = "Diyarbakır karpuzu";
urun2.Fiyat = 199;
urun2.Id = 2;
Urun[] urunler = new Urun[]
{
elma, urun2
};
foreach (Urun urun in urunler)
{
Console.WriteLine(urun.Adi + " : " + urun.Aciklama);
}
Console.WriteLine("---------------------------------");
SepetManager sepetManager = new SepetManager();
sepetManager.Ekle(urun2);
sepetManager.Ekle(elma);
Console.WriteLine("Hello World!");
sepetManager.Ekle2("armut", "çok iyi armut", 12, 20);
}
}
}
|
672ad203f09ef6b513eedd7277c9f0c6db9031ee
|
C#
|
alaminsheikh01/C-sharp-Delegate-
|
/DelegateMethodDemo.cs
| 3.8125
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DelegateDemo
{
public delegate void showmsgdelegate(string message);
class DelegateMethodDemo
{
public void showMessage1(string msg)
{
System.Windows.MessageBox.Show("THIS IS METHOD 1: " + Environment.NewLine + msg);
}
public void showMessage2(string msg)
{
System.Windows.MessageBox.Show("THIS IS METHOD 2: " + Environment.NewLine + msg);
}
/// <summary>
/// this method returns a method hiddden behind the delegate showmsgdelegate
/// </summary>
/// <param name="methodtype">1 for showMessage1 and 2 for showMessage2</param>
/// <returns></returns>
public showmsgdelegate getMethod(string methodtype)
{
if(methodtype.Equals("1"))
{
return this.showMessage1;
}
else if(methodtype.Equals("2"))
{
return this.showMessage2;
}
else
{
throw new Exception("Invalid method type passed.");
}
}
}
}
|
a204cc59c7855b9c29e6bb94840f9cef32b41de3
|
C#
|
jenia996/Simple-single-permutation-cipher
|
/Шифр простой одинарной перестановки/DictionaryHandler.cs
| 3.484375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
namespace Шифр_простой_одинарной_перестановки
{
class DictionaryHandler
{
private String path = @"r:\University\Вычислительная Практика\Dictionary\Dictionary.txt";
private List<String> dictionary;
public DictionaryHandler ()
{
dictionary = new List<string>();
using (StreamReader reader = new StreamReader(path))
{
while (reader.EndOfStream != true)
{
dictionary.Add(reader.ReadLine());
}
}
}
private List<char> getSymbols(String input)
{
List<Char> symbols = new List<char>();
foreach(Char x in input)
{
symbols.Add(x);
}
return symbols;
}
private Boolean checkWord(String word,List<Char> symbols)
{
List<Char> matchWordSymbols = word.ToList();
if(Enumerable.SequenceEqual(matchWordSymbols.OrderBy(x =>x),symbols.OrderBy(t =>t)))
{
return true;
}
return false;
}
public List<String> findAnswers(String input)
{
// List<String>.Enumerator iterator = matches.GetEnumerator();
// iterator.MoveNext();
List<Char> symbols = getSymbols(input.ToLower());
List<String> matches = dictionary.FindAll(x => x.Length == input.Length).ToList();
List<String> answers = new List<string>();
foreach(String word in matches)
{
if(checkWord(word,symbols))
{
answers.Add(word);
}
}
return answers;
}
}
}
|
5a82294a2b0b40b364e61e18676f82b1b385220a
|
C#
|
7Mahfuz/Bitm-Project-University-Management-System
|
/UniversityManagementSystem/UniversityManagementSystem/BLL/CourseManager.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using UniversityManagementSystem.DAL;
using UniversityManagementSystem.Models;
namespace UniversityManagementSystem.BLL
{
public class CourseManager
{
private GenericUnitOfWork aUnitOfWork = null;
public CourseManager()
{
aUnitOfWork = new GenericUnitOfWork();
}
public CourseManager(GenericUnitOfWork _uow)
{
this.aUnitOfWork = _uow;
}
public string Save(Course aCourse)
{
aCourse.Name = aCourse.Name.ToUpper();
aCourse.Code = aCourse.Code.ToUpper();
bool flag = aUnitOfWork.Repository<Course>().InsertModel(aCourse);
aUnitOfWork.Save();
return "Saved Succesfully";
}
public string CheckCode(string code)
{
int x = 0;
code=code.ToUpper();
string msg = "";
x = aUnitOfWork.Repository<Course>().Count(a => a.Code == code);
if (x > 0)
{
return "Code is already Exist";
}
return null;
}
public string CheckName(string name)
{
int x = 0;
name = name.ToUpper();
bool flag = false;
x = aUnitOfWork.Repository<Course>().Count(a => a.Name == name);
if (x > 0)
{
return "Name already Exist";
}
return null;
}
public string CheckCredit(double credit)
{
if (credit < 0.5 || credit > 5.0)
{
return "Credit must be between 0.5 to 5.0";
}
return null;
}
public IEnumerable<Course> GetAllCourses()
{
IEnumerable<Course> courses = aUnitOfWork.Repository<Course>().GetList();
return courses;
}
public IEnumerable<Course> GetCourseByDeptId(int deptId)
{
IEnumerable<Course> courses = aUnitOfWork.Repository<Course>().GetList(x => x.DepartmentId == deptId);
return courses;
}
public Course GetACourse(int courseId)
{
Course aCourse = aUnitOfWork.Repository<Course>().GetModelById(courseId);
return aCourse;
}
}
}
|
3a0b9a49b24c39f4a78d180ec15a8624d2ac250e
|
C#
|
HighGroundVision/Perseverance
|
/src/MatchMessages/GameMessageConverter.cs
| 2.5625
| 3
|
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HGV.Perserverance.MatchMessages
{
public class GameMessageConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(BaseMessage).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject item = JObject.Load(reader);
var type = item["type"].Value<int>();
switch (type)
{
case 0:
return item.ToObject<Header>();
case 1:
return item.ToObject<Footer>();
case 2:
return item.ToObject<UnitSummary>();
case 3:
return item.ToObject<UnitEconomy>();
case 4:
return item.ToObject<UnitPosition>();
case 5:
return item.ToObject<WardObserver>();
case 6:
return item.ToObject<WardSentry>();
case 7:
return item.ToObject<Chat>();
case 8:
return item.ToObject<BarracksKill>();
case 9:
return item.ToObject<TowerKill>();
case 10:
return item.ToObject<TowerDeny>();
case 11:
return item.ToObject<EffegyKill>();
case 12:
return item.ToObject<FirstBlood>();
case 13:
return item.ToObject<KillRoshan>();
case 14:
return item.ToObject<AegisTaken>();
case 15:
return item.ToObject<AegisStolen>();
case 16:
return item.ToObject<AegisDenied>();
case 17:
return item.ToObject<CourierLost>();
case 18:
return item.ToObject<CourierRespawned>();
case 19:
return item.ToObject<Glyphed>();
case 20:
return item.ToObject<RunePickup>();
case 21:
return item.ToObject<RuneBottle>();
case 22:
return item.ToObject<Glyphed>();
case 23:
return item.ToObject<Prediciton>();
case 24:
return item.ToObject<Damage>();
case 25:
return item.ToObject<Heal>();
case 26:
return item.ToObject<Death>();
case 27:
return item.ToObject<Ability>();
case 28:
return item.ToObject<Item>();
case 29:
return item.ToObject<Purchase>();
case 30:
return item.ToObject<BuyBack>();
case 31:
return item.ToObject<Gold>();
case 32:
return item.ToObject<XP>();
case 33:
return item.ToObject<BuildingKill>();
case 34:
return item.ToObject<MultiKill>();
case 35:
return item.ToObject<KillStreak>();
default:
return new UnknownTypeMessage() { type = type, data = item.ToString() };
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
}
|
98601f5a7d2ed2da18b6fed30f559332565dc2e6
|
C#
|
unicaes-ing/practica-07-MarcoEsquivel1
|
/practica7/ejercicio5.cs
| 3.59375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace practica7
{
class ejercicio5
{
//Marco René Esquivel Juárez
//11-sep-2019
public void ejer5()
{
int[,] m1 = new int[3, 3];
int[,] m2 = new int[3, 3];
Console.WriteLine("Matriz 1");
for (int i = 0; i < m1.GetLength(0) ; i++)
{
Console.WriteLine("Ingrese los valores para la fila {0}", i+1);
for (int j = 0; j < m1.GetLength(1) ; j++)
{
m1[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.WriteLine("Matriz 2");
for (int i = 0; i < m2.GetLength(0); i++)
{
Console.WriteLine("Ingrese los valores para la fila {0}", i + 1);
for (int j = 0; j < m2.GetLength(1); j++)
{
m2[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.Clear();
suma(m1, m2);
Console.ReadLine();
}
static void suma(int[,] m1, int[,] m2)
{
int[,] sumar = new int[3, 3];
for (int i = 0; i < m1.GetLength(0); i++)
{
for (int j = 0; j < m1.GetLength(1); j++)
{
sumar[i, j] = m1[i, j] + m2[i, j];
Console.Write(sumar[i,j] + "");
}
Console.WriteLine();
}
}
}
}
|
f074dc87ee9f8b27f084bb4d139ab2b855117f84
|
C#
|
Mechetel/emulatorMT
|
/ZedGraph/NearestPoint/Form1.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ZedGraph;
namespace NearestPoint
{
public partial class Form1 : Form
{
public Form1 ()
{
InitializeComponent ();
DrawGraph ();
}
/// <summary>
/// MouseClick -
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void zedGraph_MouseClick (object sender, MouseEventArgs e)
{
// ,
CurveItem curve;
// ,
int index;
GraphPane pane = zedGraph.GraphPane;
// ,
// , .
GraphPane.Default.NearestTol = 10;
bool result = pane.FindNearestPoint (e.Location, out curve, out index);
if (result)
{
// NearestTol
// ,
PointPairList point = new PointPairList ();
point.Add (curve[index]);
// , .
LineItem curvePount = pane.AddCurve ("",
new double[] { curve[index].X },
new double[] { curve[index].Y },
Color.Blue,
SymbolType.Circle);
//
curvePount.Line.IsVisible = false;
// -
curvePount.Symbol.Fill.Color = Color.Blue;
// -
curvePount.Symbol.Fill.Type = FillType.Solid;
//
curvePount.Symbol.Size = 7;
}
}
private double f (double x)
{
if (x == 0)
{
return 1;
}
return Math.Sin (x) / x;
}
private void DrawGraph ()
{
//
GraphPane pane = zedGraph.GraphPane;
// ,
pane.CurveList.Clear ();
//
PointPairList list = new PointPairList ();
double xmin = -50;
double xmax = 50;
//
for (double x = xmin; x <= xmax; x += 0.01)
{
//
list.Add (x, f (x));
}
// "Sinc",
// (Color.Blue),
// (SymbolType.None)
LineItem myCurve = pane.AddCurve ("Sinc", list, Color.Blue, SymbolType.None);
//
pane.XAxis.MajorGrid.IsVisible = true;
pane.YAxis.MajorGrid.IsVisible = true;
// AxisChange (), .
// ,
// ,
zedGraph.AxisChange ();
//
zedGraph.Invalidate ();
}
}
}
|
f39b09bd4cf5e784122ff9d7b93eeab2aaee1058
|
C#
|
ANANC/TransmitDemo
|
/Assets/Scripts/Unit/Id/IdDistributionChunk.cs
| 2.5625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IdDistributionChunk
{
private int firstId;
private int interval;
private int currentId;
private bool isCanUseDiscardId;
private List<int> discardIdList;
public void Init()
{
discardIdList = new List<int>();
SetFirstId(0);
SetInterval(1);
SetIsCanUseDiscardId(false);
}
public void UnInit()
{
discardIdList.Clear();
}
public void SetFirstId(int firstId)
{
this.firstId = firstId;
currentId = this.firstId;
}
public void SetInterval(int interval)
{
this.interval = interval;
}
public void SetIsCanUseDiscardId(bool isCanUseDiscardId)
{
this.isCanUseDiscardId = isCanUseDiscardId;
}
public int Pop()
{
if (isCanUseDiscardId)
{
if(discardIdList.Count> 0)
{
return PopDiscardId();
}
else
{
return PopNewID();
}
}
else
{
return PopNewID();
}
}
private int PopDiscardId()
{
int id = discardIdList[1];
discardIdList.Remove(1);
return id;
}
private int PopNewID()
{
int id = currentId;
currentId = currentId + interval;
return id;
}
public void Push(int id)
{
discardIdList.Add(id);
}
}
|
b5f520c12f5c7ae4d77790ebb8221cbd759bcaeb
|
C#
|
javonn13/PONG
|
/movement.cs
| 2.96875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI
public class movement : MonoBehaviour {
{
public float movementSpeed;
public float extraSpeedPerHit;
public float maxExtraSpeed;
int hitCounter = 0;
// Start is called before the first frame update
void Start() {
Start.Coroutine(this.StartBall());
}
public IEnumerator StartBall(bool isStartingPlayer1 = true){
this.hitCounter = 0;
yied return new WaitForSeconds(2);
if (isStartingPlayer1)
this.Moveball(new vector2 (-1, 0));
else {
this.Moveball(new vector2 (1, 0));
}
}
public void MoveBall(vector2 dir){
dir = dir.normalized;
float speed = this movementSpeed + this.hitCounter * this.extraSpeedPerHit;
Rigidbody2D rigidBody2D = this.gameObject.GetComponent<Rigidbody2D>();
rigidBody2D.velocity = dir * speed;
}
public void IncreaseHitCounter()
{
if(this.hitCounter * this.extraSpeedPerHit <= this.maxExtraSpeed){ {
this.hitCounter++;
}
}
}
|
31c49f5f6a252b54341bdc6290c488735d851c33
|
C#
|
JaZolynski/Snake
|
/Snake/Board.cs
| 3.609375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Snake
{
class Board
{
int weidth;
int height;
public Board(int w=50,int h=20)
{
weidth = w;
height = h;
}
public void draw()
{
for (int i = 0; i < height; i++)
{
for (int j = 0; j < weidth; j++)
if ((i == 0) || (i == height - 1) ||(j == 0) || (j==weidth-1))
Console.Write("#");
else
Console.Write(" ");
Console.WriteLine();
}
}
}
}
|