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
|
|---|---|---|---|---|---|---|
79f148a35e3562aa7de0db953b22bc4acbb46e77
|
C#
|
melliemello/TelerikAcademyHomeworks
|
/C#-Part-I/Exam/02/02/Program.cs
| 3.703125
| 4
|
using System;
namespace _02
{
class Program
{
static void Main()
{
double secret = Int32.Parse(Console.ReadLine());
double temp;
double result;
string text = Console.ReadLine();
int len = text.Length;
for (int i = 0; i < len; i++ )
{
if(text[i].ToString() == "@")
{
break;
}
if(Char.IsLetter(text[i]))
{
temp = ((int)text[i] * secret) + 1000;
}
else if (Char.IsDigit(text[i]))
{
temp = ((int)text[i] + secret) + 500;
}
else
{
temp = (int)text[i] - secret;
}
if (i % 2 == 0)
{
result = temp / 100;
result = Math.Round(result, 2);
Console.WriteLine("{0:F2}", result);
}
else
{
result = temp * 100;
result = Math.Round(result, 2);
Console.WriteLine("{0}", result);
}
}
}
}
}
|
b4d7b95bc4e1c9b21fd641b134af815cf5106ca9
|
C#
|
andrewwdk/NET.S.2019.Zhidenko
|
/NET.S.2019.Zhidenko.13/Matrixes/MatrixChangeEventArgs.cs
| 2.640625
| 3
|
using System;
namespace Matrixes
{
public class MatrixChangeEventArgs<T> : EventArgs
{
public MatrixChangeEventArgs(int i, int j, T element)
{
this.I = i;
this.J = j;
this.Element = element;
}
public int I { get; private set; }
public int J { get; private set; }
public T Element { get; private set; }
}
}
|
f0afa5ca3302974be6539af41aab0ec00305e7e1
|
C#
|
shendongnian/download4
|
/code6/1046871-26999002-77936827-2.cs
| 2.8125
| 3
|
Public Class MyClass
Dim NextValidTime as DateTime
public sub Some_Event_Handler()
If Now() > NextValidtime Then
'do stuff
NextValidTime = DateAdd(DateInterval.Second, 1, Now)
Else
' Not enough time has passed - do nothing
End If
end sub
End Class
|
ce1e0f2da24b48ac0408680a571c2e58a5347e7a
|
C#
|
shendongnian/download4
|
/first_version_download2/278001-22397513-60355224-2.cs
| 2.6875
| 3
|
var ar = DateTime.Now.ToString("dd/MM/yy HH:mm:ss tt",
new System.Globalization.CultureInfo("ar-AE"));
// 14/03/14 06:14:34 ص
var us = DateTime.Now.ToString("dd/MM/yy HH:mm:ss tt",
new System.Globalization.CultureInfo("en-US"));
// 14/03/14 06:14:44 AM
|
7b0a1ca92f399497b865b0ac797dd9fa3779a6b9
|
C#
|
gabrielmt07/MinhaApiRest
|
/Api.Domain/Pessoa.cs
| 2.75
| 3
|
using System.ComponentModel.DataAnnotations;
namespace Api.Domain
{
public class Pessoa
{
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Campo obrigatório")]
[MaxLength(500, ErrorMessage = "Campo deve ter no máximo {1} caracteres")]
[MinLength(3, ErrorMessage = "Campo deve ter, no mínimo, {1} caracteres")]
public string Nome { get; set; }
[Required(ErrorMessage = "Idade obrigatória")]
public int Idade { get; set; }
}
}
|
b512f8d38e8cf36edbeb64265fffd1428b51871e
|
C#
|
PopovychMykhailo/TrainingInCyberBionicSystematics
|
/.Net/C# Starter/Lesson 4 (2021.07.19) - if else, switch case/004_Conditions/015_Switch Expression/Program.cs
| 3.890625
| 4
|
using System;
using System.Text;
namespace _015_Switch_Expression
{
class Program
{
static void Main(string[] args)
{
Console.OutputEncoding = Encoding.Unicode;
Console.InputEncoding = Encoding.Unicode;
Console.WriteLine("Введите название дня недели:");
string dayOfWeek = Console.ReadLine();
string dayOfWeekInLowerCase = dayOfWeek.ToLower(); // ToLower() - приводит строку в нижний регистр
int dayOfWeekNumber = dayOfWeekInLowerCase switch
{
"понедельник" => 1,
"вторник" => 2,
"среда" => 3,
"четверг" => 4,
"пятница" => 5,
"суббота" => 6,
"воскресенье" => 7,
_ => -1
};
if (dayOfWeekNumber > 0)
{
Console.WriteLine($"{dayOfWeek} это {dayOfWeekNumber} день недели.");
}
else
{
Console.WriteLine($"Я не знаю дня недели под названием {dayOfWeek}");
}
}
}
}
|
5b8d2cd333b445d9b4b8786ba5b6f544d83ef22b
|
C#
|
nickworonekin/puyotools
|
/src/PuyoTools.Core/Textures/Gim/PixelCodecs/Index8PixelCodec.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace PuyoTools.Core.Textures.Gim.PixelCodecs
{
/// <inheritdoc/>
internal class Index8PixelCodec : PixelCodec
{
public override bool CanEncode => true;
public override int BitsPerPixel => 8;
public override int PaletteEntries => 256;
public override byte[] Decode(byte[] source, int width, int height, int pixelsPerRow, int pixelsPerColumn)
{
if (Palette is null)
{
throw new InvalidOperationException("Palette must be set.");
}
var destination = new byte[width * height * 4];
int sourceIndex;
int destinationIndex;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
sourceIndex = (y * pixelsPerRow) + x;
destinationIndex = ((y * width) + x) * 4;
byte paletteIndex = source[sourceIndex];
for (int i = 0; i < 4; i++)
{
destination[destinationIndex + i] = Palette[(paletteIndex * 4) + i];
}
}
}
return destination;
}
public override byte[] Encode(byte[] source, int width, int height, int pixelsPerRow, int pixelsPerColumn)
{
var destination = new byte[pixelsPerRow * pixelsPerColumn];
int sourceIndex;
int destinationIndex;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
sourceIndex = (y * width) + x;
destinationIndex = (y * pixelsPerRow) + x;
destination[destinationIndex] = source[sourceIndex];
}
}
return destination;
}
}
}
|
1ff81caf6106ee0ab3f67c95feff2ceac7f238e4
|
C#
|
DevArcana/GameParadeSummer2021
|
/Assets/Scripts/Ability/AbilitySlots.cs
| 3.078125
| 3
|
using System;
using Ability.Abilities;
using Arena;
namespace Ability
{
public class AbilitySlots
{
private BaseAbility[] _slots = new BaseAbility[3];
public BaseAbility SelectedAbility => SelectedSlot != -1 ? _slots[SelectedSlot] : null;
public int SelectedSlot { get; private set; } = -1;
public class AbilitySelectionChangedEventArgs : EventArgs
{
public int Slot { get; set; }
}
public event EventHandler<AbilitySelectionChangedEventArgs> AbilitySelectionChanged;
private void OnAbilitySelectionChanged()
{
AbilitySelectionChanged?.Invoke(this, new AbilitySelectionChangedEventArgs {Slot = SelectedSlot});
}
public bool HasAbility(int slot)
{
return _slots[slot] != null;
}
public void PopulateAbilities(GridEntity entity)
{
var random = new Random();
const double secondSlotTwoCostProbability = 0.5;
const double thirdSlotThreeCostProbability = 0.5;
SetAbility(0, AbilityFactory.GetRandomOneCostAbility(entity));
SetAbility(1, random.NextDouble() <= secondSlotTwoCostProbability ? AbilityFactory.GetRandomTwoCostAbility(entity) : AbilityFactory.GetRandomOneCostAbility(entity));
SetAbility(2, random.NextDouble() <= thirdSlotThreeCostProbability ? AbilityFactory.GetRandomThreeCostAbility(entity) : AbilityFactory.GetRandomTwoCostAbility(entity));
}
public void SetAbility(int slot, BaseAbility ability)
{
_slots[slot] = ability;
if (SelectedSlot == slot)
{
Deselect();
}
}
public BaseAbility GetAbility(int slot)
{
return _slots[slot];
}
public bool SelectAbility(int slot)
{
if (!HasAbility(slot))
{
return false;
}
SelectedSlot = slot;
OnAbilitySelectionChanged();
return true;
}
public void Deselect()
{
SelectedSlot = -1;
OnAbilitySelectionChanged();
}
}
}
|
e528a3b04b52d024d6516c3db514b85c55c9fdc5
|
C#
|
ali50m/education
|
/asp.net-mvc/the-complete-aspnet-mvc-5-course/src/Vidly/Vidly/Controllers/MovieController.cs
| 2.625
| 3
|
namespace Vidly.Controllers
{
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using Vidly.Models;
using Vidly.ViewModels;
public class MovieController : Controller
{
private ApplicationDbContext _context;
public MovieController()
{
_context = new ApplicationDbContext();
}
protected override void Dispose(bool disposing)
{
_context.Dispose();
}
// GET: Movie/Index
public ActionResult Index()
{
var movies = _context.Movies.Include(m => m.Genre);
return View(movies);
}
// GET: Movie/New
public ActionResult New()
{
var viewModel = new ManageMovieViewModel(_context.Genres, null);
return View("ManageMovie", viewModel);
}
// GET: Movie/Edit/{id}
public ActionResult Edit(int id)
{
Movie movie = _context.Movies.SingleOrDefault(m => m.Id == id);
if (movie == null)
{
return HttpNotFound($"There is no " +
$"{this.GetType().Name.Replace("Controller", "")} with Id = {id}");
}
ManageMovieViewModel viewModel = new ManageMovieViewModel(_context.Genres, movie);
return View("ManageMovie", viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Save(ManageMovieViewModel movieVeiwModel)
{
Movie model = movieVeiwModel.GetPopulatedMovie();
if (!ModelState.IsValid)
{
var viewModel = new ManageMovieViewModel(_context.Genres, model);
return View("ManageMovie", viewModel);
}
if (model.Id > 0)
{
// Existing Record
Movie movieFromDb = _context.Movies.SingleOrDefault(m => m.Id == model.Id);
if (movieFromDb != null)
{
movieFromDb.Name = model.Name;
movieFromDb.ReleaseDate = model.ReleaseDate;
movieFromDb.GenreId = model.GenreId;
movieFromDb.NumberInStock = model.NumberInStock;
}
}
else
{
// New Record
_context.Movies.Add(model);
}
try
{
await _context.SaveChangesAsync();
}
catch (DbEntityValidationException e)
{
return Content(GetValidationExceptionInfo(e));
}
return RedirectToAction("Index", "Movie");
}
#region Helpers
private string GetValidationExceptionInfo(DbEntityValidationException e)
{
StringBuilder sb = new StringBuilder();
if (e != null)
{
foreach (var eve in e.EntityValidationErrors)
{
sb.Append($"Entity of type \"{eve.Entry.Entity.GetType().Name}\" in state \"{eve.Entry.State}\" has the following validation errors:");
foreach (var ve in eve.ValidationErrors)
{
sb.Append($"- Property: \"{ve.PropertyName}\", Error: \"{ve.ErrorMessage}\"");
}
}
}
return sb.ToString();
}
#endregion //Helpers
#region Demo Actions
// GET: Movie/Details/{id}
public ActionResult Details(int id)
{
Movie movie = _context.Movies
.Include(m => m.Genre)
.SingleOrDefault(m => m.Id == id);
if (movie != null)
{
return View(movie);
}
else
{
return HttpNotFound($"There is no movie with Id = {id}");
}
}
// GET: Movie/PagedIndex
public ActionResult PagedIndex(int? pageIndex, string sortBy)
{
if (!pageIndex.HasValue)
{
pageIndex = 1;
}
if (string.IsNullOrWhiteSpace(sortBy))
{
sortBy = "Name";
}
return Content($"pageIndex = {pageIndex}, sortBy = '{sortBy}'");
}
// GET: Movie/Random
public ActionResult Random()
{
RandomMovieViewModel viewModel = new RandomMovieViewModel()
{
Movie = new Movie() { Id = 777, Name = "Random movie..." },
Customers = new List<Customer>() { new Customer(1, "Steve"), new Customer(3, "John") }
};
return View(viewModel);
//return Content("Hello MVC...");
//return HttpNotFound();
//return new EmptyResult();
//return RedirectToAction("index", "home", new { page = 1, sortBy = "name" });
}
// GET: Movie/Released/{year}/{month}
[Route("movie/released/{year:regex(\\d{4})}/{month:range(1,12)}")]
public ActionResult ByReleaseDate(int year, int month)
{
return Content($"ByReleaseDate action with parameter year = {year} and " +
$"month = {month} from {this.GetType().Name}");
}
#endregion //Demo Actions
}
}
|
7d7c9993a2f6d324c8811300dca3d30f53888c19
|
C#
|
svilenb/TelerikAcademy
|
/Databases-for-Developers/Entity-Framework/05.FindSalesByRegionAndPeriod/FindSalesByRegionAndPeriod.cs
| 3.296875
| 3
|
namespace _05.FindSalesByRegionAndPeriod
{
using System;
using System.Linq;
using EntityFrameworkDatabaseFirst;
class FindSalesByRegionAndPeriod
{
static void Main(string[] args)
{
using (NorthwindEntities northwindEntities = new NorthwindEntities())
{
ListSalesByRegionAndPeriod(northwindEntities, "Canada", new DateTime(1995, 10, 22), new DateTime(1998, 10, 22));
}
}
private static void ListSalesByRegionAndPeriod(NorthwindEntities northwindEntites, string region, DateTime startDate, DateTime endDate)
{
var sales = northwindEntites.Orders
.Where(order => order.OrderDate >= startDate && order.OrderDate <= endDate && order.ShipCountry == region);
foreach (var sale in sales)
{
Console.WriteLine("{0} {1} {2}", sale.OrderID, sale.OrderDate, sale.ShipCountry);
}
}
}
}
|
69366d4d6208cb7ceef17ba02e0e484e7a845c2a
|
C#
|
TestCentric/tc-lite
|
/src/tclite/Constraints/CollectionItemsEqualConstraint.cs
| 2.890625
| 3
|
// ***********************************************************************
// Copyright (c) Charlie Poole and TestCentric contributors.
// Licensed under the MIT License. See LICENSE in root directory.
// ***********************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
namespace TCLite.Constraints
{
/// <summary>
/// CollectionItemsEqualConstraint is the abstract base class for all
/// collection constraints that apply some notion of item equality
/// as a part of their operation.
/// </summary>
public abstract class CollectionItemsEqualConstraint : CollectionConstraint
{
private readonly TCLiteEqualityComparer _comparer = new TCLiteEqualityComparer();
/// <summary>
/// Construct an empty CollectionConstraint
/// </summary>
protected CollectionItemsEqualConstraint() { }
/// <summary>
/// Construct a CollectionConstraint
/// </summary>
/// <param name="arg"></param>
protected CollectionItemsEqualConstraint(object arg) : base(arg) { }
/// <summary>
/// Get a flag indicating whether the user requested us to ignore case.
/// </summary>
protected bool IgnoringCase => _comparer.IgnoreCase;
/// <summary>
/// Get a flag indicating whether any external comparers are in use.
/// </summary>
protected bool UsingExternalComparer => _comparer.ExternalComparers.Count > 0;
#region Modifiers
/// <summary>
/// Flag the constraint to ignore case and return self.
/// </summary>
public CollectionItemsEqualConstraint IgnoreCase
{
get
{
_comparer.IgnoreCase = true;
return this;
}
}
/// <summary>
/// Flag the constraint to use the supplied EqualityAdapter.
/// NOTE: For internal use only.
/// </summary>
/// <param name="adapter">The EqualityAdapter to use.</param>
/// <returns>Self.</returns>
internal CollectionItemsEqualConstraint Using(EqualityAdapter adapter)
{
_comparer.ExternalComparers.Add(adapter);
return this;
}
/// <summary>
/// Flag the constraint to use the supplied IComparer object.
/// </summary>
/// <param name="comparer">The IComparer object to use.</param>
/// <returns>Self.</returns>
public CollectionItemsEqualConstraint Using(IComparer comparer)
{
return Using(EqualityAdapter.For(comparer));
}
/// <summary>
/// Flag the constraint to use the supplied IComparer object.
/// </summary>
/// <param name="comparer">The IComparer object to use.</param>
/// <returns>Self.</returns>
public CollectionItemsEqualConstraint Using<T>(IComparer<T> comparer)
{
return Using(EqualityAdapter.For(comparer));
}
/// <summary>
/// Flag the constraint to use the supplied Comparison object.
/// </summary>
/// <param name="comparer">The IComparer object to use.</param>
/// <returns>Self.</returns>
public CollectionItemsEqualConstraint Using<T>(Comparison<T> comparer)
{
return Using(EqualityAdapter.For(comparer));
}
/// <summary>
/// Flag the constraint to use the supplied IEqualityComparer object.
/// </summary>
/// <param name="comparer">The IComparer object to use.</param>
/// <returns>Self.</returns>
public CollectionItemsEqualConstraint Using(IEqualityComparer comparer)
{
return Using(EqualityAdapter.For(comparer));
}
/// <summary>
/// Flag the constraint to use the supplied IEqualityComparer object.
/// </summary>
/// <param name="comparer">The IComparer object to use.</param>
/// <returns>Self.</returns>
public CollectionItemsEqualConstraint Using<T>(IEqualityComparer<T> comparer)
{
return Using(EqualityAdapter.For(comparer));
}
#endregion
/// <summary>
/// Compares two collection members for equality
/// </summary>
protected bool ItemsEqual(object x, object y)
{
Tolerance tolerance = Tolerance.Exact;
return _comparer.AreEqual(x, y, ref tolerance);
}
/// <summary>
/// Return a new CollectionTally for use in making tests
/// </summary>
/// <param name="c">The collection to be included in the tally</param>
protected CollectionTally Tally(IEnumerable c)
{
return new CollectionTally(_comparer, c);
}
}
}
|
2f0a3af709f59f2213eade49d8d886fe011647e9
|
C#
|
s18636/APBD-cw1
|
/APBD-cw1/APBD-cw1/Program.cs
| 3.015625
| 3
|
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Linq;
namespace cw1
{
public class Student
{
public string Imie { get; set; }
private string _nazwisko;
//prywatne pola dawac z podkreslnikiem
public string Nazwisko
{
get { return _nazwisko; }
set
{
if (value == null) throw new ArgumentException();
_nazwisko = value;
}
}
}
public class Program
{
private static HttpClient client = new HttpClient();
public static async Task Main(string[] args)
{
try
{
//nazwy metod i zmiennych z duzej litery
//prywatne pola dawac z podkreslnikiem
//if (args.Length == 0) return;
//nie zagniezdza nam sie kod
string url = args.Length > 0 ? args[0] : "https://www.pja.edu.pl";
await RecMailSearch(url);
//Task <T>
// ThreadPool() daje nam to dostep do puli watkow
//
var zbiory = new HashSet<string>();
var list = new List<String>();
var slownik = new Dictionary<string, int>();
var znalezione = from e in list
where e.StartsWith("a")
select e;
//zadanie przechodzi rekurencyjnie po url na stronie i wypisywac z nich adresy email
var st = new Student();
st.Imie = "Jan";
}
catch (Exception exc) {
//string.Format("wystapil blad: {0}", exc.toString());
Console.WriteLine($"wystapil blad: {exc.ToString()}");
}
Console.WriteLine("Koniec");
}
public static async Task RecMailSearch(string url) {
try
{
var result = await client.GetAsync(url);
if (!result.IsSuccessStatusCode) return;
string html = await result.Content.ReadAsStringAsync();
var mailRegex = new Regex("[a-z]+[a-z0-9]*@[a-z.]+", RegexOptions.IgnoreCase);
//regex do czytania maili
var matchesMail = mailRegex.Matches(html);
foreach (var m in matchesMail)
{
Console.WriteLine(m);
}
var urlRegex = new Regex("((([A-Za-z]{3,9}:(?:\\/\\/)?)(?:[-;:&=\\+\\$,\\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\\+\\$,\\w]+@)[A-Za-z0-9.-]+)((?:\\/[\\+~%\\/.\\w-_]*)?\\??(?:[-\\+=&;%@.\\w_]*)#?(?:[\\w]*))?)");
var matchesUrl = urlRegex.Matches(html);
foreach (var u in matchesUrl)
{
await RecMailSearch(u.ToString());
}
}
catch (Exception exc) {
Console.WriteLine("blad");
}
}
}
}
|
c4aa1a0968585bce45228f6d891b11b41fccbc12
|
C#
|
jduv/IndexML
|
/IndexML/Spreadsheet/RowIndexer.cs
| 3.265625
| 3
|
namespace IndexML.Spreadsheet
{
using System;
using System.Collections.Generic;
using DocumentFormat.OpenXml.Spreadsheet;
/// <summary>
/// OpenXml utiltiy class for indexing rows.
/// </summary>
public class RowIndexer
{
#region Fields & Constants
/// <summary>
/// The capacity of the indexer.
/// </summary>
private static readonly short Capacity = 1024 * 16;
/// <summary>
/// A dictionary of cells. This can take up a bit of memory.
/// </summary>
private IDictionary<long, CellIndexer> cells = new Dictionary<long, CellIndexer>();
/// <summary>
/// The maximum column index for the indexer. Zero based.
/// </summary>
private long maxColumnIndex = 0;
#endregion
#region Constructors & Destructors
public RowIndexer(Row row)
{
if (row == null)
{
throw new ArgumentNullException("row");
}
long count = 0;
long columnIndex = 0;
foreach (var cell in row.Descendants<Cell>())
{
var cellIndexer = new CellIndexer(cell);
columnIndex = cellIndexer.ColumnIndex;
this.cells[columnIndex] = cellIndexer;
count++;
}
this.maxColumnIndex = columnIndex;
this.Count = count;
this.Row = row;
}
#endregion
#region Properties
/// <summary>
/// Gets the object associated with this indexer. Changes made to the cell will not be reflected
/// to any dependent properties inside the indexer, so use this with care.
/// </summary>
public Row Row { get; private set; }
/// <summary>
/// Gets the number of columns in this row.
/// </summary>
public long Count { get; private set; }
/// <summary>
/// Gets or sets the index for this row. This property is virtual for testing purposes.
/// </summary>
public virtual uint RowIndex
{
get
{
return this.Row.RowIndex;
}
set
{
this.Row.RowIndex = value;
}
}
/// <summary>
/// Gets a value indicating whether this row has any cells or not.
/// </summary>
public bool IsEmpty
{
get
{
return this.Count <= 0;
}
}
/// <summary>
/// Gets the maximum column index.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if there are no cells in the row.</exception>
public long MaxColumnIndex
{
get
{
if (this.IsEmpty)
{
throw new InvalidOperationException("No columns exist in the indexer!");
}
else
{
return this.maxColumnIndex + 1;
}
}
}
/// <summary>
/// Gets a list of all cells inside the indexer.
/// </summary>
public IEnumerable<CellIndexer> Cells
{
get
{
return this.cells.Values;
}
}
/// <summary>
/// Gets the cell at the target column index.
/// </summary>
/// <param name="colIndex">The column index, which should be one based.</param>
/// <returns>The cell at the target index, or null if the column doesn't exist in the row.</returns>
/// <exception cref="IndexOutOfRangeExcception">Thrown if <paramref name="colIndex"/> is
/// out of range.</exception>
public CellIndexer this[long colIndex]
{
get
{
if (colIndex > Capacity || colIndex < 1)
{
throw new IndexOutOfRangeException("Column index out of range!");
}
if (this.cells.ContainsKey(colIndex))
{
return this.cells[colIndex];
}
return null;
}
}
/// <summary>
/// Gets the cell at the target column name.
/// </summary>
/// <param name="colName">The cell name whose column to retrieve. This can be with or
/// without trailing numbers (e.g. AA and AA11 both result in a column index of 27).</param>
/// <returns>The cell at the target column name, or null if the column doesn't exist in the row.</returns>
/// <exception cref="ArgumentException">Thrown if <paramref name="colName"/> is null or
/// malformed.</exception>
/// <exception cref="IndexOutOfRangeExcception">Thrown if the translated column index is
/// out of range.</exception>
public CellIndexer this[string colName]
{
get
{
if (string.IsNullOrEmpty(colName))
{
throw new ArgumentException("The string parameter cannot be null or empty!", "columnName");
}
long colIdx;
if (CellReference.TryGetColumnIndex(colName, false, out colIdx))
{
return this[colIdx];
}
else
{
throw new InvalidOperationException("Unable to parse column index from string " + colName);
}
}
}
#endregion
#region Public Methods
/// <summary>
/// Casts the indexer into a Row object. Any changes made to the result of this
/// cast will not be reflected in the indexer, so use this with care.
/// </summary>
/// <param name="indexer">The indexer to cast.</param>
/// <returns>The indexer's wrapped object.</returns>
public static implicit operator Row(RowIndexer indexer)
{
return indexer != null ? indexer.Row : null;
}
/// <summary>
/// Clones the underlying row and returns an indexer for it.
/// </summary>
/// <returns>A new <see cref="RowIndexer"/> instance on a copy of this one's
/// Row object.</returns>
public RowIndexer Clone()
{
return new RowIndexer((Row)this.Row.Clone());
}
#endregion
}
}
|
c2bb74ccca51a88a6dfad44e91edc69fffceb48c
|
C#
|
Charlietzu/software-unit-tests
|
/Demo.Tests/AssertStringsTests.cs
| 2.921875
| 3
|
using Xunit;
namespace Demo.Tests
{
public class AssertStringsTests
{
[Fact]
public void StringsTools_JoinNames_ReturnFullName()
{
//Arrange
StringsTools sut = new StringsTools();
//Act
string fullName = sut.Join("Caio", "César");
//Assert
Assert.Equal("Caio César", fullName);
}
[Fact]
public void StringsTools_JoinNames_MustIgnoreCase()
{
//Arrange
StringsTools sut = new StringsTools();
//Act
string fullName = sut.Join("Caio", "César");
//Assert
Assert.Equal("CAIO CÉSAR", fullName, true);
}
[Fact]
public void StringsTools_JoinNames_MustContainSubString()
{
//Arrange
StringsTools sut = new StringsTools();
//Act
string fullName = sut.Join("Caio", "César");
//Assert
Assert.Contains("aio", fullName);
}
[Fact]
public void StringsTools_JoinNames_MustStartWith()
{
//Arrange
StringsTools sut = new StringsTools();
//Act
string fullName = sut.Join("Caio", "César");
//Assert
Assert.StartsWith("Cai", fullName);
}
[Fact]
public void StringsTools_JoinNames_MustEndWith()
{
//Arrange
StringsTools sut = new StringsTools();
//Act
string fullName = sut.Join("Caio", "César");
//Assert
Assert.EndsWith("sar", fullName);
}
[Fact]
public void StringsTools_JoinNames_ValidateRegularExpression()
{
//Arrange
StringsTools sut = new StringsTools();
//Act
string fullName = sut.Join("Caio", "Cesar");
//Assert
Assert.Matches("[A-Z]{1}[a-z]+ [A-Z]{1}[a-z]+", fullName);
}
}
}
|
80b61f33b424da6b2753a71499c68034050bc05a
|
C#
|
liveoffedge/CodeFights
|
/Arcade/The Core/Well of Integration/allLongestStrings.cs
| 2.84375
| 3
|
string[] allLongestStrings(string[] inputArray) {
List<String> answer = new List<String>();
answer.Add(inputArray[0]);
for (int i = 1; i < inputArray.Length; i++) {
if (inputArray[i].Length == answer[0].Length) {
answer.Add(inputArray[i]);
}
if (inputArray[i].Length > answer[0].Length) {
answer = new List<String>();
answer.Add(inputArray[i]);
}
}
return answer.ToArray();
}
|
ca7a8b318153a5d961a314e0f25ddc5d53777999
|
C#
|
kaerniteal/SkillSimulatorMHW
|
/SkillSimulatorMHW/SkillSymulatorMHW/Result/ResultData.cs
| 2.875
| 3
|
using System.Collections.Generic;
using System.Linq;
using SkillSimulatorMHW.Data;
namespace SkillSimulatorMHW.Result
{
/// <summary>
/// 結果データセット.
/// </summary>
public class ResultData
{
/// <summary>
/// コンストラクタ.
/// </summary>
public ResultData()
{
this.SatisfiedList = new List<ResultSet>();
this.ShortageSkillDic = new Dictionary<string, List<ResultSet>>();
this.ShortageSlotDic = new Dictionary<string, List<ResultSet>>();
}
/// <summary>
/// 条件未達解析を実施したかどうか.
/// </summary>
public bool AnalyzeFactors { get; set; }
/// <summary>
/// 条件を満たしたセットリスト.
/// </summary>
private List<ResultSet> SatisfiedList { get; set; }
/// <summary>
/// スキル不足セット辞書.
/// </summary>
private Dictionary<string, List<ResultSet>> ShortageSkillDic { get; set; }
/// <summary>
/// スロット不足セット辞書.
/// </summary>
private Dictionary<string, List<ResultSet>> ShortageSlotDic { get; set; }
/// <summary>
/// 条件を満たしたセットを追加する.
/// </summary>
public void AddSatisfiedSet(ResultSet resultSet)
{
this.SatisfiedList.Add(resultSet);
}
/// <summary>
/// スキル不足セットを追加する.
/// </summary>
/// <param name="key"></param>
/// <param name="resultSet"></param>
public void AddShortageSkill(string key, ResultSet resultSet)
{
if (this.ShortageSkillDic.ContainsKey(key))
{
this.ShortageSkillDic[key].Add(resultSet);
}
else
{
this.ShortageSkillDic.Add(key, new List<ResultSet> { resultSet });
}
}
/// <summary>
/// スロット不足セットを追加する.
/// </summary>
/// <param name="key"></param>
/// <param name="resultSet"></param>
public void AddShortageSlot(string key, ResultSet resultSet)
{
if (this.ShortageSlotDic.ContainsKey(key))
{
this.ShortageSlotDic[key].Add(resultSet);
}
else
{
this.ShortageSlotDic.Add(key, new List<ResultSet> { resultSet });
}
}
/// <summary>
/// 条件を満たしたセットを取得する.
/// </summary>
/// <returns></returns>
public List<ResultSet> GetSatisfiedList()
{
return this.SatisfiedList;
}
/// <summary>
/// スキル不足セットを取得する.
/// </summary>
/// <returns></returns>
public List<ResultSet> GetShortageSkillList(string key)
{
return this.ShortageSkillDic.ContainsKey(key)
? this.ShortageSkillDic[key]
: new List<ResultSet>();
}
/// <summary>
/// スロット不足セットを取得する.
/// </summary>
/// <returns></returns>
public List<ResultSet> GetShortageSlotList(string key)
{
return this.ShortageSlotDic.ContainsKey(key)
? this.ShortageSlotDic[key]
: new List<ResultSet>();
}
/// <summary>
/// 条件を満たしたセットの数を取得する.
/// </summary>
/// <returns></returns>
public int GetSatisfiedCount()
{
return this.SatisfiedList.Count;
}
/// <summary>
/// 解析結果一覧を取得する.
/// </summary>
/// <returns></returns>
public List<AnalyzeResultBase> GetAnalyzeResultList()
{
var resultList = new List<AnalyzeResultBase>();
// スキル不足を追加.
resultList.AddRange(this.ShortageSkillDic
.Keys
.OrderBy(key => key)
.Select(key => new AnalyzeResultShortageSkill(key, this.ShortageSkillDic[key]))
.ToList());
// スロット不足を追加.
resultList.AddRange(this.ShortageSlotDic
.Keys
.OrderBy(key => key)
.Select(key => new AnalyzeResultShortageSlot(key, this.ShortageSlotDic[key]))
.ToList());
// リストを返す.
return resultList;
}
}
}
|
203a7ffe1767843bb2e3e4747a2687a87af2fe96
|
C#
|
newky2k/dscomponents
|
/src/DSoft.Datatypes.Grid/Data/DSDataValue.cs
| 2.8125
| 3
|
// ****************************************************************************
// <copyright file="DSDataValue.cs" company="DSoft Developments">
// Created By David Humphreys
// Copyright © David Humphreys 2015
// </copyright>
// ****************************************************************************
using System;
using System.ComponentModel;
namespace DSoft.Datatypes.Grid.Data
{
/// <summary>
/// Stores the values for columns in a row
/// </summary>
public class DSDataValue : INotifyPropertyChanged
{
#region Fields
private object mValue;
#endregion
#region Properties
/// <summary>
/// Gets or sets the name of the column.
/// </summary>
/// <value>The name of the column.</value>
public String ColumnName { get; set;}
/// <summary>
/// Gets or sets the value.
/// </summary>
/// <value>The value.</value>
public object Value
{
get
{
return mValue;
}
set
{
if (mValue == null)
{
mValue = value;
}
else if (!mValue.Equals(value))
{
OnPropertyChanged("Value");
mValue = value;
}
}
}
#endregion
#region INotifyPropertyChanged implementation
/// <summary>
/// Occurs when property changed.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged = delegate {};
private void OnPropertyChanged(String Name)
{
PropertyChanged(this, new PropertyChangedEventArgs(Name));
}
#endregion
}
}
|
ce0ac32c4271fb022af05af53ef7ab64e0bebe5d
|
C#
|
matthew-m-moore/EduSafe-Insurance
|
/EduSafe.Core/Repositories/Excel/Converters/ScenarioLogicConverter.cs
| 2.59375
| 3
|
using System;
using EduSafe.Core.BusinessLogic.Scenarios.ScenarioLogic;
using EduSafe.Core.BusinessLogic.Scenarios.Shocks;
using EduSafe.Core.Interfaces;
using EduSafe.IO.Excel.Records;
namespace EduSafe.Core.Repositories.Excel.Converters
{
public class ScenarioLogicConverter
{
private const string _interestRateScenario = "interest rate";
private const string _optionalityScenario = "optionality";
private const string _enrollmentTargetScenario = "enrollment target";
private const string _enrollmentTransitionScenario = "enrollment transition";
public const string ServicingCostsScenario = "servicing costs";
public static IScenario ConvertToScenario(ShockParametersRecord shockParametersRecord)
{
var shockLogic = ShockLogicConvertor.Convert(
shockParametersRecord.ShockLogicType,
shockParametersRecord.ShockValue);
return ConvertToScenario(shockLogic, shockParametersRecord);
}
public static IScenario ConvertToScenario(ShockLogic shockLogic, ShockParametersRecord shockParametersRecord)
{
var shockScenarioType = shockParametersRecord.ShockType;
if (string.IsNullOrWhiteSpace(shockScenarioType))
throw new Exception("ERROR: A shock scenario type such as 'Interest Rate' or 'Enrollment Target' must be provided.");
switch (shockScenarioType.ToLower())
{
case _interestRateScenario:
return CreateInterestRateScenario(shockLogic, shockParametersRecord);
case _optionalityScenario:
return CreateOptionalityScenario(shockLogic, shockParametersRecord);
case _enrollmentTargetScenario:
return CreateEnrollmentTargetScenario(shockLogic, shockParametersRecord);
case _enrollmentTransitionScenario:
return CreateEnrollmentTransitionScenario(shockLogic, shockParametersRecord);
case ServicingCostsScenario:
return CreateServicingCostsScenario(shockLogic, shockParametersRecord);
default:
throw new Exception(string.Format("ERROR: Shock scenario type of '{0}' is not supported, please check inputs.",
shockScenarioType));
}
}
private static IScenario CreateInterestRateScenario(ShockLogic shockLogic, ShockParametersRecord shockParametersRecord)
{
var shockScenarioName = string.IsNullOrWhiteSpace(shockParametersRecord.ShockScenarioName)
? _interestRateScenario.ToUpper() + ": "
+ shockParametersRecord.ShockLogicType + ", "
+ shockParametersRecord.ShockValue
: shockParametersRecord.ShockScenarioName;
return new InterestRateShockScenario(shockLogic,
shockParametersRecord.AllowPremiumsToAdjust)
{
ScenarioName = shockScenarioName
};
}
private static IScenario CreateOptionalityScenario(ShockLogic shockLogic, ShockParametersRecord shockParametersRecord)
{
var enrollmentState = StudentEnrollmentStateConverter
.ConvertStringToEnrollmentState(shockParametersRecord.EnrollmentTargetState);
var shockScenarioName = string.IsNullOrWhiteSpace(shockParametersRecord.ShockScenarioName)
? _optionalityScenario.ToUpper() + ": "
+ enrollmentState + ", "
+ shockParametersRecord.ShockLogicType + ", "
+ shockParametersRecord.ShockValue
: shockParametersRecord.ShockScenarioName;
return new OptionalityShockScenario(enrollmentState, shockLogic,
shockParametersRecord.AllowPremiumsToAdjust)
{
ScenarioName = shockScenarioName
};
}
private static IScenario CreateEnrollmentTargetScenario(ShockLogic shockLogic, ShockParametersRecord shockParametersRecord)
{
var enrollmentTargetState = StudentEnrollmentStateConverter
.ConvertStringToEnrollmentState(shockParametersRecord.EnrollmentTargetState);
var monthlyTargetPeriod = shockParametersRecord.MonthlyTargetPeriod.GetValueOrDefault(-1);
var shockScenarioName = string.IsNullOrWhiteSpace(shockParametersRecord.ShockScenarioName)
? _enrollmentTargetScenario.ToUpper() + ": "
+ enrollmentTargetState + ", "
+ (monthlyTargetPeriod >= 0 ? "Period " + monthlyTargetPeriod : "All Periods") + ", "
+ shockParametersRecord.ShockLogicType + ", "
+ shockParametersRecord.ShockValue
: shockParametersRecord.ShockScenarioName;
return new EnrollmentModelTargetShockScenario(enrollmentTargetState, shockLogic, monthlyTargetPeriod,
shockParametersRecord.AllowPremiumsToAdjust)
{
ScenarioName = shockScenarioName
};
}
private static IScenario CreateEnrollmentTransitionScenario(ShockLogic shockLogic, ShockParametersRecord shockParametersRecord)
{
var startEnrollmentState = StudentEnrollmentStateConverter
.ConvertStringToEnrollmentState(shockParametersRecord.StartEnrollmentState);
var endEnrollmentState = StudentEnrollmentStateConverter
.ConvertStringToEnrollmentState(shockParametersRecord.EndEnrollmentState);
var monthlyPeriod = shockParametersRecord.MonthlyTargetPeriod;
var shockScenarioName = string.IsNullOrWhiteSpace(shockParametersRecord.ShockScenarioName)
? _enrollmentTransitionScenario.ToUpper() + ": "
+ startEnrollmentState + ", "
+ endEnrollmentState + ", "
+ (monthlyPeriod.HasValue ? "Period " + monthlyPeriod.Value : "All Periods") + ", "
+ shockParametersRecord.ShockLogicType + ", "
+ shockParametersRecord.ShockValue
: shockParametersRecord.ShockScenarioName;
return new EnrollmentModelTransitionShockScenario(startEnrollmentState, endEnrollmentState, shockLogic, monthlyPeriod,
shockParametersRecord.AllowPremiumsToAdjust)
{
ScenarioName = shockScenarioName
};
}
private static IScenario CreateServicingCostsScenario(ShockLogic shockLogic, ShockParametersRecord shockParametersRecord)
{
var isSpecificCostOrFeeShock = !string.IsNullOrWhiteSpace(shockParametersRecord.SpecificCostOrFeeName);
var shockScenarioName = string.IsNullOrWhiteSpace(shockParametersRecord.ShockScenarioName)
? ServicingCostsScenario.ToUpper() + ": "
+ (isSpecificCostOrFeeShock ? "'"+ shockParametersRecord.SpecificCostOrFeeName +"', " : string.Empty)
+ shockParametersRecord.ShockLogicType + ", "
+ shockParametersRecord.ShockValue
: shockParametersRecord.ShockScenarioName;
var servicingCostsShockScenario = new ServicingCostsModelShockScenario(shockLogic,
shockParametersRecord.AllowPremiumsToAdjust)
{
ScenarioName = shockScenarioName
};
if (isSpecificCostOrFeeShock)
servicingCostsShockScenario.AddCostOrFeeName(shockParametersRecord.SpecificCostOrFeeName);
return servicingCostsShockScenario;
}
}
}
|
43f8856ec7ae14a283a75dea82c525c415490baa
|
C#
|
guanlingxingfu/study
|
/013LINq/Program.cs
| 2.84375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Activation;
using System.Text;
using System.Threading.Tasks;
namespace _013LINq
{
class Program
{
static void Main(string[] args)
{
//初始化武林高手
var masterList = new List<MartialArtsMaster>(){
new MartialArtsMaster(){ Id = 1, Name = "黄蓉", Age = 18, Menpai = "丐帮", Kongfu = "打狗棒法", Level = 9 },
new MartialArtsMaster(){ Id = 2, Name = "洪七公", Age = 70, Menpai = "丐帮", Kongfu = "打狗棒法", Level = 10 },
new MartialArtsMaster(){ Id = 3, Name = "郭靖", Age = 22, Menpai = "丐帮", Kongfu = "降龙十八掌",Level = 10 },
new MartialArtsMaster(){ Id = 4, Name = "任我行", Age = 50, Menpai = "明教", Kongfu = "葵花宝典", Level = 1 },
new MartialArtsMaster(){ Id = 5, Name = "东方不败",Age = 35, Menpai = "明教", Kongfu = "葵花宝典", Level = 10 },
new MartialArtsMaster(){ Id = 6, Name = "林平之", Age = 23, Menpai = "华山", Kongfu = "葵花宝典", Level = 7 },
new MartialArtsMaster(){ Id = 7, Name = "岳不群", Age = 50, Menpai = "华山", Kongfu = "葵花宝典", Level = 8 },
new MartialArtsMaster() { Id = 8, Name = "令狐冲", Age = 23, Menpai = "华山", Kongfu = "独孤九剑", Level = 10 },
new MartialArtsMaster() { Id = 9, Name = "梅超风", Age = 23, Menpai = "桃花岛", Kongfu = "九阴真经", Level = 8 },
new MartialArtsMaster() { Id =10, Name = "黄药师", Age = 23, Menpai = "梅花岛",Kongfu = "弹指神通", Level = 10 },
new MartialArtsMaster() { Id = 11, Name = "风清扬", Age = 23, Menpai = "华山",Kongfu = "独孤九剑", Level = 10 }
};
//初始化武学
var kongfuList = new List<Kongfu>(){
new Kongfu(){Id=1, Name="打狗棒法", Power=90},
new Kongfu(){Id=2, Name="降龙十八掌",Power=95},
new Kongfu(){Id=3, Name="葵花宝典", Power=100},
new Kongfu() { Id= 4,Name = "独孤九剑",Power = 100 },
new Kongfu() { Id = 5, Name = "九阴真经", Power = 100 },
new Kongfu() { Id = 6, Name = "弹指神通", Power = 100 }
};
//查询所有武学级别大于8的武林高手
//var res = new List<MartialArtsMaster>();
//foreach (var temp in masterList)
//{
// if (temp.Level > 8)
// {
// res.Add(temp.Name);
// }
//}
//使用LINQ做查询(表达式写法)
//var res = from m in masterList
// where m.Level > 8 && m.Menpai == "丐帮" //通过&&添加并列的条件
// //from后面设置查询的集合//where后面跟上查询的条件
// //where m.Level > 8
// select m;//表示m的集合结果返回
//var res = masterList.Where(m => m.Level >= 8 && m.Menpai == "丐帮");//lambda表达式
//3.LINQ联合查询
//var res = from m in masterList
// from k in kongfuList
// where m.Kongfu == k.Name && k.Power > 90
// //select new {master = m,Kongfu = k};
// select m;
//var res =
// masterList.SelectMany(m => kongfuList, (m, k) => new {master = m, Kongfu = k})
// .Where(x => x.master.Kongfu == x.Kongfu.Name && x.Kongfu.Power > 90);
//4.对象查询结果做排序
//var res = from m in masterList
// where m.Level > 8 && m.Menpai == "丐帮" //通过&&添加并列的条件
// orderby m.Level,m.Age
// //from后面设置查询的集合//where后面跟上查询的条件
// //where m.Level > 8
// select m;//表示m的集合结果返回
//var res = masterList.Where(m =>m.Level > 8 /*&& m.Menpai == "丐帮"*/).OrderBy(m => m.Level).ThenBy(m =>m.Age)
//;
//5.join on 集合联合
//var res = from m in masterList
// join k in kongfuList on m.Kongfu equals k.Name
// where k.Power >90
// select new {master = m, kongfu = k};
//6分组查询into groups(把武林高手按照所学功夫分类,看一下那个功夫修炼的人最多)
//var res = from k in kongfuList
// join m in masterList on k.Name equals m.Kongfu
// into groups
// orderby groups.Count()
// select new {kongfu = k, count = groups.Count()};
//7按照自身字段分组group
//var res = from m in masterList
// group m by m.Menpai
// into g
// select new {count = g.Count(), key = g.Key};//g.Key key表示是按照那个属性分的组
//8.量词操作符anyall 判断集合中是否满足某个条件
//bool res = masterList.Any(m => m.Menpai == "长留");
// Console.WriteLine(res);
bool res = masterList.All(m => m.Menpai == "丐帮");
Console.WriteLine(res);
//foreach (var temp in res)
//{
// Console.WriteLine(temp);
//}
Console.ReadKey();
}
//过滤方法
static bool Test1(MartialArtsMaster master)
{
if (master.Level > 8) return true;
return false;
}
}
}
|
ce974098ed713dffade0164dcd52f450625abd72
|
C#
|
karmaecrivain94/IMDBdataProcessor
|
/Program.cs
| 3.140625
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using CsvHelper;
namespace DataProcessor
{
class Genre
{
public int count { get; set; }
public Dictionary<string, int> years { get; set;}
}
class YearAverage
{
public int count { get; set; }
public int total { get; set; }
}
class Program
{
static void Main(string[] args)
{
if (args.Length > 0)
{
Process(args);
}
else
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("IMDB Dataset analyser\n");
Console.Title = "IMDB Dataset analyser";
Thread.Sleep(200);
Console.WriteLine("Please enter the path of the IMDB dataset .tsv file to process:");
string result = Console.ReadLine();
Console.WriteLine();
Process(new string[] { result });
}
Console.WriteLine("\nPress any key to exit");
Console.ReadKey();
}
static void Process(string[] args)
{
// HackermanIntroBullshit(args);
int counter = 1;
string line;
//How the IMDB data is formatted:
//tconst,titleType,primaryTitle,originalTitle,isAdult,startYear,endYear,runtimeMinutes,genres
Console.WriteLine("Opening dataset");
Thread.Sleep(500);
StreamReader file = new System.IO.StreamReader(args[0]);
double delay = 200;
Dictionary<string, Genre> genreList = new Dictionary<string, Genre>();
Dictionary<string, Genre> primarygenreList = new Dictionary<string, Genre>();
Dictionary<string, YearAverage> averageRuntime = new Dictionary<string, YearAverage>();
int moviecount = 0;
int overallcount = 0;
List<string> AllYears = new List<string>();
Console.WriteLine("Starting analysis loop...");
while ((line = file.ReadLine()) != null)
{
counter++;
overallcount++;
var fields = line.Split('\t');
string tconst = fields[0];
string titleType = fields[1];
if (titleType == "movie")
{
string primaryTitle = fields[2];
string originalTitle = fields[3];
string isAdult = fields[4];
string startYear = fields[5];
string endYear = fields[5];
if (!AllYears.Contains(endYear))
AllYears.Add(endYear);
string runtimeMinutes = fields[7];
string[] genres = new string[3];
if (fields.Length >= 9)
{
genres = fields[8].Split(',');
if (!primarygenreList.ContainsKey(genres[0]))
{
primarygenreList.Add(genres[0], new Genre() { years = new Dictionary<string, int>() });
}
primarygenreList[genres[0]].count++;
if (!primarygenreList[genres[0]].years.ContainsKey(endYear))
{
primarygenreList[genres[0]].years.Add(endYear, 0);
}
primarygenreList[genres[0]].years[endYear]++;
}
if (runtimeMinutes != null && runtimeMinutes!=@"\N")
{
if (!averageRuntime.ContainsKey(endYear))
averageRuntime.Add(endYear, new YearAverage());
averageRuntime[endYear].count++;
averageRuntime[endYear].total += Convert.ToInt32(runtimeMinutes); ;
}
moviecount++;
foreach (string g in genres)
{
if (g != null)
{
if (!genreList.ContainsKey(g))
{
genreList.Add(g, new Genre() { years = new Dictionary<string, int>() });
}
genreList[g].count++;
if (!genreList[g].years.ContainsKey(endYear))
{
genreList[g].years.Add(endYear, 0);
}
genreList[g].years[endYear]++;
}
}
if(counter > 10000)
{
counter = 0;
Console.Write("\rProcessed " + overallcount + " titles");
}
// Console.WriteLine("Processing item " + counter + "/4879165 (" + tconst + " - " + primaryTitle + ")");
}
}
Console.WriteLine("\nDataset analysis complete");
Console.WriteLine("Analysed " + moviecount + " titles with tconst = 'movie'");
Console.WriteLine("Getting year list");
Thread.Sleep(100);
string tsv = "genre";
AllYears = AllYears.OrderBy(x => x).ToList();
foreach (var year in AllYears)
{
tsv = tsv + "\t" + year;
}
string tsv2 = tsv;
string tsv3 = tsv;
Console.WriteLine("Creating genre rows");
foreach (var genre in genreList.OrderBy(x => x.Value.count))
{
string peakYear = "";
int peakCount = 0;
if (genre.Value.count > 1 && !Regex.IsMatch(genre.Key.Trim(), @"^\d"))
{
tsv = tsv + "\n" + genre.Key;
foreach (var year in AllYears)
{
if(year != @"\N")
{
if (genre.Value.years.ContainsKey(year))
if (genre.Value.years[year] > peakCount)
{
peakYear = year;
peakCount = genre.Value.years[year];
}
}
if (genre.Value.years.ContainsKey(year))
tsv = tsv + "\t" + genre.Value.years[year];
else
tsv = tsv + "\t0";
}
Thread.Sleep(25);
}
// Console.WriteLine(" Creating genre list for " + genre.Key + " (" + genre.Value.count + " titles) - Peak year: " + peakYear + "(" + peakCount + ") ");
}
Console.WriteLine("Creating primary genres rows");
foreach (var genre in primarygenreList.OrderBy(x => x.Value.count))
{
if (genre.Value.count > 1 && !Regex.IsMatch(genre.Key.Trim(), @"^\d"))
{
tsv2 = tsv2 + "\n" + genre.Key;
foreach (var year in AllYears)
{
if (genre.Value.years.ContainsKey(year))
tsv2 = tsv2 + "\t" + genre.Value.years[year];
else
tsv2 = tsv2 + "\t0";
}
}
}
Console.WriteLine("Creating average runtime table");
tsv3 += "\n" + "runtime";
foreach(var year in averageRuntime)
{
tsv3 = tsv3 + "\t" + year.Value.total / year.Value.count;
}
Console.WriteLine("Writing file 'allgenres.tsv'");
SaveFile(AppDomain.CurrentDomain.BaseDirectory + @"\allgenres.tsv", tsv);
Console.WriteLine("Success!");
Console.WriteLine("Writing file 'primarygenres.tsv'");
SaveFile(AppDomain.CurrentDomain.BaseDirectory + @"\primarygenres.tsv", tsv2);
Console.WriteLine("Success!");
Console.WriteLine("Writing file 'runtimes.tsv'");
SaveFile(AppDomain.CurrentDomain.BaseDirectory + @"\runtimes.tsv", tsv3);
Console.WriteLine("Success!");
}
static void SaveFile(string path, string data)
{
System.IO.File.WriteAllText(path, data);
}
static void HackermanIntroBullshit(string[] args)
{
Console.WriteLine("ADVANCED IMDB DATA PROCESSOR V.1.0");
Console.Write("Loading");
Thread.Sleep(200);
Console.Write("\rLoading.");
Thread.Sleep(200);
Console.Write("\rLoading..");
Thread.Sleep(200);
Console.Write("\rLoading...");
Thread.Sleep(200);
Console.Write("\rLoading....");
Thread.Sleep(200);
Console.Write("\rLoading.....");
Thread.Sleep(200);
Console.Write("\rLoading......");
Thread.Sleep(200);
Console.Write("\rLoading.......");
Console.WriteLine("Loaded!");
Thread.Sleep(200);
Console.WriteLine("Opening file " + args[0]);
Thread.Sleep(500);
Console.WriteLine("Penetrating mainframe database");
Thread.Sleep(300);
Console.WriteLine("Firewall rejected proxy VPN attempt");
Thread.Sleep(350);
Console.Write("\rBypassing firewall.");
Thread.Sleep(300);
Console.Write("\rBypassing firewall..");
Thread.Sleep(300);
Console.Write("\rBypassing firewall...");
Thread.Sleep(300);
Console.Write("\rBypassing firewall....");
Thread.Sleep(300);
Console.Write("\rBypassing firewall.....");
Thread.Sleep(300);
Console.Write("\rBypassing firewall......");
Thread.Sleep(300);
Console.Write("\rBypassing firewall.......");
Thread.Sleep(800);
Console.WriteLine("Access granted to database!");
Thread.Sleep(200);
Console.WriteLine("Intruder detected");
Thread.Sleep(200);
Console.WriteLine("Intruder detected");
Thread.Sleep(200);
Console.WriteLine("Intruder detected");
Thread.Sleep(200);
Console.WriteLine("Intruder detected");
Thread.Sleep(200);
Console.WriteLine("Intruder detected");
Thread.Sleep(200);
Console.WriteLine("Intruder detected");
Thread.Sleep(200);
Console.WriteLine("Intruder detected");
Thread.Sleep(500);
Console.WriteLine("Intruder retro-hacked");
Thread.Sleep(200);
Console.WriteLine("Reversing access routes");
Thread.Sleep(100);
Console.Write("8473265243869237520368760248659254");
Thread.Sleep(100);
Console.Write("\r4809262859457902375428397589240575");
Thread.Sleep(100);
Console.Write("\r4986276859276802467892400996857544");
Thread.Sleep(100);
Console.Write("\r1345413513451378416348915069547254");
Thread.Sleep(100);
Console.Write("\r7852601395702986748903750932932489");
Thread.Sleep(100);
Console.WriteLine("\r5235786296395863098472843059724658");
Console.WriteLine("Database access re-routed to mainframe server");
Console.WriteLine("Initializing database keys");
Thread.Sleep(300);
}
}
}
|
5878c5b31c1173522f0c9fa92917813a41c5dac1
|
C#
|
ghostYJ/Ghost
|
/Ghost.Utility/Ghost.Utility/ExtensionMethod/MathExtensionMethod/DecimalNullableMathExtensionMethod.cs
| 3.625
| 4
|
namespace Ghost.Utility
{
/// <summary>
/// 可控DecimalMath运算
/// </summary>
public static class DecimalNullableMathExtensionMethod
{
/// <summary>
/// 加,遇到null按0计算相加,若都为null,则返回null。
/// </summary>
/// <param name="d1"></param>
/// <param name="d2"></param>
/// <returns></returns>
public static decimal? Add(this decimal? d1, decimal? d2)
{
if (d1.HasValue)
{
if (d2.HasValue)
return d1 + d2;
else
return d1.Value;
}
else
{
if (d2.HasValue)
return d2.Value;
else
return null;
}
}
/// <summary>
/// 减,遇到null按0计算相减,若都为null,则返回null。
/// </summary>
/// <param name="d1"></param>
/// <param name="d2"></param>
/// <returns></returns>
public static decimal? Sub(this decimal? d1, decimal? d2)
{
if (d1.HasValue)
{
if (d2.HasValue)
return d1 + d2;
else
return d1.Value;
}
else
{
if (d2.HasValue)
return -d2.Value;
else
return null;
}
}
/// <summary>
/// 乘,且都不为null,否则返回null。
/// </summary>
/// <param name="d1"></param>
/// <param name="d2"></param>
/// <returns></returns>
public static decimal? Mul(this decimal? d1, decimal? d2)
{
if (d1.HasValue && d2.HasValue)
return d1.Value * d2.Value;
else
return null;
}
/// <summary>
/// 除,且都不为null,否则返回null,分母为0返回null
/// </summary>
/// <param name="d1"></param>
/// <param name="d2"></param>
/// <returns></returns>
public static decimal? Div(this decimal? d1,decimal? d2)
{
if (d1.HasValue && d2.HasValue)
{
if (d2.Value == 0)
return null;
else
return d1.Value / d2.Value;
}
else
return null;
}
}
}
|
1e13cb5510c7c678bd7670a480fb5a9cd39309c5
|
C#
|
Programming-Engineering-Pmi-31/IntelligentCooking
|
/src/IntelligentCooking/IntelligentCooking.DAL/EntityConfigurations/DishConfiguration.cs
| 2.53125
| 3
|
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using IntelligentCooking.Core.Entities;
namespace IntelligentCooking.DAL.EntityConfigurations
{
public class DishConfiguration : IEntityTypeConfiguration<Dish>
{
public void Configure(EntityTypeBuilder<Dish> builder)
{
builder.HasKey(d => d.Id);
builder.HasIndex(d => d.Name)
.IsUnique();
builder.Property(d => d.Name)
.IsRequired();
builder.Property(d => d.Recipe)
.IsRequired()
.IsUnicode(false);
builder.Property(d => d.Time)
.IsRequired();
builder.Property(d => d.Description)
.IsRequired();
builder.HasMany(d => d.Images)
.WithOne(i => i.Dish)
.IsRequired()
.HasForeignKey(d => d.DishId);
builder.HasMany(d => d.DishIngredients)
.WithOne(di => di.Dish)
.IsRequired()
.HasForeignKey(di => di.DishId);
builder.HasMany(d => d.DishCategories)
.WithOne(dc => dc.Dish)
.IsRequired()
.HasForeignKey(dc => dc.DishId);
builder.HasMany(d => d.Ratings)
.WithOne(l => l.Dish)
.IsRequired()
.HasForeignKey(l => l.DishId);
builder.HasMany(d => d.Favourites)
.WithOne(f => f.Dish)
.IsRequired()
.HasForeignKey(f => f.DishId);
}
}
}
|
93981a07c03c27ff04b8d985117805e2ac9f83d2
|
C#
|
xMadFreaK/QFS_Unity
|
/Studienprojekt_Server/ClientObject.cs
| 3.0625
| 3
|
using System;
using System.Net.Sockets;
using System.Security.Cryptography;
namespace Studienprojekt_Server
{
public class ClientObject
{
public TcpClient socket;
public NetworkStream myStream; // to receive and send data from/to client
public int connectionID; // ID of client
public byte[] receiveBuffer; // stores the data the server receives from the client on the server
public ByteBuffer buffer; // vorerst externe Ressource von Kevin Kaymak
/* Constructor to create new ClientObject, also shortens the reaction time of the connection and starts the stream.
* @param TcpClient newSocket
* @param newConnectionID: an integer in which the identification number of the client-server-connection is saved
* */
public ClientObject(TcpClient newSocket, int newConnectionID)
{
if (newSocket == null) return;
socket = newSocket;
connectionID = newConnectionID;
socket.NoDelay = true; // changes Nagle algorithm: shortens reaction time (tcp fires one package after another, without awaiting the acknowledgement of the prior package)
socket.ReceiveBufferSize = 4096; // package size in bytes - makes tcp faster
socket.SendBufferSize = 4096;
myStream = socket.GetStream(); // get stream from player
receiveBuffer = new byte[4096]; // resize receiveBuffer array in accordance to package size
myStream.BeginRead(receiveBuffer, 0, socket.ReceiveBufferSize, ReceiveCallback, null); // arguments: buffer, offset, intsize, async callback,object
}
/*
* If we get information from the stream through "myStream", ReceiveCallback is called and reads the full package.
* @param IAsyncResult result: connected client
*/
private void ReceiveCallback(IAsyncResult result)
{
try
{
int readBytes = myStream.EndRead(result); // how much data are we getting in the current stream call? = getting exact length of current stream call
if (readBytes <= 0) // if no data is received, close connection and end method
{
CloseConnection();
return;
}
byte[] newBytes = new byte[readBytes];
Buffer.BlockCopy(receiveBuffer, 0, newBytes, 0, readBytes); // copies data we are getting into newBytes
ServerHandleData.HandleData(connectionID, newBytes);
myStream.BeginRead(receiveBuffer, 0, socket.ReceiveBufferSize, ReceiveCallback, null); // listen to stream call again for new data
}
catch (Exception)
{
CloseConnection(); // if there is an error, close connection
throw;
}
}
/* Closing the connection between client and server properly and emptying the occupied socket.
* */
private void CloseConnection()
{
Console.WriteLine("Connection from {0} has been terminated.", socket.Client.RemoteEndPoint.ToString());
socket.Close();
socket = null; // to empty socket
}
}
}
|
b1d9192c122dabb5079f59e3d41e2654bde1ef40
|
C#
|
meikb/fightthelandlord
|
/TWQP/trunk/牌之算法研究/扑克.cs
| 3
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace 扑克
{
public static class Handler
{
public static readonly string[][] _牌显示 = new string[][]
{
new string[] { "", "A", "2", "3", "4", "5", "6", "7", "8", "9", "⒑", "J", "Q", "K", "小鬼", "大鬼" },
new string[] { "", "黑桃A", "黑桃2", "黑桃3", "黑桃4", "黑桃5", "黑桃6", "黑桃7", "黑桃8", "黑桃9", "黑桃⒑", "黑桃J", "黑桃Q", "黑桃K" },
new string[] { "", "红桃A", "红桃2", "红桃3", "红桃4", "红桃5", "红桃6", "红桃7", "红桃8", "红桃9", "红桃⒑", "红桃J", "红桃Q", "红桃K" },
new string[] { "", "樱花A", "樱花2", "樱花3", "樱花4", "樱花5", "樱花6", "樱花7", "樱花8", "樱花9", "樱花⒑", "樱花J", "樱花Q", "樱花K" },
new string[] { "", "方块A", "方块2", "方块3", "方块4", "方块5", "方块6", "方块7", "方块8", "方块9", "方块⒑", "方块J", "方块Q", "方块K" },
new string[] { "", "", "", "", "", "", "", "", "", "", "", "", "", "", "小鬼", "大鬼" },
};
public static string ToDisplayString(this 牌 p)
{
return string.Format("{0} x {1}", _牌显示[p.花][p.点], p.张);
}
/// <summary>
/// 按点数(忽略花色),从小到大排列元素,统计并 Resize 数组本身
/// </summary>
/// <param name="ps">目标数组</param>
public static 牌[] 转为点计数牌序列(this 牌[] ps)
{
int lastIdx = ps.Length - 1;
牌 temp;
// 对比是否有重复并计数,移动到最后
for (int i = 0; i < lastIdx; i++)
{
ps[i].张 = 1;
ps[i].花 = 0;
for (int j = i + 1; j <= lastIdx; j++)
{
if (ps[i].点 == ps[j].点)
{
temp = ps[j];
ps[j] = ps[lastIdx];
ps[lastIdx] = temp;
ps[i].张++;
lastIdx--;
j--;
}
}
}
// resize
Array.Resize<牌>(ref ps, lastIdx + 1);
// 按花色从小到大排序
Array.Sort<牌>(ps, (p1, p2) => { return p1.点.CompareTo(p2.点); });
return ps;
}
/// <summary>
/// 按点数(忽略花色),从小到大排列元素,返回统计结果数据
/// </summary>
/// <param name="ps">目标数组</param>
/// <returns>计数牌数组</returns>
public static 牌[] 获取点计数牌序列(this IEnumerable<牌> ps)
{
var result = from p in ps
group p by p.点 into g
orderby g.Key
select new 牌 { 花点 = g.Key, 张 = (byte)g.Count() };
return result.ToArray();
}
public static readonly 牌[] 一副牌 = new 牌[] {
// 黑
new 牌 { 数据 = 0x010101u }, // A
new 牌 { 数据 = 0x010102u },
new 牌 { 数据 = 0x010103u },
new 牌 { 数据 = 0x010104u },
new 牌 { 数据 = 0x010105u },
new 牌 { 数据 = 0x010106u },
new 牌 { 数据 = 0x010107u },
new 牌 { 数据 = 0x010108u },
new 牌 { 数据 = 0x010109u },
new 牌 { 数据 = 0x01010Au }, // 10
new 牌 { 数据 = 0x01010Bu }, // J
new 牌 { 数据 = 0x01010Cu }, // Q
new 牌 { 数据 = 0x01010Du }, // K
// 红
new 牌 { 数据 = 0x010201u }, // A
new 牌 { 数据 = 0x010202u },
new 牌 { 数据 = 0x010203u },
new 牌 { 数据 = 0x010204u },
new 牌 { 数据 = 0x010205u },
new 牌 { 数据 = 0x010206u },
new 牌 { 数据 = 0x010207u },
new 牌 { 数据 = 0x010208u },
new 牌 { 数据 = 0x010209u },
new 牌 { 数据 = 0x01020Au }, // 10
new 牌 { 数据 = 0x01020Bu }, // J
new 牌 { 数据 = 0x01020Cu }, // Q
new 牌 { 数据 = 0x01020Du }, // K
// 樱
new 牌 { 数据 = 0x010301u }, // A
new 牌 { 数据 = 0x010302u },
new 牌 { 数据 = 0x010303u },
new 牌 { 数据 = 0x010304u },
new 牌 { 数据 = 0x010305u },
new 牌 { 数据 = 0x010306u },
new 牌 { 数据 = 0x010307u },
new 牌 { 数据 = 0x010308u },
new 牌 { 数据 = 0x010309u },
new 牌 { 数据 = 0x01030Au }, // 10
new 牌 { 数据 = 0x01030Bu }, // J
new 牌 { 数据 = 0x01030Cu }, // Q
new 牌 { 数据 = 0x01030Du }, // K
// 方
new 牌 { 数据 = 0x010401u }, // A
new 牌 { 数据 = 0x010402u },
new 牌 { 数据 = 0x010403u },
new 牌 { 数据 = 0x010404u },
new 牌 { 数据 = 0x010405u },
new 牌 { 数据 = 0x010406u },
new 牌 { 数据 = 0x010407u },
new 牌 { 数据 = 0x010408u },
new 牌 { 数据 = 0x010409u },
new 牌 { 数据 = 0x01040Au }, // 10
new 牌 { 数据 = 0x01040Bu }, // J
new 牌 { 数据 = 0x01040Cu }, // Q
new 牌 { 数据 = 0x01040Du }, // K
// 小鬼,大鬼
new 牌 { 数据 = 0x01050Eu }, // 小鬼
new 牌 { 数据 = 0x01050Fu }, // 大鬼
};
}
}
|
d7605889b2492c3d33458e48a2dd2a310b377923
|
C#
|
PPakornDev/cold_storage
|
/SIAM_Temp_App/db_manage.cs
| 2.625
| 3
|
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SIAM_Temp_App
{
public class db_manage
{
private MySqlCommand command;
private MySqlDataReader dr;
private List<DataTable> dts;
string sql;
public void insertTemp(double temp)
{
var db_conn = new db_connect();
if (db_conn.OpenConnection())
{
sql = "INSERT INTO tblTemp (temp,date_Temp) " +
"VALUES (" + temp + ",NOW())";
command = new MySqlCommand();
command.CommandType = CommandType.Text;
command.CommandText = sql;
command.Connection = db_conn.connection;
dr = command.ExecuteReader();
if (dr.RecordsAffected == 1)
{
db_conn.CloseConnection();
}
else
{
db_conn.CloseConnection();
MessageBox.Show("Error Save !!!");
}
}
else
{
MessageBox.Show("Cannot connect to server. Contact administrator.");
}
}
public void insertDamp(double damp)
{
var db_conn = new db_connect();
if (db_conn.OpenConnection())
{
sql = "INSERT INTO tblDamp (damp,date_Damp) " +
"VALUES (" + damp + ",NOW())";
command = new MySqlCommand();
command.CommandType = CommandType.Text;
command.CommandText = sql;
command.Connection = db_conn.connection;
dr = command.ExecuteReader();
if (dr.RecordsAffected == 1)
{
db_conn.CloseConnection();
}
else
{
db_conn.CloseConnection();
MessageBox.Show("Error Save !!!");
}
}
else
{
MessageBox.Show("Cannot connect to server. Contact administrator.");
}
}
public List<DataTable> getLastData()
{
var db_conn = new db_connect();
dts = new List<DataTable>();
DataTable dt = new DataTable();
if (db_conn.OpenConnection())
{
sql = "SELECT date_Temp FROM tblTemp ORDER BY id_Temp DESC LIMIT 1";
command = new MySqlCommand();
command.CommandType = CommandType.Text;
command.CommandText = sql;
command.Connection = db_conn.connection;
dr = command.ExecuteReader();
if (dr.HasRows)
{
dt.Load(dr);
dts.Add(dt);
}
sql = "SELECT date_Damp FROM tblDamp ORDER BY id_Damp DESC LIMIT 1";
command = new MySqlCommand();
command.CommandType = CommandType.Text;
command.CommandText = sql;
command.Connection = db_conn.connection;
db_conn.CloseConnection();
if (db_conn.OpenConnection())
{
dr = command.ExecuteReader();
}
if (dr.HasRows)
{
dt = null;
dt = new DataTable();
dt.Load(dr);
dts.Add(dt);
}
db_conn.CloseConnection();
return dts;
}
else
{
dt = new DataTable("No table");
dts.Add(dt);
return dts;
}
}
public bool tranData(string sql)
{
var db_conn = new db_connect();
if (db_conn.OpenConnection())
{
command = new MySqlCommand();
command.CommandType = CommandType.Text;
command.CommandText = sql;
command.Connection = db_conn.connection;
if (command.ExecuteNonQuery() == 1)
{
db_conn.CloseConnection();
return true;
}
else
{
db_conn.CloseConnection();
MessageBox.Show("Error Save !!!");
return false;
}
}
else
{
MessageBox.Show("Cannot connect to server. Contact administrator.");
return false;
}
}
public DataTable chkUser(string sql)
{
DataTable dt = new DataTable();
var db_conn = new db_connect();
if (db_conn.OpenConnection())
{
command = new MySqlCommand();
command.CommandType = CommandType.Text;
command.CommandText = sql;
command.Connection = db_conn.connection;
dr = command.ExecuteReader();
if (dr.HasRows)
{
dt.Load(dr);
db_conn.CloseConnection();
MessageBox.Show("Login Successfully.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
return dt;
}
else
{
db_conn.CloseConnection();
MessageBox.Show("Username หรือ Password ผิด", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return dt;
}
}
else
{
MessageBox.Show("Cannot connect to server. Contact administrator.");
return dt;
}
}
public string getPlan(string sql)
{
var db_conn = new db_connect();
if (db_conn.OpenConnection())
{
command = new MySqlCommand();
command.CommandType = CommandType.Text;
command.CommandText = sql;
command.Connection = db_conn.connection;
dr = command.ExecuteReader();
dr.Read();
return dr["name_Area"].ToString();
}
else
{
MessageBox.Show("Cannot connect to server. Contact administrator.");
return "";
}
}
public int lastObj(string sql)
{
var db_conn = new db_connect();
if (db_conn.OpenConnection())
{
command = new MySqlCommand();
command.CommandType = CommandType.Text;
command.CommandText = sql;
command.Connection = db_conn.connection;
dr = command.ExecuteReader();
if (dr.HasRows)
{
int count = 0;
while(dr.Read())
{
count++;
}
return count;
}
else
{
return 0;
}
}
else
{
MessageBox.Show("Cannot connect to server. Contact administrator.");
return -1;
}
}
public DataTable getData(string sql)
{
DataTable dt = new DataTable();
var db_conn = new db_connect();
if (db_conn.OpenConnection())
{
command = new MySqlCommand();
command.CommandType = CommandType.Text;
command.CommandText = sql;
command.Connection = db_conn.connection;
dr = command.ExecuteReader();
dt.Load(dr);
return dt;
}
else
{
MessageBox.Show("Cannot connect to server. Contact administrator.");
return dt;
}
}
public string lastImg(string sql)
{ var db_conn = new db_connect();
if (db_conn.OpenConnection())
{
command = new MySqlCommand();
command.CommandType = CommandType.Text;
command.CommandText = sql;
command.Connection = db_conn.connection;
dr = command.ExecuteReader();
dr.Read();
if (!dr.HasRows)
{
return "";
}
return dr["img_Name"].ToString();
}
else
{
MessageBox.Show("Cannot connect to server. Contact administrator.");
return "";
}
}
}
}
|
427f6a4f57ba71e4bfa39b13f58aafd60f4effc7
|
C#
|
RajNakkiran/simple
|
/simple/LibraryFine/LibraryFine.cs
| 3.296875
| 3
|
// https://www.hackerrank.com/challenges/library-fine
// Raj Nakkiran. Sep 1,2016
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace LibraryFine
{
class Solution
{
static void Main(string[] args)
{
string[] tokens_d1 = Console.ReadLine().Split(' ');
int d1 = Convert.ToInt32(tokens_d1[0]);
int m1 = Convert.ToInt32(tokens_d1[1]);
int y1 = Convert.ToInt32(tokens_d1[2]);
string[] tokens_d2 = Console.ReadLine().Split(' ');
int d2 = Convert.ToInt32(tokens_d2[0]);
int m2 = Convert.ToInt32(tokens_d2[1]);
int y2 = Convert.ToInt32(tokens_d2[2]);
DateTime ReturnDate = new DateTime(y1, m1, d1);
DateTime DueDate = new DateTime(y2, m2, d2);
// No Fine
if (DueDate >= ReturnDate)
{
Console.WriteLine(0);
return;
}
// More than year old. Fixed fine
if (ReturnDate.Year > DueDate.Year)
{
Console.WriteLine(10000);
return;
}
//
// Same Year.
//
int Fine = 0;
if (ReturnDate.Month > DueDate.Month)
{
// Months late
Fine = (ReturnDate.Month - DueDate.Month) * 500;
Console.WriteLine("{0}", Fine);
return;
}
//
// Same Month
//
Fine = (ReturnDate.Day - DueDate.Day) * 15;
Console.WriteLine("{0}", Fine);
return;
}
}
}
|
03fdf7b25ce0f4021c1856df10000a75cf124998
|
C#
|
ibrahimbilgic/Csharp-Examples
|
/Sekil/Program.cs
| 2.59375
| 3
|
using System;
namespace Sekil
{
class Program
{
static void Main(string[] args)
{
Sekil[] sekiller = new Sekil[5];
sekiller[0] = new Sekil();
sekiller[1] = new Daire();
sekiller[2] = new Ucgen();
sekiller[3] = new Kare();
sekiller[4] = new Daire();
for(int i = 0;i<5;i++){
sekiller[i].Ciz();
}
}
}
}
|
d2faf1dca42993236a18f4ed40a65e1df48aa6db
|
C#
|
APmoss/InCompleteControl
|
/Project_WB/Project_WB/Framework/Audio/MusicTrack.cs
| 2.84375
| 3
|
using System;
using Microsoft.Xna.Framework.Audio;
namespace Project_WB.Framework.Audio {
/// <summary>
/// A music track that plays a certain song when added to the audio manager.
/// Only one song can be playing in the audio manager at once.
/// </summary>
class MusicTrack : AudioItem {
#region Properties
/// <summary>
/// The length of the track of music.
/// </summary>
public TimeSpan SongLength {
get; protected set;
}
#endregion
public MusicTrack(SoundEffect soundEffect) : base(soundEffect) {
// Set the song length
this.SongLength = soundEffect.Duration;
}
}
}
|
b708ed5ddddc9caf74a07ca4bd01feae40396097
|
C#
|
Hans0924/Echo_Console
|
/Echo_Console/Echo_Console/Protocol/WeatherRequest.cs
| 2.9375
| 3
|
namespace Echo_Console.Protocol
{
public class WeatherRequest : IProtocalSerializable
{
protected string Command;
public string Source { get; set; }
public string Destination { get; set; }
public string Airport { get; set; }
public WeatherRequest()
{
Command = "#WX";
}
public WeatherRequest(string source, string destination, string airport) : this()
{
Source = source;
Destination = destination;
Airport = airport;
}
public string Serialize()
{
return Command + Source + ":" + Destination + ":" + Airport;
}
}
}
|
55b1735455081b97530997ca396f3d0b5a9818ff
|
C#
|
ivanstamboliyski/CSharp-Fundamentals-may-2020
|
/08.02 - Text Processing - Exercise/05. Multiply Big Number/Program.cs
| 3.75
| 4
|
using System;
namespace _02._05.Multiply_Big_Number__Exercise
{
class Program
{
static void Main()
{
string bigNumber = Console.ReadLine().TrimStart('0');
int num = int.Parse(Console.ReadLine());
string result = string.Empty;
int additive = 0;
if (num == 0)
{
Console.WriteLine("0"); ;
return;
}
for (int i = bigNumber.Length - 1; i >= 0; i--)
{
int currSymbol = int.Parse(bigNumber[i].ToString()) * num;
currSymbol += additive;
if (currSymbol <= 9)
{
result = currSymbol.ToString()[0].ToString() + result;
additive = 0;
continue;
}
result = currSymbol.ToString()[1].ToString() + result;
additive = int.Parse(currSymbol.ToString()[0].ToString());
}
if (additive > 0)
{
result = additive.ToString() + result;
}
Console.WriteLine(result);
}
}
}
|
f3df5bfcb8fefdae8e421e376c2867403c927bc9
|
C#
|
qwqdanchun-fork/DarkEye-1
|
/Classes/Objects/Data.cs
| 3.015625
| 3
|
using DarkEye.Classes.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DarkEye.Classes.Objects
{
/*
* Created by Gish_Reloaded on 27/03/2020.
*/
class Data
{
private readonly string data;
private readonly string key;
public Data(string data, string key)
{
this.data = data;
this.key = key;
}
public String GetData()
{
String decrypted = CryptUtils.Decrypt(this.data, this.key);
return decrypted;
}
public String GetDataByIndex(int index)
{
String decrypted = CryptUtils.Decrypt(this.data, this.key);
try
{
return decrypted.Split(':')[index];
}
catch (Exception ex)
{
WriteUtils.writeError("GetDataByIndex returned null");
return null;
}
}
}
}
|
fb96689cb92c6025b239861dfe6ca710a4616b0e
|
C#
|
Ryu64Emulator/Ryu64
|
/Ryu64/CLI.cs
| 2.984375
| 3
|
using System;
using System.IO;
namespace Ryu64
{
public class CLI
{
public delegate void CLIMethod(string[] args, uint CurrentPosition);
public struct CLIFlags
{
public string InputRom;
public bool UTEsyscall;
public bool Debug;
public bool NoWindow;
}
public struct CLIFlag
{
public string FlagName;
public uint Arguments;
public CLIMethod Method;
}
public static CLIFlag[] FlagList =
{
new CLIFlag
{
FlagName = "debug",
Arguments = 0,
Method = (a, i) =>
{
Flags.Debug = true;
}
},
new CLIFlag
{
FlagName = "utesyscall",
Arguments = 0,
Method = (a, i) =>
{
Flags.UTEsyscall = true;
}
},
new CLIFlag
{
FlagName = "nowindow",
Arguments = 0,
Method = (a, i) =>
{
Flags.NoWindow = true;
}
}
};
public static CLIFlags Flags;
public static void ParseArguments(string[] args)
{
for (uint i = 0; i < args.Length; ++i)
{
if (args[i][0] == '-')
{
foreach (CLIFlag Flag in FlagList)
{
if (args[i].Substring(1).ToUpper() == Flag.FlagName.ToUpper())
{
if ((args.Length - i) < Flag.Arguments)
{
Common.Logger.PrintErrorLine($"The Flag -{Flag.FlagName} needs {Flag.Arguments} arguments");
Environment.Exit(1);
}
Flag.Method(args, i);
i += Flag.Arguments;
if (i > args.Length) break;
}
}
}
else
{
Flags.InputRom = args[i];
}
}
if (string.IsNullOrWhiteSpace(Flags.InputRom))
{
Common.Logger.PrintErrorLine("Please specify a ROM to load.");
Environment.Exit(1);
}
Common.Variables.Debug = Flags.Debug;
Common.Variables.UTEsyscall = Flags.UTEsyscall;
}
}
}
|
9c8a4201d1607c0c36e6aa730799c5d765c4d0cf
|
C#
|
neil-millward/VR-Game
|
/Assets/Scripts/PlayerMovement.cs
| 2.703125
| 3
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class PlayerMovement : MonoBehaviour
{
//as public, speed propertie shows up in unity
public float speed;
//Adding a Rigidbody component to an object will put its motion under the control of Unity's physics engine
private Rigidbody rb;
//Creating a game sound obj in unity, attaching a sound file to it then playing on collision
new AudioSource audio;
void Start()
{
//initiallised at beginning of game
speed = 5;
rb = GetComponent<Rigidbody>();
// pickUpSound = new AudioClip(Resources.Load("Music/Super Mario Bros. - Coin Sound Effect.wav"));
}
void FixedUpdate()
{
//used to read input, "Horizontal" and "Vertical" are mapped to wasd and 360 controller woaaaaaaaaah
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddForce(movement * speed);
}
//used to set the pickup items to dissapear on collision
void OnTriggerEnter(Collider other)
{
//if the game object is the pickup one then dissapear
if (other.gameObject.CompareTag("Pick Up"))
{
other.gameObject.SetActive(false);
if (audio == null)
{
print("audio not found");
}
else
{
audio.Play();
}
// print(count.ToString());
}
}
}
|
c7d9aa1c8d73411f0859b26683d6048cb8330cd6
|
C#
|
stefanovnm/TelerikAcademyHomeworks
|
/CSharp-OOP-2016/OOP-Principles-Part1/03.Animals/Tests.cs
| 3.953125
| 4
|
namespace _03.Animals
{
using System;
using System.Collections.Generic;
using System.Linq;
public class Tests
{
public static void Main()
{
Cat[] cats = new Cat[]
{
new Cat("Pesho", 2, Sex.male),
new Cat("Rijko", 6, Sex.male),
new Cat("Bella", 3, Sex.female),
new Cat("Maca", 1, Sex.female),
new Cat("Mara", 8, Sex.female),
};
Console.WriteLine("Cats:");
foreach (var cat in cats)
{
Console.WriteLine(cat);
}
Console.WriteLine("\nAverage age of all cats is: {0}\n", Animal.CalculateAverageAge(cats));
Console.WriteLine("Dogs:");
Dog[] dogs = new Dog[]
{
new Dog("Roby", 4, Sex.male),
new Dog("Charlie", 5, Sex.male),
new Dog("Molly", 3, Sex.female),
new Dog("Abby", 1, Sex.female),
new Dog("Sara", 10, Sex.female),
};
foreach (var dog in dogs)
{
Console.WriteLine(dog);
}
Console.WriteLine("\nAverage age of all dogs is: {0}\n", Animal.CalculateAverageAge(dogs));
Kitten[] kittens = new Kitten[]
{
new Kitten("Bella", 3),
new Kitten("Maca", 1),
new Kitten("Mara", 8),
};
Tomcat[] tomcats = new Tomcat[]
{
new Tomcat("Pesho", 2),
new Tomcat("Rijko", 6),
};
var allAnimals = new List<Animal>();
allAnimals.AddRange(tomcats);
allAnimals.AddRange(kittens);
allAnimals.AddRange(dogs);
Console.WriteLine("Average age of all animals is: "+ Animal.CalculateAverageAge(allAnimals));
var dogsFromAll = from animal in allAnimals
where animal.GetType() == typeof(Dog)
select animal;
Console.WriteLine("\nAverage age of all dogs from a list of all animals is :"+Animal.CalculateAverageAge(dogsFromAll));
}
}
}
|
1c5e7465c7c9538bbd6136eeddc85adfaaabcdad
|
C#
|
lulzzz/GridDomain
|
/GridDomain.EventSourcing/DomainSerializer.cs
| 2.9375
| 3
|
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Text;
using Newtonsoft.Json;
namespace GridDomain.EventSourcing
{
public class DomainSerializer
{
public DomainSerializer(JsonSerializerSettings settings = null)
{
JsonSerializerSettings = settings ?? GetDefaultSettings();
}
public JsonSerializerSettings JsonSerializerSettings { get; }
public static JsonSerializerSettings GetDefaultSettings()
{
return new JsonSerializerSettings
{
Formatting = Formatting.Indented,
TypeNameHandling = TypeNameHandling.Objects,
TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple,
CheckAdditionalContent = false,
ContractResolver = new DomainContractResolver(),
ConstructorHandling = ConstructorHandling.Default
};
}
// <summary>
// Serializes the given object into a byte array
// </summary>
/// <param name="obj">The object to serialize </param>
/// <param name="jsonSerializerSettings"></param>
/// <returns>A byte array containing the serialized object</returns>
public byte[] ToBinary(object obj, JsonSerializerSettings jsonSerializerSettings = null)
{
//TODO: use faster realization with reusable serializer
var stringJson = JsonConvert.SerializeObject(obj, jsonSerializerSettings ?? JsonSerializerSettings);
return Encoding.Unicode.GetBytes(stringJson);
}
/// <summary>
/// Deserializes a byte array into an object using the type hint
/// </summary>
/// <param name="bytes">The array containing the serialized object</param>
/// <param name="type">The type hint of the object contained in the array</param>
/// <returns>The object contained in the array</returns>
public object FromBinary(byte[] bytes, Type type, JsonSerializerSettings settings = null)
{
using (var stream = new MemoryStream(bytes))
using (var reader = new StreamReader(stream, Encoding.Unicode))
{
var jsonString = reader.ReadToEnd();
if (string.IsNullOrEmpty(jsonString))
return null;
var deserializeObject = JsonConvert.DeserializeObject(jsonString, type, settings ?? JsonSerializerSettings);
if (deserializeObject == null)
throw new SerializationException("json string: " + jsonString);
return deserializeObject;
}
}
}
}
|
a4a12ed46cb2923a234289c9751739a90795a90d
|
C#
|
cuteofdragon/UWPSamples
|
/UWPSamples/PhotosBrowser/MainViewModel.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PhotosBrowser
{
public class MainViewModel
{
public List<Photo> Photos { get; set; }
public MainViewModel()
{
InitData();
}
private void InitData()
{
Photos = new List<Photo>
{
new Photo { ImageUri = new Uri("ms-appx:///Assets/1.png") },
new Photo { ImageUri = new Uri("ms-appx:///Assets/2.png") },
new Photo { ImageUri = new Uri("ms-appx:///Assets/3.jpg") }
};
}
}
public class Photo
{
public Uri ImageUri { get; set; }
}
}
|
4e6b7be1ebb20c1ea0b3ca4d0af33bbfd40d4234
|
C#
|
stephenmuecke/mvc-collectionvalidation
|
/scr/Validation/RequireInCollection.cs
| 3.171875
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using System.Web.Mvc;
namespace Sandtrap.Web.Validation
{
/// <summary>
/// Validation attribute to assert that at least one object in the collection must
/// have a property equal to a specified value.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class RequireInCollectionAttribute : CollectionValidationAttribute
{
#region .Declarations
private int? _Maximum;
#endregion
#region .Constructors
/// <summary>
/// Constructor to specify the property name and required value.
/// </summary>
/// <param name="propertyName">
/// The name of the property to validate.
/// </param>
/// <param name="requiredValue">
/// The required value of the property.
/// </param>
/// <remarks>
/// The following placeholders can be used when setting <see cref="ValidationAttribute.ErrorMessage"/>
/// - {0} The display name of the collection property the attribute is applied to
/// - {1} The display name of the property
/// - {2} The required value
/// - {3} The minimum value
/// - {4} The maximum value
/// </remarks>
public RequireInCollectionAttribute(string propertyName, object requiredValue)
{
PropertyName = propertyName;
RequiredValue = requiredValue;
Minimum = 1;
}
#endregion
#region .Properties
/// <summary>
/// Gets the required value for the <see cref="CollectionValidationAttribute.PropertyName"/>
/// </summary>
public object RequiredValue { get; private set; }
/// <summary>
/// Gets or sets the minimum number of items in the collection where the
/// <see cref="CollectionValidationAttribute.PropertyName"/> must have
/// the <see cref="RequiredValue"/>.
/// </summary>
/// <remarks>
/// The default is 1. The value cannot be less that 1.
/// </remarks>
public int Minimum { get; set; }
/// <summary>
/// Gets of sets the maximum number of items in the collection where the
/// property has the value.
/// </summary>
public int Maximum
{
get { return _Maximum ?? int.MaxValue; }
set { _Maximum = value; }
}
#endregion
#region .Methods
/// <summary>
/// Override of <see cref="ValidationAttribute.IsValid(object)"/>
/// </summary>
/// <param name="value">
/// The collection to test.
/// </param>
/// <returns>
/// Returns <c>true</c> if the collection is valid.
/// </returns>
/// <exception cref="ArgumentException">
/// is thrown of the property the attibute is applied to is not a collection, or
/// the object in the collection does not contain <see cref="CollectionValidationAttribute.PropertyName"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// is thrown is the <see cref="Minimum"/> is less than 1,
/// or if <see cref="Maximum"/> is less than <see cref="Minimum"/>
/// </exception>
public override bool IsValid(object value)
{
if (value == null)
{
// In normal validation attributes, this would return true because a RequiredAttribute
// is responsible for asserting a property has a value
return false;
}
var collection = value as IEnumerable;
// Check arguments
CheckCollection(collection);
CheckMinMax();
// Loop through the collection to determine the number of valid matches
int matches = 0;
foreach (var item in collection)
{
PropertyInfo property = item.GetType().GetProperty(PropertyName);
if (property.GetValue(item).Equals(RequiredValue))
{
matches++;
}
// Exit the loop as soon as its known to be valid or invalid
if (matches >= Minimum && !_Maximum.HasValue)
{
// Its valid
break;
}
else if (_Maximum.HasValue && matches > _Maximum.Value)
{
// Its invalid
break;
}
}
return (matches >= Minimum) && (_Maximum.HasValue ? matches <= _Maximum.Value : true);
}
/// <summary>
/// Override of <see cref="ValidationAttribute.FormatErrorMessage"/>
/// </summary>
/// <param name="name">
/// The name to of the collection property the attribute is applied to.
/// </param>
/// <returns>
/// A localized string to describe the requirement.
/// </returns>
public override string FormatErrorMessage(string name)
{
if (ErrorMessage == null)
{
// Create the default message
string defaultMessage = null;
if (RequiredValue is bool)
{
// Assume the view is generating checkboxes for selection
// TODO: what if the value is false (would it even make sense?)
defaultMessage = "Please select at least one {0}";
if (Minimum > 1 && !_Maximum.HasValue)
{
defaultMessage = "Please select at least {3} {0}";
}
if (_Maximum.HasValue)
{
defaultMessage = "Please select between {3} and {4} {0}";
}
}
else
{
defaultMessage = "At least one {0} must have it {1} property equal to {2}";
if (Minimum > 1 && !_Maximum.HasValue)
{
defaultMessage = "At least {3} {0} must have their {1} property equal to {2}";
}
if (_Maximum.HasValue)
{
defaultMessage = "At least {3} and not more than {4} {0} must have their {1} property equal to {2}";
}
}
ErrorMessage = defaultMessage;
}
return string.Format(ErrorMessageString, name, PropertyName, RequiredValue, Minimum, _Maximum);
}
/// <summary>
/// Returns a Dictionary containing the name/value pairs used to generate the
/// html data-* attributes used for client side validation.
/// </summary>
/// <param name="metadata">
/// The metadata of the collection.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// is thrown if the <see cref="Minimum"/> is less than 1,
/// or if <see cref="Maximum"/> is less than <see cref="Minimum"/>
/// </exception>
public override Dictionary<string, object> GetHtmlDataAttributes(ModelMetadata metadata)
{
// Validate attributes
CheckCollection(metadata.Model as IEnumerable);
CheckMinMax();
string errorMessage = FormatErrorMessage(metadata.GetDisplayName());
object requiredValue = RequiredValue is bool ? RequiredValue.ToString().ToLower() : RequiredValue;
Dictionary<string, object> attributes = new Dictionary<string, object>();
attributes.Add("data-col-require", errorMessage);
attributes.Add("data-col-require-property", PropertyName);
attributes.Add("data-col-require-value", requiredValue);
attributes.Add("data-col-require-minimum", Minimum);
if (_Maximum.HasValue)
{
attributes.Add("data-col-require-maximum", _Maximum.Value);
}
return attributes;
}
#endregion
#region .Helper methods
/// <summary>
/// Checks that the values for <see cref="Minimum"/> and <see cref="Maximum"/> are valid.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">
/// is thrown is the <see cref="Minimum"/> is less than 1,
/// or if <see cref="Maximum"/> is less than <see cref="Minimum"/>
/// </exception>
private void CheckMinMax()
{
if (Minimum < 1)
{
// TODO: Add to resource file
string errMsg = "The minimum must be greater than 0";
throw new ArgumentOutOfRangeException(errMsg);
}
if (_Maximum.HasValue && _Maximum.Value < Minimum)
{
// TODO: Add to resource file
string errMsg = "The maximum must be greater than or equal to the minumum ('{1}')";
string errorMessage = String.Format(errMsg, Minimum);
throw new ArgumentOutOfRangeException(errorMessage);
}
}
#endregion
}
}
|
d67ea45a40ed31496dc05d21e46cad485ad76b57
|
C#
|
pires11d/CourseApp
|
/Course.Domain/Entities/Banking/Account.cs
| 3.859375
| 4
|
using System;
namespace Course.Entities
{
public class Account
{
private static int LastNumber { get; set; }
public int Number { get; private set; }
public string Holder { get; set; }
public double Balance { get; set; }
public double WithdrawLimit { get; set; }
public Account(string holder)
{
Holder = holder;
Balance = 0;
WithdrawLimit = 1000.0;
GenerateNumber();
}
public Account(string holder, double balance) : this(holder)
{
Balance = balance;
}
public Account(string holder, double balance, double withdrawLimit) : this(holder, balance)
{
WithdrawLimit = withdrawLimit;
}
public Account(int number, string holder, double balance, double withdrawLimit) : this(holder, balance, withdrawLimit)
{
Number = number;
}
private void GenerateNumber()
{
LastNumber += 1;
Number = LastNumber;
}
public void Deposit(double amount)
{
Balance += amount;
Console.WriteLine($"Operação de depósito realizada com sucesso!\n" +
$"Saldo atual: {Balance:F2}");
}
public void Withdraw(double amount)
{
if (amount > WithdrawLimit)
{
throw new ApplicationException("Limite de saque excedido!");
}
if (amount > Balance)
{
throw new ApplicationException("Saldo insuficiente!");
}
Balance -= amount;
Console.WriteLine($"Operação de saque realizada com sucesso!\n" +
$"Saldo atual: {Balance:F2}");
}
public override string ToString()
{
return $"Conta n°: \t {Number}\n" +
$"Titular: \t {Holder}\n" +
$"Saldo atual: \t {Balance.ToString("F2")} \n";
}
}
}
|
daaaf09c4f2eed96ca261ab108f29fc98532865c
|
C#
|
Satenik-Khchoyan/EncapsulationInheritancePolymorphism
|
/UserRegister/Program.cs
| 3.5
| 4
|
using System;
using System.Collections.Generic;
namespace UserRegister
{
class Program
{
static void Main(string[] args)
{
//Polymorfism ger koden flexibilitet.
//Ex. bas klassens samma metod kan implementeras på olika sätt i subklasserna, beroende på deras behov.
//Interface har bara publika medlemmar och innehåller bara definitioner.
//Medan abstract klassen kan ha blandning av public och private. Och kan ha definitioner av abstrakta metoder
//samt implementerade vanliga metoder.
//Men i C# 8 Interface har också fått möjlighet att innehålla private och implementationer.
//Så jag tror skillnaden mellan de twå är nu att vi kan ärva från flera interface, men bara en abstract klass.
List<UserError> errorList = new List<UserError>();
errorList.Add(new NumericInputError());
errorList.Add(new TextInputError());
errorList.Add(new InvalidInputError());
errorList.Add(new MandatoryFieldInputError());
errorList.Add(new SymbolInputError());
foreach (var error in errorList)
{
Console.WriteLine( error.UEMessage() );
}
foreach (var error in errorList)
{
if (error is InvalidInputError)
{
var invalidError = error as InvalidInputError;
Console.WriteLine(invalidError.UEMessage(true));
}
else
if(error is MandatoryFieldInputError)
{
var mandError = error as MandatoryFieldInputError;
Console.WriteLine(mandError.UEMessage("error"));
}
else
if(error is SymbolInputError)
{
var symbError = error as SymbolInputError;
Console.WriteLine(symbError.UEMessage("+"));
}
}
}
}
}
|
70d347087fbd913eaa03d985ace59c962824842c
|
C#
|
khanhkk96/SaleApplication
|
/SaleProject/DataObjectAccess/Models/Import.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataObjectAccess.Models
{
/// <summary>
/// Information of importing the product
/// </summary>
public class Import
{
[Key]
public Guid Id { get; set; }
[DisplayName("Id sản phẩm"), Browsable(false)]
public Guid ProductId { get; set; }
[ForeignKey("ProductId"), DisplayName("Sản phẩm")]
public virtual Product Product { get; set; }
[DataType(DataType.Date), DisplayName("Ngày nhập")]
public DateTime ImportedDate { get; set; }
[DisplayName("Số lượng")]
public int Quantity { get; set; }
[DataType(DataType.Currency), DisplayName("Giá")]
public double Price { get; set; }
[StringLength(100), DisplayName("Ghi chú")]
public string Note { get; set; }
}
}
|
7fe1231cdd0256bf1871cc9e30b8addfce0d7693
|
C#
|
Joelpina93/DA1
|
/Parking/Parking/Entities/Sms.cs
| 2.671875
| 3
|
using Entities.Validation;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Entities
{
public class Sms
{
[ForeignKey("Purchase")]
public int SmsId { get; set; }
public string Plates { get; set; }
public string Minutes { get; set; }
public DateTime StartingHour { get; set; }
public DateTime EndingHour { get; set; }
public DateTime LowerHourLimit { get; set; }
public DateTime UpperHourLimit { get; set; }
public virtual Purchase Purchase { get; set; }
public static List<ISmsValidator> SmsValidators { get; set; } = InitializeSmsValidators();
public Sms()
{
this.Plates = "";
this.Minutes = "";
this.StartingHour = DateTime.MinValue;
this.EndingHour = DateTime.MinValue;
this.LowerHourLimit = DateTime.Parse("10:00");
this.UpperHourLimit = DateTime.Parse("22:00");
}
public Sms(DateTime LowerHourLimit, DateTime UpperHourLimit)
{
this.Plates = "";
this.Minutes = "";
this.StartingHour = DateTime.MinValue;
this.EndingHour = DateTime.MinValue;
this.LowerHourLimit = LowerHourLimit;
this.UpperHourLimit = UpperHourLimit;
}
public static List<ISmsValidator> InitializeSmsValidators()
{
List<ISmsValidator> smsValidators = new List<ISmsValidator>();
smsValidators.Add(new UySmsValidator());
smsValidators.Add(new ArgSmsValidator());
return smsValidators;
}
public static ISmsValidator GetSmsValidator(Country country)
{
return SmsValidators.Find(s => s.SmsValidatorCountry.ToString() == country.Name);
}
public void SetHourBounds(DateTime lowerBound, DateTime upperBound)
{
this.LowerHourLimit = lowerBound;
this.UpperHourLimit = upperBound;
}
public override bool Equals(object obj)
{
var sms = obj as Sms;
if (sms == null)
return false;
return this.Plates == sms.Plates && this.Minutes == sms.Minutes && this.StartingHour == sms.StartingHour;
}
public override int GetHashCode()
{
var hash = 11;
hash = (hash * 11) + this.Plates.GetHashCode();
hash = (hash * 11) + this.Minutes.GetHashCode();
return hash;
}
}
}
|
08cdf1a5aa77730226970dc012b81b521b156ed3
|
C#
|
berbulalauri/web-project-01
|
/modules-.NET/06-collections/Tutorials/tutorial-01/tutorial-01/Program.cs
| 3.640625
| 4
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace tutorial_01
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please Write the line: ");
var userInput = Console.ReadLine();
var result = CompleteTutorial1(userInput);
Console.WriteLine(result);
}
static string CompleteTutorial1(string userInput)
{
string sortedString = String.Empty;
List<double> listOfDouble = userInput.Split(" ", StringSplitOptions.RemoveEmptyEntries).ToList().Select(
x => double.TryParse(x, out double val) ? val : 1).ToList();
var orderList = listOfDouble.OrderByDescending(x => x).ToList();
orderList.ForEach(x => sortedString += $"{x} ");
var multiplicationResult = orderList.FirstOrDefault() * orderList.LastOrDefault();
return ComposeStringResult(userInput,sortedString, multiplicationResult);
}
static string ComposeStringResult(string inputStirng, string sortedString, string resultOfMultiplication)
{
var result = $"Input String: {inputStirng}{Environment.NewLine}";
result += $"sorted String: {sortedString}{Environment.NewLine}";
result += $"Multiplication String: {resultOfMultiplication}{Environment.NewLine}";
return result;
}
static string ComposeStringResult(string inputStirng, string sortedString, double resultOfMultiplication)
{
var result = $"Input String: {inputStirng}{Environment.NewLine}";
result += $"sorted String: {sortedString}{Environment.NewLine}";
result += $"Multiplication String: {resultOfMultiplication}{Environment.NewLine}";
return result;
}
}
}
|
f26e55660ea8bc1eac8dc420b69e84861cbf18fd
|
C#
|
wikitools/wikigraph
|
/Assets/Scripts/Services/History/Actions/NodeSelectedAction.cs
| 2.578125
| 3
|
using Model;
using System;
namespace Services.History.Actions {
public class NodeSelectedAction : UserAction {
private uint? oldSelectedNode;
private uint? newSelectedNode;
bool isRouteAction;
public static Action<uint?, bool> selectNodeAction;
public NodeSelectedAction(uint? oldNode, uint? newNode, bool isRoute) {
oldSelectedNode = oldNode;
newSelectedNode = newNode;
isRouteAction = isRoute;
}
private void passSelectAction(uint? node) {
selectNodeAction(node, isRouteAction);
}
#region UserAction functions
public void Execute() {
passSelectAction(newSelectedNode);
}
public void UnExecute() {
passSelectAction(oldSelectedNode);
}
public bool IsRoute() {
return isRouteAction;
}
#endregion
}
}
|
8f7b8fd60c5fdd97648bf12bbd6e543076c4d1fb
|
C#
|
AugustasMacijauskas/CS-OOP-Homework
|
/PavyzdinisKontrolinukas/Program.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace PavyzdinisKontrolinukas
{
class Mokinys
{
string vardas;
string pavarde;
string lytis;
int amzius;
string klase;
double pazVidurkis;
public Mokinys()
{
}
public Mokinys(string pv, string v, string lytis, int amzius, string kl, double pazV)
{
pavarde = pv;
vardas = v;
this.lytis = lytis;
this.amzius = amzius;
klase = kl;
pazVidurkis = pazV;
}
public override string ToString()
{
string naujas;
naujas = string.Format("{0, -15} {1, -15} {2, -8} {3, -4:d} {4, -8} {5, 5:f} ", pavarde, vardas, lytis, amzius, klase, pazVidurkis);
return naujas;
}
public static bool operator <=(Mokinys m1, Mokinys m2)
{
int poz1 = String.Compare(m1.pavarde, m2.pavarde, StringComparison.CurrentCulture);
int poz2 = String.Compare(m1.vardas, m2.vardas, StringComparison.CurrentCulture);
return ((m1.pazVidurkis > m2.pazVidurkis) || ((m1.pazVidurkis == m2.pazVidurkis) && poz1 < 0) || ((m1.pazVidurkis == m2.pazVidurkis) && (poz1 == 0) && (poz2 < 0)));
}
public static bool operator >=(Mokinys m1, Mokinys m2)
{
int poz1 = String.Compare(m1.pavarde, m2.pavarde, StringComparison.CurrentCulture);
int poz2 = String.Compare(m1.vardas, m2.vardas, StringComparison.CurrentCulture);
return ((m1.pazVidurkis < m2.pazVidurkis) || ((m1.pazVidurkis == m2.pazVidurkis) && poz1 > 0) || ((m1.pazVidurkis == m2.pazVidurkis) && (poz1 == 0) && (poz2 > 0)));
}
public string KokiaKlase() { return klase; }
public string KokiaLytis() { return lytis; }
public double KoksVidurkis() { return pazVidurkis; }
}
class MokiniuKonteineris
{
const int max = 100;
int n = 0;
Mokinys[] mok;
public MokiniuKonteineris()
{
mok = new Mokinys[max];
}
public int KoksMax() { return max; }
public int Imti() { return n; }
public void Deti(Mokinys ob) { mok[n++] = ob; }
public Mokinys Imti(int k) { return mok[k]; }
public void Rikiuoti()
{
Mokinys temp;
int minInd;
for (int i = 0; i < n - 1; i++)
{
minInd = i;
for (int j = i + 1; j < n; j++)
{
if (mok[j] <= mok[minInd])
{
minInd = j;
}
}
temp = mok[i];
mok[i] = mok[minInd];
mok[minInd] = temp;
}
}
public void Įterpti(string pav, string var, string lyt, int gimM, string kl, double vidur)
{
Mokinys naujas = new Mokinys(pav, var, lyt, gimM, kl, vidur);
int i;
for (i = 0; (i < n) && (mok[i] <= naujas); i++)
{
}
//int i = 0;
//while (i < n && mok[i] < naujas)
// i++;
for (int j = n; j > i; j--)
{
mok[j] = mok[j - 1];
}
mok[i] = naujas;
n = n + 1;
}
public double Vidurkis(string lyt)
{
double vid = 0;
int countas = 0;
for (int i = 0; i < n; i++)
{
if (mok[i].KokiaLytis() == lyt)
{
vid += mok[i].KoksVidurkis();
countas++;
}
}
if (countas > 0)
return vid / countas;
else
return -1;
}
}
class Program
{
const string duom = "..\\..\\Mokinys.txt";
const string rez = "..\\..\\MokinysRez.txt";
static void Main(string[] args)
{
Console.OutputEncoding = Encoding.GetEncoding(1257);
MokiniuKonteineris mok = new MokiniuKonteineris();
string pavadinimas;
Skaityti(mok, out pavadinimas);
if (File.Exists(rez))
File.Delete(rez);
Spausdinti(mok, string.Format("Pradiniai duomenys:\n{0}", pavadinimas));
if (mok.Vidurkis("moteris") > -1)
Console.WriteLine(mok.Vidurkis("moteris"));
else
Console.WriteLine("Šiame masyve vidurkio pagal sąlygą nėra");
mok.Rikiuoti();
Spausdinti(mok, "Surikiuotas masyvas:");
//string vardas;
//string pavarde;
//string lytis;
//int amzius;
//string klase;
//double pazVidurkis;
//Console.WriteLine("Iveskite mokinio pavardę: ");
//pavarde = Console.ReadLine();
//Console.WriteLine("Iveskite mokinio vardą: ");
//vardas = Console.ReadLine();
//Console.WriteLine("Iveskite mokinio lytį: ");
//lytis = Console.ReadLine();
//Console.WriteLine("Iveskite mokinio gimimo metus: ");
//amzius = int.Parse(Console.ReadLine());
//Console.WriteLine("Iveskite mokinio klasę: ");
//klase = Console.ReadLine();
//Console.WriteLine("Iveskite mokinio pažymių vidurkį: ");
//pazVidurkis = double.Parse(Console.ReadLine());
mok.Įterpti("Jonaitis", "Benas", "vyras", 2000, "IIIm", 9.5);
Spausdinti(mok, "Įterptas elementas:");
if (mok.Vidurkis("moteris") > -1)
Console.WriteLine(mok.Vidurkis("moteris"));
else
Console.WriteLine("Šiame masyve vidurkio pagal sąlygą nėra");
MokiniuKonteineris naujas = new MokiniuKonteineris();
//string kokiaKlase;
//Console.WriteLine("Iveskite kokios klasės mokiniai turi būti naujame masyve: ");
//kokiaKlase = double.Parse(Console.ReadLine());
NaujoMasyvoFormavimas(mok, naujas, "123");
Spausdinti(naujas, "Naujo masyvo formavimas");
if (naujas.Vidurkis("moteris") > -1)
Console.WriteLine(naujas.Vidurkis("moteris"));
else
Console.WriteLine("Šiame masyve vidurkio pagal sąlygą nėra");
Console.WriteLine("Programa baigė darbą!");
}
static void NaujoMasyvoFormavimas(MokiniuKonteineris mok, MokiniuKonteineris naujas, string klase)
{
for (int i = 0; i < mok.Imti(); i++)
{
if (mok.Imti(i).KokiaKlase() == klase)
{
naujas.Deti(mok.Imti(i));
}
}
}
static void Skaityti(MokiniuKonteineris mok, out string pavadinimas)
{
using(StreamReader reader = new StreamReader(duom))
{
string pavarde;
string vardas;
string lytis;
int amzius;
string klase;
double pazVidurkis;
string line;
string[] splitas;
pavadinimas = reader.ReadLine();
while ((line = reader.ReadLine()) != null && mok.Imti() < mok.KoksMax())
{
splitas = line.Split(';');
pavarde = splitas[0].Trim();
vardas = splitas[1].Trim();
lytis = splitas[2].Trim();
amzius = int.Parse(splitas[3].Trim());
klase = splitas[4].Trim();
pazVidurkis = double.Parse(splitas[5].Trim());
Mokinys naujas = new Mokinys(pavarde, vardas, lytis, amzius, klase, pazVidurkis);
mok.Deti(naujas);
}
}
}
static void Spausdinti(MokiniuKonteineris mok, string antraste)
{
const string virsus = "----------------------------------------------------------------------------------------------------------------\r\n" +
" Nr. Pavardė Vardas Lytis Gim. metai Klasė Vidurkis \r\n" +
"----------------------------------------------------------------------------------------------------------------";
using(var fr = File.AppendText(rez))
{
if (mok.Imti() > 0)
{
fr.WriteLine(antraste);
fr.WriteLine(virsus);
for (int i = 0; i < mok.Imti(); i++)
{
fr.WriteLine(" {0, 4:d} {1}", i + 1, mok.Imti(i).ToString());
}
fr.WriteLine("----------------------------------------------------------------------------------------------------------------\n\n");
}
else
{
fr.WriteLine("Sąrašas tuščias");
}
}
}
}
}
|
b19c25dbc3008bef5e425d746823f9639a51747d
|
C#
|
gblouin/Meek
|
/code/Meek.Specs/ThumbnailGeneratorSpecs.cs
| 2.5625
| 3
|
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Machine.Fakes;
using Machine.Specifications;
using Meek.Content;
using It = Machine.Specifications.It;
using GivenIt = Moq.It;
namespace Meek.Specs
{
public class When_asking_for_an_image_thumbnail : WithSubject<JpegThumbnailGenerator>
{
Establish that = () =>
The<ImageResizer>()
.WhenToldTo(_ => _.Resize(GivenIt.IsAny<Image>(), 125))
.Return(new Bitmap(200,200));
private Because of = () =>
{
var image = new Bitmap(200, 200);
var stream = new MemoryStream();
image.Save(stream, ImageFormat.Gif);
thumbnail = Subject.MakeThumbnail("image/gif", stream.ToArray(), "testing.gif", 125);
};
It should_of_used_the_resizer = () =>
The<ImageResizer>()
.WasToldTo(_ => _.Resize(GivenIt.IsAny<Image>(), 125))
.OnlyOnce();
It should_return_the_thumbnail = () =>
thumbnail.File.ShouldNotBeNull();
It should_name_the_file_properly = () =>
thumbnail.Name.ShouldEqual("testing.jpg");
It should_set_a_proper_content_type = () =>
thumbnail.ContentType.ShouldEqual("image/jpeg");
private static Thumbnail thumbnail;
}
}
|
7e48ed813c0edd736fbc67610c699297467d87a1
|
C#
|
bubdm/Ao.SavableConfig
|
/src/Ao.SavableConfig.Binder/Compiling/ConstructCompiled.cs
| 2.671875
| 3
|
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace Ao.SavableConfig.Binder
{
public delegate object ObjectCreator(params object[] @params);
public class ConstructCompiled : IEquatable<ConstructCompiled>
{
private static readonly Type ObjectArrayType = typeof(object[]);
public ConstructCompiled(ConstructorInfo constructor)
{
Constructor = constructor ?? throw new ArgumentNullException(nameof(constructor));
Creator = BuildCreate();
}
public ConstructorInfo Constructor { get; }
public ObjectCreator Creator { get; }
public override bool Equals(object obj)
{
return Equals(obj as ConstructCompiled);
}
public override int GetHashCode()
{
return Constructor.GetHashCode();
}
public bool Equals(ConstructCompiled other)
{
if (other == null)
{
return false;
}
return other.Constructor == Constructor;
}
protected ObjectCreator BuildCreate()
{
var constPars = Constructor.GetParameters();
var par = Expression.Parameter(ObjectArrayType);
var convs = new Expression[constPars.Length];
for (int i = 0; i < constPars.Length; i++)
{
var arg = Expression.Convert(
Expression.ArrayIndex(par, Expression.Constant(i)),
constPars[i].ParameterType);
convs[i] = arg;
}
var newBlock = Expression.New(Constructor, convs);
var lambda = Expression.Lambda<ObjectCreator>(newBlock,
par).Compile();
return lambda;
}
}
}
|
41f1290edc3188c1b4320c6abc4bb56506e4ce80
|
C#
|
Monikashree/DemoMvc
|
/OnlineTrainTicketBookingApp.DAL/TicketBookingRepository.cs
| 2.890625
| 3
|
using OnlineTrainTicketBookingApp.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
namespace OnlineTrainTicketBookingApp.DAL
{
public interface ITicketBookingRepository //Interface to highlight Ticket booking methods
{
bool AddBookingDetails(TicketBooking ticketBooking);
bool AddPassengerDetails(PassengerDetails passengerDetails);
List<PassengerDetails> GetPassengerDetails(int bookingId);
TicketBooking GetNoOfPassengers(int bookingId);
int GetPassengerCountByID(int bookingId);
List<TicketBooking> GetBookingId(int trainId, int classId, DateTime DOJ);
bool ClearSeats(int bookingId);
List<TicketBooking> GetBookingDetailsByIdandDOJ(int trainId, DateTime DOJ);
int GetTotalCost(int bookingId);
}
public class TicketBookingRepository : ITicketBookingRepository //Class to implement an interface Ticket booking repository
{
public bool AddBookingDetails(TicketBooking ticketBooking) // Method to add booking details to db
{
try
{
using (TrainTicketBookingDbContext dbContext = new TrainTicketBookingDbContext())
{
dbContext.TicketBooking.Add(ticketBooking);
//dbContext.Database.ExecuteSqlCommand(@"SET IDENTITY_INSERT [dbo].[TrainDetails] ON");
dbContext.SaveChanges();
return true;
}
}
catch (Exception)
{
return false;
}
}
public bool AddPassengerDetails(PassengerDetails passengerDetails) //Method to add passenger details to db
{
try
{
using (TrainTicketBookingDbContext dbContext = new TrainTicketBookingDbContext())
{
dbContext.PassengerDetails.Add(passengerDetails);
//dbContext.Database.ExecuteSqlCommand(@"SET IDENTITY_INSERT [dbo].[TrainDetails] ON");
dbContext.SaveChanges();
return true;
}
}
catch (Exception)
{
return false;
}
}
public List<PassengerDetails> GetPassengerDetails(int bookingId) //Method to get passenger details based on booking id
{
using (TrainTicketBookingDbContext dbContext = new TrainTicketBookingDbContext())
{
return dbContext.PassengerDetails.Where(m => m.BookingId == bookingId).ToList();
}
}
public TicketBooking GetNoOfPassengers(int bookingId) //method to get number of passengers based on booking id
{
//TicketBooking ticketBooking;
using (TrainTicketBookingDbContext dbContext = new TrainTicketBookingDbContext())
{
//var data = from tb in dbContext.TicketBooking where tb.BookingId == bookingId select tb.NoOfPassengers;
return dbContext.TicketBooking.Where(m => m.BookingId == bookingId).FirstOrDefault();
}
//return passenger;
}
public int GetPassengerCountByID(int bookingId) //Method to get passenger count in passenger details based on current booking id
{
using (TrainTicketBookingDbContext dbContext = new TrainTicketBookingDbContext())
{
return (from x in dbContext.PassengerDetails where x.BookingId == bookingId && x.SeatNo != 0 select x).Count();
}
}
public List<TicketBooking> GetBookingId(int trainId, int classId, DateTime DOJ) //method to get booking id based on train id and class id
{
using (TrainTicketBookingDbContext dbContext = new TrainTicketBookingDbContext())
{
return dbContext.TicketBooking.Where(m => m.TrainId == trainId && m.ClassId == classId && m.JourneyDate == DOJ).ToList();
}
}
public bool ClearSeats(int bookingId) //method to make the seat no to 0 if the user cancel the booking
{
try
{
using (TrainTicketBookingDbContext dbContext = new TrainTicketBookingDbContext())
{
var seats = dbContext.PassengerDetails.Where(m => m.BookingId == bookingId);
foreach (var item in seats)
{
item.SeatNo = 0;
}
// dbContext.TicketBooking.Where(m=> m.BookingId == bookingId).
dbContext.SaveChanges();
return true;
}
}
catch
{
return false;
}
}
public List<TicketBooking> GetBookingDetailsByIdandDOJ(int trainId, DateTime DOJ) //Method to get booking details based on traind id and Date of journey
{
using (TrainTicketBookingDbContext dbContext = new TrainTicketBookingDbContext())
{
return dbContext.TicketBooking.Where(m => m.TrainId == trainId && m.JourneyDate == DOJ).ToList();
}
}
public int GetTotalCost(int bookingId) //Method to get total money
{
using (TrainTicketBookingDbContext dbContext = new TrainTicketBookingDbContext())
{
return dbContext.PassengerDetails.Where(m => m.BookingId == bookingId).Sum(m => m.Cost);
}
}
}
}
|
65b876b37949a3304254b365cb5bdf3c58ecf8bb
|
C#
|
ttn218/ChatbotGame
|
/GreatWall_Start/Dialogs/neoGame/GameStartDialog.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using LionKing.Dialogs.Rank;
using LionKing.Model;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
namespace LionKing.Dialogs.neoGame
{
[Serializable]
public class GameStartDialog : IDialog<string>
{
// 랭킹 인스턴스
public string level;
public string type = "neo";
// 요기까지
string strMessage;
private string strWelcomMMessage = "게임난이도를 정해주세요. (Nomal, Hard)";
public async Task StartAsync(IDialogContext context)
{
var message = context.MakeMessage();
var actions = new List<CardAction>();
actions.Add(new CardAction() { Title = "1. Nomal", Value = "Nomal", Type = ActionTypes.ImBack });
actions.Add(new CardAction() { Title = "2. Hard", Value = "Hard", Type = ActionTypes.ImBack });
message.Attachments.Add(new HeroCard { Title = strWelcomMMessage, Buttons = actions }.ToAttachment());
await context.PostAsync(message);
context.Wait(MessageReceivedAsync);
}
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
{
Activity activity = await result as Activity;
string strSelected = activity.Text.Trim();
if (strSelected == "Nomal")
{
level = "N";
context.Call(new GameLoopDialog(Level.NOMAL), Rank);
}
else if (strSelected == "Hard")
{
level = "H";
context.Call(new GameLoopDialog(Level.HARD), Rank);
}
else
{
strMessage = "목록중에서 골라 주세요";
await context.PostAsync(strMessage);
context.Wait(MessageReceivedAsync);
return;
}
}
public async Task Rank(IDialogContext context, IAwaitable<string> result)
{
string score = await result;
context.Call(new insertRankDialog(type, level, score), GameOver);
}
private async Task GameOver(IDialogContext context, IAwaitable<string> result)
{
try
{
strMessage = "Your Score : " + await result;
await context.PostAsync(strMessage);
context.Done("Game Over");
}
catch (TooManyAttemptsException)
{
await context.PostAsync("Error occurred...");
}
}
}
}
|
05a8f91eea75e23b40495f94d6d587ec0072f3a3
|
C#
|
nissafors/Expressions
|
/Expressions/MainWindow.xaml.cs
| 2.734375
| 3
|
// TODO:
// * Variables
// * Constants
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
namespace Expressions
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private ReadOnlyCollection<string> _symbols;
private double _result;
// <summary>
// Main entry point for UI.</summary>
public MainWindow()
{
InitializeComponent();
char[] vars = {'x', 'y', 'z', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'a', 'b', 'c', 'd'};
initVarGrid(VarGrid, vars);
}
// <summary>
// Write out variable grid on main window.</summary>
private void initVarGrid(Panel parent, char[] vars)
{
int n = vars.Length;
Grid[] cell = new Grid[n];
ColumnDefinition[] lblCol = new ColumnDefinition[n];
ColumnDefinition[] txtCol = new ColumnDefinition[n];
Label[] lbl = new Label[n];
TextBox[] txt = new TextBox[n];
for (int i = 0; i < n; i++)
{
cell[i] = new Grid();
cell[i].Margin = new Thickness(5);
lblCol[i] = new ColumnDefinition();
lblCol[i].Width = new GridLength(1, GridUnitType.Star);
cell[i].ColumnDefinitions.Add(lblCol[i]);
lbl[i] = new Label();
lbl[i].Content = vars[i].ToString() + " =";
Grid.SetColumn(lbl[i], 0);
txtCol[i] = new ColumnDefinition();
txtCol[i].Width = new GridLength(3, GridUnitType.Star);
cell[i].ColumnDefinitions.Add(txtCol[i]);
txt[i] = new TextBox();
txt[i].Name = vars[i].ToString() + "Var";
txt[i].VerticalContentAlignment = VerticalAlignment.Center;
Grid.SetColumn(txt[i], 1);
cell[i].Children.Add(lbl[i]);
cell[i].Children.Add(txt[i]);
parent.Children.Add(cell[i]);
}
}
// <summary>
// Event handler for TextChanged in Input.
// Calls Lexer and Parser and prints the result.</summary>
private void Input_TextChanged(object sender, TextChangedEventArgs e)
{
try
{
_symbols = Lexer.GetSymbols(Input.Text);
if (_symbols.Count > 0)
_result = Parser.GetResult(_symbols);
else
_result = 0;
Output.Content = _result;
}
catch (ArgumentException)
{
Output.Content = "---";
}
}
}
}
|
913cb75a3a84787bdbd0e2219eaefd823e81660c
|
C#
|
SaniaGos/CatchMe
|
/CatchMe/Form1.cs
| 2.84375
| 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;
using System.Windows.Forms;
namespace CatchMe
{
public partial class Form1 : Form
{
private int point;
private int time;
public Form1()
{
InitializeComponent();
point = 0;
time = 0;
}
//
// Mouse
//
private void buttonMouse_Click(object sender, EventArgs e)
{
MessageBox.Show("Вспіймали", "Яй!!!", MessageBoxButtons.OK, MessageBoxIcon.Information);
buttonMouse.Location = new Point(panel.Width / 2 - 20, panel.Height / 2 - 20);
point++;
labelPoint.Text = $"Point: {point}";
}
private void buttonMouse_MouseMove(object sender, MouseEventArgs e)
{
Point tmp = new Point(buttonMouse.Location.X + 20, buttonMouse.Location.Y + 20);
tmp.X += 50;
if (tmp.X <= this.Width - 45)
{
buttonMouse.Location = new Point(tmp.X - 20, tmp.Y - 20);
return;
}
tmp.X -= 100;
if (tmp.X >= 30)
{
buttonMouse.Location = new Point(tmp.X - 20, tmp.Y - 20);
return;
}
tmp.X += 50;
tmp.Y += 50;
if (tmp.Y <= this.Height - 55)
{
buttonMouse.Location = new Point(tmp.X - 20, tmp.Y - 20);
return;
}
tmp.Y -= 100;
if (tmp.Y >= 30)
{
buttonMouse.Location = new Point(tmp.X - 20, tmp.Y - 20);
return;
}
if (IsHouse())
{
ChooseDoor();
}
}
//
// Strip Menu
//
private void StripMenu_Click(object sender, EventArgs e)
{
this.panel.MouseMove -= new System.Windows.Forms.MouseEventHandler(this.panel_MouseMove);
this.buttonMouse.MouseMove -= new System.Windows.Forms.MouseEventHandler(this.buttonMouse_MouseMove);
timerFreeze.Start();
}
private void contextMenuStrip1_MouseLeave(object sender, EventArgs e)
{
contextMenuStrip.Close();
}
//
// Timer Freeze
//
private void timer_Tick(object sender, EventArgs e)
{
timerFreeze.Stop();
this.panel.MouseMove += new System.Windows.Forms.MouseEventHandler(this.panel_MouseMove);
this.buttonMouse.MouseMove += new System.Windows.Forms.MouseEventHandler(this.buttonMouse_MouseMove);
}
//
// Timer time
//
private void timerTime_Tick(object sender, EventArgs e)
{
time += 1;
string tmp = Convert.ToString((double)time / 10);
if ((time % 10) == 0)
tmp += ".0";
labelTime.Text = tmp + " Time";
}
//
// Panel game field
//
private void panel_MouseMove(object sender, MouseEventArgs e)
{
Point tmp = new Point(buttonMouse.Location.X + 20, buttonMouse.Location.Y + 20);
int distance = Distanse(tmp, e.Location);
if (distance < 50)
{
tmp.X += 10;
if (tmp.X <= panel.Width - 20 && Distanse(tmp, e.Location) >= 50)
{
buttonMouse.Location = new Point(tmp.X - 20, tmp.Y - 20);
return;
}
tmp.X -= 20;
if (tmp.X >= 30 && Distanse(tmp, e.Location) >= 50)
{
buttonMouse.Location = new Point(tmp.X - 20, tmp.Y - 20);
return;
}
tmp.X += 10;
tmp.Y += 10;
if (tmp.Y <= panel.Height - 30 && Distanse(tmp, e.Location) >= 50)
{
buttonMouse.Location = new Point(tmp.X - 20, tmp.Y - 20);
return;
}
tmp.Y -= 20;
if (tmp.Y >= 30 && Distanse(tmp, e.Location) >= 50)
{
buttonMouse.Location = new Point(tmp.X - 20, tmp.Y - 20);
return;
}
}
if (distance < 50 && IsHouse())
{
ChooseDoor();
}
}
private void panel_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
contextMenuStrip.Show(new Point(this.Location.X + e.X, this.Location.Y + e.Y + 50));
}
//
// Support methods
//
private void ChooseDoor()
{
int door = MyRand.GetRand(1, 4);
switch (door)
{
case 1:
buttonMouse.Location = new Point(20, 20);
break;
case 2:
buttonMouse.Location = new Point(panel.Width - 50, 20);
break;
case 3:
buttonMouse.Location = new Point(20, panel.Height - 50);
break;
case 4:
buttonMouse.Location = new Point(panel.Width - 50, panel.Height - 50);
break;
default:
break;
}
}
private bool IsHouse()
{
if (buttonMouse.Location.X < 40 && buttonMouse.Location.Y < 40)
return true;
if (buttonMouse.Location.X + 40 > panel.Width - 50 && buttonMouse.Location.Y < 40)
return true;
if (buttonMouse.Location.X < 40 && buttonMouse.Location.Y + 40 > panel.Height - 70)
return true;
if (buttonMouse.Location.X + 40 > panel.Width - 50 && buttonMouse.Location.Y + 40 > panel.Height - 70)
return true;
return false;
}
private int Distanse(Point a, Point b)
{
return (int)Math.Sqrt(Math.Pow(a.X - b.X, 2) + Math.Pow(a.Y - b.Y, 2));
}
}
}
|
c6990b4f8d0a7b11bd1cd033bc5631520b264c50
|
C#
|
VadHane/TelegramBotForChnuChar
|
/Models/Text.cs
| 3.140625
| 3
|
using Telegram.Bot.Types;
namespace ChatBot.Models
{
public static class Text
{
public const string ForPrivedChat = "Я працюю виключно в <b>чаті студентів ЧНУ</b>!";
public static string DeleteWord(Word word)
{
return "<b>Я видалив слово із словника. </b> \n" +
$"Слово - <em>{word.Text}</em>.";
}
public static string AddWord(Word word)
{
return "<b>Я добавив нове слово в словник. </b> \n" +
$"Слово - <em>{word.Text}</em>.";
}
public static string DeletedMessage(Message message)
{
return "<b>Я видалив повідомлення! \nІнформація про повідомлення:</b>" +
$"\nВідправник: {message.From.FirstName} {message.From.LastName} " +
$"[<a href=\"https://t.me/{message.From.Username}\">Profile</a>]" +
$"\nУнікальний ідентифікатор відправника: {message.From.Id}" +
$"\nЧат: {message.Chat.FirstName} {message.Chat.LastName}" +
$"\nЧас відправлення: {message.Date.TimeOfDay}" +
$"\nПовідомлення: {message.Text}";
}
public static string CantDeleteMessage(Message message)
{
return "<b>Я не зміг видалити повідомлення! \nІнформація про повідомлення:</b>" +
$"\nВідправник: {message.From.FirstName} {message.From.LastName} " +
$"[<a href=\"https://t.me/{message.From.Username}\">Profile</a>]" +
$"\nЧат: {message.Chat.FirstName} {message.Chat.LastName}" +
$"\nЧас відправлення: {message.Date.TimeOfDay}" +
$"\nПовідомлення: {message.Text}" +
"\n\n\n<em>Можлива причина цієї помилки - повідомлення було видалено скоріше, ніж це зміг зробити я!</em>";
}
public static string Warn(string username, string name, int telegramId)
{
string result = "";
if (username.Length > 1)
{
result += $"<a href=\"https://t.me/{username}\">{name}</a> [@{username}]";
}
else
{
result += $"<a href=\"https://t.me/{telegramId}\">{name}</a> ";
}
return result + "буть обережнішим з висловлюваннями!";
}
}
}
|
de5a7fa32c747dce2b1a742cd4cab98dfb2969b3
|
C#
|
wegiangb/breeze.js.samples
|
/net/NoDb/NoDb/Models/TodoItem.cs
| 2.625
| 3
|
namespace NoDb.Models {
public class TodoItem {
public int TodoItemId { get; set; }
public string Title { get; set; }
public bool IsDone { get; set; }
public int TodoListId { get; set; } // Foreign key
// navigation property to item's parent TodoList
public virtual TodoList TodoList { get; set; }
public string Validate()
{
var errs = string.Empty;
if (TodoItemId <= 0)
{
errs += "TodoItemId must be a positive integer";
}
if (string.IsNullOrWhiteSpace(Title))
{
errs += "Title is required";
}
else if (Title.Length > 30)
{
errs += "Title cannot be longer than 30 characters";
}
if (TodoListId <= 0)
{
errs += "TodoListId must be a positive integer";
}
return errs;
}
}
}
|
fffaa3d38570d9859786ea42dedfa613214c2e59
|
C#
|
VladimirMakarevich/AutoDoc
|
/AutoDoc/Mappers/BookmarkMapper.cs
| 2.5625
| 3
|
using AutoDoc.DAL.Entities;
using AutoDoc.Models;
using AutoMapper;
using System.Collections.Generic;
using System.Linq;
using AutoDoc.BL.Models;
using System;
namespace AutoDoc.Mappers
{
public class BookmarkMapper
{
private readonly IMapper _mapper;
public BookmarkMapper(IMapper mapper)
{
_mapper = mapper;
}
public List<Bookmark> ToBookmarks(List<string> bookmarksList)
{
var bookmarks = bookmarksList.Select(ToMapNameBookmark).ToList();
return bookmarks;
}
public Bookmark ToMapNameBookmark(string bookmark)
{
return new Bookmark { Name = bookmark };
}
public Bookmark ToBookmark(BookmarkJsonModel bookmark)
{
return _mapper.Map<BookmarkJsonModel, Bookmark>(bookmark);
}
public BookmarkJsonModel ToBookmarkJsonModel(Bookmark bookmark)
{
return _mapper.Map<Bookmark, BookmarkJsonModel>(bookmark);
}
public Bookmark ToBookmarkFromName(WordBookmark bookmarkName, int id)
{
return new Bookmark
{
Name = bookmarkName.BookmarkData.Key,
MessageJson = bookmarkName.Message,
DocumentId = id,
Type = bookmarkName.BookmarkType
};
}
}
}
|
986482d97b839e83d4e1f17f25a905afd5856034
|
C#
|
DKorzhovnik/Shine
|
/Data/Models/Config/PersonConfig.cs
| 2.578125
| 3
|
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Shine.Data.Models.Config {
public class PersonConfig : IEntityTypeConfiguration<Person> {
public void Configure(EntityTypeBuilder<Person> builder) {
builder.HasDiscriminator(p => p.PersonType)
.HasValue<Customer>(false)
.HasValue<Supplier>(true);
builder.HasMany(p => p.Orders)
.WithOne(o => o.Person)
.OnDelete(DeleteBehavior.Restrict);
builder.Property(p => p.PersonType).Metadata
.AfterSaveBehavior = PropertySaveBehavior.Save;
builder.Property(p => p.DateOfBirth)
.HasColumnType("date");
}
}
}
|
f68c2008cd1c97977c5d77bab7f65450934366ed
|
C#
|
SignedUp/omni-foundation
|
/foundation/tags/1.2.0/src/Omniscient.Foundation.Data/IEntity.cs
| 2.96875
| 3
|
using System;
namespace Omniscient.Foundation.Data
{
/// <summary>
/// Represents an entity.
/// </summary>
public interface IEntity
{
/// <summary>
/// Gets or sets the status of the entity.
/// </summary>
EntityStatus Status { get; set; }
/// <summary>
/// Copies the values of the entity to another entity. Copies on the data values, skipping the Id and Status.
/// </summary>
/// <param name="target">The entity to copy values to.</param>
void CopyTo(IEntity target);
}
public interface IEntity<TId> : IEntity
{
/// <summary>
/// Gets an id that uniquely represents an entity in a given space. For example, and IEntity<Guid>
/// will be unique in the universe, while an IEntity<long> will probably be unique amongst other
/// entities of the same type.
/// </summary>
TId Id { get; }
}
}
|
59c00679b120a07e6b38960ea21fdfe584068be5
|
C#
|
binckbank-api/client-csharp
|
/OrderModel.cs
| 2.515625
| 3
|
namespace ClientCsharp
{
using System;
using System.Reflection;
using Newtonsoft.Json;
/// <summary>
/// The order update
/// </summary>
[Obfuscation(Feature = "preserve-name-binding")]
[Obfuscation(Feature = "preserve-identity")]
public class OrderModel
{
/// <summary>
/// The number of the account
/// </summary>
[JsonProperty(PropertyName= "accountNumber", Required = Required.Always)]
public string AccountNumber { get; set; }
/// <summary>
/// Order sequence number for the account
/// </summary>
[JsonProperty(PropertyName = "number", Required = Required.Always)]
public long Number { get; set; }
/// <summary>
/// Instrument for which the order has been placed
/// </summary>
[JsonProperty(PropertyName = "instrument", Required = Required.Always)]
public InstrumentModel Instrument { get; set; }
/// <summary>
/// Order status
/// </summary>
[JsonProperty(PropertyName = "status", Required = Required.Always)]
public string Status { get; set; }
/// <summary>
/// [Optional] Limit price
/// </summary>
[JsonProperty(PropertyName = "limitPrice", Required = Required.Default, NullValueHandling = NullValueHandling.Ignore)]
public decimal? LimitPrice { get; set; }
/// <summary>
/// [Optional] Order (price condition) type
/// </summary>
[JsonProperty(PropertyName = "type", Required = Required.Default, NullValueHandling = NullValueHandling.Ignore)]
public string OrderType { get; set; }
/// <summary>
/// [Optional] Expiration date
/// </summary>
[JsonProperty(PropertyName = "expirationDate", Required = Required.Default, NullValueHandling = NullValueHandling.Ignore)]
public DateTime? ExpirationDate { get; set; }
/// <summary>
/// Date and time of update
/// </summary>
[JsonProperty(PropertyName = "dt", Required = Required.Always)]
public DateTime TransactionDateTime { get; set; }
/// <summary>
/// [Optional] Combination strategy. Pay or Receive
/// </summary>
[JsonProperty(PropertyName = "combinationCondition", Required = Required.Default, NullValueHandling = NullValueHandling.Ignore)]
public string Condition { get; set; }
/// <summary>
/// [Optional] Order reference id
/// </summary>
[JsonProperty(PropertyName = "referenceId", Required = Required.Default, NullValueHandling = NullValueHandling.Ignore)]
public string ReferenceId { get; set; }
}
/// <summary>
/// Instrument for which the order has been placed
/// </summary>
public class InstrumentModel
{
/// <summary>
/// Instrument id
/// </summary>
[JsonProperty(PropertyName = "id", Required = Required.Always)]
public string Id { get; set; }
}
}
|
00c61434d8e2dd51a2ebf4058128558c39db4443
|
C#
|
HendrikMennen/Dash2D
|
/TestGame/src/effects/AlcoholPlayerEffect.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestGame.src.input;
using TestGame.src.tools;
namespace TestGame.src.effects
{
class AlcoholPlayerEffect : PlayerEffect
{
bool dir = true;
public override void update(Input input)
{
if(duration > 1)
{
if (dir)
{
Global.camera.Rotation += 0.01f;
if (Global.camera.Rotation > 1f) dir = false;
}
else
{
Global.camera.Rotation -= 0.01f;
if (Global.camera.Rotation < -1f) dir = true;
}
duration--;
}else
{
duration = 0;
if (Global.camera.Rotation > 0.1f) Global.camera.Rotation -= 0.01f;
else if (Global.camera.Rotation < -0.1f) Global.camera.Rotation += 0.01f;
else Global.camera.Rotation = 0;
}
}
}
}
|
ac3edd7aa8be114cd88d8226a60010ddef20f7e3
|
C#
|
OscarBarter/Y13CompSci
|
/Stack/Program.cs
| 3.90625
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stack
{
class Program
{
static void Main(string[] args)
{
// declare a Stack of strings call myStack
var myStack = new StackArray<string>();
myStack.Push("apples");
myStack.Push("milk");
myStack.Push("ham");
myStack.Push("pears");
Console.WriteLine("Number of items in stack: " + myStack.Count);
Console.Write("Peeking the top: ");
Console.WriteLine(myStack.Peek());
Console.WriteLine("Popping all elements");
// Pop and output all the elements of the
while (!myStack.Empty())
{
Console.WriteLine(myStack.Pop());
}
Console.ReadLine();
}
}
}
|
849b3370bd870c9f4c5e7c664a8d83e1370eefab
|
C#
|
jonfuller/presentations
|
/dependencies/src/NoInjection.cs
| 2.75
| 3
|
public class MovieLister
{
private readonly IMovieFinder _finder;
public MovieLister()
{
_finder = new ImdbMovieFinder();
}
public IEnumerable<Movie> MoviesDirectedBy(string director)
{
return _finder
.FindAll()
.Where(movie => movie.Director == director);
}
}
|
0bd725d07cb85c57af8b04e133a81092266e1598
|
C#
|
Nomil98/Carrera
|
/Carrera.cs
| 3.15625
| 3
|
class Carrera
{
private int _NumeroCorredor;
protected int _Posicion;
private static Random ran = new Random();
public int NumeroCorredor
{
get { return _NumeroCorredor; }
}
public int Posicion
{
get { return _Posicion; }
}
public Carrera (int NumeroCorredor)
{
/// Le damos el número al corredor e inicializamos la posición
/// de los corredores en 0.
_NumeroCorredor = NumeroCorredor;
_Posicion = 0;
}
public override string ToString()
{
return _NumeroCorredor.ToString() + _Posicion.ToString();
}
public int Correr()
{
return ran.Next(20) + 1;
///Generará un numero aleatorio del 0 al 19 y le sumará 1.
}
|
8f04def3f961dfe81ba0bb4377aa7de9005e362e
|
C#
|
wiyonoaten/dev4goodHacks
|
/ServicesLib/Models/Converters/LocationListConverter.cs
| 2.953125
| 3
|
using Microsoft.WindowsAzure.MobileServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Windows.Data.Json;
namespace ServicesLib.Models.Converters
{
public class LocationListConverter : IDataMemberJsonConverter
{
private static readonly IJsonValue NullJson = JsonValue.Parse("null");
public object ConvertFromJson(IJsonValue value)
{
List<Location> result = null;
if (value != null && value.ValueType == JsonValueType.String)
{
string valueInStr = value.GetString();
var locationPairs = valueInStr.Split(';');
if (locationPairs != null)
{
result = new List<Location>();
foreach (var locationPair in locationPairs)
{
if (locationPair.Length > 0)
{
var latLong = locationPair.Split(',');
result.Add(new Location()
{
Latitude = Convert.ToDouble(latLong[0]),
Longitude = Convert.ToDouble(latLong[1]),
});
}
}
}
}
return result;
}
public IJsonValue ConvertToJson(object instance)
{
if (instance is List<Location>)
{
StringBuilder sb = new StringBuilder();
foreach (var loc in (instance as List<Location>))
{
sb.Append(String.Format(";{0},{1}", loc.Latitude, loc.Longitude));
}
return JsonValue.CreateStringValue(sb.ToString());
}
else
{
return NullJson;
}
}
}
}
|
1b3cd4be2eee7f13c03cb9df8e986217b24d2767
|
C#
|
Almantask/Sudoku-
|
/src/Sudoku.Core/SudokuGenerator/RandomGame.cs
| 2.578125
| 3
|
using Sudoku.Core.Extensions;
using Sudoku.Core.Rules;
using Sudoku.Core.SudokuElements;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sudoku.Core.SudokuGenerator
{
internal class RandomGame: Game
{
private protected override void Guess(Game game, CellWithSolutions cellWithLeastSolutions)
{
var mixedSolutions = cellWithLeastSolutions.Solutions.ToList().Shuffle();
foreach (var guess in mixedSolutions)
{
var gameSnapshot = game.Clone();
gameSnapshot.AssignGuess(cellWithLeastSolutions, guess);
Solve(gameSnapshot);
}
}
}
}
|
eaba37e35d4e523a9e6bbedb4dc8b812caa1d5fc
|
C#
|
christerk/FFBUnity
|
/Assets/Scripts/Model/Types/PlayerAction.cs
| 2.53125
| 3
|
namespace Fumbbl.Model.Types
{
public class PlayerAction : FfbEnumerationFactory
{
public string Action => Name;
public int Type { get; set; }
public string ShortDescription { get; set; }
public string Description { get; set; }
public bool ShowActivity => Description != null;
public PlayerAction(string name) : base(name) { }
public static PlayerAction move = new PlayerAction("move") { ShortDescription="Move", Description = "starts a Move Action" };
public static PlayerAction block = new PlayerAction("block") { ShortDescription = "Block", Description = "starts a Block Action" };
public static PlayerAction blitz = new PlayerAction("blitz");
public static PlayerAction blitzMove = new PlayerAction("blitzMove") { ShortDescription = "Blitz", Description = "starts a Blitz Action" };
public static PlayerAction handOver = new PlayerAction("handOver");
public static PlayerAction handOverMove = new PlayerAction("handOverMove") { ShortDescription = "Hand Over", Description = "starts a Hand Over Action" };
public static PlayerAction pass = new PlayerAction("pass");
public static PlayerAction passMove = new PlayerAction("passMove") { ShortDescription = "Pass", Description = "starts a Pass Action" };
public static PlayerAction foul = new PlayerAction("foul");
public static PlayerAction foulMove = new PlayerAction("foulMove") { ShortDescription = "Foul", Description = "starts a Foul Action" };
public static PlayerAction standUp = new PlayerAction("standUp") { ShortDescription = "Stand Up", Description = "stands up" };
public static PlayerAction throwTeamMate = new PlayerAction("throwTeamMate");
public static PlayerAction throwTeamMateMove = new PlayerAction("throwTeamMateMove");
public static PlayerAction removeConfusion = new PlayerAction("removeConfusion");
public static PlayerAction gaze = new PlayerAction("gaze");
public static PlayerAction multipleBlock = new PlayerAction("multipleBlock") { ShortDescription = "Block", Description = "starts a Block Action" };
public static PlayerAction hailMaryPass = new PlayerAction("hailMaryPass");
public static PlayerAction dumpOff = new PlayerAction("dumpOff");
public static PlayerAction standUpBlitz = new PlayerAction("standUpBlitz") { ShortDescription = "Blitz", Description = "stands up with Blitz" };
public static PlayerAction throwBomb = new PlayerAction("throwBomb") { ShortDescription = "Bomb", Description = "starts a Bomb Action" };
public static PlayerAction hailMaryBomb = new PlayerAction("hailMaryBomb");
public static PlayerAction swoop = new PlayerAction("swoop");
}
}
|
d8910c580e4a7a43564ba1603eaa95c1dc53ae8a
|
C#
|
sergik/Cardio
|
/Cardio.Shared/Input/InputManager.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
namespace Cardio.UI.Input
{
public static class InputManager
{
#region Touch
public static List<GestureSample> Gestures { get; set; }
#endregion
#region Mouse
public static MouseState CurrentMouseState { get; private set; }
private static MouseState _previousMouseState;
public static bool IsMouseButtonTriggered(Func<MouseState, ButtonState> buttonSelector)
{
return buttonSelector(CurrentMouseState) == ButtonState.Pressed &&
buttonSelector(_previousMouseState) == ButtonState.Released;
}
public static bool IsMouseMoved()
{
return (_previousMouseState.X - CurrentMouseState.X + _previousMouseState.Y - CurrentMouseState.Y != 0);
}
public static float GetMouseWheelScroll()
{
return CurrentMouseState.ScrollWheelValue - _previousMouseState.ScrollWheelValue;
}
#endregion
#region Keyboard
/// <summary>
/// The state of the keyboard as of the last update.
/// </summary>
public static KeyboardState CurrentKeyboardState { get; private set; }
/// <summary>
/// The state of the keyboard as of the previous update.
/// </summary>
private static KeyboardState _previousKeyboardState;
/// <summary>
/// Check if a key is pressed.
/// </summary>
public static bool IsKeyPressed(Keys key)
{
return CurrentKeyboardState.IsKeyDown(key);
}
/// <summary>
/// Check if a key was just pressed in the most recent update.
/// </summary>
public static bool IsKeyTriggered(Keys key)
{
return (CurrentKeyboardState.IsKeyDown(key)) &&
(!_previousKeyboardState.IsKeyDown(key));
}
#endregion
static InputManager()
{
Gestures = new List<GestureSample>();
}
/// <summary>
/// Initializes the default control keys for all actions.
/// </summary>
public static void Initialize()
{
TouchPanel.EnabledGestures = GestureType.Tap | GestureType.VerticalDrag | GestureType.HorizontalDrag
| GestureType.Flick;
Gestures = new List<GestureSample>();
}
/// <summary>
/// Updates the keyboard and gamepad control states.
/// </summary>
public static void Update()
{
Gestures.Clear();
// update the keyboard state
_previousKeyboardState = CurrentKeyboardState;
CurrentKeyboardState = Keyboard.GetState();
_previousMouseState = CurrentMouseState;
CurrentMouseState = Mouse.GetState();
while (TouchPanel.IsGestureAvailable)
{
var gesture = TouchPanel.ReadGesture();
Gestures.Add(gesture);
}
}
public static bool IsExitPressed()
{
return IsKeyTriggered(Keys.Escape);
}
public static bool IsButtonClicked(Rectangle position)
{
return IsMouseButtonTriggered(x => x.LeftButton) && position.Contains(CurrentMouseState.X, CurrentMouseState.Y);
}
}
}
|
b5586210b833e6131ba16779059f4f497fe60c54
|
C#
|
askeip/blablblabl
|
/Poker/Assets/Scripts/SidePot.cs
| 2.71875
| 3
|
using UnityEngine;
using System.Collections;
using System.Linq;
using System.Collections.Generic;
public class SidePot
{
public float Pot { get; set; }
public float MinBet { get; set; }
public SidePot(float pot, float minBet)
{
Pot = pot;
MinBet = minBet;
}
}
public class PotCounter
{
public float mainPot { get; set; }
public float lastPot { get; set; }
public List<SidePot> pots{ get; private set; }
public PotCounter()
{
mainPot = 0;
lastPot = 0;
pots = new List<SidePot> ();
}
public void CountPots(List<PlayerBasicScript> players,List<PlayerBasicScript> allinPlayers)
{
allinPlayers = allinPlayers.OrderBy (z => z.moveController.playerInfo.PlayerBet)
.ToList ();
foreach (var allinPlayer in allinPlayers)
{
AddPot(players, allinPlayer.moveController.playerInfo.PlayerBet);
}
}
public void AddPot(List<PlayerBasicScript> players,float allinPlayerBet)
{
float prevBet = pots.Count > 0 ? pots [pots.Count - 1].MinBet : 0f;
if (prevBet == allinPlayerBet)
return;
var folded = players.Where(z=>z.moveController.playerInfo.PlayerBet > prevBet && z.moveController.playerInfo.PlayerBet < allinPlayerBet)
.ToList();
var foldedMoney = folded.Sum(z=>z.moveController.playerInfo.PlayerBet) - folded.Count * prevBet;
players = players.Where(z=>z.moveController.playerInfo.PlayerBet >= allinPlayerBet)
.ToList();
float pot = players.Count * allinPlayerBet + foldedMoney - prevBet * players.Count;
pots.Add (new SidePot (pot, allinPlayerBet));
RecountLastPot ();
}
public void RecountLastPot()
{
lastPot -= pots [pots.Count - 1].Pot;
}
public void CountPot(float lastBet)
{
mainPot += lastBet;
lastPot += lastBet;
}
public void GivePOT(List<PlayerBasicScript> winners,float pot)
{
for (int i=0;i<winners.Count;i++)
{
winners[i].moveController.GetMoney(pot/winners.Count);
}
}
}
|
15d1e8b1bb379d2c7e46ce23d09bfd81a782fadd
|
C#
|
lukeschofield2000/steve-ass-2
|
/steve ass 2/steve allison assignment 2.cs
| 2.90625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Windows.Forms.DataVisualization.Charting;
namespace steve_ass_2
{
public partial class Form1 : Form
{
class row
{
public double time;
public double altitude;
public double velocity;
public double acceleration;
}
List<row> table = new List<row>();
public Form1()
{
InitializeComponent();
}
void derivative()
{
for (int i = 1; i < table.Count; i++)
{
double dh = table[i].altitude - table[i - 1].altitude;
double dt = table[i].time - table[i - 1].time;
table[i].velocity = dh / dt;
}
}
void secondderivative()
{
for (int i = 1; i < table.Count; i++)
{
double dV = table[i].velocity - table[i - 1].velocity;
double dt = table[i].time - table[i - 1].time;
table[i].acceleration = dV / dt;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void currentToolStripMenuItem_Click(object sender, EventArgs e)
{
chart1.Series.Clear();
chart1.ChartAreas[0].AxisX.IsMarginVisible = false;
Series series1 = new Series
{
Name = "Voltage (V)",
Color = Color.Blue,
IsVisibleInLegend = true,
IsXValueIndexed = true,
ChartType = SeriesChartType.Spline,
BorderWidth = 2
};
chart1.Series.Add(series1);
for (int i = 0; i < table.Count; i++)
{
series1.Points.AddXY(table[i].time, table[i].altitude);
}
chart1.ChartAreas[0].AxisX.Title = "time (s)";
chart1.ChartAreas[0].AxisY.Title = "Altitude (m)";
chart1.ChartAreas[0].RecalculateAxesScale();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog1.FileName = "";
openFileDialog1.Filter = "csv files |*.csv";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
try
{
using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
{
string line = sr.ReadLine();
while (!sr.EndOfStream)
{
table.Add(new row());
string[] r = sr.ReadLine().Split(',');
table.Last().time = double.Parse(r[0]);
table.Last().altitude = double.Parse(r[1]);
}
}
derivative();
secondderivative();
}
catch (IOException)
{
MessageBox.Show(openFileDialog1.FileName + "failed to open.");
}
catch (FormatException)
{
MessageBox.Show(openFileDialog1.FileName + "is not in the required format.");
}
catch (IndexOutOfRangeException)
{
MessageBox.Show(openFileDialog1.FileName + "is not in the required format.");
}
}
}
}
}
|
53e5e0bb7bf434b2333bbedb089776f57f34826d
|
C#
|
Elmona/1DV607-Workshop2
|
/view/UserView.cs
| 3.0625
| 3
|
using System;
using System.Collections.Generic;
namespace View
{
class UserView
{
public enum Event
{
ViewCompactList,
ViewDetailedList,
ViewSpecificMember,
AddMember,
RemoveMember,
EditMember,
AddBoat,
RemoveBoat,
ChangeBoatData,
None,
Quit
}
public enum Errors
{
MemberDontExist,
InvalidAction,
InvalidBoat,
UserHasNoBoats
}
public void displayInstructions()
{
Console.ResetColor();
Console.WriteLine("");
Console.WriteLine("######################################");
Console.WriteLine("# Welcome to the Boat club. #");
Console.WriteLine("######################################");
Console.WriteLine("");
Console.WriteLine("What do you want to do?");
Console.WriteLine("1. View Compact list of members");
Console.WriteLine("2. View Detailed list of members");
Console.WriteLine("3. Add member");
Console.WriteLine("4. Remove member");
Console.WriteLine("5. Edit member");
Console.WriteLine("6. Add boat");
Console.WriteLine("7. Remove boat");
Console.WriteLine("8. Change boat information");
Console.WriteLine("9. View specific member");
Console.WriteLine("x. Quit");
Console.Write("? ");
}
public Event getInputEvent()
{
char inputtedCharacter = Console.ReadKey().KeyChar;
if (inputtedCharacter == '1') return Event.ViewCompactList;
if (inputtedCharacter == '2') return Event.ViewDetailedList;
if (inputtedCharacter == '3') return Event.AddMember;
if (inputtedCharacter == '4') return Event.RemoveMember;
if (inputtedCharacter == '5') return Event.EditMember;
if (inputtedCharacter == '6') return Event.AddBoat;
if (inputtedCharacter == '7') return Event.RemoveBoat;
if (inputtedCharacter == '8') return Event.ChangeBoatData;
if (inputtedCharacter == '9') return Event.ViewSpecificMember;
if (inputtedCharacter == 'x') return Event.Quit;
return Event.None;
}
public void viewMemberListCompact(IEnumerable<Model.Member> members)
{
Console.WriteLine("\nViewing Compact");
foreach (var member in members)
{
viewMemberCompact(member);
}
}
public void viewMemberListVerbose(IEnumerable<Model.Member> members)
{
Console.WriteLine("\nViewing Verbose");
foreach (var member in members)
{
viewMemberVerbose(member);
}
}
public void viewMemberVerbose(Model.Member m)
{
Console.WriteLine($"ID: {m.MemberId,-2} Name: {m.Name,-10} Social security number: {m.SocialId} Number of boats: {m.getNumberOfBoats()}");
viewBoats(m.getBoats());
}
public void viewMemberCompact(Model.Member m)
{
Console.WriteLine($"ID: {m.MemberId,-2} Name: {m.Name,-10} Social security number: {m.SocialId} Number of boats: {m.getNumberOfBoats()}");
}
public void viewBoats(IEnumerable<Model.Boat> boats)
{
int i = 0;
foreach (var boat in boats)
{
Console.WriteLine($" Boat ID: {i} {boat.Type,15} {boat.Length} cm");
i++;
}
}
public Model.Member addMember()
{
string name;
long socialNumber;
Console.WriteLine("\n");
Console.WriteLine("\nPlease enter a name.");
Console.Write("? ");
name = Console.ReadLine();
do
{
Console.WriteLine("\nPlease enter members social security number.");
Console.WriteLine("Format: yymmddxxxx.\n");
Console.Write(": ");
} while (!long.TryParse(Console.ReadLine(), out socialNumber));
Console.WriteLine("\n--------------------------------\n");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Member was successfully added!");
Console.WriteLine("");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Press any key to return to main menu.");
Console.ReadKey();
return new Model.Member(name, 1, socialNumber);
}
public Model.Member editMember(int id)
{
long newSocialId = 1;
Console.WriteLine("\n");
Console.WriteLine("Enter a name to change it, or leave it blank to not change it.");
Console.Write(": ");
string newName = Console.ReadLine();
if (newName == "")
newName = "x";
do
{
Console.WriteLine("\n");
Console.WriteLine("Please enter members social security number.");
Console.WriteLine("Format: yymmddxxxx.");
Console.WriteLine("Enter '1' to not change it.");
Console.Write(": ");
} while (!long.TryParse(Console.ReadLine(), out newSocialId));
return new Model.Member(newName, id, newSocialId);
}
public int removeMember()
{
int memberToBeRemoved;
Console.WriteLine("\nYou chose to remove a member.");
Console.WriteLine("--------------------------------");
do
{
Console.WriteLine("Please enter the id of the member you want to delete.");
Console.Write(": ");
} while (!int.TryParse(Console.ReadLine(), out memberToBeRemoved));
return memberToBeRemoved;
}
public bool removeBoat(Model.Member member)
{
bool successfullyRemoved = false;
int boatIdToBeDeleted;
bool memberHasBoats = false;
Console.WriteLine("\nYou chose to remove a boat.");
Console.WriteLine("--------------------------------\n");
if (!member.hasBoats())
{
return memberHasBoats;
}
else if (member.hasBoats())
{
do
{
Console.WriteLine("You're currently editing this member:");
Console.WriteLine("--------------------------------");
Console.ForegroundColor = ConsoleColor.Yellow;
viewMemberVerbose(member);
Console.ResetColor();
Console.WriteLine("\nPlease enter the id of the boat you want to delete.");
Console.Write(": ");
} while (!int.TryParse(Console.ReadLine(), out boatIdToBeDeleted));
successfullyRemoved = member.removeBoat(boatIdToBeDeleted);
while (!successfullyRemoved && boatIdToBeDeleted != 0)
{
Console.WriteLine("");
Console.WriteLine("\n--------------------------------");
Console.ForegroundColor = ConsoleColor.Red;
System.Console.WriteLine("No boat with that Id exists, please enter the id of the boat you want to delete.");
Console.ResetColor();
Console.WriteLine("\n--------------------------------");
do
{
Console.WriteLine("Please enter the id of the boat you want to delete.");
Console.WriteLine("Enter '0' to return.");
Console.Write(": ");
} while (!int.TryParse(Console.ReadLine(), out boatIdToBeDeleted));
successfullyRemoved = member.removeBoat(boatIdToBeDeleted);
}
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("\nBoat was successfully removed from member!");
Console.WriteLine("--------------------------------");
Console.WriteLine("\nPress any key to return to main menu.");
Console.ReadKey();
return successfullyRemoved;
}
public Model.Boat addBoat()
{
int boatLength;
int correctChoice;
Console.WriteLine("\nYou chose to add a boat.");
Console.WriteLine("--------------------------------");
do
{
Console.WriteLine("\nPlease enter the length of the boat you want to add (in centimeters)");
Console.Write(": ");
} while (!int.TryParse(Console.ReadLine(), out boatLength));
do
{
Console.WriteLine("\nPlease select what type of the boat you want to add.\n");
Console.WriteLine("1. Sailboat");
Console.WriteLine("2. MotorSailer");
Console.WriteLine("3. Kayak/Canoe");
Console.WriteLine("4. Other");
Console.Write(": ");
} while (!int.TryParse(Console.ReadLine(), out correctChoice) && (correctChoice > 0 && correctChoice < 5));
Model.BoatType returnType = (Model.BoatType)Enum.ToObject(typeof(Model.BoatType), correctChoice);
Console.ForegroundColor = ConsoleColor.Green;
System.Console.WriteLine("\nBoat was successfully added to member!");
Console.WriteLine("--------------------------------");
Console.WriteLine("\nPress any key to return to main menu.");
Console.ReadKey();
return new Model.Boat(returnType, boatLength);
}
public int selectBoat(Model.Member member)
{
int boatIndex;
viewMemberVerbose(member);
do
{
Console.WriteLine("Select which boat to change.");
Console.Write(": ");
} while (!int.TryParse(Console.ReadLine(), out boatIndex));
return boatIndex;
}
public int getUserId()
{
int userId;
do
{
Console.WriteLine("Enter member ID:");
Console.Write(": ");
} while (!int.TryParse(Console.ReadLine(), out userId));
return userId;
}
public void viewSpecificMember(Model.Member member)
{
Console.WriteLine("\nShowing specific member:");
Console.ForegroundColor = ConsoleColor.Green;
viewMemberVerbose(member);
Console.ResetColor();
}
public void pause() => Console.ReadKey();
public void errorInput(Enum Errors)
{
Console.WriteLine("\n--------------------------------\n");
Console.ForegroundColor = ConsoleColor.Red;
switch (Errors)
{
case View.UserView.Errors.MemberDontExist:
Console.WriteLine("A Member with that ID does not exist!");
break;
case View.UserView.Errors.InvalidBoat:
Console.WriteLine("There is no boat with that id.");
break;
case View.UserView.Errors.UserHasNoBoats:
Console.WriteLine("That user has no boats to be removed!");
break;
case View.UserView.Errors.InvalidAction:
Console.WriteLine("Please press one of the characters that corresponds to your desired action");
break;
default:
Console.WriteLine("Default case");
break;
}
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("\nPress any key to return to continue.");
Console.ReadKey();
}
}
}
|
a84ca4155a1ae81ecd2f78e71dce0c8cf125c3b4
|
C#
|
adamjoyce/slot-machine
|
/Assets/Scripts/BulletController.cs
| 2.53125
| 3
|
using UnityEngine;
using System.Collections;
public class BulletController : MonoBehaviour {
private float spawnTime;
public int bulletDamage = 5;
public int fireballDamage = 15;
// Use this for initialization
void Start () {
spawnTime = Time.fixedTime;
}
// Update is called once per frame
void Update () {
if (spawnTime + 5 < Time.fixedTime)
Destroy(this.gameObject);
}
void OnTriggerEnter2D(Collider2D collide)
{
if (this.name == "Bullet(Clone)" && (collide.name.Length >= 5 && collide.name.Substring(0,5) == "Enemy"))
{
collide.gameObject.GetComponent<Enemy>().inflictDamage(bulletDamage);
Destroy(this.gameObject);
}
else if (this.name == "Fireball(Clone)" && (collide.name == "Player" || collide.name == "Player(Clone)"))
{
collide.gameObject.GetComponent<PlayerController>().inflictDamage(fireballDamage, this.transform.position);
Destroy(this.gameObject);
}
}
}
|
417307f4da9a7986a297a382d5f1e90882a5f5cb
|
C#
|
panoramicsystems/LoopInterval
|
/PanoramicSystems.LoopInterval/LoopInterval.cs
| 3.09375
| 3
|
using Humanizer;
using Humanizer.Localisation;
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace PanoramicSystems
{
public abstract class LoopInterval
{
private readonly TimeSpan _timeSpanInterval;
public ILogger Logger { get; }
protected LoopInterval(string name, TimeSpan timeSpanInterval, ILogger logger)
{
_timeSpanInterval = timeSpanInterval;
Logger = new PrefixLogger(name, logger);
}
public abstract Task ExecuteAsync(CancellationToken cancellationToken);
/// <summary>
/// Loops attempting to keep a minimum interval between the start of each execution.
/// Exits when complete or cancelled.
/// </summary>
/// <param name="cancellationToken">CancellationToken</param>
public async Task LoopAsync(CancellationToken cancellationToken)
{
// Create a Stopwatch to monitor how long the sync takes
var stopwatch = Stopwatch.StartNew();
while (!cancellationToken.IsCancellationRequested)
{
stopwatch.Restart();
Logger.LogInformation("Starting...");
try
{
await ExecuteAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is OperationCanceledException || ex is TaskCanceledException)
{
Logger.LogInformation(ex, "Cancelled during execution.");
}
catch (Exception ex)
{
Logger.LogError(ex, $"An unexpected error occurred during the LoopInterval execution: {ex.Message}");
}
// We always continue here so we can continue if an Exception occurred during execution that was not related to cancellation
stopwatch.Stop();
Logger.LogInformation($"Finished in {stopwatch.Elapsed.Humanize(7, minUnit: TimeUnit.Second)}.");
if (cancellationToken.IsCancellationRequested)
{
// Return gracefully rather than throw an exeception
return;
}
// YES - determine the interval
var remainingTimeInInterval = _timeSpanInterval.Subtract(stopwatch.Elapsed);
if (remainingTimeInInterval.TotalSeconds > 0)
{
Logger.LogInformation($"Next will start in {remainingTimeInInterval.Humanize(7, minUnit: TimeUnit.Second)} at {DateTime.UtcNow.Add(remainingTimeInInterval)}.");
try
{
await Task.Delay(remainingTimeInInterval, cancellationToken).ConfigureAwait(false);
}
catch (TaskCanceledException ex)
{
Logger.LogInformation(ex, "Cancelled during interval delay.");
}
}
else
{
Logger.LogWarning($"Next execution will start immediately as it took {stopwatch.Elapsed}, which is longer than the configured TimeSpan {_timeSpanInterval}.");
}
}
}
}
}
|
f32e2ec97ba98fc84fc70ad3e35dc0ce09efa96e
|
C#
|
danbystrom/factor10.Obj2Db
|
/factor10.Obj2Db/LinkedFieldInfo.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
namespace factor10.Obj2Db
{
public sealed class LinkedFieldInfo
{
private static readonly Dictionary<string, Func<IConvertible, object>> Cohersions = new Dictionary<string, Func<IConvertible, object>>
{
{"Int32", _ => _.ToInt32(null)},
{"Int64", _ => _.ToInt64(null)},
{"Int16", _ => _.ToInt16(null)},
{"Decimal", _ => _.ToDecimal(null)},
{"DateTime", _ => _.ToDateTime(null)},
{"Double", _ => _.ToDouble(null)},
{"Single", _ => _.ToSingle(null)},
{"String", _ => _.ToString(null)},
{"Boolean", _ => _.ToBoolean(null)},
{"Guid", _ => _}
};
private readonly FieldInfo _fieldInfo;
private readonly PropertyInfo _propertyInfo;
public readonly LinkedFieldInfo Next;
public readonly Type IEnumerable;
public Type FieldType { get; private set; }
private readonly Func<IConvertible, object> _coherse;
private readonly Func<object, object> _getValue;
public LinkedFieldInfo(Type type, string name)
{
if (name == "@")
{
// auto-referencing
FieldType = type;
_getValue = _ => _;
}
else
{
var split = name.Split(".".ToCharArray(), 2);
_fieldInfo = type.GetField(split[0], BindingFlags.Public | BindingFlags.Instance);
if (_fieldInfo == null)
{
_propertyInfo = type.GetProperty(split[0], BindingFlags.Public | BindingFlags.Instance);
if (_propertyInfo == null)
throw new ArgumentException($"Field or property '{name}' not found in type '{type.Name}'");
if (split.Length > 1)
Next = new LinkedFieldInfo(_propertyInfo.PropertyType, split[1]);
}
else if (split.Length > 1)
Next = new LinkedFieldInfo(_fieldInfo.FieldType, split[1]);
var x = this;
while (x.Next != null)
x = x.Next;
FieldType = x._fieldInfo?.FieldType ?? x._propertyInfo.PropertyType;
if (_propertyInfo != null)
_getValue = generateFastPropertyFetcher(type, _propertyInfo);
else if (_fieldInfo != null)
_getValue = generateFastFieldFetcher(type, _fieldInfo);
}
IEnumerable = CheckForIEnumerable(FieldType);
Cohersions.TryGetValue(StripNullable(FieldType).Name, out _coherse);
}
public static Type StripNullable(Type type)
{
return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)
? Nullable.GetUnderlyingType(type)
: type;
}
public static Type CheckForIEnumerable(Type type)
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
return type;
return type != typeof(string) && type != typeof(byte[]) // a string implements IEnumerable<Char> - but forget that
? type.GetInterfaces().SingleOrDefault(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IEnumerable<>))
: null;
}
private Func<object, object> generateFastPropertyFetcher(Type type, PropertyInfo propertyInfo)
{
try
{
return generateFastFetcher(type, propertyInfo.PropertyType, il =>
{
il.Emit(OpCodes.Callvirt, propertyInfo.GetGetMethod());
});
}
catch (Exception e)
{
Console.WriteLine(e);
throw new Exception($"Could not generate propery fetcher for '{type.Name}'.{propertyInfo.Name}");
}
}
private Func<object, object> generateFastFieldFetcher(Type type, FieldInfo fieldInfo)
{
try
{
return generateFastFetcher(type, fieldInfo.FieldType, il =>
{
il.Emit(OpCodes.Ldfld, fieldInfo);
});
}
catch (Exception e)
{
Console.WriteLine(e);
throw new Exception($"Could not generate field fetcher for '{type.Name}'.{fieldInfo.Name}");
}
}
private Func<object, object> generateFastFetcher(Type sourceObjectType, Type resultType, Action<ILGenerator> ilGenAction)
{
var method = new DynamicMethod("", typeof(object), new[] {typeof(object)}, sourceObjectType, true);
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Castclass, sourceObjectType);
if (sourceObjectType.IsValueType)
il.Emit(OpCodes.Unbox, sourceObjectType);
ilGenAction(il);
if (resultType.IsValueType)
il.Emit(OpCodes.Box, resultType);
il.Emit(OpCodes.Ret);
return (Func<object, object>) method.CreateDelegate(typeof(Func<object, object>));
}
public static LinkedFieldInfo Null(Type type)
{
return new LinkedFieldInfo(type, "@");
}
public object GetValueSlower(object obj)
{
if (obj == null)
return null;
object value;
if (_fieldInfo != null)
value = _fieldInfo.GetValue(obj);
else if (_propertyInfo != null)
value = _propertyInfo.GetValue(obj);
else
return obj;
return Next == null ? value : Next.GetValue(value);
}
public object GetValue(object obj)
{
if (obj == null)
return null;
var value = _getValue(obj);
return Next == null ? value : Next.GetValue(value);
}
public object CoherseType(object obj)
{
var iconvertible = obj as IConvertible;
return iconvertible != null && _coherse != null ? _coherse(iconvertible) : obj;
}
public static object CoherseType(Type type, object obj)
{
var iconvertible = obj as IConvertible;
Func<IConvertible, object> coherse;
Cohersions.TryGetValue(StripNullable(type).Name, out coherse);
return iconvertible != null && coherse != null ? coherse(iconvertible) : obj;
}
public static List<NameAndType> GetAllFieldsAndProperties(Type type)
{
var list = new List<NameAndType>();
if (type == typeof(string) || type == typeof(DateTime) || type.IsArray ||
(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)))
return list;
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(_ => _.GetIndexParameters().Length == 0);
var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance).Where(_ => !_.IsSpecialName);
list.AddRange(properties.Select(_ => new NameAndType(_)));
list.AddRange(fields.Select(_ => new NameAndType(_)));
for (; type != null && type != typeof(object); type = type.BaseType)
if (type.IsGenericType)
{
var genTypDef = type.GetGenericTypeDefinition();
if (genTypDef == typeof(List<>) || genTypDef == typeof(IList<>))
list.RemoveAll(_ => new[] {"Capacity", "Count"}.Contains(_.Name));
if (genTypDef == typeof(Dictionary<,>) || genTypDef == typeof(IDictionary<,>))
list.RemoveAll(_ => new[] {"Comparer", "Count", "Keys", "Values"}.Contains(_.Name));
}
return list;
}
public static string FriendlyTypeName(Type type)
{
if (type == null)
return null;
var innerType = StripNullable(type);
return innerType == type
? type.Name
: innerType.Name + "?";
}
}
}
|
2e5e2116599f1d282701de77c2573ddd8103ec58
|
C#
|
AdvoXS/Chat
|
/chatick/Forms/history_messages_Form.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading.Tasks;
namespace chatick
{
public partial class history_messages_Form : Form
{
public history_messages_Form()
{
InitializeComponent();
set_Properties_Elements();
}
void set_Properties_Elements()
{
dateTimePicker1.CustomFormat = "dd.MM.yyyy";
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.Value = DateTime.Now;
dateTimePicker2.CustomFormat = "dd.MM.yyyy";
dateTimePicker2.Format = DateTimePickerFormat.Custom;
dateTimePicker2.Value = DateTime.Now;
}
private void Button1_Click(object sender, EventArgs e)
{
textBox1.Text = "\tЗагружаем данные с сервера...";
List<string> historyMes = null;
Task task = new Task(() => {
try
{
historyMes = DataBasePostgres.get_history_message_to_view(dateTimePicker1.Text, dateTimePicker2.Text);
}
catch (Npgsql.PostgresException ex)
{
MessageBox.Show("Ошибка соединения с базой данных");
Logs.LogClass logClass = new Logs.LogClass("DB", "Получение истории сообщений. Ошибка postgres: " + ex.MessageText);
}
catch (Npgsql.NpgsqlException ex)
{
MessageBox.Show("Ошибка соединения с базой данных");
Logs.LogClass logClass = new Logs.LogClass("DB", "Получение истории сообщений. Ошибка связи: " + ex.Message);
}
catch (Exception ex)
{
MessageBox.Show("Неизвестная ошибка");
Logs.LogClass logClass = new Logs.LogClass("System", "Имя объекта вызвавшего ошибку: " + ex.Source + " Ошибка " + ex.Message);
}
if (historyMes.Count > 0)
{
Action messNullAction = () => textBox1.Text = "";
textBox1.Invoke(messNullAction);
for (int i = 0; i < historyMes.Count; i++)
{
Action messAddRowAction = () => textBox1.Text += historyMes[i] + "\r\n";
textBox1.Invoke(messAddRowAction);
}
}
else
{
Action messNullAction = () => textBox1.Text = "\tДанных о переписках на данный период нет!";
textBox1.Invoke(messNullAction);
}
});
task.Start();
}
private void Label1_DoubleClick(object sender, EventArgs e)
{
debugWindow debugger = new debugWindow();
debugger.Show();
}
}
}
|
f876066a85ccab014b08cb63e441021f4778a280
|
C#
|
DhanuIngalahalli/RegexUsingLambda
|
/UserRegUsingLambda/Program.cs
| 3.234375
| 3
|
using System;
namespace UserRegUsingLambda
{
class Program
{
static string Regex_password = "^(?=.*[A-Z])(?=.*\\d)(?=[\\w]*[\\W][\\w]*$)[\\S]{8,}$";
public static string Regex_name = "^[A-Z]{1}[a-z]{2,}$";
public static string Regex_email = "^[0-9A-Za-z]+([._+-]*[0-9A-Za-z]+)*[@][0-9A-Za-z]+.([a-zA-Z]{2,3})*(.[a-zA-Z]{2})?$";
public static string Regex_phone = "^[1-9]{1}[0-9]{1}\\s[1-9]{1}[0-9]{9}$";
static Patterns patterns = new Patterns();
static void Main(string[] args)
{
Console.WriteLine("Enter the First name :");
string firstName = Console.ReadLine();
if (patterns.IsValidFirstName(firstName, Regex_name) == true)
Console.Write("valid");
else
Console.WriteLine("invalid");
Console.ReadKey();
Console.WriteLine("Enter the last name :");
string lastName = Console.ReadLine();
if (patterns.IsValidFirstName(lastName, Regex_name) == true)
Console.Write("valid");
else
Console.WriteLine("invalid");
Console.ReadKey();
Console.WriteLine("Enter the email :");
string Email = Console.ReadLine();
if (patterns.IsValidFirstName(Email, Regex_email) == true)
Console.Write("valid");
else
Console.WriteLine("invalid");
Console.ReadKey();
Console.WriteLine("Enter the password :");
string passWord = Console.ReadLine();
if (patterns.IsValidPasswordRule(passWord, Regex_password) == true)
Console.Write("valid");
else
Console.WriteLine("invalid");
Console.ReadKey();
Console.WriteLine("Enter the Phone number :");
string phoneNo = Console.ReadLine();
if (patterns.IsValidPasswordRule(phoneNo, Regex_phone) == true)
Console.Write("valid");
else
Console.WriteLine("invalid");
Console.ReadKey();
}
}
}
|
c30c85c22d5541162ecfebccfb8bbe9db72e678c
|
C#
|
santoshp1995/Space-Invaders
|
/GameObject/Aliens/AlienColumn.cs
| 2.609375
| 3
|
using System;
using System.Diagnostics;
namespace SpaceInvaders
{
public class AlienColumn : Composite
{
public AlienColumn(GameObject.Name name, GameSprite.Name spriteName, float posX, float posY)
: base(name, spriteName)
{
this.x = posX;
this.y = posY;
//this.poColObj.pColSprite.SetLineColor(0, 0, 1);
}
public override void Accept(ColVisitor other)
{
// Important: at this point we have an BirdColumn
// Call the appropriate collision reaction
other.VisitColumn(this);
}
public override void VisitMissileGroup(MissileGroup m)
{
// BirdColumn vs MissileGroup
Debug.WriteLine(" collide: {0} <-> {1}", m.name, this.name);
// MissileGroup vs Columns
GameObject pGameObj = (GameObject)Iterator.GetChild(this);
ColPair.Collide(m, pGameObj);
}
public override void Update()
{
base.BaseUpdateBoundingBox(this);
base.Update();
int bomb = random.Next(0, 1000);
Alien lowestAlien = null;
float lowestY = 5000.0f;
if(bomb == 1)
{
Alien pTemp = (Alien)this.poHead;
while(pTemp != null)
{
if(pTemp.y < lowestY)
{
lowestAlien = pTemp;
lowestY = lowestAlien.y;
}
pTemp = (Alien)pTemp.pNext;
}
// if lowest alien is null, then there are no aliens in this column
// if its not null, this is the lwoest alien, make it rain bombs
if(lowestAlien != null)
{
lowestAlien.DropBomb();
}
}
}
// Data
}
}
|
79b96fe358a4f1736e4d4367d2e56a2bb1d45176
|
C#
|
ualehosaini/NetFabric.Hyperlinq
|
/NetFabric.Hyperlinq.UnitTests/Element/ElementAt/ElementAt.ArraySegment.Tests.cs
| 2.625
| 3
|
using NetFabric.Assertive;
using System;
using System.Linq;
using Xunit;
namespace NetFabric.Hyperlinq.UnitTests.Element.ElementAt
{
public class ArraySegmentTests
{
[Fact]
public void ElementAt_With_NullArray_Must_Succeed()
{
// Arrange
var source = default(ArraySegment<int>);
// Act
var result = ArrayExtensions
.ElementAt(source, 0);
// Assert
_ = result.Must()
.BeOfType<Option<int>>()
.EvaluateTrue(option => option.IsNone);
}
[Theory]
[MemberData(nameof(TestData.SkipTakeEmpty), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.SkipTakeSingle), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.SkipTakeMultiple), MemberType = typeof(TestData))]
public void ElementAt_With_OutOfRange_Must_Return_None(int[] source, int skip, int take)
{
// Arrange
var (offset, count) = Utils.SkipTake(source.Length, skip, take);
var wrapped = new ArraySegment<int>(source, offset, count);
// Act
var optionTooSmall = ArrayExtensions
.ElementAt(wrapped, -1);
var optionTooLarge = ArrayExtensions
.ElementAt(wrapped, take);
// Assert
_ = optionTooSmall.Must()
.BeOfType<Option<int>>()
.EvaluateTrue(option => option.IsNone);
_ = optionTooLarge.Must()
.BeOfType<Option<int>>()
.EvaluateTrue(option => option.IsNone);
}
[Theory]
[MemberData(nameof(TestData.SkipTakeSingle), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.SkipTakeMultiple), MemberType = typeof(TestData))]
public void ElementAt_With_ValidData_Must_Return_Some(int[] source, int skip, int take)
{
// Arrange
var (offset, count) = Utils.SkipTake(source.Length, skip, take);
var wrapped = new ArraySegment<int>(source, offset, count);
var expected = Enumerable
.ToList(wrapped);
for (var index = 0; index < expected.Count; index++)
{
// Act
var result = ArrayExtensions
.ElementAt(wrapped, index);
// Assert
_ = result.Match(
value => value.Must().BeEqualTo(expected[index]),
() => throw new Exception());
}
}
[Theory]
[MemberData(nameof(TestData.SkipTakePredicateEmpty), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.SkipTakePredicateSingle), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.SkipTakePredicateMultiple), MemberType = typeof(TestData))]
public void ElementAt_Predicate_With_OutOfRange_Must_Return_None(int[] source, int skip, int take, Func<int, bool> predicate)
{
// Arrange
var wrapped = new ArraySegment<int>(source);
// Act
var optionTooSmall = ArrayExtensions
.Skip(wrapped, skip)
.Take(take)
.Where(predicate)
.ElementAt(-1);
var optionTooLarge = ArrayExtensions
.Skip(wrapped, skip)
.Take(take)
.Where(predicate)
.ElementAt(take);
// Assert
_ = optionTooSmall.Must()
.BeOfType<Option<int>>()
.EvaluateTrue(option => option.IsNone);
_ = optionTooLarge.Must()
.BeOfType<Option<int>>()
.EvaluateTrue(option => option.IsNone);
}
[Theory]
[MemberData(nameof(TestData.SkipTakePredicateSingle), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.SkipTakePredicateMultiple), MemberType = typeof(TestData))]
public void ElementAt_Predicate_With_ValidData_Must_Return_Some(int[] source, int skip, int take, Func<int, bool> predicate)
{
// Arrange
var wrapped = new ArraySegment<int>(source);
var expected = Enumerable
.Skip(source, skip)
.Take(take)
.Where(predicate)
.ToList();
for (var index = 0; index < expected.Count; index++)
{
// Act
var result = ArrayExtensions
.Skip(wrapped, skip)
.Take(take)
.Where(predicate)
.ElementAt(index);
// Assert
_ = result.Match(
value => value.Must().BeEqualTo(expected[index]),
() => throw new Exception());
}
}
[Theory]
[MemberData(nameof(TestData.SkipTakePredicateAtEmpty), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.SkipTakePredicateAtSingle), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.SkipTakePredicateAtMultiple), MemberType = typeof(TestData))]
public void ElementAt_PredicateAt_With_OutOfRange_Must_Return_None(int[] source, int skip, int take, Func<int, int, bool> predicate)
{
// Arrange
var wrapped = new ArraySegment<int>(source);
// Act
var optionTooSmall = ArrayExtensions
.Skip(wrapped, skip)
.Take(take)
.Where(predicate)
.ElementAt(-1);
var optionTooLarge = ArrayExtensions
.Skip(wrapped, skip)
.Take(take)
.Where(predicate)
.ElementAt(take);
// Assert
_ = optionTooSmall.Must()
.BeOfType<Option<int>>()
.EvaluateTrue(option => option.IsNone);
_ = optionTooLarge.Must()
.BeOfType<Option<int>>()
.EvaluateTrue(option => option.IsNone);
}
[Theory]
[MemberData(nameof(TestData.SkipTakePredicateAtSingle), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.SkipTakePredicateAtMultiple), MemberType = typeof(TestData))]
public void ElementAt_PredicateAt_With_ValidData_Must_Return_Some(int[] source, int skip, int take, Func<int, int, bool> predicate)
{
// Arrange
var wrapped = new ArraySegment<int>(source);
var expected = Enumerable
.Skip(source, skip)
.Take(take)
.Where(predicate)
.ToList();
for (var index = 0; index < expected.Count; index++)
{
// Act
var result = ArrayExtensions
.Skip(wrapped, skip)
.Take(take)
.Where(predicate)
.ElementAt(index);
// Assert
_ = result.Match(
value => value.Must().BeEqualTo(expected[index]),
() => throw new Exception());
}
}
[Theory]
[MemberData(nameof(TestData.SkipTakeSelectorEmpty), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.SkipTakeSelectorSingle), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.SkipTakeSelectorMultiple), MemberType = typeof(TestData))]
public void ElementAt_Selector_With_OutOfRange_Must_Return_None(int[] source, int skip, int take, Func<int, string> selector)
{
// Arrange
var wrapped = new ArraySegment<int>(source);
// Act
var optionTooSmall = ArrayExtensions
.Skip(wrapped, skip)
.Take(take)
.Select(selector)
.ElementAt(-1);
var optionTooLarge = ArrayExtensions
.Skip(wrapped, skip)
.Take(take)
.Select(selector)
.ElementAt(take);
// Assert
_ = optionTooSmall.Must()
.BeOfType<Option<string>>()
.EvaluateTrue(option => option.IsNone);
_ = optionTooLarge.Must()
.BeOfType<Option<string>>()
.EvaluateTrue(option => option.IsNone);
}
[Theory]
[MemberData(nameof(TestData.SkipTakeSelectorSingle), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.SkipTakeSelectorMultiple), MemberType = typeof(TestData))]
public void ElementAt_Selector_With_ValidData_Must_Return_Some(int[] source, int skip, int take, Func<int, string> selector)
{
// Arrange
var wrapped = new ArraySegment<int>(source);
var expected = Enumerable
.Skip(source, skip)
.Take(take)
.Select(selector)
.ToList();
for (var index = 0; index < expected.Count; index++)
{
// Act
var result = ArrayExtensions
.Skip(wrapped, skip)
.Take(take)
.Select(selector)
.ElementAt(index);
// Assert
_ = result.Match(
value => value.Must().BeEqualTo(expected[index]),
() => throw new Exception());
}
}
[Theory]
[MemberData(nameof(TestData.SkipTakeSelectorAtEmpty), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.SkipTakeSelectorAtSingle), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.SkipTakeSelectorAtMultiple), MemberType = typeof(TestData))]
public void ElementAt_SelectorAt_With_OutOfRange_Must_Return_None(int[] source, int skip, int take, Func<int, int, string> selector)
{
// Arrange
var wrapped = new ArraySegment<int>(source);
// Act
var optionTooSmall = ArrayExtensions
.Skip(wrapped, skip)
.Take(take)
.Select(selector)
.ElementAt(-1);
var optionTooLarge = ArrayExtensions
.Skip(wrapped, skip)
.Take(take)
.Select(selector)
.ElementAt(take);
// Assert
_ = optionTooSmall.Must()
.BeOfType<Option<string>>()
.EvaluateTrue(option => option.IsNone);
_ = optionTooLarge.Must()
.BeOfType<Option<string>>()
.EvaluateTrue(option => option.IsNone);
}
[Theory]
[MemberData(nameof(TestData.SkipTakeSelectorAtSingle), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.SkipTakeSelectorAtMultiple), MemberType = typeof(TestData))]
public void ElementAt_SelectorAt_With_ValidData_Must_Return_Some(int[] source, int skip, int take, Func<int, int, string> selector)
{
// Arrange
var wrapped = new ArraySegment<int>(source);
var expected = Enumerable
.Skip(source, skip)
.Take(take)
.Select(selector)
.ToList();
for (var index = 0; index < expected.Count; index++)
{
// Act
var result = ArrayExtensions
.Skip(wrapped, skip)
.Take(take)
.Select(selector)
.ElementAt(index);
// Assert
_ = result.Match(
value => value.Must().BeEqualTo(expected[index]),
() => throw new Exception());
}
}
[Theory]
[MemberData(nameof(TestData.SkipTakePredicateSelectorEmpty), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.SkipTakePredicateSelectorSingle), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.SkipTakePredicateSelectorMultiple), MemberType = typeof(TestData))]
public void ElementAt_Predicate_Selector_With_OutOfRange_Must_Return_None(int[] source, int skip, int take, Func<int, bool> predicate, Func<int, string> selector)
{
// Arrange
var wrapped = new ArraySegment<int>(source);
// Act
var optionTooSmall = ArrayExtensions
.Skip(wrapped, skip)
.Take(take)
.Where(predicate)
.Select(selector)
.ElementAt(-1);
var optionTooLarge = ArrayExtensions
.Skip(wrapped, skip)
.Take(take)
.Where(predicate)
.Select(selector)
.ElementAt(take);
// Assert
_ = optionTooSmall.Must()
.BeOfType<Option<string>>()
.EvaluateTrue(option => option.IsNone);
_ = optionTooLarge.Must()
.BeOfType<Option<string>>()
.EvaluateTrue(option => option.IsNone);
}
[Theory]
[MemberData(nameof(TestData.SkipTakePredicateSelectorSingle), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.SkipTakePredicateSelectorMultiple), MemberType = typeof(TestData))]
public void ElementAt_Predicate_Selector_With_ValidData_Must_Return_Some(int[] source, int skip, int take, Func<int, bool> predicate, Func<int, string> selector)
{
// Arrange
var wrapped = new ArraySegment<int>(source);
var expected = Enumerable
.Skip(source, skip)
.Take(take)
.Where(predicate)
.Select(selector)
.ToList();
for (var index = 0; index < expected.Count; index++)
{
// Act
var result = ArrayExtensions
.Skip(wrapped, skip)
.Take(take)
.Where(predicate)
.Select(selector)
.ElementAt(index);
// Assert
_ = result.Match(
value => value.Must().BeEqualTo(expected[index]),
() => throw new Exception());
}
}
}
}
|
804867d41e170dfd16ca9a55318a08959b959e7b
|
C#
|
DST-Tools/DSTEd-Publisher
|
/DSTEd Publisher/Actions/List.cs
| 2.9375
| 3
|
using System;
using System.Collections.Generic;
using DSTEd.Publisher.SteamWorkshop;
namespace DSTEd.Publisher.Actions {
class List : ActionClass {
public List() {
this.Name = "list";
this.Description = "Displays a list of all published Steam-WorkShop items.";
this.Arguments = "<Begin page (optional)>";
}
public override int Run(string[] arguments) {
uint page = 1;
if(!Steam.Start(Steam.APP_ID)) {
Console.WriteLine("Steam is not running...");
return -1;
}
if(arguments.Length >= 1) {
page = uint.Parse(arguments[0]);
}
Console.WriteLine("Page: " + page);
Steam.GetWorkShopItems(page, delegate(Steam.ExitCodes error, List<WorkshopItem> results, uint count, uint total) {
#if DEBUG
Console.WriteLine("Callback");
#endif
if (error != 0) {
Console.WriteLine($"Some UGC Error! (Code: {error}");
return;
}
Console.WriteLine($"You have published {total} mod(s) in total.\nThis is page {page} with {count} results (max. 50 per page)");
foreach(WorkshopItem entry in results) {
Console.WriteLine(entry.ToString());
}
// @ToDo create output
});
Steam.Stop();
return 0;
}
}
}
|
1aec5500d951dfb37ae7346f2fb9bf76cc60c919
|
C#
|
Ken0327/Leetcode
|
/src/Stack/20_ValidParentheses/ValidParentheses.cs
| 3.703125
| 4
|
/*
Runtime: 68 ms, faster than 98.42% of C# online submissions for Valid Parentheses.
Memory Usage: 37.5 MB, less than 39.06% of C# online submissions for Valid Parentheses.
*/
public class Solution {
public bool IsValid(string s) {
var stack = new Stack<char>();
for (var i = 0; i < s.Length; i++)
{
if (s[i] == '[' || s[i] == '(' || s[i] == '{')
stack.Push(s[i]);
else
{
if (stack.Count == 0){
return false;
}
else
{
if (s[i] == ']' && stack.Pop() != '[')
{
return false;
}
else if (s[i] == ')' && stack.Pop() != '(')
{
return false;
}
else if (s[i] == '}' && stack.Pop() != '{')
{
return false;
}
}
}
}
return stack.Count() == 0;
}
}
/*
Complexity Analysis
Time Complexity: O(n) , where n = len(s)
Space Complexity: O(n)
Stored n Rows of Stack.
*/
|
8d7bf3edd10994b8d72e40dd06e56c36f424ce1d
|
C#
|
hienmx95/utils-backend
|
/Utils/Entities/File.cs
| 2.734375
| 3
|
using Utils.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace Utils.Entities
{
public class File : DataEntity
{
public long Id { get; set; }
public string Key
{
get
{
using (SHA256 sha256Hash = SHA256.Create())
{
// ComputeHash - returns byte array
byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(Path));
// Convert byte array to a string
StringBuilder builder = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
builder.Append(bytes[i].ToString("x2"));
}
return builder.ToString();
}
}
}
public string Name { get; set; }
public byte[] Content { get; set; }
public string MimeType
{
get
{
FileInfo fileInfo = new FileInfo(Path);
if (fileInfo.Extension.ToLower() == ".jpg" || fileInfo.Extension.ToLower() == ".jpeg")
return "image/jpeg";
if (fileInfo.Extension.ToLower() == ".png")
return "image/png";
if (fileInfo.Extension.ToLower() == ".gif")
return "image/gif";
return "application/octet-stream";
}
}
public bool IsFile { get; set; }
public string Path { get; set; }
public long Level { get; set; }
public Guid RowId { get; set; }
public DateTime CreatedAt { get; set; }
}
public class FileFilter : FilterEntity
{
public IdFilter Id { get; set; }
public StringFilter Path { get; set; }
public LongFilter Level { get; set; }
public bool? IsFile { get; set; }
public FileOrder OrderBy { get; set; }
}
public enum FileOrder
{
Id = 1,
Path = 2,
Level = 3,
IsFile = 4,
}
}
|
11201e69708e3da7ce652023a50a5c647d1fc4f2
|
C#
|
afanner/Fanner-Furry-Friends
|
/DogStore/DSWebUI/Controllers/DogManagerController.cs
| 2.515625
| 3
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DSBL;
using DSWebUI.Models;
using Serilog;
namespace DSWebUI.Controllers
{
public class DogManagerController : Controller
{
private IManagerBL _managerBL;
public DogManagerController(IManagerBL managerBL)
{
_managerBL = managerBL;
}
// GET: DogManagerController
public ActionResult Index()
{
return View(_managerBL.GetAllManagers()
.Select(manager => new DogManagerVM(manager)).ToList());
}
// GET: DogManagerController/Details/5
public ActionResult Details(int id)
{
return View();
}
// GET: DogManagerController/Create
public ActionResult Create()
{
Log.Information("Sending user to Dog Manager View");
return View();
}
// POST: DogManagerController/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(DogManagerVM dogManagerVM)
{
try
{
if (ModelState.IsValid)
{
_managerBL.AddManager(new DSModels.DogManager
{
Name = dogManagerVM.Name,
Address = dogManagerVM.Address,
PhoneNumber = dogManagerVM.PhoneNumber
}
);
Log.Information("Added phone number with " + dogManagerVM.PhoneNumber.ToString());
return RedirectToAction(nameof(Index));
}
else return View();
}
catch
{
return View();
}
}
// GET: DogManagerController/Edit/5
public ActionResult Edit(int id)
{
return View();
}
// POST: DogManagerController/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, IFormCollection collection)
{
try
{
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
// GET: DogManagerController/Delete/5
public ActionResult Delete(int id)
{
return View();
}
// POST: DogManagerController/Delete/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id, IFormCollection collection)
{
try
{
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
}
}
|
64ccc8b6a699accdb518d9df556c9c99c6aaf6b7
|
C#
|
DanMannMann/Reflekt
|
/Marsman.Reflekt/Tree Enumerator/TreeEnumerableExtensions.cs
| 2.625
| 3
|
using System.Collections.Generic;
namespace Marsman.Reflekt
{
public static class TreeEnumerableExtensions
{
public static IEnumerable<Tvalue> AsTreeEnumerable<Tvalue>(this object rootObject,
TreeEnumerationStrategy enumerationStrategy,
TreeBranchingStrategy branchingStrategy,
int maxDepth = int.MaxValue,
params Filter[] filters)
{
return new TreeEnumerable<Tvalue>(rootObject, branchingStrategy, enumerationStrategy, maxDepth, filters);
}
public static IEnumerable<Tvalue> AsTreeEnumerable<Tvalue>(this object rootObject,
int maxDepth = int.MaxValue,
params Filter[] filters) =>
AsTreeEnumerable<Tvalue>(rootObject,
TreeEnumerationStrategy.DepthFirst,
TreeBranchingStrategy.AllProperties,
maxDepth,
filters);
public static IEnumerable<Tvalue> AsTreeEnumerable<Tvalue>(this object rootObject,
TreeEnumerationStrategy enumerationStrategy,
int maxDepth = int.MaxValue,
params Filter[] filters) =>
AsTreeEnumerable<Tvalue>(rootObject,
enumerationStrategy,
TreeBranchingStrategy.AllProperties,
maxDepth,
filters);
public static IEnumerable<Tvalue> AsTreeEnumerable<Tvalue>(this object rootObject,
TreeBranchingStrategy branchingStrategy,
int maxDepth = int.MaxValue,
params Filter[] filters) =>
AsTreeEnumerable<Tvalue>(rootObject,
TreeEnumerationStrategy.DepthFirst,
branchingStrategy,
maxDepth,
filters);
public static IEnumerable<TreeEnumerationContext<Tvalue>> AsTreeEnumerableWithContext<Tvalue>(this object rootObject,
TreeEnumerationStrategy enumerationStrategy,
TreeBranchingStrategy branchingStrategy,
int maxDepth = int.MaxValue,
params Filter[] filters)
{
return new ContextualTreeEnumerable<Tvalue>(rootObject, branchingStrategy, enumerationStrategy, maxDepth, filters);
}
public static IEnumerable<TreeEnumerationContext<Tvalue>> AsTreeEnumerableWithContext<Tvalue>(this object rootObject,
int maxDepth = int.MaxValue,
params Filter[] filters) =>
AsTreeEnumerableWithContext<Tvalue>(rootObject,
TreeEnumerationStrategy.DepthFirst,
TreeBranchingStrategy.AllProperties,
maxDepth,
filters);
public static IEnumerable<TreeEnumerationContext<Tvalue>> AsTreeEnumerableWithContext<Tvalue>(this object rootObject,
TreeEnumerationStrategy enumerationStrategy,
int maxDepth = int.MaxValue,
params Filter[] filters) =>
AsTreeEnumerableWithContext<Tvalue>(rootObject,
enumerationStrategy,
TreeBranchingStrategy.AllProperties,
maxDepth,
filters);
public static IEnumerable<TreeEnumerationContext<Tvalue>> AsTreeEnumerableWithContext<Tvalue>(this object rootObject,
TreeBranchingStrategy branchingStrategy,
int maxDepth = int.MaxValue,
params Filter[] filters) =>
AsTreeEnumerableWithContext<Tvalue>(rootObject,
TreeEnumerationStrategy.DepthFirst,
branchingStrategy,
maxDepth,
filters);
public static IEnumerable<Tvalue> AsTreeEnumerable<Tvalue>(this object rootObject,
TreeEnumerationStrategy enumerationStrategy,
TreeBranchingStrategy branchingStrategy,
params Filter[] filters)
{
return new TreeEnumerable<Tvalue>(rootObject, branchingStrategy, enumerationStrategy, int.MaxValue, filters);
}
public static IEnumerable<Tvalue> AsTreeEnumerable<Tvalue>(this object rootObject,
params Filter[] filters) =>
AsTreeEnumerable<Tvalue>(rootObject,
TreeEnumerationStrategy.DepthFirst,
TreeBranchingStrategy.AllProperties,
filters);
public static IEnumerable<Tvalue> AsTreeEnumerable<Tvalue>(this object rootObject,
TreeEnumerationStrategy enumerationStrategy,
params Filter[] filters) =>
AsTreeEnumerable<Tvalue>(rootObject,
enumerationStrategy,
TreeBranchingStrategy.AllProperties,
filters);
public static IEnumerable<Tvalue> AsTreeEnumerable<Tvalue>(this object rootObject,
TreeBranchingStrategy branchingStrategy,
params Filter[] filters) =>
AsTreeEnumerable<Tvalue>(rootObject,
TreeEnumerationStrategy.DepthFirst,
branchingStrategy,
filters);
public static IEnumerable<TreeEnumerationContext<Tvalue>> AsTreeEnumerableWithContext<Tvalue>(this object rootObject,
TreeEnumerationStrategy enumerationStrategy,
TreeBranchingStrategy branchingStrategy,
params Filter[] filters)
{
return new ContextualTreeEnumerable<Tvalue>(rootObject, branchingStrategy, enumerationStrategy, int.MaxValue, filters);
}
public static IEnumerable<TreeEnumerationContext<Tvalue>> AsTreeEnumerableWithContext<Tvalue>(this object rootObject,
params Filter[] filters) =>
AsTreeEnumerableWithContext<Tvalue>(rootObject,
TreeEnumerationStrategy.DepthFirst,
TreeBranchingStrategy.AllProperties,
int.MaxValue,
filters);
public static IEnumerable<TreeEnumerationContext<Tvalue>> AsTreeEnumerableWithContext<Tvalue>(this object rootObject,
TreeEnumerationStrategy enumerationStrategy,
params Filter[] filters) =>
AsTreeEnumerableWithContext<Tvalue>(rootObject,
enumerationStrategy,
TreeBranchingStrategy.AllProperties,
int.MaxValue,
filters);
public static IEnumerable<TreeEnumerationContext<Tvalue>> AsTreeEnumerableWithContext<Tvalue>(this object rootObject,
TreeBranchingStrategy branchingStrategy,
params Filter[] filters) =>
AsTreeEnumerableWithContext<Tvalue>(rootObject,
TreeEnumerationStrategy.DepthFirst,
branchingStrategy,
int.MaxValue,
filters);
}
}
|
9ac462a096aa2418dee09faf29f7ee5f114cf4a4
|
C#
|
MattHoneycutt/SpecsFor
|
/SpecsFor.Core/ShouldExtensions/Matcher.cs
| 2.84375
| 3
|
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace SpecsFor.Core.ShouldExtensions
{
public class Matcher
{
[ThreadStatic]
public static Matcher LastMatcher;
public static void Create<T>(Expression<Func<T, bool>> matcher, string message)
{
LastMatcher = new Matcher<T>(matcher, message);
}
}
public class Matcher<T> : Matcher
{
private readonly Expression<Func<T, bool>> _matcher;
private readonly string _message;
public Matcher(Expression<Func<T, bool>> matcher, string message)
{
_matcher = matcher ?? (x => true);
_message = message;
}
public override bool Equals(object obj)
{
if (!ObjectIsCompatibleWithType(obj))
{
return false;
}
var matcher = _matcher.Compile();
return matcher((T)obj);
}
protected bool Equals(Matcher<T> other)
{
return Equals(_matcher, other._matcher) && string.Equals(_message, other._message);
}
public override int GetHashCode()
{
unchecked
{
return ((_matcher != null ? _matcher.GetHashCode() : 0) * 397) ^ (_message != null ? _message.GetHashCode() : 0);
}
}
private static bool ObjectIsCompatibleWithType(object obj)
{
if (obj is T || obj == null) return true;
if (IsNullable(typeof(T)) && GetInnerTypeFromNullable(typeof(T)) == obj.GetType())
return true;
return false;
}
public override string ToString()
{
return _message;
}
// From https://github.com/structuremap/structuremap/blob/master/src/StructureMap/TypeExtensions.cs
private static bool IsNullable(Type type)
{
return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
}
private static Type GetInnerTypeFromNullable(Type nullableType)
{
return nullableType.GetGenericArguments()[0];
}
}
}
|
c89a3ee99ee322d00d117ccf8573b43ddc83805a
|
C#
|
brchho/ELEC-371-proj
|
/brian/GUIElements.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
namespace cam_aforge1
{
class GUIElements
{
//Important Variables:
//DO NOT CHANGE UNLESS YOU KNOW WHAT YOU'RE DOING
GUI gui;
public Graphics g;
//This is where you can declare variables that you will be changing as the Run()
//method executes.
//Step 0: To try out the sample code, uncomment all the variables from line 21-27
int circleX1 = 50;
int circleY1 = 50;
public int squareX1;
public int squareY1;
public int squareX1_2 = 100;
public int squareY1_2 = 100;
int speed = 5;
bool cirDir = true;
bool sqrDir = true;
long scansizeincrement = 2;
long scansizeincrement_2 = 2;
int range = 15;
int counter = 0;
public int start_pixel_flag = 1;
//End Variable declaration.
//Main constructor of this class
public GUIElements(GUI _gui)
{
this.gui = _gui;
}
//This function runs every frame
public void Run(int r, int G, int b, Bitmap img, int begin_r, int begin_r_2, int begin_G, int begin_G_2, int begin_b, int begin_b_2)
{
Square sqr = new Square(Color.Blue, 4, squareX1, squareY1, 100);
Square sqr_2 = new Square(Color.Red, 4, squareX1_2, squareY1_2, 100);
//Step 6: Now let's display text on the screen. Uncomment lines 115-116.
Text count = new Text("Count: " + counter.ToString(), Color.Red, 300, 0, 35);
count.Draw(g);
// DAG YO
stayontrack();
stayontrack_2();
void stayontrack()
{
if ((squareX1) > 5 && (squareY1 + 50) <= 410)
{
if ((change_panel_color(img, 1) > (begin_r+range) || change_panel_color(img, 1) < (begin_r - range)) || (change_panel_color(img, 2) > (begin_G + range) || change_panel_color(img, 2) < (begin_G - range)) || (change_panel_color(img, 3) > (begin_b + range) || change_panel_color(img, 3) < (begin_b - range)))
{
squareY1 = squareY1 + 2;
squareX1 = squareX1 - 2;
sqr.x1 = squareX1;
sqr.y1 = squareY1;
//sqr.Draw(g);
}
else
{
scansizeincrement = 2;
sqr.Draw(g);
return;
}
}
for (long i = 0; i < scansizeincrement; i++)
{
if ((squareY1) > 5)
{
if ((change_panel_color(img, 1) > (begin_r + range) || change_panel_color(img, 1) < (begin_r - range)) || (change_panel_color(img, 2) > (begin_G + range) || change_panel_color(img, 2) < (begin_G - range)) || (change_panel_color(img, 3) > (begin_b + range) || change_panel_color(img, 3) < (begin_b - range)))
{
squareY1 = squareY1 - 3;
squareX1 = squareX1;
sqr.x1 = squareX1;
sqr.y1 = squareY1;
//sqr.Draw(g);
}
else
{
scansizeincrement = 2;
return;
}
}
}
for (long i = 0; i < scansizeincrement; i++)
{
if ((squareX1 + 50) <= 560)
{
if ((change_panel_color(img, 1) > (begin_r + range) || change_panel_color(img, 1) < (begin_r - range)) || (change_panel_color(img, 2) > (begin_G + range) || change_panel_color(img, 2) < (begin_G - range)) || (change_panel_color(img, 3) > (begin_b + range) || change_panel_color(img, 3) < (begin_b - range)))
{
squareY1 = squareY1;
squareX1 = squareX1 + 3;
sqr.x1 = squareX1;
sqr.y1 = squareY1;
//sqr.Draw(g);
}
else
{
scansizeincrement = 2;
return;
}
}
}
for (long i = 0; i < scansizeincrement; i++)
{
if ((squareY1 + 50) <= 410)
{
if ((change_panel_color(img, 1) > (begin_r + range) || change_panel_color(img, 1) < (begin_r - range)) || (change_panel_color(img, 2) > (begin_G + range) || change_panel_color(img, 2) < (begin_G - range)) || (change_panel_color(img, 3) > (begin_b + range) || change_panel_color(img, 3) < (begin_b - range)))
{
squareY1 = squareY1 + 3;
squareX1 = squareX1;
sqr.x1 = squareX1;
sqr.y1 = squareY1;
//sqr.Draw(g);
}
else
{
scansizeincrement = 2;
return;
}
}
}
for (long i = 0; i < scansizeincrement; i++)
{
if ((squareX1) > 5)
{
if ((change_panel_color(img, 1) > (begin_r + range) || change_panel_color(img, 1) < (begin_r - range)) || (change_panel_color(img, 2) > (begin_G + range) || change_panel_color(img, 2) < (begin_G - range)) || (change_panel_color(img, 3) > (begin_b + range) || change_panel_color(img, 3) < (begin_b - range)))
{
squareY1 = squareY1;
squareX1 = squareX1 - 3;
sqr.x1 = squareX1;
sqr.y1 = squareY1;
//sqr.Draw(g);
}
else
{
scansizeincrement = 2;
return;
}
}
}
scansizeincrement = scansizeincrement + 2;
}
void stayontrack_2()
{
if ((squareX1_2) > 5 && (squareY1_2 + 50) <= 410)
{
if ((change_panel_color_2(img, 1) > (begin_r_2 + range) || change_panel_color_2(img, 1) < (begin_r_2 - range)) || (change_panel_color_2(img, 2) > (begin_G_2 + range) || change_panel_color_2(img, 2) < (begin_G_2 - range)) || (change_panel_color_2(img, 3) > (begin_b_2 + range) || change_panel_color_2(img, 3) < (begin_b_2 - range)))
{
squareY1_2 = squareY1_2 + 2;
squareX1_2 = squareX1_2 - 2;
sqr_2.x1 = squareX1_2;
sqr_2.y1 = squareY1_2;
//sqr_2.Draw(g);
}
else
{
scansizeincrement_2 = 2;
sqr_2.Draw(g);
return;
}
}
for (long i = 0; i < scansizeincrement_2; i++)
{
if ((squareY1_2) > 5)
{
if ((change_panel_color_2(img, 1) > (begin_r_2 + range) || change_panel_color_2(img, 1) < (begin_r_2 - range)) || (change_panel_color_2(img, 2) > (begin_G_2 + range) || change_panel_color_2(img, 2) < (begin_G_2 - range)) || (change_panel_color_2(img, 3) > (begin_b_2 + range) || change_panel_color_2(img, 3) < (begin_b_2 - range)))
{
squareY1_2 = squareY1_2 - 3;
squareX1_2 = squareX1_2;
sqr_2.x1 = squareX1_2;
sqr_2.y1 = squareY1_2;
//sqr_2.Draw(g);
}
else
{
scansizeincrement_2 = 2;
return;
}
}
}
for (long i = 0; i < scansizeincrement_2; i++)
{
if ((squareX1_2 + 50) <= 560)
{
if ((change_panel_color_2(img, 1) > (begin_r_2 + range) || change_panel_color_2(img, 1) < (begin_r_2 - range)) || (change_panel_color_2(img, 2) > (begin_G_2 + range) || change_panel_color_2(img, 2) < (begin_G_2 - range)) || (change_panel_color_2(img, 3) > (begin_b_2 + range) || change_panel_color_2(img, 3) < (begin_b_2 - range)))
{
squareY1_2 = squareY1_2;
squareX1_2 = squareX1_2 + 3;
sqr_2.x1 = squareX1_2;
sqr_2.y1 = squareY1_2;
//sqr_2.Draw(g);
}
else
{
scansizeincrement_2 = 2;
return;
}
}
}
for (long i = 0; i < scansizeincrement_2; i++)
{
if ((squareY1_2 + 50) <= 410)
{
if ((change_panel_color_2(img, 1) > (begin_r_2 + range) || change_panel_color_2(img, 1) < (begin_r_2 - range)) || (change_panel_color_2(img, 2) > (begin_G_2 + range) || change_panel_color_2(img, 2) < (begin_G_2 - range)) || (change_panel_color_2(img, 3) > (begin_b_2 + range) || change_panel_color_2(img, 3) < (begin_b_2 - range)))
{
squareY1_2 = squareY1_2 + 3;
squareX1_2 = squareX1_2;
sqr_2.x1 = squareX1_2;
sqr_2.y1 = squareY1_2;
//sqr_2.Draw(g);
}
else
{
scansizeincrement_2 = 2;
return;
}
}
}
for (long i = 0; i < scansizeincrement_2; i++)
{
if ((squareX1_2) > 5)
{
if ((change_panel_color_2(img, 1) > (begin_r_2 + range) || change_panel_color_2(img, 1) < (begin_r_2 - range)) || (change_panel_color_2(img, 2) > (begin_G_2 + range) || change_panel_color_2(img, 2) < (begin_G_2 - range)) || (change_panel_color_2(img, 3) > (begin_b_2 + range) || change_panel_color_2(img, 3) < (begin_b_2 - range)))
{
squareY1_2 = squareY1_2;
squareX1_2 = squareX1_2 - 3;
sqr_2.x1 = squareX1_2;
sqr_2.y1 = squareY1_2;
//sqr_2.Draw(g);
}
else
{
scansizeincrement_2 = 2;
return;
}
}
}
scansizeincrement_2 = scansizeincrement_2 + 2;
}
//Console.WriteLine(change_panel_color_2(img, 1) + " " + change_panel_color_2(img, 2) + " " + change_panel_color_2(img, 3)+ " " + begin_r + " " + begin_G + " " + begin_b + " " + begin_r_2 + " " + begin_G_2 + " " + begin_b_2);
}
public int change_panel_color(Bitmap img, int sel)
{
int X1 = squareX1;
int Y1 = squareY1;
//int square = squareSize;
//int count = 0;
int r = 0;
int G = 0;
int b = 0;
Color pixelColor = img.GetPixel(X1+50, Y1+50);
r += pixelColor.R;
G += pixelColor.G;
b += pixelColor.B;
if (sel == 1)
{
return r;
}
else if (sel == 2)
{
return G;
}
else if (sel == 3)
{
return b;
}
else
{
return 0;
}
}
public int change_panel_color_2(Bitmap img, int sel)
{
int X1_2 = squareX1_2;
int Y1_2 = squareY1_2;
//int square = squareSize;
//int count = 0;
int r_2 = 0;
int G_2 = 0;
int b_2 = 0;
Color pixelColor = img.GetPixel(X1_2 + 50, Y1_2 + 50);
r_2 += pixelColor.R;
G_2 += pixelColor.G;
b_2 += pixelColor.B;
if (sel == 1)
{
return r_2;
}
else if (sel == 2)
{
return G_2;
}
else if (sel == 3)
{
return b_2;
}
else
{
return 0;
}
}
//Below is Sample Code on how to implement a button
public void ButtonWasClicked()
{
//Step 8 on GUI.cs will enable this code
counter++;
}
}
}
|
8c6b821fece1a803c0c05b4e3be25d5b8a66baed
|
C#
|
jelias7/EjerciciosLibroCSharp
|
/Tarea1/Capitulo4/Cap4Ejercicio1.cs
| 3.390625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace CSharpEjercicios1
{
class Cap4Ejercicio1
{
static void Main(string[] args)
{
int numero, resultado;
Console.WriteLine("Numero que se le mostrara la tabla del 1 al 10 ");
numero = int.Parse(Console.ReadLine());
for (int i=0; i<11; i++)
{
resultado = numero*i;
Console.WriteLine(numero + "*" + i + "=" + resultado);
}
Console.Read();
}
}
}
|
a9b2ff1319796075f1c18167c0febb9bf03f12fe
|
C#
|
pusher/pusher-http-dotnet
|
/PusherServer.Tests/UnitTests/PusherOptions.cs
| 2.53125
| 3
|
using NSubstitute;
using NUnit.Framework;
using PusherServer.Tests.Helpers;
using System;
namespace PusherServer.Tests.UnitTests
{
[TestFixture]
public class When_creating_a_new_PusherOptions_instance
{
[Test]
public void a_default_RestClient_should_be_used_if_one_is_not_set_on_PusherOptions_parameter()
{
var options = new PusherOptions();
Assert.IsNotNull(options.RestClient);
}
[Test]
public void Port_defaults_to_80()
{
var options = new PusherOptions();
Assert.AreEqual(80, options.Port);
}
[Test]
public void when_Encrypted_option_is_set_Port_is_changed_to_443()
{
var options = new PusherOptions() { Encrypted = true };
Assert.AreEqual(443, options.Port);
}
[Test]
public void when_Encrypted_option_is_set_Port_is_changed_to_443_unless_Port_has_already_been_modified()
{
var options = new PusherOptions() { Port = 90 };
options.Encrypted = true;
Assert.AreEqual(90, options.Port);
}
[Test]
public void the_default_options_should_be_used_to_create_the_base_url_when_no_settings_are_changed()
{
var options = new PusherOptions();
StringAssert.IsMatch("http://api.pusherapp.com", options.GetBaseUrl().AbsoluteUri);
}
[Test]
public void the_default_cluster_is_null()
{
var options = new PusherOptions();
Assert.AreEqual(null, options.Cluster);
}
[Test]
public void the_default_encrypted_options_should_be_used_to_create_the_base_url_when_encrypted_is_true()
{
var options = new PusherOptions();
options.Encrypted = true;
StringAssert.IsMatch("https://api.pusherapp.com", options.GetBaseUrl().AbsoluteUri);
}
[Test]
public void the_new_cluster_should_be_used_to_create_the_base_url()
{
var options= new PusherOptions();
options.Cluster = "eu";
StringAssert.IsMatch("http://api-eu.pusher.com", options.GetBaseUrl().AbsoluteUri);
}
[Test]
public void the_new_port_should_be_used_to_create_the_base_url()
{
var options = new PusherOptions();
options.Port = 100;
StringAssert.IsMatch("http://api.pusherapp.com:100", options.GetBaseUrl().AbsoluteUri);
}
[Test]
public void the_new_port_should_be_used_to_create_the_base_url_when_its_encrypted()
{
var options = new PusherOptions();
options.Encrypted = true;
options.Port = 100;
StringAssert.IsMatch("https://api.pusherapp.com:100", options.GetBaseUrl().AbsoluteUri);
}
[Test]
public void the_new_cluster_should_be_used_to_create_the_base_url_when_its_encrypted_and_has_a_custom_port()
{
var options = new PusherOptions();
options.Encrypted = true;
options.Cluster = "eu";
options.Port = 100;
StringAssert.IsMatch("https://api-eu.pusher.com:100", options.GetBaseUrl().AbsoluteUri);
}
[Test]
public void the_cluster_should_be_ignored_when_host_name_is_set_first()
{
var options = new PusherOptions();
options.HostName = "api.my.domain.com";
options.Cluster = "eu";
StringAssert.IsMatch("http://api.my.domain.com", options.GetBaseUrl().AbsoluteUri);
Assert.AreEqual(null, options.Cluster);
}
[Test]
public void the_cluster_should_be_ignored_when_host_name_is_set_after()
{
var options = new PusherOptions();
options.Cluster = "eu";
StringAssert.IsMatch("http://api-eu.pusher.com", options.GetBaseUrl().AbsoluteUri);
options.HostName = "api.my.domain.com";
StringAssert.IsMatch("http://api.my.domain.com", options.GetBaseUrl().AbsoluteUri);
Assert.AreEqual(null, options.Cluster);
}
[Test]
[ExpectedException(typeof(FormatException))]
public void https_scheme_is_not_allowed_when_setting_host()
{
var httpsOptions = new PusherOptions();
httpsOptions.HostName = "https://api.pusherapp.com";
}
[Test]
[ExpectedException(typeof(FormatException))]
public void http_scheme_is_not_allowed_when_setting_host()
{
var httpsOptions = new PusherOptions();
httpsOptions.HostName = "http://api.pusherapp.com";
}
[Test]
[ExpectedException(typeof(FormatException))]
public void ftp_scheme_is_not_allowed_when_setting_host()
{
var httpsOptions = new PusherOptions();
httpsOptions.HostName = "ftp://api.pusherapp.com";
}
[Test]
public void the_json_deserialiser_should_be_the_default_one_when_none_is_set()
{
var options = new PusherOptions();
Assert.IsInstanceOf<DefaultDeserializer>(options.JsonDeserializer);
}
[Test]
public void the_json_deserialiser_should_be_the_supplied_one_when_set()
{
var options = new PusherOptions();
options.JsonDeserializer = new FakeDeserialiser();
Assert.IsInstanceOf<FakeDeserialiser>(options.JsonDeserializer);
}
[Test]
public void the_json_deserialiser_should_be_the_supplied_one_when_set_with_a_custom_and_the_set_to_null()
{
var options = new PusherOptions();
options.JsonDeserializer = new FakeDeserialiser();
options.JsonDeserializer = null;
Assert.IsInstanceOf<DefaultDeserializer>(options.JsonDeserializer);
}
[Test]
public void the_json_serialiser_should_be_the_default_one_when_none_is_set()
{
var options = new PusherOptions();
Assert.IsInstanceOf<DefaultSerializer>(options.JsonSerializer);
}
[Test]
public void the_json_serialiser_should_be_the_supplied_one_when_set()
{
var options = new PusherOptions();
options.JsonSerializer = new FakeSerialiser();
Assert.IsInstanceOf<FakeSerialiser>(options.JsonSerializer);
}
[Test]
public void the_json_serialiser_should_be_the_default_one_when_set_with_a_custom_and_the_set_to_null()
{
var options = new PusherOptions();
options.JsonSerializer = new FakeSerialiser();
options.JsonSerializer = null;
Assert.IsInstanceOf<DefaultSerializer>(options.JsonSerializer);
}
private class FakeDeserialiser : IDeserializeJsonStrings
{
public T Deserialize<T>(string stringToDeserialize)
{
throw new NotImplementedException();
}
}
private class FakeSerialiser : ISerializeObjectsToJson
{
public string Serialize(object objectToSerialize)
{
throw new NotImplementedException();
}
}
}
}
|
d1d30524c304bfb0d104da9cf2b2421e9368c6b7
|
C#
|
Dchan21/WebAppWood
|
/WebAppWood/Models/ModelOtherWood.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace WebAppWood.Models
{
public class ModelOtherWood
{
public int id { get; set; }
public int Vendedor { get; set; }
public DateTime FechaIngreso { get; set; }
public string Nombre { get; set; }
public string Cedula { get; set; }
public string Codigo { get; set; }
public int Consecutivo { get; set; }
public double LargosMetros { get; set; }
public string Talla { get; set; }
public double Hoppus { get; set; }
public double Girth { get; set; }
public int Tipo { get; set; }
public List<ModelOtherWood> ListaOtros { get; set; }
SqlConnection connection = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
public void CreateTroza(ModelOtherWood troza)
{
SqlCommand ins = new SqlCommand();
ins.CommandText = "INSERT INTO dbo.TrozaOtros(Vendedor,Consecutivo,Codigo,FechaIngreso,LargosMetros,Talla,Hoppus,Girth,Tipo)" +
"VALUES(@Vendedor,@Consecutivo,@Codigo,@FechaIngreso,@LargosMetros,@Talla,@Hoppus,@Girth,@Tipo)";
ins.Parameters.AddWithValue("@Vendedor", troza.Vendedor);
ins.Parameters.AddWithValue("@Consecutivo", troza.Consecutivo);
ins.Parameters.AddWithValue("@Codigo", troza.Codigo);
ins.Parameters.AddWithValue("@FechaIngreso", troza.FechaIngreso);
ins.Parameters.AddWithValue("@LargosMetros", troza.LargosMetros);
ins.Parameters.AddWithValue("@Talla", troza.Talla);
ins.Parameters.AddWithValue("@Hoppus", troza.Hoppus);
ins.Parameters.AddWithValue("@Girth", troza.Girth);
ins.Parameters.AddWithValue("@Tipo", troza.Tipo);
ins.Connection = connection;
connection.Open();
ins.ExecuteNonQuery();
connection.Close();
}
public ModelOtherWood TrozasDetails(int id)
{
ModelOtherWood troza = new ModelOtherWood();
SqlCommand sel = new SqlCommand("Select * from dbo.TrozaOtros where Id=@Id");
sel.Parameters.AddWithValue("@Id", id);
sel.Connection = connection;
connection.Open();
SqlDataReader read = sel.ExecuteReader();
if (read.HasRows)
{
while (read.Read())
{
troza.id = Convert.ToInt32(read["id"]);
troza.Vendedor = Convert.ToInt32(read["Vendedor"]);
troza.Consecutivo = Convert.ToInt32(read["Consecutivo"]);
troza.Codigo = (read["Codigo"]).ToString();
troza.FechaIngreso = Convert.ToDateTime(read["FechaIngreso"]);
troza.LargosMetros = Convert.ToDouble(read["LargosMetros"]);
troza.Talla = Convert.ToDouble(read["Talla"]).ToString() ;
troza.Hoppus = Convert.ToDouble(read["Hoppus"]);
troza.Girth = Convert.ToDouble(read["Girth"]);
}
}
connection.Close();
return troza;
}
public void EditTroza(ModelOtherWood troza)
{
SqlCommand ins = new SqlCommand();
ins.CommandText = "UPDATE dbo.TrozaOtros SET id = @id ,Vendedor = @Vendedor ,Consecutivo = @Consecutivo ,Codigo = @Codigo ,FechaIngreso = @FechaIngreso ,"+
"LargosMetros = @LargosMetros ,Talla = @Talla ,Hoppus = @Hoppus ,Girth = @Girth WHERE id = @id";
ins.Parameters.AddWithValue("@id", troza.id);
ins.Parameters.AddWithValue("@Vendedor", troza.Vendedor);
ins.Parameters.AddWithValue("@Consecutivo", troza.Consecutivo);
ins.Parameters.AddWithValue("@Codigo", troza.Codigo);
ins.Parameters.AddWithValue("@FechaIngreso", troza.FechaIngreso);
ins.Parameters.AddWithValue("@LargosMetros", troza.LargosMetros);
ins.Parameters.AddWithValue("@Talla", troza.Talla);
ins.Parameters.AddWithValue("@Hoppus", troza.Hoppus);
ins.Parameters.AddWithValue("@Girth", troza.Girth);
ins.Connection = connection;
connection.Open();
ins.ExecuteNonQuery();
connection.Close();
}
public List<ModelOtherWood> ListTrozasGMelina()
{
List<ModelOtherWood> List = new List<ModelOtherWood>();
SqlCommand sel = new SqlCommand("Select * from dbo.TrozaOtros where Tipo=2");
sel.Connection = connection;
connection.Open();
SqlDataReader read = sel.ExecuteReader();
if (read.HasRows)
{
while (read.Read())
{
List.Add(new ModelOtherWood
{
id = Convert.ToInt32(read["id"]),
Codigo = (read["Codigo"]).ToString(),
Consecutivo = Convert.ToInt32(read["Consecutivo"]),
Tipo = Convert.ToInt32(read["Tipo"]),
LargosMetros = Convert.ToDouble(read["LargosMetros"]),
Hoppus = Convert.ToDouble(read["Hoppus"]),
Girth = Convert.ToDouble(read["Girth"]),
Talla = read["Talla"].ToString(),
FechaIngreso = Convert.ToDateTime(read["FechaIngreso"])
});
}
}
connection.Close();
return List;
}
public List<ModelOtherWood> ListTrozasPino()
{
List<ModelOtherWood> List = new List<ModelOtherWood>();
SqlCommand sel = new SqlCommand("Select * from dbo.TrozaOtros where Tipo=3");
sel.Connection = connection;
connection.Open();
SqlDataReader read = sel.ExecuteReader();
if (read.HasRows)
{
while (read.Read())
{
List.Add(new ModelOtherWood
{
id = Convert.ToInt32(read["id"]),
Codigo = (read["Codigo"]).ToString(),
Consecutivo = Convert.ToInt32(read["Consecutivo"]),
Tipo = Convert.ToInt32(read["Tipo"]),
LargosMetros = Convert.ToDouble(read["LargosMetros"]),
Hoppus = Convert.ToDouble(read["Hoppus"]),
Girth = Convert.ToDouble(read["Girth"]),
Talla = read["Talla"].ToString(),
FechaIngreso = Convert.ToDateTime(read["FechaIngreso"])
});
}
}
connection.Close();
return List;
}
public List<ModelOtherWood> ListTrozasTeca()
{
List<ModelOtherWood> List = new List<ModelOtherWood>();
SqlCommand sel = new SqlCommand("Select * from dbo.TrozaOtros where Tipo=4");
sel.Connection = connection;
connection.Open();
SqlDataReader read = sel.ExecuteReader();
if (read.HasRows)
{
while (read.Read())
{
List.Add(new ModelOtherWood
{
id = Convert.ToInt32(read["id"]),
Codigo = (read["Codigo"]).ToString(),
Consecutivo = Convert.ToInt32(read["Consecutivo"]),
Tipo = Convert.ToInt32(read["Tipo"]),
LargosMetros = Convert.ToDouble(read["LargosMetros"]),
Hoppus = Convert.ToDouble(read["Hoppus"]),
Girth = Convert.ToDouble(read["Girth"]),
Talla = read["Talla"].ToString(),
FechaIngreso = Convert.ToDateTime(read["FechaIngreso"])
});
}
}
connection.Close();
return List;
}
public List<ModelOtherWood> ListaTecaUltima()
{
List<ModelOtherWood> List = new List<ModelOtherWood>();
SqlCommand sel = new SqlCommand("Select* from dbo.TrozaOtros tc " +
"inner join(select max(FechaIngreso) as MaxDate from TrozaOtros t where t.Tipo=4) tm on tc.FechaIngreso = tm.MaxDate where tc.Tipo=4");
sel.Connection = connection;
connection.Open();
SqlDataReader read = sel.ExecuteReader();
if (read.HasRows)
{
while (read.Read())
{
List.Add(new ModelOtherWood
{
id = Convert.ToInt32(read["id"]),
Codigo = (read["Codigo"]).ToString(),
Consecutivo = Convert.ToInt32(read["Consecutivo"]),
Tipo = Convert.ToInt32(read["Tipo"]),
LargosMetros = Convert.ToDouble(read["LargosMetros"]),
Hoppus = Convert.ToDouble(read["Hoppus"]),
Girth = Convert.ToDouble(read["Girth"]),
Talla = read["Talla"].ToString(),
FechaIngreso = Convert.ToDateTime(read["FechaIngreso"])
});
}
}
connection.Close();
return List;
}
public List<ModelOtherWood> ListaPinoUltima()
{
List<ModelOtherWood> List = new List<ModelOtherWood>();
SqlCommand sel = new SqlCommand("Select* from dbo.TrozaOtros tc " +
"inner join(select max(FechaIngreso) as MaxDate from TrozaOtros t where t.Tipo=3) tm on tc.FechaIngreso = tm.MaxDate where tc.Tipo=3");
sel.Connection = connection;
connection.Open();
SqlDataReader read = sel.ExecuteReader();
if (read.HasRows)
{
while (read.Read())
{
List.Add(new ModelOtherWood
{
id = Convert.ToInt32(read["id"]),
Codigo = (read["Codigo"]).ToString(),
Consecutivo = Convert.ToInt32(read["Consecutivo"]),
Tipo = Convert.ToInt32(read["Tipo"]),
LargosMetros = Convert.ToDouble(read["LargosMetros"]),
Hoppus = Convert.ToDouble(read["Hoppus"]),
Girth = Convert.ToDouble(read["Girth"]),
Talla = read["Talla"].ToString(),
FechaIngreso = Convert.ToDateTime(read["FechaIngreso"])
});
}
}
connection.Close();
return List;
}
public List<ModelOtherWood> ListaGMelinaUltima()
{
List<ModelOtherWood> List = new List<ModelOtherWood>();
SqlCommand sel = new SqlCommand("Select* from dbo.TrozaOtros tc " +
"inner join(select max(FechaIngreso) as MaxDate from TrozaOtros t where t.Tipo=2) tm on tc.FechaIngreso = tm.MaxDate where tc.Tipo=2");
sel.Connection = connection;
connection.Open();
SqlDataReader read = sel.ExecuteReader();
if (read.HasRows)
{
while (read.Read())
{
List.Add(new ModelOtherWood
{
id = Convert.ToInt32(read["id"]),
Codigo = (read["Codigo"]).ToString(),
Consecutivo = Convert.ToInt32(read["Consecutivo"]),
Tipo = Convert.ToInt32(read["Tipo"]),
LargosMetros=Convert.ToDouble(read["LargosMetros"]),
Hoppus=Convert.ToDouble(read["Hoppus"]),
Girth=Convert.ToDouble(read["Girth"]),
Talla = read["Talla"].ToString(),
FechaIngreso = Convert.ToDateTime(read["FechaIngreso"])
});
}
}
connection.Close();
return List;
}
public List<ModelOtherWood> ListaInsertadosHoy(DateTime fecha, string Codigo,int tipo)
{
List<ModelOtherWood> List = new List<ModelOtherWood>();
SqlCommand sel = new SqlCommand("Select * from dbo.TrozaOtros where FechaIngreso=@FechaIngreso and Codigo=@Codigo and Tipo=@Tipo");
sel.Parameters.AddWithValue("@FechaIngreso", fecha.ToShortDateString());
sel.Parameters.AddWithValue("@Codigo", Codigo);
sel.Parameters.AddWithValue("@Tipo", Tipo);
sel.Connection = connection;
connection.Open();
SqlDataReader read = sel.ExecuteReader();
if (read.HasRows)
{
while (read.Read())
{
List.Add(new ModelOtherWood
{
id = Convert.ToInt32(read["id"]),
Codigo = (read["Codigo"]).ToString(),
Consecutivo = Convert.ToInt32(read["Consecutivo"]),
Tipo = Convert.ToInt32(read["Tipo"]),
LargosMetros = Convert.ToDouble(read["LargosMetros"]),
Hoppus = Convert.ToDouble(read["Hoppus"]),
Girth = Convert.ToDouble(read["Girth"]),
Talla = read["Talla"].ToString(),
FechaIngreso = Convert.ToDateTime(read["FechaIngreso"])
});
}
}
connection.Close();
return List;
}
}
}
|
8aadad0809af69131a1a766e948f9d0e8661987f
|
C#
|
AleksandrPopov96/VSProductivity
|
/QuickActionsAndRefactoring/SomeDomainClass.cs
| 3.25
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QuickActionsAndRefactoring
{
/*
* Быстрые действия и рефакторинг - Ctrl+. или Alt+Enter:
* 1. Проверка на null всех входных параметров.
* 2. Создание конструктора (обязательный и необязательный параметры).
* 3. Добавление параметров в конструктор.
* 4. Создание свойств через параметры конструктора
* 5. Вынесение кода в локальную функцию или метод.
* 6. Перемещение элемента (класс, структура, интерфйес) в новый файл.
* 7. Переопределение Equals() и GetHashCode(), реализация IEquitable<>, переопределение операторов == и !=
* как для всех свойств класса, так и для части
* 8. Вынесение константы.
* 9. Выделение базового класса или интерфейса.
* 10. Сортировка и удаление лишних using.
* 11. Рефакторинг swicth и методов (inline реализация), а также циклов (инвертирование, изменение типа цикла и др.)
* 12. Приведение имени файла к названию класса и наоборот
* 13. Добавление метода к интерфейсу
* 14. Реализаия абстрактных классов и интерфейсов
* а так же многое другое
*
* Более детальную информацию смотри по ссылкам ниже:
* https://docs.microsoft.com/en-us/visualstudio/ide/quick-actions?view=vs-2019
* https://docs.microsoft.com/en-us/visualstudio/ide/refactoring-in-visual-studio?view=vs-2019
*/
public class SomeDomainClass
{
public SomeDomainClass(int myPropertyOne, string myPropertyTwo, double myPropertyThree)
{
MyPropertyOne = myPropertyOne;
MyPropertyTwo = myPropertyTwo;
MyPropertyThree = myPropertyThree;
}
public int MyPropertyOne { get; set; }
public string MyPropertyTwo { get; set; }
public double MyPropertyThree { get; set; }
public override bool Equals(object obj)
{
return obj is SomeDomainClass @class &&
MyPropertyOne == @class.MyPropertyOne &&
MyPropertyTwo == @class.MyPropertyTwo &&
MyPropertyThree == @class.MyPropertyThree;
}
public override int GetHashCode()
{
return HashCode.Combine(MyPropertyOne, MyPropertyTwo, MyPropertyThree);
}
}
public struct SomeDomainStruct : IFoo, IEquatable<SomeDomainStruct>
{
private const int gfdhgs = 100;
public int MyPropertyOne { get; set; }
public string MyPropertyTwo { get; set; }
public double MyPropertyThree { get; set; }
public int Id { get; }
public void DisplayProperties(SomeDomainClass someClassFirst, SomeDomainClass someClassSecond)
{
if (someClassFirst is null)
{
throw new ArgumentNullException(nameof(someClassFirst));
}
if (someClassSecond is null)
{
throw new ArgumentNullException(nameof(someClassSecond));
}
Console.WriteLine(someClassFirst.MyPropertyOne);
Console.WriteLine(someClassFirst.MyPropertyTwo);
Console.WriteLine(someClassFirst.MyPropertyThree);
MyMethod(someClassSecond);
}
private static void MyMethod(SomeDomainClass someClassSecond)
{
//Автодополнение кода - Ctrl+Space
Console.WriteLine(someClassSecond.MyPropertyOne);
var ids = Enumerable.Range(1, 10).ToList();
for (int i = 0; i < ids.Count; i++)
{
Console.WriteLine(ids[i]);
}
}
public long DivideByConstant(long number)
{
if (DateTime.IsLeapYear(DateTime.Now.Year) || DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month) == 31)
return number / gfdhgs;
return number;
}
public long FabricMethod(string key)
{
switch (key)
{
case "one": return 1;
case "two": return 2;
case "three": return 3;
default: throw new NotImplementedException();
}
}
public override bool Equals(object obj)
{
return obj is SomeDomainStruct @struct && Equals(@struct);
}
public bool Equals(SomeDomainStruct other)
{
return MyPropertyOne == other.MyPropertyOne &&
MyPropertyTwo == other.MyPropertyTwo &&
MyPropertyThree == other.MyPropertyThree &&
Id == other.Id;
}
public override int GetHashCode()
{
return HashCode.Combine(MyPropertyOne, MyPropertyTwo, MyPropertyThree, Id);
}
public static bool operator ==(SomeDomainStruct left, SomeDomainStruct right)
{
return left.Equals(right);
}
public static bool operator !=(SomeDomainStruct left, SomeDomainStruct right)
{
return !(left == right);
}
}
}
|
b8f0f9ae431df2c602b507640a18baa504b3a4be
|
C#
|
yenagetorp/NiceC-exercise
|
/OperatorOverloading/ValueTuples/Program.cs
| 3.796875
| 4
|
using System;
namespace ValueTuples
{
class Program
{
static void Main(string[] args)
{
var what = GetIntString();
var what1 = GetAgeName();
Console.WriteLine(what1.age);
var person = Tuple.Create(2, "Yen");
Console.WriteLine(person.Item1);
(int age, string name) = GetAgeName();
Console.WriteLine(age);
}
/*Tuple requires at lest two values.*/
static (int, string) GetIntString()
{
return (1, "Håkan");
}
static (int age, string Name) GetAgeName()
{
return (1, "Håkan");
}
}
}
|
6f38d8e1e0ae89872fa3914ca0c1b45953dde8aa
|
C#
|
kajstof/DotNetDesignPatterns
|
/SampleDotNet/1_Creational/BuilderAbstractExample.cs
| 3.59375
| 4
|
using System;
namespace SampleDotNet._1_Creational
{
class Person
{
public string Name { get; set; }
public string Position { get; set; }
public class Builder : PersonJobBuilder<Builder>
{
}
public static Builder New => new Builder();
public override string ToString()
{
return $"{nameof(Name)}: {Name}, {nameof(Position)}: {Position}";
}
public abstract class PersonBuilder
{
protected Person person = new Person();
public Person Build()
{
return person;
}
}
public class PersonInfoBuilder<TSelf> : PersonBuilder
where TSelf : PersonInfoBuilder<TSelf>
{
public TSelf Called(string name)
{
person.Name = name;
return (TSelf) this;
}
}
public class PersonJobBuilder<TSelf> : PersonInfoBuilder<PersonJobBuilder<TSelf>>
where TSelf : PersonJobBuilder<TSelf>
{
public TSelf WorksAsA(string position)
{
person.Position = position;
return (TSelf) this;
}
}
}
public static class BuilderAbstractExample
{
public static void Run()
{
// var builder = new Person.PersonJobBuilder();
// builder.Called("Krzyś").WorksAsA
// Console.WriteLine("Hello World!");
var person = Person.New
.Called("Krzyś")
.WorksAsA("Quant")
.Build();
Console.WriteLine(person);
}
}
}
|
a1d5df8b11f193691da6807a80bcead453e1f0df
|
C#
|
hanspach/NetRadio
|
/ViewModels/JsonHelper.cs
| 2.703125
| 3
|
using System.IO;
using Newtonsoft.Json;
using System.Linq;
using System.Net;
using System.Reflection;
using log4net;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace NetRadio.ViewModels
{
class Category : IEquatable<Category>
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
public override bool Equals(object o)
{
var c = o as Category;
return c != null && Id == c.Id;
}
public bool Equals(Category c)
{
if (c == null) return false;
return (this.Id.Equals(c.Id));
}
public override int GetHashCode()
{
return 2108858624 + EqualityComparer<string>.Default.GetHashCode(Id);
}
public override string ToString()
{
return Title;
}
}
class JsonStream
{
[JsonProperty("stream")]
public string Url { get; set; }
[JsonProperty("bitrate")]
public int? Bitrate { get; set; }
[JsonProperty("content_type")]
public string ContentType { get; set; }
[JsonProperty("status")]
public int Status { get; set; }
[JsonProperty("listeners")]
public int Listeners { get; set; }
public override string ToString()
{
return Url;
}
}
class State
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("country_code")]
public string CountryCode { get; set; }
[JsonProperty("region")]
public string Continent { get; set; }
public override string ToString()
{
return string.Format("code:{0} country:{1}", CountryCode, Name);
}
}
class ProgramProps : ViewModelBase, IComparable<ProgramProps>
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("country")]
public string CountryCode { get; set; }
[JsonProperty("website")]
public string Website { get; set; }
[JsonProperty("categories")]
public List<Category> Categories { get; set; }
[JsonProperty("streams")]
public List<JsonStream> Streams { get; set; }
public int CompareTo(ProgramProps other)
{
return CountryCode.CompareTo(other.CountryCode);
}
private JsonStream currentStream;
public JsonStream CurrentStream {
get {
if(currentStream == null)
{
if (Streams == null || Streams.Count == 0)
currentStream = new JsonStream();
else
currentStream = Streams[0];
}
return currentStream;
}
set { SetProperty<JsonStream>(ref currentStream, value); }
}
public override string ToString()
{
string cats = string.Empty;
foreach (Category c in Categories)
cats += c.ToString() + ", ";
return string.Format("Name:{0} country_code:{1} categories:{2}", Name, CountryCode, cats);
}
}
static class JsonHelper
{
static ILog log = LogManager.GetLogger(System.Reflection.MethodBase.
GetCurrentMethod().DeclaringType);
public static int EntriesPerPage = 20;
static string jsonPath = Path.GetDirectoryName(
Assembly.GetExecutingAssembly().Location) + @"\Resources\";
public static List<Category> Categories { get; private set; }
public static List<State> States { get; private set; }
static JsonHelper()
{
Categories = new List<Category>();
if (File.Exists(jsonPath + "categories.json"))
{
var categories = GetEntries<Category>("categories.json");
if (categories != null)
Categories.AddRange(categories);
}
States = new List<State>();
if (File.Exists(jsonPath + "countries.json"))
{
var countries = GetEntries<State>("countries.json");
if (countries != null)
States.AddRange(countries);
}
}
static void WriteToJsonFile<T>(string filename, string content, string delimiter)
{
int idx, oldidx = 0;
using (StreamWriter writer = new StreamWriter(new FileStream(filename, FileMode.Create)))
{
while ((idx = content.IndexOf(delimiter, oldidx)) != -1)
{
idx += delimiter.Length + 1;
writer.WriteLine(content.Substring(oldidx, idx - oldidx));
oldidx = idx;
}
}
}
static void WriteToJsonFile<T>(string filename, List<T> list, string delimiter)
{
string sum = JsonConvert.SerializeObject(list);
WriteToJsonFile<T>(filename, sum, delimiter);
}
static async Task<string> ReadJsonFileAsync(string filename)
{
try
{
using (StreamReader r = new StreamReader(jsonPath + filename))
{
return await r.ReadToEndAsync();
}
}
catch (Exception e)
{
log.ErrorFormat("{0}\n{1}", e.Message, e.StackTrace);
return null;
}
}
public static IEnumerable<T> GetEntries<T>(string filename)
{
IEnumerable<T> res = null;
Task<string> task = ReadJsonFileAsync(filename);
task.Wait();
if (!string.IsNullOrEmpty(task.Result))
{
res = JsonConvert.DeserializeObject<IEnumerable<T>>(task.Result);
}
return res;
}
public static IEnumerable<T> GetEntries<T>(string filename, int start, int len)
{
var res = new List<T>();
IEnumerable<T> allEntries = GetEntries<T>(filename);
for (int i = start; i < start + len && i < allEntries.Count(); ++i)
{
res.Add(allEntries.ElementAt(i));
}
return res;
}
static string GetDataFromWebService(string url)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
using (WebResponse response = request.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
catch (Exception e)
{
Console.WriteLine("{0} - {1}", e.Message, e.StackTrace);
return null;
}
}
public static void StoreData<T>(string filename, string url)
{
string content = GetDataFromWebService(url);
if (!string.IsNullOrEmpty(content))
{
WriteToJsonFile<T>(filename, content, ",");
}
}
public static List<ProgramProps> GetDownloadedStations(string filename, string country = "", string category = "",string filter="")
{
var stations = GetEntries<ProgramProps>(filename);
if (stations != null)
{
if (!string.IsNullOrEmpty(country))
{
State state = States.Find(s => s.Name == country);
if (state != null)
stations = stations.Where(i => i.CountryCode == state.CountryCode);
}
if (!string.IsNullOrEmpty(category))
{
stations = stations.Where(i => i.Categories.Exists(c => c.Title == category));
}
if (!string.IsNullOrEmpty(filter))
{
stations = stations.Where(i => i.Name.StartsWith(filter, StringComparison.CurrentCultureIgnoreCase) || i.Name.ToLower().Contains(filter.ToLower()));
}
foreach (var item in stations)
{
item.CurrentStream = item.Streams[0];
}
return stations.ToList();
}
return new List<ProgramProps>();
}
public static List<string> GetExistingStates(string filename)
{
var states = new List<string>();
var q = GetEntries<ProgramProps>(filename).GroupBy(i => i.CountryCode);
if (q != null)
{
if (q.Count() > 1)
states.Add("All countries");
foreach (var g in q)
{
states.Add(States.Find(i => i.CountryCode == g.Key).Name);
}
}
return states;
}
public static List<string> GetExistingCategories(string filename)
{
var cats = new Dictionary<string, string>();
var res = new List<string>();
res.Add("All categories");
foreach (var p in GetEntries<ProgramProps>(filename))
{
foreach (Category c in p.Categories)
{
if (!cats.ContainsKey(c.Id))
cats.Add(c.Id, c.Title);
}
}
res.AddRange(cats.Values.ToList());
return res;
}
static void AddStations(string key, string country = "", string category = "", string preurl = "http://api.dirble.com/v2/", string filename = "data.json")
{
string url = preurl;
string countrycode = string.Empty;
if (!string.IsNullOrEmpty(country))
{
var v = States.First(i => i.Name == country);
if (v != null)
{
countrycode = v.CountryCode;
url += "countries/" + countrycode + "/";
}
}
else if (!string.IsNullOrEmpty(category))
{
var c = Categories.First(i => i.Title == category);
if (c != null)
{
string id = c.Id;
url += "category/" + id + "/";
}
}
var stations = GetDownloadedStations(filename, countrycode);
int page = stations.Count() / EntriesPerPage + 1;
url += string.Format("stations?page={0}&token={1}", page, key);
Console.WriteLine("Url:{0}", url);
string content = GetDataFromWebService(url); // to errors 404 not found auswerten!
if (!string.IsNullOrEmpty(content))
{
List<ProgramProps> list = JsonConvert.DeserializeObject<List<ProgramProps>>(content);
stations.AddRange(list);
string sum = JsonConvert.SerializeObject(stations);
using (StreamWriter writer = new StreamWriter(new FileStream(filename, FileMode.Create)))
{
writer.Write(sum);
}
}
}
}
}
|
09b4dd5e88ebeffe9c9b52098628caaef800653c
|
C#
|
Pireax/neovim.cs
|
/Example/NeovimDemo/MainWindow.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using MsgPack;
using Neovim;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
using QuickFont;
namespace NeovimDemo
{
public partial class MainWindow : Form
{
private readonly SynchronizationContext _uiContext;
private NeovimClient _neovim;
private RectangleF _cursor;
private RectangleF _scrollRegion;
private int _rows = 24;
private int _columns = 80;
private float _width;
private float _height;
private FontGroup _font;
private Color _fgColor = Color.White;
private Color _bgColor = Color.DarkSlateGray;
private FrameBuffer _backBuffer;
private FrameBuffer _pingPongBuffer;
private char[] charBuffer;
public MainWindow()
{
InitializeComponent();
_uiContext = SynchronizationContext.Current;
_neovim = new NeovimClient(@"C:\Program Files\Neovim\bin\nvim.exe");
// Event is asynchronous so we need to handle the redraw event in the UI thread
_neovim.Redraw += (o, args) => _uiContext.Post((x) => NeovimOnRedraw(o, args), null);
_neovim.ui_attach(_columns, _rows, true);
}
private Color ColorFromRgb(int rgb)
{
byte r = (byte)(rgb >> 16);
byte g = (byte)(rgb >> 8);
byte b = (byte)(rgb >> 0);
return Color.FromArgb(r, g, b);
}
private void NeovimOnRedraw(object sender, NeovimRedrawEventArgs e)
{
bool shouldInvalidate = false;
_backBuffer.Bind();
foreach (var method in e.Methods)
{
switch (method.Method)
{
case RedrawMethodType.Clear:
shouldInvalidate = true;
GL.Clear(ClearBufferMask.ColorBufferBit);
break;
// case RedrawMethodType.Resize:
// _term.Resize(args[0][1].AsInt32(), args[0][0].AsInt32());
// break;
case RedrawMethodType.UpdateForeground:
_font.Color = ColorFromRgb(method.Params[0][0].AsInt32());
break;
case RedrawMethodType.UpdateBackground:
_bgColor = ColorFromRgb(method.Params[0][0].AsInt32());
GL.ClearColor(_bgColor);
break;
case RedrawMethodType.HighlightSet:
foreach (var arg in method.Params)
{
var dict = arg[0].AsDictionary();
foreach (var entry in dict)
{
var str = entry.Key.AsString(Encoding.Default);
if (str == "foreground")
_font.Color = ColorFromRgb(entry.Value.AsInt32());
else if (str == "bold")
if (entry.Value.AsBoolean())
_font.FontStyle |= FontStyle.Bold;
else _font.FontStyle &= ~FontStyle.Bold;
else if (str == "italic")
if (entry.Value.AsBoolean())
_font.FontStyle |= FontStyle.Italic;
else _font.FontStyle &= FontStyle.Italic;
}
}
break;
case RedrawMethodType.EolClear:
shouldInvalidate = true;
DrawRectangle(new RectangleF(_cursor.X, _cursor.Y, _columns * _width - _cursor.X, _height), _bgColor);
break;
case RedrawMethodType.SetTitle:
Text = method.Params[0][0].AsString(Encoding.Default);
break;
case RedrawMethodType.Put:
shouldInvalidate = true;
List<byte> bytes = new List<byte>();
foreach (var arg in method.Params)
bytes.AddRange(arg[0].AsBinary());
var text = Encoding.Default.GetString(bytes.ToArray());
var tSize = _font.Measure(text);
DrawRectangle(new RectangleF(_cursor.Location, tSize), _bgColor);
GL.Enable(EnableCap.Blend);
_font.Print(text, new Vector2(_cursor.X, _cursor.Y));
GL.Disable(EnableCap.Blend);
GL.Color4(Color.White);
_cursor.X += tSize.Width;
if (_cursor.X >= _columns*_width) // Dont know if this is needed
{
_cursor.X = 0;
_cursor.Y += _height;
}
break;
case RedrawMethodType.CursorGoto:
shouldInvalidate = true;
_cursor.Y = method.Params[0][0].AsInt32() * _height;
_cursor.X = method.Params[0][1].AsInt32() * _width;
break;
case RedrawMethodType.Scroll:
// Amount to scroll
var count = method.Params[0][0].AsSByte();
if (count == 0) return;
var srcRect = new RectangleF();
var dstRect = new RectangleF();
var clearRect = new RectangleF();
// Scroll up
if (count >= 1)
{
srcRect = new RectangleF(_scrollRegion.X, _scrollRegion.Y + _height, _scrollRegion.Width,
_scrollRegion.Height - _height);
dstRect = new RectangleF(_scrollRegion.X, _scrollRegion.Y, _scrollRegion.Width,
_scrollRegion.Height - _height);
clearRect = new RectangleF(_scrollRegion.X, _scrollRegion.Y + _scrollRegion.Height - _height,
_scrollRegion.Width, _height + 1);
}
// Scroll down
else if (count <= -1)
{
srcRect = new RectangleF(_scrollRegion.X, _scrollRegion.Y, _scrollRegion.Width,
_scrollRegion.Height - _height);
dstRect = new RectangleF(_scrollRegion.X, _scrollRegion.Y + _height, _scrollRegion.Width,
_scrollRegion.Height - _height);
clearRect = new RectangleF(_scrollRegion.X, _scrollRegion.Y, _scrollRegion.Width,
_height + 1);
}
_pingPongBuffer.Bind();
_backBuffer.Texture.Bind();
DrawTexturedRectangle(srcRect, dstRect);
_backBuffer.Bind();
_pingPongBuffer.Texture.Bind();
DrawTexturedRectangle(dstRect, dstRect);
Texture2D.Unbind();
DrawRectangle(clearRect, _bgColor);
break;
case RedrawMethodType.SetScrollRegion:
var x = method.Params[0][2].AsUInt32() * _width;
var y = method.Params[0][0].AsUInt32() * _height;
var width = (method.Params[0][3].AsUInt32() + 1) * _width;
var height = (method.Params[0][1].AsUInt32() + 1) * _height;
_scrollRegion = new RectangleF(x, y, width, height);
break;
case RedrawMethodType.ModeChange:
shouldInvalidate = true;
var mode = method.Params[0][0].AsString(Encoding.Default);
if (mode == "insert")
_cursor.Width = _width / 4;
else if (mode == "normal")
_cursor.Width = _width;
break;
// case RedrawMethodType.BusyStart:
// break;
// case RedrawMethodType.BusyStop:
// break;
// case RedrawMethodType.MouseOn:
// break;
// case RedrawMethodType.MouseOff:
// break;
}
}
FrameBuffer.Unbind();
if (shouldInvalidate)
glControl.Invalidate();
}
private void glControl_Load(object sender, EventArgs e)
{
_font = new FontGroup(glControl.Font);
_font.Color = _fgColor;
_width = _font.MonoSpaceWidth;
_height = _font.LineSpacing;
glControl.Width = Convert.ToInt32(_width * _columns);
glControl.Height = Convert.ToInt32(_height * _rows);
_cursor = new RectangleF(0, 0, _width, _height);
_backBuffer = new FrameBuffer(glControl.Width, glControl.Height);
_pingPongBuffer = new FrameBuffer(glControl.Width, glControl.Height);
GL.MatrixMode(MatrixMode.Projection);
GL.LoadIdentity();
GL.Ortho(0, glControl.Width, glControl.Height, 0, -1, 1);
GL.Viewport(0, 0, glControl.Width, glControl.Height);
GL.MatrixMode(MatrixMode.Modelview);
GL.LoadIdentity();
GL.Disable(EnableCap.DepthTest);
GL.Disable(EnableCap.Lighting);
GL.ClearColor(_bgColor);
}
private void glControl_Paint(object sender, PaintEventArgs e)
{
_backBuffer.Texture.Bind();
GL.Begin(PrimitiveType.Quads);
// Backbuffer needs inverted TexCoords, origin of TexCoords is bottom-left corner
GL.TexCoord2(0, 1); GL.Vertex2(0, 0);
GL.TexCoord2(1, 1); GL.Vertex2(glControl.Width, 0);
GL.TexCoord2(1, 0); GL.Vertex2(glControl.Width, glControl.Height);
GL.TexCoord2(0, 0); GL.Vertex2(0, glControl.Height);
GL.End();
Texture2D.Unbind();
// Invert cursor color depending on the background for now
GL.Enable(EnableCap.Blend);
GL.BlendFunc(BlendingFactorSrc.OneMinusDstColor, BlendingFactorDest.Zero);
DrawRectangle(_cursor, Color.White);
GL.Disable(EnableCap.Blend);
glControl.SwapBuffers();
}
private void DrawRectangle(RectangleF rect, Color color)
{
GL.Color3(color);
GL.Begin(PrimitiveType.Quads);
GL.Vertex2(rect.X, rect.Y);
GL.Vertex2(rect.X + rect.Width, rect.Y);
GL.Vertex2(rect.X + rect.Width, rect.Y + rect.Height);
GL.Vertex2(rect.X, rect.Y + rect.Height);
GL.End();
GL.Color4(Color.White);
}
private void DrawTexturedRectangle(RectangleF rectSrc, RectangleF rectDst)
{
GL.Begin(PrimitiveType.Quads);
var wScale = 1.0f/glControl.Width;
var hScale = 1.0f/glControl.Height;
var flippedRectSrc = new RectangleF(rectSrc.X, glControl.Height - rectSrc.Bottom, rectSrc.Width, rectSrc.Height);
GL.TexCoord2(wScale * flippedRectSrc.X, hScale * (flippedRectSrc.Y + flippedRectSrc.Height)); GL.Vertex2(rectDst.X, rectDst.Y);
GL.TexCoord2(wScale * (flippedRectSrc.X + flippedRectSrc.Width), hScale * (flippedRectSrc.Y + flippedRectSrc.Height)); GL.Vertex2(rectDst.X + rectDst.Width, rectDst.Y);
GL.TexCoord2(wScale * (flippedRectSrc.X + flippedRectSrc.Width), hScale * flippedRectSrc.Y); GL.Vertex2(rectDst.X + rectDst.Width, rectDst.Y + rectDst.Height);
GL.TexCoord2(wScale * flippedRectSrc.X, hScale * (flippedRectSrc.Y)); GL.Vertex2(rectDst.X, rectDst.Y + rectDst.Height);
GL.End();
}
private void glControl_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.ShiftKey || e.KeyCode == Keys.Alt || e.KeyCode == Keys.ControlKey)
return;
string keys = Input.Encode((int)e.KeyCode);
if (keys != null)
_neovim.vim_input(keys);
e.Handled = true;
}
}
}
|
8b9bfbf3178825e6fec14988ab7febc44115ad59
|
C#
|
fkbaggett/samples-c-sharp
|
/lynda/C-Sharp-Essentials/10_PreprocessorDirectives/PreprocessorDirectives.cs
| 2.953125
| 3
|
//#define DEBUGCODE
#define JOE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _10_PreprocessorDirectives
{
// Preprocessor Directives
class PreprocessorDirectives
{
static void Main(string[] args)
{
#region This is the main function
#if DEBUGCODE
Console.WriteLine("This is a debug code.");
#else
Console.WriteLine("This only gets written out in non-debug code");
#endif
#if JOE
Console.WriteLine("Joe wins here!");
#endif
Console.ReadLine();
#endregion
}
}
}
|
a57825e3b329d3beda0edce8e581883cdafbbcaf
|
C#
|
Taksaporn/week-1
|
/Lab/Lab1-2/Program.cs
| 3.640625
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lab1_2
{
class BubbleSortFunction
{
static void Main(string[] args)
{
BubbleSortFunction iput = new BubbleSortFunction(); // if not call class is not call function plss remember
int[] a = iput.input();
iput.process(a);
iput.output(a);
}
// input
public int []input()
{
string v;
Console.Write("Enter number for sort: ");
v = Console.ReadLine();
int[] input;
input = v.Split(' ').Select(y => Convert.ToInt32(y)).ToArray();
return input;
//int[] x = { 4, 5, 2, 8, 9, 1, 2, 4, 3, 1 };
//return x;
}
public void process(int[] input) {
bool flag = true;
while (flag)
{
flag = false;
for (int i = 0; i != input.Length - 1; i++)
{
if (input[i] > input[i + 1])
{
int temp = input[i];
input[i] = input[i + 1];
input[i + 1] = temp;
flag = true;
}
}
}
}
public void output(int[] input)
{
for (int i = 0; i != input.Length; i++)
{
Console.Write(input[i]);
Console.Write(" ");
}
Console.ReadKey();
}
}
}
|
684c24f317408da5a7a160ae19e8dff609ea4812
|
C#
|
rsenna/kakfa-diff-dotnetcore
|
/Common/Impl/ConsoleLogger.cs
| 2.625
| 3
|
using System;
namespace Kafka.Diff.Common.Impl
{
internal class ConsoleLogger<T> : ILogger<T>
{
private readonly string _section;
public ConsoleLogger()
{
_section = typeof(T).FullName;
}
public void Info(string message)
{
Console.WriteLine($"Info: {_section}: {message}");
}
public void Error(Exception ex)
{
Console.WriteLine($"Error: {_section}: {ex.Message}");
}
}
}
|
1fd96bd6efe173697cc2c5d7b856b8cd802a0bf8
|
C#
|
azraelzc/ZCGame
|
/Server/CommonServer/ServerManager.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common;
using System.Net.Sockets;
using CommonUnit;
using CommonDataBases;
namespace CommonServer
{
public class ServerManager
{
public delegate void SendEvent(Socket client, object obj);
private SendEvent mSendEvent;
public event SendEvent OnSendEvent { add { mSendEvent += value; } remove { mSendEvent -= value; } }
private static ServerManager mInstance = null;
private ServerSocket socket = null;
private ServerMessagePool pool = null;
private ConnectDB DB = null;
public static ServerManager Instance
{
get
{
if (mInstance == null)
{
mInstance = new ServerManager();
}
return mInstance;
}
}
public void Init()
{
pool = new ServerMessagePool();
socket = new ServerSocket();
socket.Init();
DB.Init();
}
public bool AddClient(Socket client)
{
return pool.AddClient(client);
}
public bool RemoveClient(Socket client)
{
return pool.RemoveClient(client.GetHashCode());
}
public bool HasSocket(int id)
{
return pool.HasSocket(id);
}
public void C2B(int clientCode,object obj)
{
pool.PutSendMessageInPool(clientCode,obj);
}
public void B2C(int clientCode, object obj)
{
pool.PutReciveMessageInPool(clientCode,obj);
}
public void UpdatePingTime(int delta)
{
Dictionary<int, int> pingList = pool.GetPingList;
List<int> key = new List<int>(pingList.Keys);
for (int i = 0; i < key.Count; i++)
{
int time = pingList[key[i]];
time += delta;
if (time > PublicConstants.PING_LOST_TIMEMS)
{
socket.Close(pool.GetClientById(key[i]));
}
else
{
pingList[key[i]] = time;
}
}
}
public void Update(int delta)
{
UpdatePingTime(delta);
while (true)
{
ServerClass c = pool.HasSendMessages();
if (c == null)
{
break;
}
Queue<object> messages = c.messages;
Socket client = pool.GetClientById(c.id);
if (client != null)
{
while(messages.Count > 0)
{
mSendEvent.Invoke(client, messages.Dequeue());
}
}
}
while (true)
{
ServerClass c = pool.HasReciveMessages();
if (c == null)
{
break;
}
Queue<object> messages = c.messages;
Socket client = pool.GetClientById(c.id);
if (client != null)
{
while (messages.Count > 0)
{
object obj = messages.Dequeue();
if (obj is PingClass)
{
pool.ResetPing(c.id);
}
else
{
OnEvent(obj);
}
}
}
}
}
public void OnEvent(object obj)
{
Console.WriteLine("======OnEvent======{0}", obj);
if (obj is Player)
{
Player p = obj as Player;
DB.Insert("insert into * from test");
}
else if (obj is BuffEvent)
{
BuffEvent buff = obj as BuffEvent;
DB.Query("select * from test");
}
}
}
}
|
19384971486a68084716840e521710964e656313
|
C#
|
LONG-xy/DotNetHomeWork
|
/Week6/OrderManagementSystem(WebAPI)/Models/OrderItem.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace OrderManagementSystem.Models {
public class OrderItem {
private double _amount;
private double _price;
public string OrderId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public double Price {
get => _price;
set {
if (value > 0) {
_price = value;
}
else {
throw new InvalidDataException("价格不能位负数");
}
}
}
[Required]
public double Amount {
get => _amount;
set {
if (value > 0) {
_amount = value;
}
else {
throw new InvalidDataException("数量不能为负数");
}
}
}
}
}
|
15749ffd6fd2db9b3eef58d008002d158a423300
|
C#
|
cuteant/SpanNetty
|
/src/DotNetty.Codecs.Http/Utilities/HttpUtility.Html.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.Encodings.Web;
using DotNetty.Common.Internal;
namespace DotNetty.Codecs.Http.Utilities
{
partial class HttpUtility
{
#region -- HtmlEncode --
private static readonly HtmlEncoder s_htmlEncoder = HtmlEncoder.Default;
public static string HtmlEncode(string value)
{
if (string.IsNullOrEmpty(value)) { return value; }
return s_htmlEncoder.Encode(value);
}
public static void HtmlEncode(TextWriter output, string value)
{
s_htmlEncoder.Encode(output, value, 0, value.Length);
}
public static void HtmlEncode(TextWriter output, string value, int startIndex, int characterCount)
{
if (string.IsNullOrEmpty(value)) { return; }
s_htmlEncoder.Encode(output, value, startIndex, characterCount);
}
public static void HtmlEncode(TextWriter output, char[] value, int startIndex, int characterCount)
{
if (value is null || 0u >= (uint)value.Length) { return; }
s_htmlEncoder.Encode(output, value, startIndex, characterCount);
}
#endregion
#region -- HtmlAttributeEncode --
public static string HtmlAttributeEncode(string value)
{
if (string.IsNullOrEmpty(value)) { return value; }
// Don't create string writer if we don't have nothing to encode
int pos = IndexOfHtmlAttributeEncodingChars(value, 0);
if (pos == -1) { return value; }
StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
HtmlAttributeEncode(value, writer);
return writer.ToString();
}
public static void HtmlAttributeEncode(string value, TextWriter output)
{
if (value is null) { return; }
if (output is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.output); }
HtmlAttributeEncodeInternal(value, output);
}
private static unsafe void HtmlAttributeEncodeInternal(string s, TextWriter output)
{
int index = IndexOfHtmlAttributeEncodingChars(s, 0);
if (index == -1)
{
output.Write(s);
}
else
{
int cch = s.Length - index;
fixed (char* str = s)
{
char* pch = str;
while (index-- > 0)
{
output.Write(*pch++);
}
while (cch-- > 0)
{
char ch = *pch++;
if (ch <= '<')
{
switch (ch)
{
case '<':
output.Write("<");
break;
case '"':
output.Write(""");
break;
case '\'':
output.Write("'");
break;
case '&':
output.Write("&");
break;
default:
output.Write(ch);
break;
}
}
else
{
output.Write(ch);
}
}
}
}
}
#endregion
#region ** IndexOfHtmlAttributeEncodingChars **
private static unsafe int IndexOfHtmlAttributeEncodingChars(string s, int startPos)
{
Debug.Assert(0 <= startPos && startPos <= s.Length, "0 <= startPos && startPos <= s.Length");
int cch = s.Length - startPos;
fixed (char* str = s)
{
for (char* pch = &str[startPos]; cch > 0; pch++, cch--)
{
char ch = *pch;
if (ch <= '<')
{
switch (ch)
{
case '<':
case '"':
case '\'':
case '&':
return s.Length - cch;
}
}
}
}
return -1;
}
#endregion
#region -- HtmlDecode --
private const char HIGH_SURROGATE_START = '\uD800';
private const char LOW_SURROGATE_START = '\uDC00';
private const char LOW_SURROGATE_END = '\uDFFF';
private const int UNICODE_PLANE00_END = 0x00FFFF;
private const int UNICODE_PLANE01_START = 0x10000;
private const int UNICODE_PLANE16_END = 0x10FFFF;
private const int UnicodeReplacementChar = '\uFFFD';
private static readonly char[] s_htmlEntityEndingChars = new char[] { ';', '&' };
public static string HtmlDecode(string value)
{
if (string.IsNullOrEmpty(value)) { return value; }
// Don't create StringBuilder if we don't have anything to encode
if (!StringRequiresHtmlDecoding(value)) { return value; }
var sb = StringBuilderManager.Allocate(value.Length);
HtmlDecodeImpl(value, sb);
return StringBuilderManager.ReturnAndFree(sb);
}
public static void HtmlDecode(string value, TextWriter output)
{
if (value is null) { return; }
if (output is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.output); }
output.Write(HtmlDecode(value));
}
#endregion
#region ** HtmlDecodeImpl **
private static void HtmlDecodeImpl(string value, StringBuilder output)
{
Debug.Assert(output is object);
int l = value.Length;
for (int i = 0; i < l; i++)
{
char ch = value[i];
if (ch == '&')
{
// We found a '&'. Now look for the next ';' or '&'. The idea is that
// if we find another '&' before finding a ';', then this is not an entity,
// and the next '&' might start a real entity (VSWhidbey 275184)
int index = value.IndexOfAny(s_htmlEntityEndingChars, i + 1);
if (index > 0 && value[index] == ';')
{
int entityOffset = i + 1;
int entityLength = index - entityOffset;
if (entityLength > 1 && value[entityOffset] == '#')
{
// The # syntax can be in decimal or hex, e.g.
// å --> decimal
// å --> same char in hex
// See http://www.w3.org/TR/REC-html40/charset.html#entities
bool parsedSuccessfully;
uint parsedValue;
if (value[entityOffset + 1] == 'x' || value[entityOffset + 1] == 'X')
{
parsedSuccessfully = uint.TryParse(value.Substring(entityOffset + 2, entityLength - 2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out parsedValue);
}
else
{
parsedSuccessfully = uint.TryParse(value.Substring(entityOffset + 1, entityLength - 1), NumberStyles.Integer, CultureInfo.InvariantCulture, out parsedValue);
}
if (parsedSuccessfully)
{
// decoded character must be U+0000 .. U+10FFFF, excluding surrogates
parsedSuccessfully = ((parsedValue < HIGH_SURROGATE_START) || (LOW_SURROGATE_END < parsedValue && parsedValue <= UNICODE_PLANE16_END));
}
if (parsedSuccessfully)
{
if (parsedValue <= UNICODE_PLANE00_END)
{
// single character
_ = output.Append((char)parsedValue);
}
else
{
// multi-character
char leadingSurrogate, trailingSurrogate;
ConvertSmpToUtf16(parsedValue, out leadingSurrogate, out trailingSurrogate);
_ = output.Append(leadingSurrogate);
_ = output.Append(trailingSurrogate);
}
i = index; // already looked at everything until semicolon
continue;
}
}
else
{
string entity = value.Substring(entityOffset, entityLength);
i = index; // already looked at everything until semicolon
char entityChar = HtmlEntities.Lookup(entity);
if (entityChar != (char)0)
{
ch = entityChar;
}
else
{
_ = output.Append('&');
_ = output.Append(entity);
_ = output.Append(';');
continue;
}
}
}
}
_ = output.Append(ch);
}
}
#endregion
#region ** ConvertSmpToUtf16 **
// similar to Char.ConvertFromUtf32, but doesn't check arguments or generate strings
// input is assumed to be an SMP character
private static void ConvertSmpToUtf16(uint smpChar, out char leadingSurrogate, out char trailingSurrogate)
{
Debug.Assert(UNICODE_PLANE01_START <= smpChar && smpChar <= UNICODE_PLANE16_END);
int utf32 = (int)(smpChar - UNICODE_PLANE01_START);
leadingSurrogate = (char)((utf32 / 0x400) + HIGH_SURROGATE_START);
trailingSurrogate = (char)((utf32 % 0x400) + LOW_SURROGATE_START);
}
#endregion
#region ** StringRequiresHtmlDecoding **
private static bool StringRequiresHtmlDecoding(string s)
{
// this string requires html decoding if it contains '&' or a surrogate character
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
if (c == '&' || Char.IsSurrogate(c))
{
return true;
}
}
return false;
}
#endregion
#region ** class HtmlEntities **
// helper class for lookup of HTML encoding entities
private static class HtmlEntities
{
#if DEBUG
static HtmlEntities()
{
// Make sure the initial capacity for s_lookupTable is correct
Debug.Assert(s_lookupTable.Count == Count, $"There should be {Count} HTML entities, but {nameof(s_lookupTable)} has {s_lookupTable.Count} of them.");
}
#endif
// The list is from http://www.w3.org/TR/REC-html40/sgml/entities.html, except for ', which
// is defined in http://www.w3.org/TR/2008/REC-xml-20081126/#sec-predefined-ent.
private const int Count = 253;
// maps entity strings => unicode chars
private static readonly Dictionary<string, char> s_lookupTable =
new Dictionary<string, char>(Count, StringComparer.Ordinal)
{
["quot"] = '\x0022',
["amp"] = '\x0026',
["apos"] = '\x0027',
["lt"] = '\x003c',
["gt"] = '\x003e',
["nbsp"] = '\x00a0',
["iexcl"] = '\x00a1',
["cent"] = '\x00a2',
["pound"] = '\x00a3',
["curren"] = '\x00a4',
["yen"] = '\x00a5',
["brvbar"] = '\x00a6',
["sect"] = '\x00a7',
["uml"] = '\x00a8',
["copy"] = '\x00a9',
["ordf"] = '\x00aa',
["laquo"] = '\x00ab',
["not"] = '\x00ac',
["shy"] = '\x00ad',
["reg"] = '\x00ae',
["macr"] = '\x00af',
["deg"] = '\x00b0',
["plusmn"] = '\x00b1',
["sup2"] = '\x00b2',
["sup3"] = '\x00b3',
["acute"] = '\x00b4',
["micro"] = '\x00b5',
["para"] = '\x00b6',
["middot"] = '\x00b7',
["cedil"] = '\x00b8',
["sup1"] = '\x00b9',
["ordm"] = '\x00ba',
["raquo"] = '\x00bb',
["frac14"] = '\x00bc',
["frac12"] = '\x00bd',
["frac34"] = '\x00be',
["iquest"] = '\x00bf',
["Agrave"] = '\x00c0',
["Aacute"] = '\x00c1',
["Acirc"] = '\x00c2',
["Atilde"] = '\x00c3',
["Auml"] = '\x00c4',
["Aring"] = '\x00c5',
["AElig"] = '\x00c6',
["Ccedil"] = '\x00c7',
["Egrave"] = '\x00c8',
["Eacute"] = '\x00c9',
["Ecirc"] = '\x00ca',
["Euml"] = '\x00cb',
["Igrave"] = '\x00cc',
["Iacute"] = '\x00cd',
["Icirc"] = '\x00ce',
["Iuml"] = '\x00cf',
["ETH"] = '\x00d0',
["Ntilde"] = '\x00d1',
["Ograve"] = '\x00d2',
["Oacute"] = '\x00d3',
["Ocirc"] = '\x00d4',
["Otilde"] = '\x00d5',
["Ouml"] = '\x00d6',
["times"] = '\x00d7',
["Oslash"] = '\x00d8',
["Ugrave"] = '\x00d9',
["Uacute"] = '\x00da',
["Ucirc"] = '\x00db',
["Uuml"] = '\x00dc',
["Yacute"] = '\x00dd',
["THORN"] = '\x00de',
["szlig"] = '\x00df',
["agrave"] = '\x00e0',
["aacute"] = '\x00e1',
["acirc"] = '\x00e2',
["atilde"] = '\x00e3',
["auml"] = '\x00e4',
["aring"] = '\x00e5',
["aelig"] = '\x00e6',
["ccedil"] = '\x00e7',
["egrave"] = '\x00e8',
["eacute"] = '\x00e9',
["ecirc"] = '\x00ea',
["euml"] = '\x00eb',
["igrave"] = '\x00ec',
["iacute"] = '\x00ed',
["icirc"] = '\x00ee',
["iuml"] = '\x00ef',
["eth"] = '\x00f0',
["ntilde"] = '\x00f1',
["ograve"] = '\x00f2',
["oacute"] = '\x00f3',
["ocirc"] = '\x00f4',
["otilde"] = '\x00f5',
["ouml"] = '\x00f6',
["divide"] = '\x00f7',
["oslash"] = '\x00f8',
["ugrave"] = '\x00f9',
["uacute"] = '\x00fa',
["ucirc"] = '\x00fb',
["uuml"] = '\x00fc',
["yacute"] = '\x00fd',
["thorn"] = '\x00fe',
["yuml"] = '\x00ff',
["OElig"] = '\x0152',
["oelig"] = '\x0153',
["Scaron"] = '\x0160',
["scaron"] = '\x0161',
["Yuml"] = '\x0178',
["fnof"] = '\x0192',
["circ"] = '\x02c6',
["tilde"] = '\x02dc',
["Alpha"] = '\x0391',
["Beta"] = '\x0392',
["Gamma"] = '\x0393',
["Delta"] = '\x0394',
["Epsilon"] = '\x0395',
["Zeta"] = '\x0396',
["Eta"] = '\x0397',
["Theta"] = '\x0398',
["Iota"] = '\x0399',
["Kappa"] = '\x039a',
["Lambda"] = '\x039b',
["Mu"] = '\x039c',
["Nu"] = '\x039d',
["Xi"] = '\x039e',
["Omicron"] = '\x039f',
["Pi"] = '\x03a0',
["Rho"] = '\x03a1',
["Sigma"] = '\x03a3',
["Tau"] = '\x03a4',
["Upsilon"] = '\x03a5',
["Phi"] = '\x03a6',
["Chi"] = '\x03a7',
["Psi"] = '\x03a8',
["Omega"] = '\x03a9',
["alpha"] = '\x03b1',
["beta"] = '\x03b2',
["gamma"] = '\x03b3',
["delta"] = '\x03b4',
["epsilon"] = '\x03b5',
["zeta"] = '\x03b6',
["eta"] = '\x03b7',
["theta"] = '\x03b8',
["iota"] = '\x03b9',
["kappa"] = '\x03ba',
["lambda"] = '\x03bb',
["mu"] = '\x03bc',
["nu"] = '\x03bd',
["xi"] = '\x03be',
["omicron"] = '\x03bf',
["pi"] = '\x03c0',
["rho"] = '\x03c1',
["sigmaf"] = '\x03c2',
["sigma"] = '\x03c3',
["tau"] = '\x03c4',
["upsilon"] = '\x03c5',
["phi"] = '\x03c6',
["chi"] = '\x03c7',
["psi"] = '\x03c8',
["omega"] = '\x03c9',
["thetasym"] = '\x03d1',
["upsih"] = '\x03d2',
["piv"] = '\x03d6',
["ensp"] = '\x2002',
["emsp"] = '\x2003',
["thinsp"] = '\x2009',
["zwnj"] = '\x200c',
["zwj"] = '\x200d',
["lrm"] = '\x200e',
["rlm"] = '\x200f',
["ndash"] = '\x2013',
["mdash"] = '\x2014',
["lsquo"] = '\x2018',
["rsquo"] = '\x2019',
["sbquo"] = '\x201a',
["ldquo"] = '\x201c',
["rdquo"] = '\x201d',
["bdquo"] = '\x201e',
["dagger"] = '\x2020',
["Dagger"] = '\x2021',
["bull"] = '\x2022',
["hellip"] = '\x2026',
["permil"] = '\x2030',
["prime"] = '\x2032',
["Prime"] = '\x2033',
["lsaquo"] = '\x2039',
["rsaquo"] = '\x203a',
["oline"] = '\x203e',
["frasl"] = '\x2044',
["euro"] = '\x20ac',
["image"] = '\x2111',
["weierp"] = '\x2118',
["real"] = '\x211c',
["trade"] = '\x2122',
["alefsym"] = '\x2135',
["larr"] = '\x2190',
["uarr"] = '\x2191',
["rarr"] = '\x2192',
["darr"] = '\x2193',
["harr"] = '\x2194',
["crarr"] = '\x21b5',
["lArr"] = '\x21d0',
["uArr"] = '\x21d1',
["rArr"] = '\x21d2',
["dArr"] = '\x21d3',
["hArr"] = '\x21d4',
["forall"] = '\x2200',
["part"] = '\x2202',
["exist"] = '\x2203',
["empty"] = '\x2205',
["nabla"] = '\x2207',
["isin"] = '\x2208',
["notin"] = '\x2209',
["ni"] = '\x220b',
["prod"] = '\x220f',
["sum"] = '\x2211',
["minus"] = '\x2212',
["lowast"] = '\x2217',
["radic"] = '\x221a',
["prop"] = '\x221d',
["infin"] = '\x221e',
["ang"] = '\x2220',
["and"] = '\x2227',
["or"] = '\x2228',
["cap"] = '\x2229',
["cup"] = '\x222a',
["int"] = '\x222b',
["there4"] = '\x2234',
["sim"] = '\x223c',
["cong"] = '\x2245',
["asymp"] = '\x2248',
["ne"] = '\x2260',
["equiv"] = '\x2261',
["le"] = '\x2264',
["ge"] = '\x2265',
["sub"] = '\x2282',
["sup"] = '\x2283',
["nsub"] = '\x2284',
["sube"] = '\x2286',
["supe"] = '\x2287',
["oplus"] = '\x2295',
["otimes"] = '\x2297',
["perp"] = '\x22a5',
["sdot"] = '\x22c5',
["lceil"] = '\x2308',
["rceil"] = '\x2309',
["lfloor"] = '\x230a',
["rfloor"] = '\x230b',
["lang"] = '\x2329',
["rang"] = '\x232a',
["loz"] = '\x25ca',
["spades"] = '\x2660',
["clubs"] = '\x2663',
["hearts"] = '\x2665',
["diams"] = '\x2666',
};
public static char Lookup(string entity)
{
char theChar;
_ = s_lookupTable.TryGetValue(entity, out theChar);
return theChar;
}
}
#endregion
}
}
|
7eea955669f0b91aef0e735f657eec187cb2e622
|
C#
|
Yongfou/jo
|
/Bank/ProgressBarExample/ProgressBarExample/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.Windows.Forms;
using System.Threading; // Required for this example
namespace ProgressBarExample
{
public partial class Form1 : Form
{
// Flag that indcates if a process is running
private bool isProcessRunning = false;
//Auto-generated form constructor
public Form1()
{
InitializeComponent();
}
// Simulates a running background process with a quantifiable
// indicator of progress, using the progress bar within the
// main form
private void button1_Click(object sender, EventArgs e)
{
// If a process is already running, warn the user and cancel the operation
if (isProcessRunning)
{
MessageBox.Show("A process is already running.");
return;
}
// Initialize the thread that will handle the background process
Thread backgroundThread = new Thread(
new ThreadStart(() =>
{
// Set the flag that indicates if a process is currently running
isProcessRunning = true;
// Iterate from 0 - 99
// On each iteration, pause the thread for .05 seconds, then update the progress bar
for (int n = 0; n < 100; n++ )
{
Thread.Sleep(50);
progressBar1.BeginInvoke(new Action(() => progressBar1.Value = n));
}
// Show a dialog box that confirms the process has completed
MessageBox.Show("Thread completed!");
// Reset the progress bar's value if it is still valid to do so
if (progressBar1.InvokeRequired)
progressBar1.BeginInvoke(new Action(() => progressBar1.Value = 0));
// Reset the flag that indicates if a process is currently running
isProcessRunning = false;
}
));
// Start the background process thread
backgroundThread.Start();
}
// Simulates a running background process with a quantifiable
// indicator of progress, using a seperate modal dialog containing
// a progress bar
private void button2_Click(object sender, EventArgs e)
{
// If a process is already running, warn the user and cancel the operation
if (isProcessRunning)
{
MessageBox.Show("A process is already running.");
return;
}
// Initialize the dialog that will contain the progress bar
ProgressDialog progressDialog = new ProgressDialog();
// Initialize the thread that will handle the background process
Thread backgroundThread = new Thread(
new ThreadStart(() =>
{
// Set the flag that indicates if a process is currently running
isProcessRunning = true;
// Iterate from 0 - 99
// On each iteration, pause the thread for .05 seconds, then update the dialog's progress bar
for (int n = 0; n < 100; n++)
{
Thread.Sleep(50);
progressDialog.UpdateProgress(n);
}
// Show a dialog box that confirms the process has completed
MessageBox.Show("Thread completed!");
// Close the dialog if it hasn't been already
if (progressDialog.InvokeRequired)
progressDialog.BeginInvoke(new Action(() => progressDialog.Close()));
// Reset the flag that indicates if a process is currently running
isProcessRunning = false;
}
));
// Start the background process thread
backgroundThread.Start();
// Open the dialog
progressDialog.ShowDialog();
}
// Simulates a running background process without a quantifiable
// indicator of progress, using a seperate modal dialog containing
// a progress bar
private void button3_Click(object sender, EventArgs e)
{
// If a process is already running, warn the user and cancel the operation
if (isProcessRunning)
{
MessageBox.Show("A process is already running.");
return;
}
// Initialize the dialog that will contain the progress bar
ProgressDialog progressDialog = new ProgressDialog();
// Initialize the thread that will handle the background process
Thread backgroundThread = new Thread(
new ThreadStart(() =>
{
// Set the flag that indicates if a process is currently running
isProcessRunning = true;
// Set the dialog to operate in indeterminate mode
progressDialog.SetIndeterminate(true);
// Pause the thread for five seconds
Thread.Sleep(5000);
// Show a dialog box that confirms the process has completed
MessageBox.Show("Thread completed!");
// Close the dialog if it hasn't been already
if (progressBar1.InvokeRequired)
progressDialog.BeginInvoke(new Action(() => progressDialog.Close()));
// Reset the flag that indicates if a process is currently running
isProcessRunning = false;
}
));
// Start the background process thread
backgroundThread.Start();
// Open the dialog
progressDialog.ShowDialog();
}
}
}
|
3daec1b4b6ec867472065e473968e0923bc4e595
|
C#
|
DmitryAstapchik/NET.W.2017.Astapchik.15
|
/BLL.Tests/BankAccountMapperTests.orig.cs
| 2.71875
| 3
|
namespace BLL.Tests
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BLL;
using BLL.Interface;
using DAL.Interface;
using NUnit.Framework;
[TestFixture]
public class BankAccountMapperTests
{
static IEnumerable<BankAccountDTO> FromDTOTestCases
{
get
{
yield return new BankAccountDTO("123", "owner1", 120m, 2.33f, typeof(StandardAccount).FullName);
yield return new BankAccountDTO("456", "owner2", 5000m, 5.44f, typeof(GoldAccount).FullName);
yield return new BankAccountDTO("789", "owner3", 10001m, 3.11f, typeof(PlatinumAccount).FullName);
}
}
static IEnumerable<BankAccount> ToDTOTestCases
{
get
{
yield return new StandardAccount("123", "owner1", 120m, 2.33f);
yield return new GoldAccount("456", "owner2", 50m, 5.44f);
yield return new PlatinumAccount("789", "owner3", 100m, 3.11f);
}
}
[TestCaseSource("FromDTOTestCases")]
public void FromDTOTest(BankAccountDTO dto)
{
var account = BankAccountMapper.FromDTO(dto);
Assert.That(account.IBAN == dto.IBAN && account.Owner == dto.Owner && account.Balance == dto.Balance && account.BonusPoints == dto.BonusPoints && account.GetType().FullName == dto.AccountType);
}
[TestCaseSource("ToDTOTestCases")]
public void ToDTOTest(BankAccount account)
{
var dto = BankAccountMapper.ToDTO(account);
Assert.That(dto.IBAN == account.IBAN && dto.Owner == account.Owner && dto.Balance == account.Balance && dto.BonusPoints == account.BonusPoints && dto.AccountType == account.GetType().FullName);
}
}
}
|
6278c762ed077badfa8b5e605959f5f67a64b788
|
C#
|
Hina96/AI-Project
|
/AIproject/Assets/Scripts/RoomNode.cs
| 2.75
| 3
|
using UnityEngine;
public class RoomNode : Node
{
private int typeOfRoom;
public RoomNode(Vector2Int bottomLeftAreaCorner, Vector2Int topRightAreaCorner, Node parentNode, int index, int typeOfRoom) : base(parentNode)
{
// Creation of a rectangle
this.BottomLeftAreaCorner = bottomLeftAreaCorner;
this.TopRightAreaCorner = topRightAreaCorner;
this.BottomRightAreaCorner = new Vector2Int(topRightAreaCorner.x, bottomLeftAreaCorner.y);
this.TopLeftAreaCorner = new Vector2Int(bottomLeftAreaCorner.x, TopRightAreaCorner.y);
this.TreeLayerIndex = index;
this.typeOfRoom = typeOfRoom;
}
public int Width { get => (int)(TopRightAreaCorner.x - BottomLeftAreaCorner.x); }
public int Length { get => (int)(TopRightAreaCorner.y - BottomLeftAreaCorner.y); }
// Parameter that will be used for future implementation
public int TypeOfRoom { get => typeOfRoom; set => typeOfRoom = value; }
}
|
7888b11b0762d9d1f0bd9597c7106b93b37ef615
|
C#
|
Pathoschild/smapi-mod-dump
|
/source/PlatoTK/PlatoTK/UI/Styles/GridStyle.cs
| 2.546875
| 3
|
/*************************************************
**
** You're viewing a file in the SMAPI mod dump, which contains a copy of every open-source SMAPI mod
** for queries and analysis.
**
** This is *not* the original file, and not necessarily the latest version.
** Source repository: https://github.com/Platonymous/PlatoTK
**
*************************************************/
using Microsoft.Xna.Framework;
using PlatoTK.UI.Components;
namespace PlatoTK.UI.Styles
{
public class GridStyle : Style
{
public int Cols { get; set; } = 12;
public int Rows { get; set; } = 12;
public int Col { get; set; } = 0;
public int Row { get; set; } = 0;
public int ColSpan { get; set; } = 1;
public int RowSpan { get; set; } = 1;
public GridStyle(IPlatoHelper helper, string option = "")
: base(helper, option)
{
}
public override string[] PropertyNames => new string[] { "Grid", "Col", "Row", "ColSpan", "RowSpan" };
public override void Apply(IComponent component)
{
Rectangle baseBounds = component.Parent.Bounds;
Rectangle cellBounds = new Rectangle(0, 0, baseBounds.Width / Cols, baseBounds.Height / Rows);
component.Bounds = new Rectangle(cellBounds.Width * Col, cellBounds.Height * Row, cellBounds.Width * ColSpan, cellBounds.Height * RowSpan);
base.Apply(component);
}
public override void Parse(string property, string value, IComponent component)
{
switch (property.ToLower())
{
case "grid":
{
string[] parts = value.Split(' ');
if (parts.Length > 0 && int.TryParse(parts[0], out int cols))
{
Cols = cols;
Rows = cols;
}
if (parts.Length > 1 && int.TryParse(parts[1], out int rows))
Rows = rows;
break;
}
case "col": Col = int.TryParse(value, out int col) ? col : Col; break;
case "colspan": ColSpan = int.TryParse(value, out int colSpan) ? colSpan : ColSpan; break;
case "row": Row = int.TryParse(value, out int row) ? row : Row; break;
case "rowspan": RowSpan = int.TryParse(value, out int rowSpan) ? rowSpan : RowSpan; break;
}
}
}
}
|
52c3c0039093cfa565e3c64987486148bc5201cc
|
C#
|
areknoster/planar-three-colouring
|
/Planar3Coloring/Planar3Coloring/BFS.cs
| 3.046875
| 3
|
using QuikGraph;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Planar3Coloring
{
static class BFS
{
public static (List<HashSet<int>>, UndirectedGraph<int, IEdge<int>>, Dictionary<int, (int, int)>) GetBFSTree(UndirectedGraph<int, IEdge<int>> graph, int root)
{
UndirectedGraph<int, IEdge<int>> BFSTree = new UndirectedGraph<int, IEdge<int>>(false);
List<HashSet<int>> levels = new List<HashSet<int>>();
Dictionary<int, (int, int)> dict = new Dictionary<int, (int, int)>();
HashSet<int> enqueued = new HashSet<int>();
int level = 0;
int intNumberOnLevel = 0;
levels.Add(new HashSet<int>());
Queue<int> queue = new Queue<int>();
int nextLevelMark = -1;
queue.Enqueue(root);
enqueued.Add(root);
queue.Enqueue(nextLevelMark);
while (queue.Count>0)
{
int v = queue.Dequeue();
//Moving to next level
if (v == nextLevelMark)
{
level++;
if (queue.Count == 0)
break;
queue.Enqueue(nextLevelMark);
levels.Add(new HashSet<int>());
intNumberOnLevel = 0;
continue;
}
levels[level].Add(v);
dict.Add(v, (level, intNumberOnLevel));
intNumberOnLevel++;
//Add all v neighbours to queue
foreach (IEdge<int> e in graph.AdjacentEdges(v))
if (!enqueued.Contains(e.GetOtherVertex(v)))
{
queue.Enqueue(e.GetOtherVertex(v));
enqueued.Add(e.GetOtherVertex(v));
BFSTree.AddVerticesAndEdge(new Edge<int>(v, e.GetOtherVertex(v)));
}
}
levels.Add(new HashSet<int>());
return (levels, BFSTree, dict);
}
}
}
|