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
|
|---|---|---|---|---|---|---|
e231babb6ec4987c22f5fe75e7fdeb20fe6e6c65
|
C#
|
sinshu/tinyroomacoustics
|
/TinyRoomAcoustics/MirrorMethod/MirroredRoomIndex.cs
| 3.296875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using MathNet.Numerics;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Double;
namespace TinyRoomAcoustics.MirrorMethod
{
/// <summary>
/// Represents the index of a mirrored room generated in the mirror method.
/// Since the shape of rooms is cuboid, mirrored rooms are arranged in a grid pattern.
/// A room can be therefore identified by the three integers which represents the XYZ position of the grid.
/// The index of the original room is (0, 0, 0).
/// The index of the mirrored room next to the right side of the original room is (1, 0, 0), for instance.
/// </summary>
public sealed class MirroredRoomIndex
{
private readonly int x;
private readonly int y;
private readonly int z;
/// <summary>
/// Create a new room index.
/// </summary>
/// <param name="x">The X position of the room.</param>
/// <param name="y">The Y position of the room.</param>
/// <param name="z">The Z position of the room.</param>
public MirroredRoomIndex(int x, int y, int z)
{
this.x = x;
this.y = y;
this.z = z;
}
public override string ToString()
{
return "(" + x + ", " + y + ", " + z + ")";
}
/// <summary>
/// The X position of the room.
/// </summary>
public int X => x;
/// <summary>
/// The Y position of the room.
/// </summary>
public int Y => y;
/// <summary>
/// The Z position of the room.
/// </summary>
public int Z => z;
}
}
|
1a48270ec0adcb1735c78edc77f8f093d88d633b
|
C#
|
alibek123/PP2labs
|
/Week 1/Task2/Program.cs
| 3.921875
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Student
{
string name;
string id;
public Student(string n, string i)
{
name = n; //Creating the class "Student" with 2 parameters
id = i;
}
public void PrintInfo()
{
int n = 1;
for (int i = 0; i < 4; i++)
{
Console.WriteLine(name + " " + id + " " + n++); //Function will write student name and id 4 times repeatedly
}
}
}
class Program
{
static void Main(string[] args)
{
Student a = new Student("Alibek", "18BD110"); //Student info, entering the class
a.PrintInfo(); //Calling function
}
}
}
|
ae4f82aedf21ad16cf400ad329ba992e77f83410
|
C#
|
BrokenEmpire/NMSTools.Framework
|
/Primitives/Vector2.cs
| 3.203125
| 3
|
using System;
using System.Runtime.InteropServices;
using Newtonsoft.Json;
namespace NMSTools.Framework.Primitives
{
[JsonObject]
[StructLayout(LayoutKind.Sequential)]
public struct Vector2 : IEquatable<Vector2>
{
public double X;
public double Y;
public Vector2(double x, double y)
{
X = x;
Y = y;
}
public Vector2(Vector3 vector)
{
X = vector.X;
Y = vector.Y;
}
public double this[int index]
{
get
{
return index switch
{
0 => X,
1 => Y,
_ => 0,
};
}
set
{
switch (index)
{
case 0:
X = value;
break;
case 1:
Y = value;
break;
default:
throw new Exception();
}
}
}
public static Vector2 operator +(Vector2 left, Vector2 right)
{
left.X += right.X;
left.Y += right.Y;
return left;
}
public static Vector2 operator -(Vector2 left, Vector2 right)
{
left.X -= right.X;
left.Y -= right.Y;
return left;
}
public static Vector2 operator -(Vector2 vec)
{
vec.X = -vec.X;
vec.Y = -vec.Y;
return vec;
}
public static Vector2 operator *(Vector2 vec, double f)
{
vec.X *= f;
vec.Y *= f;
return vec;
}
public static Vector2 operator *(double f, Vector2 vec)
{
vec.X *= f;
vec.Y *= f;
return vec;
}
public static Vector2 operator /(Vector2 vec, double f)
{
double mult = 1.0 / f;
vec.X *= mult;
vec.Y *= mult;
return vec;
}
public static Vector2 operator /(double f, Vector2 vec)
{
vec.X = f / vec.X;
vec.Y = f / vec.Y;
return vec;
}
public static bool operator ==(Vector2 left, Vector2 right)
=> left.Equals(right);
public static bool operator !=(Vector2 left, Vector2 right)
=> !left.Equals(right);
public override string ToString()
=> string.Format("{0:g18},{1:g18}", X, Y);
public override int GetHashCode()
=> new { X, Y }.GetHashCode();
public override bool Equals(object obj)
=> obj is Vector2 v && Equals(v);
public bool Equals(Vector2 other)
=> X == other.X &&
Y == other.Y;
public bool Equals(Vector2 other, double errorRange)
=> (X < other.X + errorRange && X > other.X - errorRange) &&
(Y < other.Y + errorRange && Y > other.Y - errorRange);
}
}
|
b288e2b0d9b0d7281f4685a175b52c0cebdd49c7
|
C#
|
ghcver/Home
|
/CAPTCHA/ConsoleApplication17/Binarization.cs
| 3.109375
| 3
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication17
{
abstract class BinarizationBase
{
public abstract Bitmap Binarize(Bitmap bitmap);
}
class Binarization1 : BinarizationBase
{
private byte th = 120;
public override Bitmap Binarize(Bitmap bitmap)
{
for (int i = 1; i < bitmap.Width - 1; i++)
{
for (int j = 1; j < bitmap.Height - 1; j++)
{
if (Hit(bitmap.GetPixel(i, j)) == true)
{
int hit = 0;
if (Hit(bitmap.GetPixel(i, j - 1)) == true)
{
hit++;
}
if (Hit(bitmap.GetPixel(i + 1, j - 1)) == true)
{
hit++;
}
if (Hit(bitmap.GetPixel(i + 1, j)) == true)
{
hit++;
}
if (Hit(bitmap.GetPixel(i + 1, j + 1)) == true)
{
hit++;
}
if (Hit(bitmap.GetPixel(i, j + 1)) == true)
{
hit++;
}
if (Hit(bitmap.GetPixel(i - 1, j + 1)) == true)
{
hit++;
}
if (Hit(bitmap.GetPixel(i - 1, j)) == true)
{
hit++;
}
if (Hit(bitmap.GetPixel(i - 1, j - 1)) == true)
{
hit++;
}
if (hit >= 4)
{
bitmap.SetPixel(i, j, Color.White);
}
else
{
bitmap.SetPixel(i, j, Color.Black);
}
}
else
{
bitmap.SetPixel(i, j, Color.Black);
}
}
}
bitmap = bitmap.Clone(new Rectangle(1, 1, bitmap.Width - 2, bitmap.Height - 2), PixelFormat.Format24bppRgb);
return bitmap;
}
private bool Hit(Color color)
{
if (color.R > th && color.G > th && color.B > th)
{
return true;
}
else
{
return false;
}
}
}
class Binarization2 : BinarizationBase
{
private byte th = 10;
private class ColorRange
{
public byte R_L;
public byte R_U;
public byte G_L;
public byte G_U;
public byte B_L;
public byte B_U;
}
private ColorRange GetColorRange(Color color)
{
ColorRange range = new ColorRange();
range.R_L = (byte)(color.R - th < 0 ? 0 : color.R - th);
range.R_U = (byte)(color.R + th > 255 ? 255 : color.R + th);
range.G_L = (byte)(color.G - th < 0 ? 0 : color.G - th);
range.G_U = (byte)(color.G + th > 255 ? 255 : color.G + th);
range.B_L = (byte)(color.B - th < 0 ? 0 : color.B - th);
range.B_U = (byte)(color.B + th > 255 ? 255 : color.B + th);
return range;
}
public override Bitmap Binarize(Bitmap bitmap)
{
Dictionary<Color, int> colorDic = new Dictionary<Color, int>();
for (int i = 0; i < bitmap.Width; i++)
{
for (int j = 0; j < bitmap.Height; j++)
{
Color color = bitmap.GetPixel(i, j);
if(colorDic.ContainsKey(color) == true)
{
colorDic[color] = colorDic[color] + 1;
}
else
{
colorDic[color] = 1;
}
}
}
Dictionary<Color, int> colorRank = new Dictionary<Color, int>();
foreach(var item in colorDic)
{
int rank = 0;
Color color = item.Key;
ColorRange colorRange = GetColorRange(color);
foreach (var innerItem in colorDic)
{
Color innerColor = innerItem.Key;
if((innerColor.R >= colorRange.R_L && innerColor.R <= colorRange.R_U) && (innerColor.G >= colorRange.G_L && innerColor.G <= colorRange.G_U) && (innerColor.B >= colorRange.B_L && innerColor.B <= colorRange.B_U))
{
rank = rank + innerItem.Value;
}
}
colorRank[color] = rank;
}
Bitmap result = new Bitmap(bitmap.Width, bitmap.Height, PixelFormat.Format24bppRgb);
Color hitColor = colorRank.OrderByDescending(i => i.Value).ToArray()[0].Key;
for (int i = 0; i < bitmap.Width; i++)
{
for (int j = 0; j < bitmap.Height; j++)
{
ColorRange colorRange = GetColorRange(hitColor);
Color color = bitmap.GetPixel(i, j);
if ((color.R >= colorRange.R_L && color.R <= colorRange.R_U) && (color.G >= colorRange.G_L && color.G <= colorRange.G_U) && (color.B >= colorRange.B_L && color.B <= colorRange.B_U))
{
result.SetPixel(i, j, Color.White);
}
else
{
result.SetPixel(i, j, Color.Black);
}
}
}
return result;
}
}
class Binarization3 : BinarizationBase
{
private byte th = 200;
public override Bitmap Binarize(Bitmap bitmap)
{
Bitmap result = new Bitmap(bitmap.Width, bitmap.Height, PixelFormat.Format24bppRgb);
for (int i = 0; i < bitmap.Width; i++)
{
for (int j = 0; j < bitmap.Height; j++)
{
Color color = bitmap.GetPixel(i, j);
result.SetPixel(i, j, Color.FromArgb((color.R + color.G + color.B) / 3, (color.R + color.G + color.B) / 3, (color.R + color.G + color.B) / 3));
}
}
for (int i = 0; i < result.Width; i++)
{
for (int j = 0; j < result.Height; j++)
{
Color color = result.GetPixel(i, j);
if (color.R > th)
{
result.SetPixel(i, j, Color.White);
}
else
{
result.SetPixel(i, j, Color.Black);
}
}
}
return result;
}
}
}
|
6bc5138832de072757e03e71fad98c5140b5d2b6
|
C#
|
ichivers/pingrecorder
|
/PingRecorder/PingRecorder/Program.cs
| 2.828125
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.NetworkInformation;
using System.IO;
using System.Threading;
namespace PingRecorder
{
class Program
{
private static TextWriter writer;
static void Main(string[] args)
{
Console.TreatControlCAsInput = false;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
Console.WriteLine("Press Ctrl + C to quit");
Arguments commandLine = new Arguments(args);
int delay = commandLine["delay"] == null ? 60000 : Convert.ToInt32(commandLine["delay"]);
if (args.Length == 0)
{
Console.WriteLine("");
Console.WriteLine("usage: pingrecorder [-timeout milliseconds] [-delay milliseconds]");
Console.WriteLine(" [-output output_filename] target_name");
Console.WriteLine("");
Console.WriteLine("Options:");
Console.WriteLine(" -output filename File to write output");
Console.WriteLine(" -timeout milliseconds Timeout in millseconds to wait for each reply");
Console.WriteLine(" -delay milliseconds Delay in milliseconds between each ping");
}
else
{
FileInfo output = new FileInfo(commandLine["output"]);
writer = output.CreateText();
while (true)
{
Thread pingThread = new Thread(new ParameterizedThreadStart(ping));
pingThread.Start(args);
Thread.Sleep(delay);
}
}
}
static void ping(object param)
{
Ping pingSender = new Ping();
PingOptions options = new PingOptions();
string[] args = (string[])param;
Arguments commandLine = new Arguments((string[])param);
options.DontFragment = true;
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = commandLine["timeout"] == null ? 5000 : Convert.ToInt32(commandLine["timeout"]);
PingReply reply = pingSender.Send(args[args.Length - 1], timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
writer.WriteLine(DateTime.Now.ToString("hh:mm") + "," + reply.RoundtripTime.ToString());
Console.WriteLine(DateTime.Now.ToString() + ": Reply from " + reply.Address + " bytes=32 time=" + reply.RoundtripTime + "ms");
}
else
{
writer.WriteLine(DateTime.Now.ToString("hh:mm") + "," + timeout.ToString());
Console.WriteLine(DateTime.Now.ToString() + ": Request timed out");
}
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
writer.Close();
}
}
}
|
b20f5d88febaa0f0fb23e29f2c8f339faead48de
|
C#
|
PhilJollans/WpfShapes
|
/WpfShapes/RingOfRectangularTicks.cs
| 2.75
| 3
|
using System;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;
namespace WpfShapes
{
/// <summary>
/// RingOfRectangularTicks is a ring of n rectangles, evenly spaced on a circle.
/// The width of each rectangle is approximately the spacing between rectangles
/// defined by SizeRatio.
/// </summary>
public class RingOfRectangularTicks : Shape
{
private string _path = null ;
public static readonly DependencyProperty InnerRadiusProperty =
DependencyProperty.Register ( "InnerRadius",
typeof(double),
typeof(RingOfRectangularTicks),
new FrameworkPropertyMetadata ( 70.0,
FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure,
OnShapeChanged ) ) ;
public static readonly DependencyProperty OuterRadiusProperty =
DependencyProperty.Register ( "OuterRadius",
typeof(double),
typeof(RingOfRectangularTicks),
new FrameworkPropertyMetadata ( 80.0,
FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure,
OnShapeChanged ) ) ;
public static readonly DependencyProperty SizeRatioProperty =
DependencyProperty.Register ( "SizeRatio",
typeof(double),
typeof(RingOfRectangularTicks),
new FrameworkPropertyMetadata ( 7.0,
FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure,
OnShapeChanged ) ) ;
public static readonly DependencyProperty NumberOfTicksProperty =
DependencyProperty.Register ( "NumberOfTicks",
typeof(int),
typeof(RingOfRectangularTicks),
new FrameworkPropertyMetadata ( 32,
FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure,
OnShapeChanged ) ) ;
public static readonly DependencyProperty CenterProperty =
DependencyProperty.Register ( "Center",
typeof(Point),
typeof(RingOfRectangularTicks),
new FrameworkPropertyMetadata ( new Point(0,0),
FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure,
OnShapeChanged ) ) ;
public RingOfRectangularTicks ()
{
// Initialise the geometry with the default parameters.
InitializeGeometry() ;
}
protected override Geometry DefiningGeometry
{
get
{
return Geometry.Parse ( _path ) ;
}
}
//-------------------------------------------------------------------------
// Getters and setters for the dependency properties
//-------------------------------------------------------------------------
public double InnerRadius
{
get { return Convert.ToDouble(GetValue(InnerRadiusProperty)); }
set { SetValue(InnerRadiusProperty, value); }
}
public double OuterRadius
{
get { return Convert.ToDouble(GetValue(OuterRadiusProperty)); }
set { SetValue(OuterRadiusProperty, value); }
}
public double SizeRatio
{
get { return Convert.ToDouble(GetValue(SizeRatioProperty)); }
set { SetValue(SizeRatioProperty, value); }
}
public int NumberOfTicks
{
get { return Convert.ToInt32(GetValue(NumberOfTicksProperty)); }
set { SetValue(NumberOfTicksProperty, value); }
}
public Point Center
{
get { return (Point)GetValue(CenterProperty); }
set { SetValue(CenterProperty, value); }
}
//-------------------------------------------------------------------------
// Property changed callbacks
//-------------------------------------------------------------------------
public static void OnShapeChanged ( DependencyObject d, DependencyPropertyChangedEventArgs e )
{
var ao = d as RingOfRectangularTicks ;
ao.InitializeGeometry() ;
}
//-------------------------------------------------------------------------
// Member functions
//-------------------------------------------------------------------------
private void InitializeGeometry()
{
var CenterVector = (Vector)Center ;
double w = 2 * Math.PI * OuterRadius / ( NumberOfTicks * SizeRatio ) ;
double h = w / 2 ;
var sb = new StringBuilder() ;
for ( int i = 0 ; i < NumberOfTicks ; i++ )
{
double a = Math.PI * 2 * i / NumberOfTicks ;
double c = Math.Cos ( a ) ;
double s = Math.Sin ( a ) ;
var pOuterMiddle = new Point ( OuterRadius * s, OuterRadius * c ) + CenterVector ;
var pInnerMiddle = new Point ( InnerRadius * s, InnerRadius * c ) + CenterVector;
var offset = new Vector ( h * c, -h * s ) ;
var p1 = pOuterMiddle + offset ;
var p2 = pInnerMiddle + offset ;
var p3 = pInnerMiddle - offset ;
var p4 = pOuterMiddle - offset ;
sb.AppendFormat ( CultureInfo.InvariantCulture, "M {0:F3},{1:F3} ", p1.X, p1.Y ) ;
sb.AppendFormat ( CultureInfo.InvariantCulture, "L {0:F3},{1:F3} ", p2.X, p2.Y ) ;
sb.AppendFormat ( CultureInfo.InvariantCulture, "L {0:F3},{1:F3} ", p3.X, p3.Y ) ;
sb.AppendFormat ( CultureInfo.InvariantCulture, "L {0:F3},{1:F3} ", p4.X, p4.Y ) ;
sb.Append ( "Z " ) ;
}
_path = sb.ToString() ;
Debug.WriteLine ( _path ) ;
}
}
}
|
1389fe513c636578ffe2130a89d11da24c4d1b3e
|
C#
|
thanhlcm90/moorwohsesirnus
|
/DataAccess/DataAccess/News.cs
| 3.0625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Showroom.Models.DataAccess
{
public partial class ShowroomRepository
{
/// <summary>
/// Lấy toàn bộ danh sách nhóm sản phẩm
/// </summary>
/// <returns>List of New</returns>
public List<News> GetNewsList()
{
try
{
var list = from p in _dataContext.News select p;
return list.ToList();
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Lấy thông tin của 1 nhóm sản phẩm
/// </summary>
/// <param name="id">Mã nhóm sản phẩm</param>
/// <returns></returns>
public News GetNewsInfo(int id)
{
try
{
var item = from p in _dataContext.News
where p.Id == id
select p;
// Trả về 1 giá trị hoặc mặc định (null)
return item.SingleOrDefault();
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Thêm mới 1 nhóm sản phẩm
/// </summary>
/// <param name="item">Đối tượng cần thêm</param>
/// <returns>True: Thành công; False: Thất bại</returns>
public bool InsertNews(News item)
{
try
{
_dataContext.News.InsertOnSubmit(item);
_dataContext.SubmitChanges();
return true;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Thay đổi thông tin của đối tượng theo Id chứa trong Object
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool UpdateNews(News item)
{
try
{
// Tìm kiếm đối tượng có Id cần sửa đổi
News itemUpdate = (from p in _dataContext.News where p.Id == item.Id select p).SingleOrDefault();
// Nếu không tìm thấy thì trả về False
if (itemUpdate == null) return false;
// Copy toàn bộ giá trị từ item sang itemUpdate. Submit thay đổi
item.CopyProperties(itemUpdate);
_dataContext.SubmitChanges();
return true;
}
catch (Exception ex)
{
throw ex;
}
}
public bool DeleteNews(int Id)
{
try
{
// Tìm kiếm đối tượng có Id cần sửa đổi
News itemDelete = (from p in _dataContext.News where p.Id == Id select p).SingleOrDefault();
// Nếu không tìm thấy thì trả về False
if (itemDelete == null) return false;
// Xóa và Submit thay đổi
_dataContext.News.DeleteOnSubmit(itemDelete);
_dataContext.SubmitChanges();
return true;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Lấy danh sách News theo Catalogue ID
/// </summary>
/// <param name="IdNewsCatalogue"></param>
/// <returns></returns>
public List<News> GetListNewsByCATAID(int IdNewsCatalogue)
{
try
{
var list = from p in _dataContext.News
where p.CatelogueId == IdNewsCatalogue
select p;
return list.ToList();
}
catch (Exception)
{
throw;
}
}
}
}
|
6c9e5cf45c6a4b784ee028c89a66f13c35e7e9b2
|
C#
|
CECS-491A/GC-GreetNGroup
|
/Backend/ManagerLayer/SearchManager/SearchManager.cs
| 2.59375
| 3
|
using System.Collections.Generic;
using Gucci.DataAccessLayer.DataTransferObject;
using Gucci.ServiceLayer.Services;
namespace Gucci.ManagerLayer.SearchManager
{
// This class provides an interface for interaction with required search functions
public class SearchManager
{
private readonly ISearchable<List<DefaultEventSearchDto>> _eventSearchManager = new EventSearchManager();
private readonly ISearchable<List<DefaultUserSearchDto>> _userSearchManager = new UserSearchManager();
private readonly EventService _eventService = new EventService();
// Used to return list of events given a name -- List is allowed to be empty
public List<DefaultEventSearchDto> GetEventListByName(string name)
{
return _eventService.FilterOutPastEvents(_eventSearchManager.SearchByName(name));
}
// Used to return User given username -- User is allowed to be null
public List<DefaultUserSearchDto> GetUserByUsername(string name)
{
return _userSearchManager.SearchByName(name);
}
// Used to return Username given id -- user is allowed to be null
public List<DefaultUserSearchDto> GetUserByUserId(int id)
{
return _userSearchManager.SearchById(id);
}
}
}
|
cc93548308903d474d5d88dcf7e02d7e3f3a4a0e
|
C#
|
YadielRosario/IT1050Final-Project
|
/bankaccount.cs
| 3.484375
| 3
|
using System;
class BankAccount{
private string accountNumber;
protected double balance;
private DateTime dateCreated;
private string AccountNumber{
get{return accountNumber;}
set{
if (value.Length == 6)
accountNumber = value;
else
Console.WriteLine("Account number must be 6 digits in length.");
}
}
private string Name {get; set;}
private double Balance {
get{return balance;}
set{
if (value >= 0)
balance = value;
else
Console.WriteLine("Starting account balance cannot be negative.");
}
}
private DateTime DateCreated{
get{return dateCreated;}
set{
if(value < DateTime.Now)
dateCreated = value;
else
Console.WriteLine("Account creation date cannot be in the future.");
}
}
public BankAccount()
{
DateCreated = DateTime.Now;
}
public BankAccount(string accnbr, string nme, double bal)
{
AccountNumber = accnbr;
Name = nme;
Balance = bal;
DateCreated = DateTime.Now;
}
public void DisplayAccountInfo()
{
Console.WriteLine("Account number: {0}", AccountNumber);
Console.WriteLine("Name: {0}", Name);
Console.WriteLine("Balance: {0}", Balance);
}
public void Deposit(double amount)
{
Balance += amount;
Console.WriteLine("Balance: {0}", Balance);
}
public virtual void Withdraw(double amount)
{
if (Balance > amount)
Balance -= amount;
else
Console.WriteLine("Error, withdrawal amount cannot be greater than balance");
Console.WriteLine("Balance: {0}", Balance);
}
public virtual void CalculateInterest(int years)
{
Console.WriteLine("This method will calculate interest.");
}
}
|
2caae50cd67af136e03312454b3739bba40d925c
|
C#
|
AdrianSkr/All-Assignments---Project-Case
|
/catch_enum_struct/catch_enum_struct/Program.cs
| 3.328125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mandag280518TryCatch
{
class Program
{
static void Main(string[] args)
{
/*
* #region TryParseFinally
//string s = "5555555555555555555555555555555555555";
//try
//{
// int i = int.Parse(s);
//}
//catch (ArgumentNullException ee)
//{
// Console.WriteLine(ee.Message);
//}
//catch (FormatException e)
//{
// Console.WriteLine(e.Message + " " + e.StackTrace);
//}
//catch (Exception eee) ///generel type, der fanger alle andre exceptions uanset type (toppen af hierakiet)
//{
// Console.WriteLine(eee.Message);
// //Environment.FailFast("FailFast"); //for programmet til at lukke ned uden her og nu, uden finally gennemføres
//}
//finally
//{
// Console.WriteLine("Dette bliver altid udført - finally");
//}
#endregion
#region throw exception
try
{
string s = OpendAndParse(null);
}
catch (ArgumentNullException e)
{
Console.WriteLine("Arg null ex: " + e.Message);
}
#endregion
}
private static string OpendAndParse(string filename)
{
if (string.IsNullOrWhiteSpace(filename))
{
throw new ArgumentNullException("filename", "filename is required");
}
return File.ReadAllText(filename);
*/
string str = "123a";
//int i = int.Parse(str);
try
{
int i = int.Parse(str);
Console.WriteLine("Der kom ikke en exception");
}
catch (ArgumentNullException)
{
Console.WriteLine("Du skal angives en værdi");
}
catch (Exception e)
{
Console.WriteLine("Der kom en exception, {0} er ikke valid", str);
Console.WriteLine("Message: " + e.Message);
Console.WriteLine("StackTrace: " + e.StackTrace);
Console.WriteLine("HelpLink: " + e.HelpLink);
Console.WriteLine("InnerException: " + e.InnerException);
Console.WriteLine("TargetSite: " + e.TargetSite);
Console.WriteLine("Source: " + e.Source);
//Environment.FailFast("Program fejler lukkes ned");
}
finally
{
//kode udføres altid
Console.WriteLine("Program afsluttes");
Console.ReadKey();
}
Console.ReadKey();
}
}
}
|
19a499b7d999bbf9dee6a720c6f9a06039c55163
|
C#
|
andycmaj/OmniSharpServer
|
/OmniSharp/AutoComplete/CompletionDataExtensions.cs
| 2.734375
| 3
|
using System.Collections.Generic;
using System.Linq;
using ICSharpCode.NRefactory.Completion;
namespace OmniSharp.AutoComplete
{
public static class CompletionDataExtensions
{
public static IEnumerable<ICompletionData> FlattenOverloads(this IEnumerable<ICompletionData> completions)
{
var res = new List<ICompletionData>();
foreach (var completion in completions)
{
res.AddRange(completion.HasOverloads ? completion.OverloadedData : new[] { completion });
}
return res;
}
public static IEnumerable<ICompletionData> RemoveDupes(this IEnumerable<ICompletionData> data)
{
return data.GroupBy(x => x.DisplayText,
(k, g) => g.Aggregate((a, x) => (CompareTo(x, a) == -1) ? x : a));
}
private static int CompareTo(ICompletionData a, ICompletionData b)
{
if (a.CompletionCategory == null && b.CompletionCategory == null)
return 0;
if (a.CompletionCategory == null)
return -1;
if (b.CompletionCategory == null)
return 1;
return a.CompletionCategory.CompareTo(b.CompletionCategory);
}
}
}
|
e0d3be8938b5d1b588d96c5d5da688902789fa2a
|
C#
|
AlbertBaffour/4_on_a_row-WPF
|
/WpfProjectAlbert/Model/SchijfDataService.cs
| 3.125
| 3
|
using Dapper;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WpfProjectAlbert.Model
{
class SchijfDataService
{
// Ophalen ConnectionString uit App.config
private static string connectionString =
ConfigurationManager.ConnectionStrings["azure"].ConnectionString;
// Stap 1 Dapper
// Aanmaken van een object uit de IDbConnection class en
// instantiëren van een SqlConnection.
// Dit betekent dat de connectie met de database automatisch geopend wordt.
private static IDbConnection db = new SqlConnection(connectionString);
public Schijf GetSchijf(int id)
{
Schijf s = new Schijf();
string sql = "SELECT * from Schijf where Id=" + id +";";
var schijf = db.Query<Schijf>(sql);
foreach (var attr in schijf)
{
s.Id = attr.Id;
s.FillColor=attr.FillColor;
}
return s;
}
public List<Schijf> GetSchijfjes()
{
// Stap 2 Dapper
// Uitschrijven SQL statement & bewaren in een string.
string sql = "Select * from Schijf;";
// Stap 3 Dapper
// Uitvoeren SQL statement op db instance
// Type casten van het generieke return type naar een collectie van contactpersonen
return (List<Schijf>)db.Query<Schijf>(sql);
}
}
}
|
048acf0faa394f6887b2d81f894f9d9445da1153
|
C#
|
qowsley/TechElevator-1
|
/module-1/09_Classes_Encapsulation/lecture-final/dotnet/EncapsulationLecture/CollectionsReviewScratch.cs
| 3.40625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace CollectionsPart2Lecture
{
public class CollectionsReviewScratch
{
public void LectureReview()
{
List<string> colors = new List<string>();
colors.Add("Purple");
colors.Add("Steel Blue");
colors.Add("Dark Clear");
colors.Add("Orange");
// Foreach vs For
for (int i = 0; i < colors.Count; i++)
{
string color = colors[i];
Console.WriteLine(color);
}
foreach (string color in colors)
{
Console.WriteLine(color);
}
// Storing an Int in a List of Strings
int number = 4;
List<string> fizzBuzzAnswers = new List<string>();
fizzBuzzAnswers.Add(number.ToString()); // "4"
// Dictionary Example
Dictionary<string, int> speedingOffenses = new Dictionary<string, int>();
for (int i = 0; i < 42; i++)
{
// Check to see if they know about me (if I have any prior entries)
if (speedingOffenses.ContainsKey("T00 F4ST"))
{
speedingOffenses["T00 F4ST"] = speedingOffenses["T00 F4ST"] + 1;
}
else
{
speedingOffenses["T00 F4ST"] = 1;
}
}
int clientsSpeedingTickets = speedingOffenses["T00 F4ST"];
}
}
}
|
b1c18901e11dc0da1afeba5b5a1d02bac6c4b5ca
|
C#
|
mohsenyousefiyan/RsaAesEnctyption
|
/Core/EncryptionTools/AESFileCryptographyService.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Core.EncryptionTools
{
public class AESFileCryptographyService
{
private int KeySize;
private PaddingMode PaddingMode;
private CipherMode CipherMode;
public AESFileCryptographyService()
{
KeySize = 256;
PaddingMode = PaddingMode.PKCS7;
CipherMode = CipherMode.ECB;
}
public byte[] EncryptFile(byte[] fileContent, string base64Key)
{
KeyValidation(base64Key);
try
{
byte[] encrypted;
byte[] IV;
byte[] keyByte = StringHelper.Base64ToByteArray(base64Key);
using (Aes aesAlg = Aes.Create())
{
IV = GenerateRandomNumber(aesAlg.BlockSize / 8);
aesAlg.Key = keyByte;
aesAlg.IV = IV;
aesAlg.Mode = CipherMode.CBC;
var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (var memStream = new MemoryStream())
{
CryptoStream cryptoStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(fileContent, 0, fileContent.Length);
cryptoStream.FlushFinalBlock();
encrypted = memStream.ToArray();
}
}
var combinedIvCt = new byte[IV.Length + encrypted.Length];
Array.Copy(IV, 0, combinedIvCt, 0, IV.Length);
Array.Copy(encrypted, 0, combinedIvCt, IV.Length, encrypted.Length);
return combinedIvCt;
}
catch
{
return null;
}
}
public byte[] DecryptFile(byte[] fileContent, string base64Key)
{
KeyValidation(base64Key);
try
{
byte[] keyByte = StringHelper.Base64ToByteArray(base64Key);
var cipherTextCombined = fileContent;
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = keyByte;
byte[] IV = new byte[aesAlg.BlockSize / 8];
byte[] cipherText = new byte[cipherTextCombined.Length - IV.Length];
Array.Copy(cipherTextCombined, IV, IV.Length);
Array.Copy(cipherTextCombined, IV.Length, cipherText, 0, cipherText.Length);
aesAlg.IV = IV;
aesAlg.Mode = CipherMode.CBC;
var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (var memStream = new MemoryStream())
{
CryptoStream cryptoStream = new CryptoStream(memStream, decryptor,
CryptoStreamMode.Write);
cryptoStream.Write(cipherText, 0, cipherText.Length);
cryptoStream.FlushFinalBlock();
return memStream.ToArray();
}
}
}
catch
{
return null;
}
}
private AesCryptoServiceProvider CreateAESProvider()
{
return new AesCryptoServiceProvider
{
KeySize = 256,
BlockSize = 128,
Padding = PaddingMode.PKCS7,
Mode = CipherMode.ECB
};
}
private void KeyValidation(string base64Key)
{
if (StringHelper.Base64ToByteArray(base64Key).Length * 8 != this.KeySize)
throw new Exception("Key Length And KeySize Is Not Compatible");
}
private byte[] GenerateRandomNumber(int size)
{
var random = new RNGCryptoServiceProvider();
var number = new byte[size];
random.GetBytes(number);
return number;
}
}
}
|
ec615ddfe5d73345bb21e374ee00f291cb8cdb90
|
C#
|
maron6/SEIDR
|
/SEIDR/DataBase/DatabaseManagerExtensions.cs
| 3.140625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Data;
namespace SEIDR.DataBase
{
public static class DatabaseManagerExtensions
{
/// <summary>
/// Flag Parameter direction to determine if the value needs to be checked after execution
/// </summary>
public const ParameterDirection CheckOutput = ParameterDirection.Output | ParameterDirection.ReturnValue;
/// <summary>
/// Returns the mapped name (by FieldMapping attribute), or the property's actual name if there is no populated mapping.
/// </summary>
/// <param name="prop"></param>
/// <returns></returns>
public static string GetMappedName(this PropertyInfo prop)
{
var att = prop.GetCustomAttribute(typeof(DatabaseManagerFieldMappingAttribute));
if (att != null)
return ((DatabaseManagerFieldMappingAttribute)att).MappedName ?? prop.Name;
return prop.Name;
}
/// <summary>
/// Returns a dictionary of the mapped property names and their getMethods
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public static Dictionary<string, MethodInfo> GetGetters(this Type t)
{
return t
.GetProperties()
.Where(p => p.CanRead && !p.MappingIgnored(false))
.ToDictionary(pn => pn.GetMappedName(), pn => pn.GetMethod);
}
/// <summary>
/// Checks if the property should be ignored by the DatabaseManager when working with SqlParameters
/// </summary>
/// <param name="prop"></param>
/// <param name="forOutParameter">Ignores the mapping only when checking Out Parameters for their updated values</param>
/// <returns></returns>
public static bool MappingIgnored(this PropertyInfo prop, bool forOutParameter)
{
DatabaseManagerIgnoreMappingAttribute att = prop.GetCustomAttribute(typeof(DatabaseManagerIgnoreMappingAttribute)) as DatabaseManagerIgnoreMappingAttribute;
if (att == null)
return false;
if (forOutParameter)
return att.IgnoreReadOut;
return att.IgnoreSet;
}
}
/// <summary>
/// Tells the DatabaseManager to ignore a mapping. Should only be used if there's a default value
/// </summary>
public class DatabaseManagerIgnoreMappingAttribute :Attribute
{
/// <summary>
/// Ignore setting the value in parameters when populating the SqlCommand's parameters if the direction to ignore is either <see cref="ParameterDirection.Input"/> or <see cref="ParameterDirection.InputOutput"/>
/// </summary>
public bool IgnoreSet { get; private set; } = false;
/// <summary>
/// Ignore reading the output parameters of the SqlCommand after execution if the direction to ignore is <see cref="ParameterDirection.InputOutput"/>, <see cref="ParameterDirection.Output"/>, or <see cref="ParameterDirection.ReturnValue"/>
/// </summary>
public bool IgnoreReadOut { get; private set; } = false;
/// <summary>
/// Tells DatabaseManager to ignore the parameter for the specified direction
/// </summary>
/// <param name="directionToIgnore"></param>
public DatabaseManagerIgnoreMappingAttribute(ParameterDirection directionToIgnore)
{
if((directionToIgnore & DatabaseManagerExtensions.CheckOutput) != 0)
{
IgnoreReadOut = true;
}
if((directionToIgnore
& (ParameterDirection.Input | ParameterDirection.InputOutput))
!= 0)
{
IgnoreSet = true;
}
}
}
public class DatabaseManagerIgnoreOutParameterAttribute :Attribute { }
/// <summary>
/// Changes the name for properties by the DatabaseManager when doing any mappings from/to objects
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple =false, Inherited = false)]
public class DatabaseManagerFieldMappingAttribute:Attribute
{
/// <summary>
/// Name to be used by DatabaseManagers
/// </summary>
public readonly string MappedName;
/// <summary>
/// Maps the property to a different name for use in DatabaseManager mappings
/// </summary>
/// <param name="Map">Name to use. Note: This value will be trimmed and set to null if empty. If a property should be ignored in mapping, use the DatabaseManagerIgnoreMapping attribute</param>
public DatabaseManagerFieldMappingAttribute(string Map)
{
MappedName = Map.nTrim(true);
}
}
}
|
dd4fb7402b74aff3d5ab3ad8923c82fdc336f893
|
C#
|
block-core/blockcore
|
/src/Blockcore/NBitcoin/Target.cs
| 2.9375
| 3
|
using System;
using System.Globalization;
using System.Linq;
using Blockcore.NBitcoin.BouncyCastle.math;
namespace Blockcore.NBitcoin
{
/// <summary>
/// Represent the challenge that miners must solve for finding a new block
/// </summary>
public class Target
{
private static Target difficulty1 = new Target(new byte[] { 0x1d, 0x00, 0xff, 0xff });
public static Target Difficulty1
{
get
{
return difficulty1;
}
}
public Target(uint compact) : this(ToBytes(compact))
{
}
private static byte[] ToBytes(uint bits)
{
return new byte[]
{
(byte)(bits >> 24),
(byte)(bits >> 16),
(byte)(bits >> 8),
(byte)(bits)
};
}
private BigInteger target;
public Target(byte[] compact)
{
if (compact.Length == 4)
{
byte exp = compact[0];
var val = new BigInteger(compact.SafeSubarray(1, 3));
this.target = val.ShiftLeft(8 * (exp - 3));
}
else
{
throw new FormatException("Invalid number of bytes");
}
}
public Target(BigInteger target)
{
this.target = target;
this.target = new Target(ToCompact()).target;
}
public Target(uint256 target)
{
this.target = new BigInteger(target.ToBytes(false));
this.target = new Target(ToCompact()).target;
}
public static implicit operator Target(uint a)
{
return new Target(a);
}
public static implicit operator uint(Target a)
{
byte[] bytes = a.target.ToByteArray();
byte[] val = bytes.SafeSubarray(0, Math.Min(bytes.Length, 3));
Array.Reverse(val);
byte exp = (byte)(bytes.Length);
if (exp == 1 && bytes[0] == 0)
exp = 0;
int missing = 4 - val.Length;
if (missing > 0)
val = val.Concat(new byte[missing]).ToArray();
if (missing < 0)
val = val.Take(-missing).ToArray();
return (uint)val[0] + (uint)(val[1] << 8) + (uint)(val[2] << 16) + (uint)(exp << 24);
}
private double? difficulty;
public double Difficulty
{
get
{
if (this.difficulty == null)
{
BigInteger[] qr = Difficulty1.target.DivideAndRemainder(this.target);
BigInteger quotient = qr[0];
BigInteger remainder = qr[1];
BigInteger decimalPart = BigInteger.Zero;
for (int i = 0; i < 12; i++)
{
BigInteger div = (remainder.Multiply(BigInteger.Ten)).Divide(this.target);
decimalPart = decimalPart.Multiply(BigInteger.Ten);
decimalPart = decimalPart.Add(div);
remainder = remainder.Multiply(BigInteger.Ten).Subtract(div.Multiply(this.target));
}
this.difficulty = double.Parse(quotient.ToString() + "." + decimalPart.ToString(), new NumberFormatInfo()
{
NegativeSign = "-",
NumberDecimalSeparator = "."
});
}
return this.difficulty.Value;
}
}
public override bool Equals(object obj)
{
var item = obj as Target;
if (item == null)
return false;
return this.target.Equals(item.target);
}
public static bool operator ==(Target a, Target b)
{
if (ReferenceEquals(a, b))
return true;
if (((object)a == null) || ((object)b == null))
return false;
return a.target.Equals(b.target);
}
public static bool operator !=(Target a, Target b)
{
return !(a == b);
}
public override int GetHashCode()
{
return this.target.GetHashCode();
}
public BigInteger ToBigInteger()
{
return this.target;
}
public uint ToCompact()
{
return (uint)this;
}
public uint256 ToUInt256()
{
return ToUInt256(this.target);
}
internal static uint256 ToUInt256(BigInteger input)
{
return ToUInt256(input.ToByteArray());
}
internal static uint256 ToUInt256(byte[] array)
{
int missingZero = 32 - array.Length;
if (missingZero < 0)
throw new InvalidOperationException("Awful bug, this should never happen");
if (missingZero != 0)
{
Span<byte> buffer = stackalloc byte[32];
array.AsSpan().CopyTo(buffer.Slice(missingZero));
return new uint256(buffer, false);
}
return new uint256(array, false);
}
public override string ToString()
{
return this.ToUInt256().ToString();
}
}
}
|
de302ef9ded81b58c23f74ecb9c613d2e736f57f
|
C#
|
artursolekss/sessionExamples
|
/Interfaces/Circle.cs
| 3.546875
| 4
|
using System;
namespace AbstractClInterfaces
{
public class Circle : IFigure
{
private double radiuss;
public double GetRadiuss()
{
return this.radiuss;
}
public void SetRadiuss(double radiuss)
{
this.radiuss = radiuss;
}
public double CalculatePerimeter()
{
return 2 * this.radiuss * Math.PI;
}
public double CalculateArea()
{
return Math.PI * this.radiuss * this.radiuss;
}
public override string ToString()
{
return "Circle";
}
}
}
|
028a6d56538503eba963457707c331c808a3981c
|
C#
|
ncoder83/carbon
|
/Business/Calculator.cs
| 3.140625
| 3
|
namespace Carbon.Business
{
public class Calculator
{
public static decimal TotalPaidYearly(int numberOfPaychecks, decimal amountPerPaycheck)
{
var total = numberOfPaychecks * amountPerPaycheck;
if (total <= 0)
return 0.00m;
return total;
}
public static decimal TotalFromBenefit(decimal benefitCost, decimal costPerDependents, int numberOfDependents, decimal discount = 0)
{
var totalBenefit = benefitCost + (numberOfDependents * costPerDependents);
var totalDiscount = totalBenefit * discount * 0.01m;
return totalBenefit - totalDiscount;
}
public static decimal TotalDiscount(string name)
{
name = name.Trim();
return name[0].ToString().ToLower() == "a" ? 10.00m : 0.00m;
}
}
}
|
6b01fe85f07830435361d4618480688c4e93481d
|
C#
|
MrMorham/Battleship-Commander
|
/Battleships v2/Enemy Manager.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
namespace Battleships_v2
{
public class EnemyManager
{
public List<string> Designations = new List<string> { "ALPHA", "BRAVO", "CHARLIE", "DELTA", "ECHO", "FOXTROT", "GOLF", "HOTEL", "INDIA", "JULIETT", "KILO", "LIMA", "MIKE", "NOVEMBER", "OSCAR", "PAPA", "QUEBEC", "ROMEO", "SIERRA", "TANGO", "UNIFORM", "VICTOR", "WHISKEY", "XRAY", "YANKEE", "ZULU" };
public List<string> Available = new List<string> { };
public SortedDictionary<string, Enemy> Enemies = new SortedDictionary<string, Enemy>();
public List<string> DestroyedEnemies = new List<string> { };
public Random Rand = new Random();
public int EnemyCount = 0;
public void NewEnemy ()
{
int Percentage = Rand.Next(0, 101);
if (Percentage > 50 && EnemyCount < 26)
{
Enemy BadGuy = new Enemy(GenerateHealth(), GenerateSpeed(), GenerateBearing(), GenerateDistance());
BadGuy.Classify(BadGuy.Health);
Enemies.Add(Designations[0], BadGuy);
Designations.Remove(Designations[0]);
EnemyCount++;
}
//Designations.Sort();
}
public int GenerateHealth ()
{
int health;
health = Rand.Next(25, 201);
return health;
}
public int GenerateBearing ()
{
int bearing;
bearing = Rand.Next(0, 360);
return bearing;
}
public int GenerateDistance ()
{
int distance;
distance = Rand.Next(300, 601);
return distance;
}
public int GenerateSpeed ()
{
int speed;
speed = Rand.Next(5, 21);
return speed;
}
public void Move ()
{
foreach (KeyValuePair<string, Enemy> instance in Enemies)
{
switch (instance.Value.Classification)
{
case "BATTLESHIP":
if (instance.Value.Distance - instance.Value.Velocity < instance.Value.Orbit_Distance)
{
instance.Value.Velocity = instance.Value.Orbit_Distance - (instance.Value.Distance - instance.Value.Velocity);
instance.Value.Distance = instance.Value.Orbit_Distance;
instance.Value.Move_Orbit();
}
else
{
instance.Value.Move_Approach();
}
break;
default:
if (instance.Value.Distance - instance.Value.Velocity < 0)
{
instance.Value.Distance = 0;
instance.Value.ChangeHealth(instance.Value.Health);
}
else
{
instance.Value.Move_Approach();
}
break;
}
}
}
public void CollectDead ()
{
foreach (KeyValuePair<string, Enemy> instance in Enemies)
{
if (instance.Value.Status == "DESTROYED")
{
DestroyedEnemies.Add(instance.Key);
}
}
}
public void DestroyDead ()
{
foreach (string enemy in DestroyedEnemies)
{
DestroyEnemy(enemy);
}
DestroyedEnemies.Clear();
}
public void DestroyEnemy (string enemy)
{
Designations.Add(enemy);
Enemies.Remove(enemy);
EnemyCount--;
}
}
}
|
66c8ffb26262c2383117b877bce48d7283604f27
|
C#
|
Pathoschild/smapi-mod-dump
|
/source/~daleao/Shared/Events/EventManager.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/daleao/sdv-mods
**
*************************************************/
namespace DaLion.Shared.Events;
#region using directives
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using DaLion.Shared.Attributes;
using DaLion.Shared.Extensions.Collections;
using DaLion.Shared.Extensions.Reflection;
using HarmonyLib;
using StardewModdingAPI.Events;
#endregion using directives
/// <summary>
/// Instantiates and manages dynamic enabling and disabling of <see cref="IManagedEvent"/> classes in an
/// assembly or namespace.
/// </summary>
internal sealed class EventManager
{
/// <summary>Cache of <see cref="IManagedEvent"/> instances by type.</summary>
private readonly ConditionalWeakTable<Type, IManagedEvent> _eventCache = new();
/// <inheritdoc cref="IModRegistry"/>
private readonly IModRegistry _modRegistry;
/// <summary>Initializes a new instance of the <see cref="EventManager"/> class.</summary>
/// <param name="modEvents">The <see cref="IModEvents"/> API for the current mod.</param>
/// <param name="modRegistry">API for fetching metadata about loaded mods.</param>
internal EventManager(IModEvents modEvents, IModRegistry modRegistry)
{
this._modRegistry = modRegistry;
this.ModEvents = modEvents;
}
/// <inheritdoc cref="IModEvents"/>
internal IModEvents ModEvents { get; }
/// <summary>Gets an enumerable of all <see cref="IManagedEvent"/>s instances.</summary>
internal IEnumerable<IManagedEvent> Managed => this._eventCache.Select(pair => pair.Value);
/// <summary>Gets an enumerable of all <see cref="IManagedEvent"/>s currently enabled for the local player.</summary>
internal IEnumerable<IManagedEvent> Enabled => this.Managed.Where(e => e.IsEnabled);
/// <summary>Enumerates all <see cref="IManagedEvent"/>s currently enabled for the specified screen.</summary>
/// <param name="screenId">The screen ID.</param>
/// <returns>A <see cref="IEnumerable{T}"/> of enabled <see cref="IManagedEvent"/>s in the specified screen.</returns>
internal IEnumerable<IManagedEvent> EnabledForScreen(int screenId)
{
return this.Managed
.Where(e => e.IsEnabledForScreen(screenId));
}
/// <summary>Adds the <paramref name="event"/> instance to the cache.</summary>
/// <param name="event">An <see cref="IManagedEvent"/> instance.</param>
internal void Manage(IManagedEvent @event)
{
this._eventCache.Add(@event.GetType(), @event);
Log.D($"[EventManager]: Now managing {@event.GetType().Name}.");
}
/// <summary>Implicitly manages <see cref="IManagedEvent"/> types in the assembly.</summary>
internal void ManageAll()
{
Log.D("[EventManager]: Gathering all events...");
this.ManageImplicitly();
}
/// <summary>Implicitly manages <see cref="IManagedEvent"/> types in the specified namespace.</summary>
/// <param name="namespace">The desired namespace.</param>
internal void ManageNamespace(string @namespace)
{
Log.D($"[EventManager]: Gathering events in {@namespace}...");
this.ManageImplicitly(t => t.Namespace?.Contains(@namespace) == true);
}
/// <summary>Implicitly manages <see cref="IManagedEvent"/> types with the specified attribute type.</summary>
/// <typeparam name="TAttribute">An <see cref="Attribute"/> type.</typeparam>
internal void ManageWithAttribute<TAttribute>()
where TAttribute : Attribute
{
Log.D($"[EventManager]: Gathering events with {nameof(TAttribute)}...");
this.ManageImplicitly(t => t.GetCustomAttribute<TAttribute>() is not null);
}
/// <summary>Disposes the <paramref name="event"/> instance and removes it from the cache.</summary>
/// <param name="event">An <see cref="IManagedEvent"/> instance.</param>
internal void Unmanage(IManagedEvent @event)
{
if (!this._eventCache.TryGetValue(@event.GetType(), out var managed) || managed != @event)
{
Log.D($"[EventManager]:{@event.GetType().Name} was not being managed.");
return;
}
@event.Dispose();
this._eventCache.Remove(@event.GetType());
Log.D($"[EventManager]: No longer managing {@event.GetType().Name}.");
}
/// <summary>Disposes all <see cref="IManagedEvent"/> instances and clear the event cache.</summary>
internal void UnmanageAll()
{
this._eventCache.ForEach(pair => pair.Value.Dispose());
this._eventCache.Clear();
Log.D("[EventManager]: No longer managing any events.");
}
/// <summary>Disposes all <see cref="IManagedEvent"/> instances belonging to the specified namespace and removes them from the cache.</summary>
/// <param name="namespace">The desired namespace.</param>
internal void UnmanageNamespace(string @namespace)
{
var toUnmanage = this.GetAllForNamespace(@namespace).ToList();
toUnmanage.ForEach(this.Unmanage);
Log.D($"[EventManager]: No longer managing events in {@namespace}.");
}
/// <summary>Disposes all <see cref="IManagedEvent"/> instances with the specified attribute type.</summary>
/// <typeparam name="TAttribute">An <see cref="Attribute"/> type.</typeparam>
internal void UnmanageWithAttribute<TAttribute>()
where TAttribute : Attribute
{
var toUnmanage = this.GetAllWithAttribute<TAttribute>().ToList();
toUnmanage.ForEach(this.Unmanage);
Log.D($"[EventManager]: No longer managing events with {nameof(TAttribute)}.");
}
/// <summary>Enable a single <see cref="IManagedEvent"/>.</summary>
/// <param name="eventType">A <see cref="IManagedEvent"/> type to enable.</param>
/// <returns><see langword="true"/> if the event's enabled status was changed, otherwise <see langword="false"/>.</returns>
internal bool Enable(Type eventType)
{
if (this.GetOrCreate(eventType)?.Enable() == true)
{
Log.D($"[EventManager]: Enabled {eventType.Name}.");
return true;
}
Log.D($"[EventManager]: {eventType.Name} was not enabled.");
return false;
}
/// <summary>Enables the specified <see cref="IManagedEvent"/> types.</summary>
/// <param name="eventTypes">The <see cref="IManagedEvent"/> types to enable.</param>
internal void Enable(params Type[] eventTypes)
{
for (var i = 0; i < eventTypes.Length; i++)
{
this.Enable(eventTypes[i]);
}
}
/// <summary>Enable a single <see cref="IManagedEvent"/>.</summary>
/// <typeparam name="TEvent">A <see cref="IManagedEvent"/> type to enable.</typeparam>
/// <returns><see langword="true"/> if the event's enabled status was changed, otherwise <see langword="false"/>.</returns>
internal bool Enable<TEvent>()
where TEvent : IManagedEvent
{
return this.Enable(typeof(TEvent));
}
/// <summary>Enables a single <see cref="IManagedEvent"/> for the specified screen.</summary>
/// <param name="eventType">A <see cref="IManagedEvent"/> type to enable.</param>
/// <param name="screenId">A local peer's screen ID.</param>
/// <returns><see langword="true"/> if the event's enabled status was changed, otherwise <see langword="false"/>.</returns>
internal bool EnableForScreen(Type eventType, int screenId)
{
if (this.GetOrCreate(eventType)?.EnableForScreen(screenId) == true)
{
Log.D($"[EventManager]: Enabled {eventType.Name}.");
return true;
}
Log.D($"[EventManager]: {eventType.Name} was not enabled.");
return false;
}
/// <summary>Enables the specified <see cref="IManagedEvent"/> types for the specified screen.</summary>
/// <param name="screenId">A local peer's screen ID.</param>
/// <param name="eventTypes">The <see cref="IManagedEvent"/> types to enable.</param>
internal void EnableForScreen(int screenId, params Type[] eventTypes)
{
for (var i = 0; i < eventTypes.Length; i++)
{
this.EnableForScreen(eventTypes[i], screenId);
}
}
/// <summary>Enables a single <see cref="IManagedEvent"/> for the specified screen.</summary>
/// <typeparam name="TEvent">A <see cref="IManagedEvent"/> type to enable.</typeparam>
/// <param name="screenId">A local peer's screen ID.</param>
/// <returns><see langword="true"/> if the event's enabled status was changed, otherwise <see langword="false"/>.</returns>
internal bool EnableForScreen<TEvent>(int screenId)
where TEvent : IManagedEvent
{
return this.EnableForScreen(typeof(TEvent), screenId);
}
/// <summary>Enables a single <see cref="IManagedEvent"/> for the specified screen.</summary>
/// <param name="eventType">A <see cref="IManagedEvent"/> type to enable.</param>
internal void EnableForAllScreens(Type eventType)
{
this.GetOrCreate(eventType)?.EnableForAllScreens();
Log.D($"[EventManager]: Enabled {eventType.Name} for all screens.");
}
/// <summary>Enables the specified <see cref="IManagedEvent"/> types for the specified screen.</summary>
/// <param name="eventTypes">The <see cref="IManagedEvent"/> types to enable.</param>
internal void EnableForAllScreens(params Type[] eventTypes)
{
for (var i = 0; i < eventTypes.Length; i++)
{
this.EnableForAllScreens(eventTypes[i]);
}
}
/// <summary>Enables a single <see cref="IManagedEvent"/> for the specified screen.</summary>
/// <typeparam name="TEvent">An <see cref="IManagedEvent"/> type to enable.</typeparam>
internal void EnableForAllScreens<TEvent>()
where TEvent : IManagedEvent
{
this.EnableForAllScreens(typeof(TEvent));
}
/// <summary>Disables a single <see cref="IManagedEvent"/>.</summary>
/// <param name="eventType">A <see cref="IManagedEvent"/> type to disable.</param>
/// <returns><see langword="true"/> if the event's enabled status was changed, otherwise <see langword="false"/>.</returns>
internal bool Disable(Type eventType)
{
if (this.GetOrCreate(eventType)?.Disable() == true)
{
Log.D($"[EventManager]: Disabled {eventType.Name}.");
return true;
}
Log.D($"[EventManager]: {eventType.Name} was not disabled.");
return false;
}
/// <summary>Disables the specified <see cref="IManagedEvent"/>s events.</summary>
/// <param name="eventTypes">The <see cref="IManagedEvent"/> types to disable.</param>
internal void Disable(params Type[] eventTypes)
{
for (var i = 0; i < eventTypes.Length; i++)
{
this.Disable(eventTypes[i]);
}
}
/// <summary>Disables a single <see cref="IManagedEvent"/>.</summary>
/// <typeparam name="TEvent">A <see cref="IManagedEvent"/> type to disable.</typeparam>
/// <returns><see langword="true"/> if the event's enabled status was changed, otherwise <see langword="false"/>.</returns>
internal bool Disable<TEvent>()
where TEvent : IManagedEvent
{
return this.Disable(typeof(TEvent));
}
/// <summary>Disables a single <see cref="IManagedEvent"/> for the specified screen.</summary>
/// <param name="eventType">A <see cref="IManagedEvent"/> type to disable.</param>
/// <param name="screenId">A local peer's screen ID.</param>
/// <returns><see langword="true"/> if the event's enabled status was changed, otherwise <see langword="false"/>.</returns>
internal bool DisableForScreen(Type eventType, int screenId)
{
if (this.GetOrCreate(eventType)?.DisableForScreen(screenId) == true)
{
Log.D($"[EventManager]: Disabled {eventType.Name}.");
return true;
}
Log.D($"[EventManager]: {eventType.Name} was not disabled.");
return false;
}
/// <summary>Disables the specified <see cref="IManagedEvent"/>s for the specified screen.</summary>
/// <param name="screenId">A local peer's screen ID.</param>
/// <param name="eventTypes">The <see cref="IManagedEvent"/> types to disable.</param>
internal void DisableForScreen(int screenId, params Type[] eventTypes)
{
for (var i = 0; i < eventTypes.Length; i++)
{
this.DisableForScreen(eventTypes[i], screenId);
}
}
/// <summary>Disables a single <see cref="IManagedEvent"/> for the specified screen.</summary>
/// <typeparam name="TEvent">An <see cref="IManagedEvent"/> type to disable.</typeparam>
/// <param name="screenId">A local peer's screen ID.</param>
/// <returns><see langword="true"/> if the event's enabled status was changed, otherwise <see langword="false"/>.</returns>
internal bool DisableForScreen<TEvent>(int screenId)
where TEvent : IManagedEvent
{
return this.DisableForScreen(typeof(TEvent), screenId);
}
/// <summary>Disables a single <see cref="IManagedEvent"/> for the specified screen.</summary>
/// <param name="eventType">A <see cref="IManagedEvent"/> type to disable.</param>
internal void DisableForAllScreens(Type eventType)
{
this.GetOrCreate(eventType)?.DisableForAllScreens();
Log.D($"[EventManager]: Enabled {eventType.Name} for all screens.");
}
/// <summary>Disables the specified <see cref="IManagedEvent"/>s for the specified screen.</summary>
/// <param name="eventTypes">The <see cref="IManagedEvent"/> types to disable.</param>
internal void DisableForAllScreens(params Type[] eventTypes)
{
for (var i = 0; i < eventTypes.Length; i++)
{
this.DisableForAllScreens(eventTypes[i]);
}
}
/// <summary>Disables a single <see cref="IManagedEvent"/> for the specified screen.</summary>
/// <typeparam name="TEvent">A <see cref="IManagedEvent"/> type to disable.</typeparam>
internal void DisableForAllScreens<TEvent>()
where TEvent : IManagedEvent
{
this.DisableForAllScreens(typeof(TEvent));
}
/// <summary>Enables all <see cref="IManagedEvent"/>s.</summary>
internal void EnableAll()
{
var count = AccessTools
.GetTypesFromAssembly(Assembly.GetAssembly(typeof(IManagedEvent)))
.Where(t => t.IsAssignableTo(typeof(IManagedEvent)) && !t.IsAbstract)
.Count(this.Enable);
Log.D($"[EventManager]: Enabled {count} events.");
}
/// <summary>Disables all <see cref="IManagedEvent"/>s.</summary>
internal void DisableAll()
{
var count = AccessTools
.GetTypesFromAssembly(Assembly.GetAssembly(typeof(IManagedEvent)))
.Where(t => t.IsAssignableTo(typeof(IManagedEvent)) && !t.IsAbstract)
.Count(this.Disable);
Log.D($"[EventManager]: Disabled {count} events.");
}
/// <summary>Enables all <see cref="IManagedEvent"/> types starting with attribute <typeparamref name="TAttribute"/>.</summary>
/// <typeparam name="TAttribute">The type of the attribute.</typeparam>
internal void EnableWithAttribute<TAttribute>()
where TAttribute : Attribute
{
var count = AccessTools
.GetTypesFromAssembly(Assembly.GetAssembly(typeof(IManagedEvent)))
.Where(t => t.IsAssignableTo(typeof(IManagedEvent)) && !t.IsAbstract && t.GetCustomAttribute<TAttribute>() is not null)
.Count(this.Enable);
Log.D($"[EventManager]: Enabled {count} events.");
}
/// <summary>Disables all <see cref="IManagedEvent"/> types starting with attribute <typeparamref name="TAttribute"/>.</summary>
/// <typeparam name="TAttribute">The type of the attribute.</typeparam>
internal void DisableWithAttribute<TAttribute>()
where TAttribute : Attribute
{
var count = AccessTools
.GetTypesFromAssembly(Assembly.GetAssembly(typeof(IManagedEvent)))
.Where(t => t.IsAssignableTo(typeof(IManagedEvent)) && !t.IsAbstract && t.GetCustomAttribute<TAttribute>() is not null)
.Count(this.Disable);
Log.D($"[EventManager]: Disabled {count} events.");
}
/// <summary>Resets the enabled status of all <see cref="IManagedEvent"/>s in the assembly for the current screen.</summary>
internal void Reset()
{
this._eventCache.ForEach(pair => pair.Value.Reset());
Log.D("[EventManager]: Reset all managed events for the current screen.");
}
/// <summary>Resets the enabled status of all <see cref="IManagedEvent"/>s in the assembly for all screens.</summary>
internal void ResetForAllScreens()
{
this._eventCache.ForEach(pair => pair.Value.ResetForAllScreens());
Log.D("[EventManager]: Reset all managed events for all screens.");
}
/// <summary>Gets the <see cref="IManagedEvent"/> instance of type <paramref name="eventType"/>.</summary>
/// <param name="eventType">A type implementing <see cref="IManagedEvent"/>.</param>
/// <returns>A <see cref="IManagedEvent"/> instance of the specified <paramref name="eventType"/> if one exists, otherwise <see langword="null"/>.</returns>
internal IManagedEvent? Get(Type eventType)
{
return this._eventCache.TryGetValue(eventType, out var got) ? got : null;
}
/// <summary>Gets the <see cref="IManagedEvent"/> instance of type <typeparamref name="TEvent"/>.</summary>
/// <typeparam name="TEvent">A type implementing <see cref="IManagedEvent"/>.</typeparam>
/// <returns>A <see cref="IManagedEvent"/> instance of type <typeparamref name="TEvent"/> if one exists, otherwise <see langword="null"/>.</returns>
internal IManagedEvent? Get<TEvent>()
where TEvent : IManagedEvent
{
return this.Get(typeof(TEvent));
}
/// <summary>Enumerates all managed <see cref="IManagedEvent"/> instances declared in the specified <paramref name="namespace"/>.</summary>
/// <param name="namespace">The desired namespace.</param>
/// <returns>An <see cref="IEnumerable{T}"/> of <see cref="IManagedEvent"/>s.</returns>
internal IEnumerable<IManagedEvent> GetAllForNamespace(string @namespace)
{
return this._eventCache
.Where(pair => pair.Key.Namespace?.Contains(@namespace) ?? false)
.Select(pair => pair.Value);
}
/// <summary>Enumerates all managed <see cref="IManagedEvent"/> instances with the specified <typeparamref name="TAttribute"/>.</summary>
/// <typeparam name="TAttribute">An <see cref="Attribute"/> type.</typeparam>
/// <returns>An <see cref="IEnumerable{T}"/> of <see cref="IManagedEvent"/>s.</returns>
internal IEnumerable<IManagedEvent> GetAllWithAttribute<TAttribute>()
where TAttribute : Attribute
{
return this._eventCache
.Where(pair => pair.Key.GetCustomAttribute<TAttribute>() is not null)
.Select(pair => pair.Value);
}
/// <summary>Determines whether the specified <see cref="IManagedEvent"/> type is enabled.</summary>
/// <typeparam name="TEvent">A type implementing <see cref="IManagedEvent"/>.</typeparam>
/// <returns><see langword="true"/> if the <see cref="IManagedEvent"/> is enabled for the local screen, otherwise <see langword="false"/>.</returns>
internal bool IsEnabled<TEvent>()
where TEvent : IManagedEvent
{
return this._eventCache.TryGetValue(typeof(TEvent), out var @event) && @event.IsEnabled;
}
/// <summary>Determines whether the specified <see cref="IManagedEvent"/> type is enabled for a specific screen.</summary>
/// <typeparam name="TEvent">A type implementing <see cref="IManagedEvent"/>.</typeparam>
/// <param name="screenId">The screen ID.</param>
/// <returns><see langword="true"/> if the <see cref="IManagedEvent"/> is enabled for the specified screen, otherwise <see langword="false"/>.</returns>
internal bool IsEnabledForScreen<TEvent>(int screenId)
where TEvent : IManagedEvent
{
return this._eventCache.TryGetValue(typeof(TEvent), out var @event) && @event.IsEnabledForScreen(screenId);
}
/// <summary>Instantiates and manages <see cref="IManagedEvent"/> classes using reflection.</summary>
/// <param name="predicate">An optional condition with which to limit the scope of managed <see cref="IManagedEvent"/>s.</param>
private void ManageImplicitly(Func<Type, bool>? predicate = null)
{
predicate ??= t => true;
var eventTypes = AccessTools
.GetTypesFromAssembly(Assembly.GetAssembly(typeof(IManagedEvent)))
.Where(t => t.IsAssignableTo(typeof(IManagedEvent)) && !t.IsAbstract && predicate(t) &&
// event classes may or not have the required internal parameterized constructor accepting only the manager instance, depending on whether they are SMAPI or mod-handled
// we only want to construct SMAPI events at this point, so we filter out the rest
t.GetConstructor(
BindingFlags.Instance | BindingFlags.NonPublic,
null,
new[] { this.GetType() },
null) is not null &&
(t.IsAssignableToAnyOf(typeof(GameLaunchedEvent), typeof(FirstSecondUpdateTickedEvent)) ||
t.GetCustomAttribute<AlwaysEnabledEventAttribute>() is not null ||
t.GetProperty(nameof(IManagedEvent.IsEnabled))?.DeclaringType == t))
.ToArray();
Log.D($"[EventManager]: Found {eventTypes.Length} event classes that should be enabled.");
if (eventTypes.Length == 0)
{
return;
}
Log.D("[EventManager]: Instantiating events....");
for (var i = 0; i < eventTypes.Length; i++)
{
var eventType = eventTypes[i];
#if RELEASE
var debugAttribute = eventType.GetCustomAttribute<DebugAttribute>();
if (debugAttribute is not null)
{
continue;
}
#endif
var ignoreAttribute = eventType.GetCustomAttribute<ImplicitIgnoreAttribute>();
if (ignoreAttribute is not null)
{
continue;
}
var modRequirementAttribute = eventType.GetCustomAttribute<ModRequirementAttribute>();
if (modRequirementAttribute is not null)
{
if (!this._modRegistry.IsLoaded(modRequirementAttribute.UniqueId))
{
Log.D(
$"[EventManager]: The target mod {modRequirementAttribute.UniqueId} is not loaded. {eventType.Name} will be ignored.");
continue;
}
if (!string.IsNullOrEmpty(modRequirementAttribute.Version) &&
this._modRegistry.Get(modRequirementAttribute.UniqueId)!.Manifest.Version.IsOlderThan(
modRequirementAttribute.Version))
{
Log.W(
$"[EventManager]: The integration event {eventType.Name} will be ignored because the installed version of {modRequirementAttribute.UniqueId} is older than minimum supported version." +
$" Please update {modRequirementAttribute.UniqueId} in order to enable integrations with this mod.");
continue;
}
}
this.GetOrCreate(eventType);
}
}
/// <summary>Retrieves an existing event instance from the cache, or caches a new instance.</summary>
/// <param name="eventType">A type implementing <see cref="IManagedEvent"/>.</param>
/// <returns>The cached <see cref="IManagedEvent"/> instance, or <see langword="null"/> if one could not be created.</returns>
private IManagedEvent? GetOrCreate(Type eventType)
{
if (this._eventCache.TryGetValue(eventType, out var instance))
{
return instance;
}
instance = this.Create(eventType);
if (instance is null)
{
Log.E($"[EventManager]: Failed to create {eventType.Name}.");
return null;
}
this._eventCache.Add(eventType, instance);
Log.D($"[EventManager]: Now managing {eventType.Name}.");
return instance;
}
/// <summary>Retrieves an existing event instance from the cache, or caches a new instance.</summary>
/// <typeparam name="TEvent">A type implementing <see cref="IManagedEvent"/>.</typeparam>
/// <returns>The cached <see cref="IManagedEvent"/> instance, or <see langword="null"/> if one could not be created.</returns>
private IManagedEvent? GetOrCreate<TEvent>()
{
return this.GetOrCreate(typeof(TEvent));
}
/// <summary>Instantiates a new <see cref="IManagedEvent"/> instance of the specified <paramref name="eventType"/>.</summary>
/// <param name="eventType">A type implementing <see cref="IManagedEvent"/>.</param>
/// <returns>A <see cref="IManagedEvent"/> instance of the specified <paramref name="eventType"/>.</returns>
private IManagedEvent? Create(Type eventType)
{
if (!eventType.IsAssignableTo(typeof(IManagedEvent)) || eventType.IsAbstract || eventType.GetConstructor(
BindingFlags.Instance | BindingFlags.NonPublic,
null,
new[] { this.GetType() },
null) is null)
{
Log.E($"[EventManager]: {eventType.Name} is not a valid event type.");
return null;
}
#if RELEASE
var debugAttribute = eventType.GetCustomAttribute<DebugAttribute>();
if (debugAttribute is not null)
{
return null;
}
#endif
var implicitIgnoreAttribute = eventType.GetCustomAttribute<ImplicitIgnoreAttribute>();
if (implicitIgnoreAttribute is not null)
{
Log.D($"[EventManager]: {eventType.Name} is will be ignored.");
return null;
}
var requiresModAttribute = eventType.GetCustomAttribute<ModRequirementAttribute>();
if (requiresModAttribute is not null)
{
if (!this._modRegistry.IsLoaded(requiresModAttribute.UniqueId))
{
Log.D(
$"[EventManager]: The target mod {requiresModAttribute.UniqueId} is not loaded. {eventType.Name} will be ignored.");
return null;
}
if (!string.IsNullOrEmpty(requiresModAttribute.Version) &&
this._modRegistry.Get(requiresModAttribute.UniqueId)!.Manifest.Version.IsOlderThan(
requiresModAttribute.Version))
{
Log.W(
$"[EventManager]: The integration event {eventType.Name} will be ignored because the installed version of {requiresModAttribute.UniqueId} is older than minimum supported version." +
$" Please update {requiresModAttribute.UniqueId} in order to enable integrations with this mod.");
return null;
}
}
return (IManagedEvent)eventType
.GetConstructor(
BindingFlags.Instance | BindingFlags.NonPublic,
null,
new[] { this.GetType() },
null)!
.Invoke(new object?[] { this });
}
}
|
60a8ce3a270b60b0ac9d7d6be97befe428915707
|
C#
|
david0718/PaintDotNet.Quantization
|
/PaintDotNet/Imaging/ColorComponentUtil.cs
| 2.8125
| 3
|
/////////////////////////////////////////////////////////////////////////////////
// paint.net //
// Copyright (C) dotPDN LLC, Rick Brewster, and contributors. //
// All Rights Reserved. //
/////////////////////////////////////////////////////////////////////////////////
using System;
using System.Runtime.CompilerServices;
namespace PaintDotNet.Imaging
{
internal static class ColorComponentUtil
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ushort Convert8UTo16U(byte c8U)
{
return unchecked((ushort)((ushort)c8U | ((ushort)c8U << 8)));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static byte Convert16UTo8U(ushort c16U)
{
return unchecked((byte)(c16U >> 8));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Convert8UTo32F(byte c8U)
{
//return ByteUtil.ToScalingFloat(c8U); // this uses a lookup table
return c8U / 255.0f;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Convert16UTo32F(ushort c16U)
{
return (float)c16U / 65535.0f;
}
}
}
|
c7356cc328d4b3e6410fa4e7c9c084d2bf42505e
|
C#
|
haleyregister1/PalindromeExercise
|
/PalindromeExercise/PalindromeExerciseTests/UnitTest1.cs
| 2.734375
| 3
|
using System;
using Xunit;
using PalindromeExercise;
namespace PalindromeExerciseTests
{
public class UnitTest1
{
[Theory]
[InlineData("racecar", true)]
[InlineData("hannah", true)]
[InlineData("hello", false)]
[InlineData("sugar", false)]
public void PalindromeTest (string word, bool expected)
{
//arrange
var sut = new Palindrome();
//act
var actual = sut.IsAPalindrome(word);
//assert
Assert.Equal(actual, expected);
}
}
}
|
2834a2e4188ec2fdcc2aceca5f67304e3eebd588
|
C#
|
taguhisaghatelyan/COmpanyy
|
/COmpanyy/Classes/Customer.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace COmpanyy
{
class Customer : Person
{
public int Amount { get; set; }
public Customer()
{
}
public Customer(int amount):base()
{
this.Amount = amount;
}
public override string ToString()
{
return $" {Name} {LastName} {Amount} ";
}
}
}
|
141a573f9040a5ecadaed4378ca9b03eb1302868
|
C#
|
UCan927/Mina.NET
|
/Mina.NET/Filter/Codec/PrefixedString/PrefixedStringEncoder.cs
| 2.9375
| 3
|
using System;
using System.Text;
using Mina.Core.Buffer;
using Mina.Core.Session;
namespace Mina.Filter.Codec.PrefixedString
{
/// <summary>
/// A <see cref="IProtocolEncoder"/> which encodes a string using a fixed-length length prefix.
/// </summary>
public class PrefixedStringEncoder : ProtocolEncoderAdapter
{
public PrefixedStringEncoder(Encoding encoding)
: this(encoding, PrefixedStringCodecFactory.DefaultPrefixLength, PrefixedStringCodecFactory.DefaultMaxDataLength)
{ }
public PrefixedStringEncoder(Encoding encoding, Int32 prefixLength)
: this(encoding, prefixLength, PrefixedStringCodecFactory.DefaultMaxDataLength)
{ }
public PrefixedStringEncoder(Encoding encoding, Int32 prefixLength, Int32 maxDataLength)
{
Encoding = encoding;
PrefixLength = prefixLength;
MaxDataLength = maxDataLength;
}
/// <summary>
/// Gets or sets the length of the length prefix (1, 2, or 4).
/// </summary>
public Int32 PrefixLength { get; set; }
/// <summary>
/// Gets or sets the maximum number of bytes allowed for encoding a single string.
/// </summary>
public Int32 MaxDataLength { get; set; }
/// <summary>
/// Gets or set the text encoding.
/// </summary>
public Encoding Encoding { get; set; }
/// <inheritdoc/>
public override void Encode(IoSession session, Object message, IProtocolEncoderOutput output)
{
String value = (String)message;
IoBuffer buffer = IoBuffer.Allocate(value.Length);
buffer.AutoExpand = true;
buffer.PutPrefixedString(value, PrefixLength, Encoding);
if (buffer.Position > MaxDataLength)
{
throw new ArgumentException("Data length: " + buffer.Position);
}
buffer.Flip();
output.Write(buffer);
}
}
}
|
9d760437522ec06436a317ddc1a4e38580813a47
|
C#
|
stg609/ClaimBasedManagementSolution
|
/Common/Infra/Extensions.cs
| 3.1875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
namespace Common.Infra
{
public static class Extensions
{
public static List<TSource> EmptyListIfEmpty<TSource>(this IEnumerable<TSource> list)
{
Type genericArgument = typeof(TSource);
Type listType = typeof(List<>);
Type finalType = listType.MakeGenericType(genericArgument);
if (list == null)
{
return Activator.CreateInstance(finalType) as List<TSource>;
}
else
{
return Activator.CreateInstance(finalType, list) as List<TSource>;
}
}
/// <summary>
/// Detech if an entity is already attached in the DBContext
/// </summary>
/// <typeparam name="TContext"></typeparam>
/// <typeparam name="TEntity"></typeparam>
/// <param name="context"></param>
/// <param name="entity"></param>
/// <see cref="https://stackoverflow.com/questions/10027493/entityframework-code-first-check-if-entity-is-attached"/>
/// <returns></returns>
public static bool Exists<TContext, TEntity>(this TContext context, TEntity entity)
where TContext : DbContext
where TEntity : class
{
return context.Set<TEntity>().Local.Any(e => e == entity);
}
}
}
|
83b747f5b22a845c63a131c04367517c1688b785
|
C#
|
benNek/FantasyHoops
|
/fantasy-hoops/fantasy-hoops/Controllers/StatsController.cs
| 2.734375
| 3
|
using fantasy_hoops.Database;
using fantasy_hoops.Repositories;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
namespace fantasy_hoops.Controllers
{
[Route("api/[controller]")]
public class StatsController : Controller
{
private readonly GameContext context;
private readonly StatsRepository _repository;
public StatsController()
{
context = new GameContext();
_repository = new StatsRepository(context);
}
[HttpGet]
public IEnumerable<Object> Get()
{
return _repository.GetStats().ToList();
}
[HttpGet("{id}")]
public IActionResult Get(int id, int start = 0, int count = 10)
{
var player = _repository.GetStats(id, start, count).FirstOrDefault();
if (player == null)
return NotFound(String.Format("Player with id {0} has not been found!", id));
return Ok(player);
}
}
}
|
396b5f4d43119e5b807805e3dbec69cd82bf219a
|
C#
|
DaleStevenJohnson/TeacherPlannerApplication
|
/TeacherPlanner/PlannerYear/ViewModels/ChooseYearViewModel.cs
| 2.84375
| 3
|
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
using Database;
using Database.DatabaseModels;
using TeacherPlanner.Helpers;
using TeacherPlanner.Login.Models;
using TeacherPlanner.PlannerYear.Models;
namespace TeacherPlanner.PlannerYear.ViewModels
{
public class ChooseYearViewModel : ObservableObject
{
private ObservableCollection<AcademicYearModel> _yearSelectModels;
public event EventHandler<AcademicYearModel> ChooseYearEvent;
public ICommand AddYearCommand { get; }
public ICommand SelectYearCommand { get; }
public ChooseYearViewModel(UserModel usermodel)
{
// Parameter Assignments
UserModel = usermodel;
// Property Assignments
YearSelectModels = GetAcademicYears();
if (!YearSelectModels.Any())
OnAddNewAcademicYear();
//Command Assignments
AddYearCommand = new SimpleCommand(_ => OnAddNewAcademicYear());
SelectYearCommand = new SimpleCommand(_ => OnSelectYear(_));
}
private UserModel UserModel { get; set; }
public ObservableCollection<AcademicYearModel> YearSelectModels
{
get => _yearSelectModels;
set => RaiseAndSetIfChanged(ref _yearSelectModels, value);
}
// Public Methods
public void OnSelectYear(object v)
{
ChooseYearEvent.Invoke(null, (AcademicYearModel)v);
}
// Private Methods
private void OnAddNewAcademicYear()
{
if (AddAcademicYearToDatabase())
YearSelectModels = GetAcademicYears();
}
private bool AddAcademicYearToDatabase()
{
var year = GetNextAcademicYear();
if (!DatabaseManager.CheckIfAcademicYearExists(UserModel.ID, year))
{
var academicYear = new AcademicYear()
{
UserID = UserModel.ID,
Year = year
};
return DatabaseManager.TryAddAcademicYear(academicYear);
}
return false;
}
private int GetNextAcademicYear()
{
// Work out which academic year to add
if (YearSelectModels == null || !YearSelectModels.Any())
return CalendarManager.GetStartingYearOfAcademicYear(DateTime.Today);
else
{
return YearSelectModels
.OrderBy(y => y.Year)
.ToList()
.Last()
.Year + 1;
}
}
private ObservableCollection<AcademicYearModel> GetAcademicYears()
{
var yearSelectModels = new ObservableCollection<AcademicYearModel>();
// Get currently stored Academic Years from database
var academicYears = DatabaseManager.GetAcademicYears(UserModel.ID);
if (academicYears.Any())
{
foreach (var year in academicYears)
{
var newYear = new AcademicYearModel(year.Year, year.ID);
yearSelectModels.Add(newYear);
}
}
return yearSelectModels;
}
}
}
|
0328b085da861a688687c19436866f1eaf559ee2
|
C#
|
mayapeneva/C-Sharp-OOP-Basic
|
/02.Encapsulation_2/FootballTeamGenerator/Player.cs
| 3.515625
| 4
|
using System.Collections.Generic;
using System.Linq;
public class Player
{
private string name;
private List<double> stats;
public Player(string name)
{
this.name = name;
this.stats = new List<double>();
}
public string Name => this.name;
public string AddStats(params double[] parameters)
{
for (int i = 0; i < parameters.Length; i++)
{
if (parameters[i] < 0 || parameters[i] > 100)
{
var stat = string.Empty;
switch (i)
{
case 0:
stat = "Endurance";
break;
case 1:
stat = "Sprint";
break;
case 2:
stat = "Dribble";
break;
case 3:
stat = "Passing";
break;
case 4:
stat = "Shooting";
break;
}
return $"{stat} should be between 0 and 100.";
}
this.stats.Add(parameters[i]);
}
return "OK";
}
public double GetOverallSkillLevel()
{
return this.stats.Average();
}
}
|
7b2b8f3d44757aa06f5f39314b01ea6863ba78dd
|
C#
|
amelleHamouch/courCsharp
|
/ConsoleApp1/ConsoleApp1/Classes/IHMBanque.cs
| 3.0625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp1.Classes
{
class IHMBanque
{
String choix;
public IHMBanque()
{
}
public void start()
{
Func<decimal> retraitNegatif;
choix = "N";
do
{
Console.WriteLine("Choisissez une action : ");
Console.WriteLine("1--- Créer un compte bancaire");
Console.WriteLine("2--- Effectuer un dépôt");
Console.WriteLine("3--- Effectuer un retrait");
Console.WriteLine("4--- Afficher opérations et solde");
int reponse = Convert.ToInt32(Console.ReadLine());
int choix;
String soldeClient;
Client client = new Client();
Compte compte = new CompteBancaire();
switch (reponse)
{
case 1:
Console.WriteLine("Veuillez nous communiquer votre nom :");
String nom = Console.ReadLine();
Console.WriteLine("Veuillez nous communiquer votre prenom :");
String prenom = Console.ReadLine();
Console.WriteLine("Veuillez nous communiquer votre téléphone :");
int tel = Convert.ToInt32(Console.ReadLine());
client.Nom = nom;
client.Prenom = prenom;
client.Tel = tel;
Console.WriteLine("Quel type de compte ?");
Console.WriteLine("1---Compte courant");
Console.WriteLine("2---Compte epargne");
Console.WriteLine("3---Compte payant");
choix = Convert.ToInt32(Console.ReadLine());
if(choix == 1)
{
Console.WriteLine("Désirez vous déposer un solde ? (O/N)");
soldeClient = Console.ReadLine();
if(soldeClient == "O")
{
Console.WriteLine("Solde à déposer :");
decimal soldeDepot = Convert.ToDecimal(Console.ReadLine());
compte = new CompteBancaire(soldeDepot);
client.AfficherSolde(compte);
}
else
{
client.AfficherSolde(compte);
}
}
break;
case 2:
Console.WriteLine("Combien désirez-vous déposer ?");
decimal montant = Convert.ToDecimal(Console.ReadLine());
client.depot(montant, compte);
client.AfficherSolde(compte);
break;
case 3:
Console.WriteLine("Combien désirez-vous retirer ?");
decimal retrait = Convert.ToDecimal(Console.ReadLine());
client.retrait(retrait, compte);
client.AfficherSolde(compte);
break;
case 4:
client.AfficherOperations(compte);
client.AfficherSolde(compte);
break;
}
}while(choix != "O");
}
}
}
|
8b2ae33fe90bd0d68b6efa39473f4f79aea284d6
|
C#
|
VolhaKudrautsava/IOContainer
|
/Program/Program/Program.cs
| 2.84375
| 3
|
using Game;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Container;
namespace Program
{
class Program
{
public static void DynamicLoad()
{
string path = Directory.GetCurrentDirectory();
try
{
IContainer dll = LoadDll(path);
dll.Register<IWeapon, Knife>();
dll.Register<IWeapon, Gun>();
dll.Register<IPlayer, Warrior>();
dll.Register<IPlayer, Samurai>(true);
dll.Register<IMedicineChest, MedicineChest>(true);
dll.RegisterType<Warrior>(true);
dll.RegisterType<Samurai>(true);
var warrior = dll.Resolve<Warrior>();
warrior = dll.Resolve<Warrior>();
Console.WriteLine(warrior.Attack());
var samurai = dll.Resolve<Samurai>();
samurai.SetWeapon(dll.Resolve<IWeapon>());
Console.WriteLine(samurai.Attack());
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
public static void StaticLoad()
{
try
{
var con = new IOCContainer();
con.Register<IWeapon, Knife>();
con.Register<IPlayer, Warrior>();
con.RegisterType<Warrior>(true);
con.Register<IPlayer, Samurai>(true);
con.Register<IMedicineChest, MedicineChest>(true);
con.RegisterType<Samurai>(true);
var warrior = con.Resolve<Warrior>();
warrior = con.Resolve<Warrior>();
Console.WriteLine(warrior.Attack());
con.Register<IWeapon, Gun>();
var samurai = con.Resolve<Samurai>();
Console.WriteLine(samurai.Attack());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
public static void DynamicLoadWithReflection()
{
const string ASSEMBLY = "IOC";
const string FULL_NAME_OF_TYPE = "IOC.IOCContainer";
Assembly ass;
try
{
ass = Assembly.Load(ASSEMBLY);
}
catch
{
Console.WriteLine("Не получилось подключить cборку");
Console.ReadLine();
return;
}
Type myClass;
try
{
myClass = ass.GetType(FULL_NAME_OF_TYPE);
if (myClass == null)
throw new Exception(" '" + FULL_NAME_OF_TYPE + "' не найден");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
return;
}
object instance = Activator.CreateInstance(myClass);//создание объекта нового класса
MethodInfo[] M = myClass.GetMethods();
if (M.Length < 5)
return;
Type[] paramaters = { typeof(IWeapon), typeof(Knife)};
MethodInfo mi = myClass.GetMethod("Register");
MethodInfo genericMI = mi.MakeGenericMethod(paramaters);
object[] param = { true };
genericMI.Invoke(instance, param);
paramaters[0] = typeof(IWeapon);
paramaters[1] = typeof(Gun);
genericMI = mi.MakeGenericMethod(paramaters);
param[0] = true;
genericMI.Invoke(instance, param);
paramaters[0] = typeof(IMedicineChest);
paramaters[1] = typeof(MedicineChest);
genericMI = mi.MakeGenericMethod(paramaters);
param[0] = true;
genericMI.Invoke(instance, param);
paramaters[0] = typeof(IPlayer);
paramaters[1] = typeof(Warrior);
genericMI = mi.MakeGenericMethod(paramaters);
param[0] = false;
genericMI.Invoke(instance, param);
mi = myClass.GetMethod("RegisterType");
paramaters = new Type[1];
paramaters[0] = typeof(Warrior);
genericMI = mi.MakeGenericMethod(paramaters);
param[0] = false;
genericMI.Invoke(instance, param);
mi = myClass.GetMethod("Resolve");
paramaters[0] = typeof(Warrior);
genericMI = mi.MakeGenericMethod(paramaters);
var warrior = (Warrior)genericMI.Invoke(instance, null);
Console.WriteLine(warrior.Attack());
Console.ReadLine();
}
private static IContainer LoadDll(string path)
{
IContainer plugin = null;
string[] files = Directory.GetFiles(path, "*.dll");
foreach (string file in files)
try
{
string fname = Path.GetFileNameWithoutExtension(file);
string dir = Directory.GetParent(file).ToString();
Assembly assembly = Assembly.LoadFile(file);
foreach (Type type in assembly.GetTypes())
{
if (type.GetInterfaces().Contains(typeof(IContainer)))
{
plugin = (IContainer)Activator.CreateInstance(type);
}
}
}
catch (Exception ex)
{
throw new Exception("Не получилось загрузить:(");
}
if (plugin == null)
{
throw new DllNotFoundException("Не найдена такая dll:(");
}
return plugin;
}
static void Main(string[] args)
{
StaticLoad();
//DynamicLoadWithReflection();
//DynamicLoad();
Console.ReadLine();
}
}
}
|
b8921aaa11bbd4e31b65bc97fac4e6e388da6fee
|
C#
|
AutismPatient/film-dy2018
|
/Macrocosm/Tool/TimeHelper.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Macrocosm.Tool
{
/// <summary>
/// 日期转换相关
/// </summary>
public static class TimeHelper
{
public static DateTime UnixToLacalTime(this int span)
{
var date = new DateTime(621355968000000000 + (long)span * (long)10000000, DateTimeKind.Utc);
return date.ToLocalTime();
}
public static long GetTimeStamp(this DateTime t)
{
long ts = (t.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
return ts;
}
}
}
|
d5bdefab2376b38269e2b531b4e4c841ecd9f7b2
|
C#
|
zkSNACKs/WalletWasabi
|
/WalletWasabi/Userfacing/Bip21/Bip21UriParser.cs
| 2.5625
| 3
|
using NBitcoin;
using NBitcoin.Payment;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics.CodeAnalysis;
using System.Web;
using WalletWasabi.Extensions;
namespace WalletWasabi.Userfacing.Bip21;
/// <summary>
/// BIP21 URI parser.
/// </summary>
/// <seealso href="https://github.com/bitcoin/bips/blob/master/bip-0021.mediawiki"/>
/// <seealso cref="BitcoinUrlBuilder">Inspired by NBitcoin's implementation.</seealso>
public class Bip21UriParser
{
/// <summary>URI scheme of all BIP21 URIs.</summary>
/// <remarks>
/// BIP mandates that:
/// The scheme component ("bitcoin:") is case-insensitive, and implementations must accept any combination of uppercase and lowercase letters.
/// </remarks>
/// <seealso href="https://github.com/bitcoin/bips/blob/master/bip-0021.mediawiki#abnf-grammar"/>
public const string UriScheme = "bitcoin";
public static readonly Error ErrorInvalidUri = new(Code: 1, "Not a valid absolute URI.");
public static readonly Error ErrorInvalidUriScheme = new(Code: 2, $"Expected '{UriScheme}' scheme.");
public static readonly Error ErrorMissingAddress = new(Code: 3, "Bitcoin address is missing.");
public static readonly Error ErrorInvalidAddress = new(Code: 4, "Invalid Bitcoin address.");
public static readonly Error ErrorInvalidUriQuery = new(Code: 5, "Not a valid absolute URI.");
public static readonly Error ErrorDuplicateParameter = new(Code: 6, "Parameter can be specified just once.");
public static readonly Error ErrorMissingAmountValue = new(Code: 7, "Missing amount value.");
public static readonly Error ErrorInvalidAmountValue = new(Code: 8, "Invalid amount value.");
public static readonly Error ErrorUnsupportedReqParameter = new(Code: 9, "Unsupported required parameter found.");
public static bool TryParse(string input, Network network, [NotNullWhen(true)] out Result? result, [NotNullWhen(false)] out Error? error)
{
result = null;
error = null;
if (!Uri.TryCreate(input, UriKind.Absolute, out Uri? parsedUri))
{
error = ErrorInvalidUri with { Details = input };
return false;
}
if (!parsedUri.Scheme.Equals(UriScheme, StringComparison.OrdinalIgnoreCase))
{
error = ErrorInvalidUriScheme with { Details = parsedUri.Scheme };
return false;
}
if (parsedUri.AbsolutePath is not { Length: > 0 } addressString)
{
error = ErrorMissingAddress;
return false;
}
Money? amount = null;
string? label = null;
string? message = null;
if (!NBitcoinExtensions.TryParseBitcoinAddressForNetwork(addressString, network, out BitcoinAddress? address))
{
error = ErrorInvalidAddress with { Details = addressString };
return false;
}
Dictionary<string, string> unknownParameters = new();
NameValueCollection queryParameters = HttpUtility.ParseQueryString(parsedUri.Query);
foreach (string? parameterName in queryParameters.AllKeys)
{
if (parameterName is null)
{
continue;
}
string? value = queryParameters[parameterName];
if (value is null)
{
continue;
}
if (parameterName == "amount")
{
if (amount is not null)
{
error = ErrorDuplicateParameter with { Details = parameterName };
return false;
}
if (value.Trim() == "")
{
error = ErrorMissingAmountValue with { Details = value };
return false;
}
if (!Money.TryParse(value, out amount))
{
error = ErrorInvalidAmountValue with { Details = value };
return false;
}
}
else if (parameterName == "label")
{
if (label is not null)
{
error = ErrorDuplicateParameter with { Details = parameterName };
return false;
}
label = value;
}
else if (parameterName == "message")
{
if (message is not null)
{
error = ErrorDuplicateParameter with { Details = parameterName };
return false;
}
message = value;
}
else if (parameterName.StartsWith("req-", StringComparison.Ordinal))
{
error = ErrorUnsupportedReqParameter with { Details = parameterName };
return false;
}
}
result = new(Uri: parsedUri, network, address, amount, Label: label, Message: message, unknownParameters);
return true;
}
/// <summary>
/// Successful result of parsing a BIP21 URI string.
/// </summary>
public record Result(Uri Uri, Network Network, BitcoinAddress Address, Money? Amount, string? Label, string? Message, Dictionary<string, string> UnknownParameters)
{
/// <summary>
/// Special constructor for <c>bitcoin:address</c> cases.
/// </summary>
public Result(Uri uri, Network network, BitcoinAddress address)
: this(uri, network, address, Amount: null, Label: null, Message: null, UnknownParameters: new())
{
}
}
/// <summary>
/// Error result of parsing a BIP21 URI string.
/// </summary>
/// <param name="Code">Unique code of the error.</param>
/// <param name="Message">Generic message of the error (with no user-provided data).</param>
/// <param name="Details">Optionally, context information. For example, if the address part of a BIP21 URI string is malformed, the string is to stored here.</param>
public record Error(int Code, string Message, string? Details = null)
{
public bool IsOfSameType(Error otherError)
{
return Code == otherError.Code && Message == otherError.Message;
}
}
}
|
41d1512171593ae9e78d7b7dab4f3209efa76921
|
C#
|
Teles1/Cookie
|
/Cookie/Protocol/messages/game/achievement/AchievementDetailedListMessage.cs
| 2.828125
| 3
|
using Cookie.IO;
using Cookie.Protocol.Network.Types;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Cookie.Protocol.Network.Messages
{
public class AchievementDetailedListMessage : NetworkMessage
{
public const uint ProtocolId = 6358;
public override uint MessageID { get { return ProtocolId; } }
public List<Achievement> StartedAchievements;
public List<Achievement> FinishedAchievements;
public AchievementDetailedListMessage()
{
}
public AchievementDetailedListMessage(
List<Achievement> startedAchievements,
List<Achievement> finishedAchievements
)
{
StartedAchievements = startedAchievements;
FinishedAchievements = finishedAchievements;
}
public override void Serialize(ICustomDataOutput writer)
{
writer.WriteShort((short)StartedAchievements.Count());
foreach (var current in StartedAchievements)
{
current.Serialize(writer);
}
writer.WriteShort((short)FinishedAchievements.Count());
foreach (var current in FinishedAchievements)
{
current.Serialize(writer);
}
}
public override void Deserialize(ICustomDataInput reader)
{
var countStartedAchievements = reader.ReadShort();
StartedAchievements = new List<Achievement>();
for (short i = 0; i < countStartedAchievements; i++)
{
Achievement type = new Achievement();
type.Deserialize(reader);
StartedAchievements.Add(type);
}
var countFinishedAchievements = reader.ReadShort();
FinishedAchievements = new List<Achievement>();
for (short i = 0; i < countFinishedAchievements; i++)
{
Achievement type = new Achievement();
type.Deserialize(reader);
FinishedAchievements.Add(type);
}
}
}
}
|
dccd64953f55b13eff1aeb2c58a9ed296c81d8c9
|
C#
|
DanielVanNoord/ASCOMStandard
|
/ASCOM.Common/ASCOM.Common.DeviceInterfaces/Enums/PointingState.cs
| 2.84375
| 3
|
namespace ASCOM.Common.DeviceInterfaces
{
/// <summary>
/// The pointing state of the mount
/// </summary>
/// <remarks>
/// <para><c>Pier side</c> is a GEM-specific term that has historically caused much confusion.
/// As of Platform 6, the PierSide property is defined to refer to the telescope pointing state. Please see the Platform Developer's Help file for
/// much more information on this topic.</para>
/// <para>In order to support Dome slaving, where it is important to know on which side of the pier the mount is actually located, ASCOM has adopted the
/// convention that the Normal pointing state will be the state where the mount is on the East side of the pier, looking West with the counterweights below
/// the optical assembly.</para>
/// </remarks>
public enum PointingState
{
/// <summary>
/// Normal pointing state - For GEMs, OTA above the counterweights, on the West side of pier looking East
/// </summary>
Normal = 0,
/// <summary>
/// Unknown or indeterminate.
/// </summary>
Unknown = -1,
/// <summary>
/// Through the pole pointing state - For GEMs, OTA above the counterweights, Mount on the East side of pier looking West
/// </summary>
ThroughThePole = 1
}
}
|
6c0f5ce73820bc3747e557762c50d09ff9e06125
|
C#
|
jackingod/jessica
|
/src/Jessica/Extensions/StringExtensions.cs
| 3.015625
| 3
|
using System.Collections.Generic;
using System.Web;
namespace Jessica.Extensions
{
public static class StringExtensions
{
public static string With(this string format, params object[] args)
{
return string.Format(format, args);
}
public static string UrlEncode(this string value)
{
return HttpUtility.UrlEncode(value);
}
public static string Join<T>(this string join, IEnumerable<T> collection)
{
return string.Join(join, collection);
}
}
}
|
4c27c3ea448005935d11e2e5d7f1cbe584f6e4a0
|
C#
|
meowside-v2/DKEngine
|
/DKEngine/Core/SystemExt/WindowControl.cs
| 2.65625
| 3
|
/*
* (C) 2017 David Knieradl
*/
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Timers;
namespace DKEngine.Core.Ext
{
/// <summary>
/// DKEngine window controller
/// </summary>
public static class WindowControl
{
[StructLayout(LayoutKind.Sequential)]
private struct COORD
{
public short X;
public short Y;
public COORD(short x, short y)
{
this.X = x;
this.Y = y;
}
}
[DllImport("kernel32.dll")]
private static extern IntPtr GetStdHandle(int handle);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetConsoleDisplayMode(IntPtr ConsoleOutput, uint Flags, out COORD NewScreenBufferDimensions);
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int cmdShow);
private static readonly IntPtr hConsole = GetStdHandle(-11);
private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
private static COORD xy = new COORD(100, 100);
private static bool ConsoleStateChangeAvailable = true;
internal static void WindowInit()
{
Console.CursorVisible = false;
Console.SetOut(TextWriter.Null);
Console.SetIn(TextReader.Null);
Console.BufferHeight = Console.LargestWindowHeight;
Console.BufferWidth = Console.LargestWindowWidth;
Console.ForegroundColor = ConsoleColor.White;
Console.BackgroundColor = ConsoleColor.Black;
Console.Clear();
WindowSizeChecker(null, null);
Timer windowChecker = new Timer()
{
AutoReset = true,
Enabled = true,
Interval = 1000f
};
windowChecker.Elapsed += WindowSizeChecker;
windowChecker.Start();
}
private static void WindowSizeChecker(object sender, ElapsedEventArgs e)
{
if (Console.WindowHeight != Console.LargestWindowHeight || Console.WindowWidth != Console.LargestWindowWidth)
{
if (ConsoleStateChangeAvailable)
{
if (!SetConsoleDisplayMode(hConsole, 1, out xy))
{
ConsoleStateChangeAvailable = false;
}
}
Console.CursorVisible = false;
}
}
}
}
|
a5aec6b4c326b1659e9802290d1812085dfa19c4
|
C#
|
AnthonySteele/Netsy
|
/Netsy/Services/ListingsService.cs
| 2.625
| 3
|
//-----------------------------------------------------------------------
// <copyright file="ListingsService.cs" company="AFS">
// This source code is part of Netsy http://github.com/AnthonySteele/Netsy/
// and is made available under the terms of the Microsoft Public License (Ms-PL)
// http://www.opensource.org/licenses/ms-pl.html
// </copyright>
//-----------------------------------------------------------------------
namespace Netsy.Services
{
using System;
using System.Linq;
using System.Collections.Generic;
using Netsy.DataModel;
using Netsy.Helpers;
using Netsy.Interfaces;
using Netsy.Requests;
/// <summary>
/// Implementation of the listings service
/// </summary>
public class ListingsService : IListingsService
{
/// <summary>
/// the Etsy context data
/// </summary>
private readonly EtsyContext etsyContext;
/// <summary>
/// the data retriever
/// </summary>
private readonly IDataRetriever dataRetriever;
/// <summary>
/// Initializes a new instance of the ListingsService class
/// </summary>
/// <param name="etsyContext">the etsy context to use</param>
public ListingsService(EtsyContext etsyContext)
: this(etsyContext, new DataRetriever())
{
}
/// <summary>
/// Initializes a new instance of the ListingsService class
/// </summary>
/// <param name="etsyContext">the etsy context to use</param>
/// <param name="dataRetriever">the data retriever to use</param>
public ListingsService(EtsyContext etsyContext, IDataRetriever dataRetriever)
{
this.etsyContext = etsyContext;
this.dataRetriever = dataRetriever;
}
#region IListingsService Members
/// <summary>
/// GetListingDetails completed event
/// </summary>
public event EventHandler<ResultEventArgs<Listings>> GetListingDetailsCompleted;
/// <summary>
/// GetAllListingscompleted event
/// </summary>
public event EventHandler<ResultEventArgs<Listings>> GetAllListingsCompleted;
/// <summary>
/// GetListingsByCategory completed event
/// </summary>
public event EventHandler<ResultEventArgs<Listings>> GetListingsByCategoryCompleted;
/// <summary>
/// GetListingsByColor completed event
/// </summary>
public event EventHandler<ResultEventArgs<Listings>> GetListingsByColorCompleted;
/// <summary>
/// GetListingsByColorAndKeywords completed event
/// </summary>
public event EventHandler<ResultEventArgs<Listings>> GetListingsByColorAndKeywordsCompleted;
/// <summary>
/// GetFrontFeaturedListings completed event
/// </summary>
public event EventHandler<ResultEventArgs<Listings>> GetFrontFeaturedListingsCompleted;
/// <summary>
/// GetListingsByKeyword completed event
/// </summary>
public event EventHandler<ResultEventArgs<Listings>> GetListingsByKeywordCompleted;
/// <summary>
/// GetListingsByMaterials completed event
/// </summary>
public event EventHandler<ResultEventArgs<Listings>> GetListingsByMaterialsCompleted;
/// <summary>
/// GetListingsByTags completed event
/// </summary>
public event EventHandler<ResultEventArgs<Listings>> GetListingsByTagsCompleted;
/// <summary>
/// Get the details of a listing.
/// </summary>
/// <param name="listingId">Specify the listing's numeric ID</param>
/// <param name="detailLevel">Control how much information to return</param>
/// <returns>the async state of the request</returns>
public IAsyncResult GetListingDetails(int listingId, DetailLevel detailLevel)
{
if (!RequestHelper.TestCallPrerequisites(this, this.GetListingDetailsCompleted, this.etsyContext))
{
return null;
}
EtsyUriBuilder etsyUriBuilder = EtsyUriBuilder.Start(this.etsyContext, "listings", listingId)
.DetailLevel(detailLevel);
return this.dataRetriever.StartRetrieve(etsyUriBuilder.Result(), this.GetListingDetailsCompleted);
}
/// <summary>
/// Get all active listings on Etsy.
/// </summary>
/// <param name="sortOn">Specify the field to sort on</param>
/// <param name="sortOrder">Specify the direction to sort on</param>
/// <param name="offset">To page through large result sets</param>
/// <param name="limit">Specify the number of results to return</param>
/// <param name="detailLevel">control how much information to return</param>
/// <returns>the async state of the request</returns>
public IAsyncResult GetAllListings(SortField sortOn, SortOrder sortOrder, int offset, int limit, DetailLevel detailLevel)
{
if (!RequestHelper.TestCallPrerequisites(this, this.GetAllListingsCompleted, this.etsyContext))
{
return null;
}
if (!RequestHelper.TestOffsetLimit(this, this.GetAllListingsCompleted, offset, limit))
{
return null;
}
EtsyUriBuilder etsyUriBuilder = EtsyUriBuilder.Start(this.etsyContext, "listings/all")
.Sort(sortOn, sortOrder)
.OffsetLimit(offset, limit)
.DetailLevel(detailLevel);
return this.dataRetriever.StartRetrieve(etsyUriBuilder.Result(), this.GetAllListingsCompleted);
}
/// <summary>
/// Search for listings by category.
/// </summary>
/// <param name="category">the category name</param>
/// <param name="sortOn">Specify the field to sort on</param>
/// <param name="sortOrder">Specify the direction to sort on</param>
/// <param name="offset">To page through large result sets</param>
/// <param name="limit">Specify the number of results to return</param>
/// <param name="detailLevel">control how much information to return</param>
/// <returns>the async state of the request</returns>
public IAsyncResult GetListingsByCategory(string category, SortField sortOn, SortOrder sortOrder, int offset, int limit, DetailLevel detailLevel)
{
if (!RequestHelper.TestCallPrerequisites(this, this.GetListingsByCategoryCompleted, this.etsyContext))
{
return null;
}
if (!RequestHelper.TestOffsetLimit(this, this.GetListingsByCategoryCompleted, offset, limit))
{
return null;
}
EtsyUriBuilder etsyUriBuilder = EtsyUriBuilder.Start(this.etsyContext, "listings/category", category)
.Sort(sortOn, sortOrder)
.OffsetLimit(offset, limit)
.DetailLevel(detailLevel);
return this.dataRetriever.StartRetrieve(etsyUriBuilder.Result(), this.GetListingsByCategoryCompleted);
}
/// <summary>
/// Search for listings by average color of primary image.
/// </summary>
/// <param name="color">The average color of primary image</param>
/// <param name="wiggle">Specify the degree of tolerance for color matching; where 0 is the most accurate, and 15 is the leas</param>
/// <param name="offset">To page through large result sets</param>
/// <param name="limit">Specify the number of results to return</param>
/// <param name="detailLevel">control how much information to return</param>
/// <returns>the async state of the request</returns>
public IAsyncResult GetListingsByColor(EtsyColor color, int wiggle, int offset, int limit, DetailLevel detailLevel)
{
if (!RequestHelper.TestCallPrerequisites(this, this.GetListingsByColorCompleted, this.etsyContext))
{
return null;
}
if (!this.TestWiggle(wiggle, this.GetListingsByColorCompleted))
{
return null;
}
if (!RequestHelper.TestOffsetLimit(this, this.GetListingsByColorCompleted, offset, limit))
{
return null;
}
EtsyUriBuilder etsyUriBuilder = EtsyUriBuilder.Start(this.etsyContext, "listings/color", color)
.Param("wiggle", wiggle)
.OffsetLimit(offset, limit)
.DetailLevel(detailLevel);
return this.dataRetriever.StartRetrieve(etsyUriBuilder.Result(), this.GetListingsByColorCompleted);
}
/// <summary>
/// Search for listings by keywords and average color of primary image.
/// </summary>
/// <param name="keywords">Specify keywords to search on, separated by spaces or semicolons. You can also use the operators AND and NOT to control keyword matching.</param>
/// <param name="color">Specify an HSV color</param>
/// <param name="wiggle">Specify the degree of tolerance for color matching; where 0 is the most accurate, and 15 is the least.</param>
/// <param name="offset">To page through large result sets</param>
/// <param name="limit">Specify the number of results to return</param>
/// <param name="detailLevel">control how much information to return</param>
/// <returns>the async state of the request</returns>
public IAsyncResult GetListingsByColorAndKeywords(IEnumerable<string> keywords, EtsyColor color, int wiggle, int offset, int limit, DetailLevel detailLevel)
{
if (!RequestHelper.TestCallPrerequisites(this, this.GetListingsByColorAndKeywordsCompleted, this.etsyContext))
{
return null;
}
if (!this.TestWiggle(wiggle, this.GetListingsByColorAndKeywordsCompleted))
{
return null;
}
if (!RequestHelper.TestOffsetLimit(this, this.GetListingsByColorAndKeywordsCompleted, offset, limit))
{
return null;
}
if ((keywords == null) || (keywords.Count() == 0))
{
RequestHelper.SendError(this, this.GetListingsByColorAndKeywordsCompleted, "No keywords");
return null;
}
EtsyUriBuilder etsyUriBuilder = EtsyUriBuilder.Start(this.etsyContext, "listings/color", color)
.Append("/keywords/").Append(keywords)
.Param("wiggle", wiggle)
.OffsetLimit(offset, limit)
.DetailLevel(detailLevel);
return this.dataRetriever.StartRetrieve(etsyUriBuilder.Result(), this.GetListingsByColorAndKeywordsCompleted);
}
/// <summary>
/// Get the featured listings on the front page for the current day.
/// </summary>
/// <param name="offset">To page through large result sets</param>
/// <param name="limit">Specify the number of results to return</param>
/// <param name="detailLevel">control how much information to return</param>
/// <returns>the async state of the request</returns>
public IAsyncResult GetFrontFeaturedListings(int offset, int limit, DetailLevel detailLevel)
{
if (!RequestHelper.TestCallPrerequisites(this, this.GetFrontFeaturedListingsCompleted, this.etsyContext))
{
return null;
}
if (!RequestHelper.TestOffsetLimit(this, this.GetFrontFeaturedListingsCompleted, offset, limit))
{
return null;
}
EtsyUriBuilder etsyUriBuilder = EtsyUriBuilder.Start(this.etsyContext, "listings/featured/front")
.OffsetLimit(offset, limit)
.DetailLevel(detailLevel);
return this.dataRetriever.StartRetrieve(etsyUriBuilder.Result(), this.GetFrontFeaturedListingsCompleted);
}
/// <summary>
/// Search for listings by keyword.
/// </summary>
/// <param name="searchTerms">Specify keywords to search on, separated by spaces or semicolons. You can also use the operators AND and NOT to control keyword matching.</param>
/// <param name="sortOn">Specify the field to sort on</param>
/// <param name="sortOrder">Specify the direction to sort on </param>
/// <param name="minPrice">Minimum for restricting price ranges. Values are in US dollars and may include cents.</param>
/// <param name="maxPrice">Maximum for restricting price ranges. Values are in US dollars and may include cents.</param>
/// <param name="searchDescription">If true, listing descriptions will count towards search matches. (This may produce less relevant results.)</param>
/// <param name="offset">To page through large result sets</param>
/// <param name="limit">Specify the number of results to return</param>
/// <param name="detailLevel">control how much information to return</param>
/// <returns>the async state of the request</returns>
public IAsyncResult GetListingsByKeyword(IEnumerable<string> searchTerms, SortField sortOn, SortOrder sortOrder, decimal? minPrice, decimal? maxPrice, bool searchDescription, int offset, int limit, DetailLevel detailLevel)
{
if (!RequestHelper.TestCallPrerequisites(this, this.GetListingsByKeywordCompleted, this.etsyContext))
{
return null;
}
// error if the given min price is more than the given max price
if (minPrice.HasValue && maxPrice.HasValue && (minPrice.Value > maxPrice.Value))
{
var errorResult = new ResultEventArgs<Listings>(null, new ResultStatus("Invalid price range", null));
RequestHelper.TestSendEvent(this.GetListingsByKeywordCompleted, this, errorResult);
return null;
}
if (!RequestHelper.TestOffsetLimit(this, this.GetListingsByKeywordCompleted, offset, limit))
{
return null;
}
if ((searchTerms == null) || (searchTerms.Count() == 0))
{
RequestHelper.SendError(this, this.GetListingsByKeywordCompleted, "No keywords");
return null;
}
EtsyUriBuilder etsyUriBuilder = EtsyUriBuilder.Start(this.etsyContext, "listings/keywords/")
.Append(searchTerms)
.Sort(sortOn, sortOrder)
.OptionalParam("min_price", minPrice)
.OptionalParam("max_price", maxPrice)
.Param("search_description", searchDescription)
.OffsetLimit(offset, limit)
.DetailLevel(detailLevel);
return this.dataRetriever.StartRetrieve(etsyUriBuilder.Result(), this.GetListingsByKeywordCompleted);
}
/// <summary>
/// Search for listings by materials used.
/// </summary>
/// <param name="materials">Specify one or more materials, separated by spaces or semicolons.</param>
/// <param name="sortOn">Specify the field to sort on</param>
/// <param name="sortOrder">Specify the direction to sort on </param>
/// <param name="offset">To page through large result sets</param>
/// <param name="limit">Specify the number of results to return</param>
/// <param name="detailLevel">control how much information to return</param>
/// <returns>the async state of the request</returns>
public IAsyncResult GetListingsByMaterials(IEnumerable<string> materials, SortField sortOn, SortOrder sortOrder, int offset, int limit, DetailLevel detailLevel)
{
if (!RequestHelper.TestCallPrerequisites(this, this.GetListingsByMaterialsCompleted, this.etsyContext))
{
return null;
}
if (!RequestHelper.TestOffsetLimit(this, this.GetListingsByMaterialsCompleted, offset, limit))
{
return null;
}
if ((materials == null) || (materials.Count() == 0))
{
RequestHelper.SendError(this, this.GetListingsByMaterialsCompleted, "No materials");
return null;
}
EtsyUriBuilder etsyUriBuilder = EtsyUriBuilder.Start(this.etsyContext, "listings/materials/")
.Append(materials)
.Sort(sortOn, sortOrder)
.OffsetLimit(offset, limit)
.DetailLevel(detailLevel);
return this.dataRetriever.StartRetrieve(etsyUriBuilder.Result(), this.GetListingsByMaterialsCompleted);
}
/// <summary>
/// Search for listings by tags.
/// </summary>
/// <param name="tags">Specify one or more tags, separated by spaces or semicolons.</param>
/// <param name="sortOn">Specify the field to sort on</param>
/// <param name="sortOrder">Specify the direction to sort on </param>
/// <param name="offset">To page through large result sets</param>
/// <param name="limit">Specify the number of results to return</param>
/// <param name="detailLevel">control how much information to return</param>
/// <returns>the async state of the request</returns>
public IAsyncResult GetListingsByTags(IEnumerable<string> tags, SortField sortOn, SortOrder sortOrder, int offset, int limit, DetailLevel detailLevel)
{
if (!RequestHelper.TestCallPrerequisites(this, this.GetListingsByTagsCompleted, this.etsyContext))
{
return null;
}
if (!RequestHelper.TestOffsetLimit(this, this.GetListingsByTagsCompleted, offset, limit))
{
return null;
}
if ((tags == null) || (tags.Count() == 0))
{
RequestHelper.SendError(this, this.GetListingsByTagsCompleted, "No tags");
return null;
}
EtsyUriBuilder etsyUriBuilder = EtsyUriBuilder.Start(this.etsyContext, "listings/tags/")
.Append(tags)
.Sort(sortOn, sortOrder)
.OffsetLimit(offset, limit)
.DetailLevel(detailLevel);
return this.dataRetriever.StartRetrieve(etsyUriBuilder.Result(), this.GetListingsByTagsCompleted);
}
#endregion
/// <summary>
/// Test the wiggle room value
/// </summary>
/// <param name="wiggle">the wiggle room</param>
/// <param name="completedEvent">the event to fire on error</param>
/// <returns>true if the value is in range</returns>
private bool TestWiggle(int wiggle, EventHandler<ResultEventArgs<Listings>> completedEvent)
{
if ((wiggle < 0) || (wiggle > EtsyColor.MaxWiggle))
{
ResultEventArgs<Listings> errorResult = new ResultEventArgs<Listings>(
null,
new ResultStatus("Wiggle must be in the range 0 to 15", null));
RequestHelper.TestSendEvent(completedEvent, this, errorResult);
return false;
}
return true;
}
}
}
|
7974ef31b69927eb0fced84d4b71123577de0d3f
|
C#
|
Lexv0lk/medium-8-homeworks
|
/1.2 TrajectorySimulation/Program.cs
| 3.625
| 4
|
using System;
using System.Collections.Generic;
namespace _1._2_TrajectorySimulation
{
class Program
{
public static void Main(string[] args)
{
List<Object> objects = new List<Object>()
{
new Object(5, 5),
new Object(10, 10),
new Object(15, 15)
};
while (true)
{
DetectCollisions(objects);
MoveObjects(objects);
RenderObjects(objects);
}
}
private static void RenderObjects(List<Object> objects)
{
for (int i = 0; i < objects.Count; i++)
{
Console.SetCursorPosition(objects[i].X, objects[i].Y);
Console.Write(i + 1);
}
}
private static void MoveObjects(List<Object> objects)
{
Random random = new Random();
foreach (var obj in objects)
{
obj.Move(random.Next(-1, 1), random.Next(-1, 1));
}
}
private static void DetectCollisions(List<Object> objects)
{
List<Object> objectsToRemove = new List<Object>();
for (int i = 0; i < objects.Count; i++)
{
if (objectsToRemove.Contains(objects[i]))
continue;
for (int j = 0; j < objects.Count; j++)
{
if (j == i || objectsToRemove.Contains(objects[i]))
continue;
if (IsCollided(objects[i], objects[j]))
{
objectsToRemove.Add(objects[i]);
objectsToRemove.Add(objects[j]);
}
}
}
foreach (var obj in objectsToRemove)
objects.Remove(obj);
}
private static bool IsCollided(Object object1, Object object2) => object1.X == object2.X && object1.Y == object2.Y;
}
class Object
{
public int X { get; private set; }
public int Y { get; private set; }
public Object(int x, int y)
{
X = x;
Y = y;
}
public void Move(int xDelta, int yDelta)
{
X += xDelta;
Y += yDelta;
if (X < 0)
X = 0;
if (Y < 0)
Y = 0;
}
}
}
|
a2301e042ed4477f6758e7f876f40f6ff202cd1e
|
C#
|
olgafadejeva/DeliveryService
|
/src/DeliveryService/Models/DriverAssignmentResult.cs
| 2.515625
| 3
|
using DeliveryService.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DeliveryService.Models
{
public class DriverAssignmentResult
{
public int RouteID { get; set; }
public DateTime DeliverByDate { get; set; }
public Vehicle Vehicle { get; set; }
public Driver Driver { get; set; }
public double AssignmentProfit { get; set; }
public DriverAssignmentResult(int id, DateTime deliverByDate, Driver driver) {
this.RouteID = id;
this.DeliverByDate = deliverByDate;
this.Driver = driver;
}
public DriverAssignmentResult() { }
}
}
|
31a4f72296b8896cfbc478a240ca0521486d427c
|
C#
|
Gietson/FlatScraper
|
/src/FlatScraper.Infrastructure/Services/ScraperService.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FlatScraper.Core.Domain;
using FlatScraper.Core.Repositories;
using FlatScraper.Infrastructure.DTO;
using FlatScraper.Infrastructure.Extensions;
using FlatScraper.Infrastructure.Services.Scrapers;
using HtmlAgilityPack;
using Serilog;
namespace FlatScraper.Infrastructure.Services
{
public class ScraperService : IScraperService
{
private static readonly ILogger Logger = Log.Logger;
private readonly IAdRepository _adRepository;
private readonly IScanPageService _scanPageService;
private IScraper scraperInstance;
public ScraperService(IScanPageService scanPageService, IAdRepository adRepository)
{
_scanPageService = scanPageService;
_adRepository = adRepository;
}
public async Task ScrapAsync()
{
Logger.Information("Start ScrapAsync");
IEnumerable<Type> scraperTypes = ScrapExtensions.GetScraperTypes();
IEnumerable<ScanPageDto> scanPages = _scanPageService.GetAllAsync().Result.Where(x => x.Active).ToList();
IEnumerable<Ad> adsDb = await _adRepository.GetAllAsync();
foreach (ScanPageDto scanPage in scanPages)
{
Logger.Information($"Start scrap page, url = '{scanPage.UrlAddress}'");
Type scrapClass = scraperTypes
.FirstOrDefault(x => x.Name.ToLower()
.Replace("Scraper", "")
.Contains(scanPage.Host.ToLower()));
if (scrapClass == null)
{
throw new Exception(
$"Invalid scan page, UrlAddress='{scanPage.UrlAddress}', Page='{scanPage.Host}'.");
}
scraperInstance = Activator.CreateInstance(scrapClass) as IScraper;
HtmlDocument scrapedDoc = ScrapExtensions.ScrapUrl(scanPage.UrlAddress);
if (scrapedDoc == null)
{
throw new Exception(
$"Problem with scrap page = '{scanPage.UrlAddress}', scrapClass='{scrapClass.Name}'.");
}
List<Ad> ads = scraperInstance.ParseHomePage(scrapedDoc, scanPage);
foreach (Ad ad in ads)
{
bool isInDb = adsDb.Any(x => x.IdAds == ad.IdAds);
if (!isInDb)
{
HtmlDocument scrapedSubPage = ScrapExtensions.ScrapUrl(ad.Url);
ad.AdDetails = scraperInstance.ParseDetailsPage(scrapedSubPage, ad);
await _adRepository.AddAsync(ad);
}
}
Logger.Information($"Complited page='{scanPage.UrlAddress}', scraped '{ads.Count}' pages.");
}
Logger.Information("End ScrapAsync");
}
}
}
|
621c369c94b25568f5d1066e331a8557abd0b8ed
|
C#
|
meherbensaid/Algorithm
|
/AlgorithmTest/FibonacciTest.cs
| 3.09375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Algorithm;
using NUnit.Framework;
namespace AlgorithmTest
{
[TestFixture]
public class FibonacciTest
{
private Fibonacci _fibonacci;
[SetUp]
public void SetUp()
{
_fibonacci=new Fibonacci();
}
[Test]
public void Should_Return_0_When_The_Number_Is_Equal_To_0()
{
var number = 0;
var expected = 0;
var actual = _fibonacci.DoFiconacci(number);
Assert.AreEqual(expected,actual);
}
[Test]
public void Should_Return_1_When_The_Number_Is_Equal_To_1()
{
var number = 1;
var expected = 1;
var actual = _fibonacci.DoFiconacci(number);
Assert.AreEqual(expected, actual);
}
[Test]
public void Should_Return_Fibonacci_Number()
{
var number = 20;
var expected = 6765;
var actual = _fibonacci.DoFiconacci(number);
Assert.AreEqual(expected, actual);
}
[Test]
public void Should_Return_Iterative_Fibonacci_Number()
{
var number = 20;
var expected = 6765;
var actual = _fibonacci.DoFibonacciIterative(number);
Assert.AreEqual(expected, actual);
}
}
}
|
e2d81de03d2e0efe5dec30ae72bef1ae49481b3f
|
C#
|
IvanCvetkov/CodeVoid
|
/CodeVoidWPF/Pages/Shop.xaml.cs
| 2.53125
| 3
|
using System;
using System.IO;
using System.Windows;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Path = System.IO.Path;
//using System.Configuration;
//using System.Data.SqlClient;
//using System.Data;
namespace CodeVoidWPF.Pages
{
/// <summary>
/// Interaction logic for Shop.xaml
/// </summary>
public partial class Shop : INotifyPropertyChanged
{
//SqlConnection connection;
//string connectionString;
//databinding interface
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public Shop()
{
InitializeComponent();
//DataContext = this;
//connectionString = ConfigurationManager.ConnectionStrings
//["Database1.Properties.Settings.Database1ConnectionString"].ConnectionString;
}
//points
private int _boundPointsNumber;
public int boundPointsNumber
{
get { return _boundPointsNumber; }
set
{
if (_boundPointsNumber != value)
{
_boundPointsNumber = value;
OnPropertyChanged();
}
}
}
private int _boundAchievements;
public int boundAchievements
{
get { return _boundAchievements; }
set
{
if (_boundAchievements != value)
{
_boundAchievements = value;
OnPropertyChanged();
}
}
}
private int _boundProducts;
public int boundProducts
{
get { return _boundProducts; }
set
{
if (_boundProducts != value)
{
_boundProducts = value;
OnPropertyChanged();
}
}
}
//Database manager
//private void DatabaseUpdate()
//{
// using (connection = new SqlConnection(connectionString))
// using (SqlDataAdapter adapter = new SqlDataAdapter("*SELECT * FROM Table", connection))
// {
// connection.Open();
// DataTable table = new DataTable();
// adapter.Fill(table);
// Balance.Text = table.ToString();
// }
//}
private void Page_Loaded(object sender, RoutedEventArgs e)
{
//...DatabaseUpdate();
string[] points = { "15", "20", "30" };
//Introduction shop logic
string desktop_Path =
Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string pathIntroduction = "CodeVoidProject/CodeVoid/CodeVoidWPF/Points/Introduction.txt";
string introductionPath = Path.Combine(desktop_Path, pathIntroduction);
if (File.ReadAllText(introductionPath).Contains(points[0]))
{
boundPointsNumber += int.Parse(points[0]);
}
//variables shop logic
string pathVariables = "CodeVoidProject/CodeVoid/CodeVoidWPF/Points/Variables.txt";
string variablesPath = Path.Combine(desktop_Path, pathVariables);
if (File.ReadAllText(variablesPath).Contains(points[1]))
{
boundPointsNumber += int.Parse(points[1]);
}
string pathDarkMode = "CodeVoidProject/CodeVoid/CodeVoidWPF/Points/DarkMode.txt";
string dmPath = Path.Combine(desktop_Path, pathDarkMode);
if (File.ReadAllText(dmPath).Contains(points[1]))
{
boundPointsNumber += int.Parse(points[1]);
}
string pathCC = "CodeVoidProject/CodeVoid/CodeVoidWPF/Points/FirstCC.txt";
string ccPath = Path.Combine(desktop_Path, pathCC);
if (File.ReadAllText(ccPath).Contains(points[1]))
{
boundPointsNumber += int.Parse(points[1]);
}
string pathLogin = "CodeVoidProject/CodeVoid/CodeVoidWPF/Points/FirstLogin.txt";
string loginPath = Path.Combine(desktop_Path, pathLogin);
if (File.ReadAllText(loginPath).Contains(points[1]))
{
boundPointsNumber += int.Parse(points[1]);
}
string pathVS = "CodeVoidProject/CodeVoid/CodeVoidWPF/Points/FirstVS.txt";
string vsPath = Path.Combine(desktop_Path, pathVS);
if (File.ReadAllText(vsPath).Contains(points[1]))
{
boundPointsNumber += int.Parse(points[1]);
}
//Money display logic
string[] separators = { "/50", "/15" };
Products.Text = boundProducts + separators[0];
Achievements.Text += boundAchievements + separators[1];
Balance.Text += boundPointsNumber;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
}
private void BtnBackShop_Click(object sender, RoutedEventArgs e)
{
MainWindow.win.NavigateLast();
}
}
}
|
e811eb0040b69644ca38c1efe9d7c009cfa384e6
|
C#
|
gtrial/dk-csharp-essential-01
|
/task03/Program.cs
| 2.53125
| 3
|
namespace task03
{
internal static class Program
{
private static void Main()
{
Book book = new Book("title1", "author1", "content1");
book.Title.Show();
book.Author.Show();
book.Content.Show();
}
}
}
|
64dfea3f9cf897988ba9e74a6cd17ad1110adf3e
|
C#
|
9Lucky9/Sky
|
/Sky/Services/Sound.cs
| 2.828125
| 3
|
using NAudio.Wave;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
namespace Sky.Services
{
class Sound
{
private WaveIn waveIn;
public List<byte> audioBytes = new List<byte>(new byte[] { });
public void StartRecord()
{
try
{
waveIn = new WaveIn();
waveIn.DeviceNumber = 0;
waveIn.DataAvailable += waveIn_DataAvailable;
waveIn.WaveFormat = new WaveFormat(48000, 16, 1);
waveIn.StartRecording();
}
catch (Exception ex)
{ MessageBox.Show(ex.Message); }
}
public void StopRecord()
{
waveIn.StopRecording();
}
private void waveIn_DataAvailable(object sender, WaveInEventArgs e)
{
audioBytes.AddRange(e.Buffer);
}
public static void PlayAudio(byte[] content)
{
WaveOut waveOut = new WaveOut();
IWaveProvider provider = new RawSourceWaveStream(
new MemoryStream(content), new WaveFormat(48000, 16, 1));
waveOut.Init(provider);
waveOut.Play();
}
}
}
|
dd9bdbad7a6afb2e2a87f4b48cb6cc5be6967ccd
|
C#
|
DominikWaldowski5510/AssetLessMarioLike
|
/Assets/Scripts/Interaction/Environment/DestroyBlock.cs
| 2.75
| 3
|
using System.Collections;
using UnityEngine;
//handles animation of making block go up and become destroyed
public class DestroyBlock : MonoBehaviour
{
[Range(0.5f, 2f)] [SerializeField] private float adjustmentAmount = 0.5f;
[Range(0.15f, 2f)] [SerializeField] private float waitTime = 0.15f;
private Pooling destructionEffect; //pooling for the effect that spawns when destructables get hit
bool isActive = false; //checks if the corutine is active to prevent double calls
[SerializeField] private bool hasSounds = false; //checks if the object plays a sound
//function that gets called from alternative script, used to set corutine that handles destruction
public virtual void TriggerBlock(bool isDestructable)
{
if (isActive == false)
{
StartCoroutine(BlockAction(isDestructable));
}
}
//stops corutine to avoid issues when the object is disabled
private void OnDisable() => StopCoroutine(BlockAction(false));
//corutine that makes block move up and down as well as triggers particles and destroys object
private IEnumerator BlockAction(bool isDestructable)
{
if (this.transform.gameObject.activeInHierarchy == true)
{
isActive = true;
Vector3 startPos = this.transform.position;
Vector3 endPos = new Vector3(this.transform.position.x, this.transform.position.y + adjustmentAmount, this.transform.position.z);
//creates effect if the block can be destroyed by pooling the effect
if (isDestructable)
{
destructionEffect = GameObject.Find("DestroyBlockParticlePool").GetComponent<Pooling>();
GameObject newEffect = destructionEffect.GetPooledObject();
newEffect.transform.position = startPos;
newEffect.SetActive(true);
}
//makes the block move up slightly
float elapsedTime = 0;
while (elapsedTime < waitTime)
{
this.transform.position = Vector3.Lerp(startPos, endPos, (elapsedTime / waitTime));
elapsedTime += Time.deltaTime;
yield return new WaitForEndOfFrame();
}
if (hasSounds == true)
{
if (isDestructable)
{
PlayerSounds.instance.PlaySound(PlayerSounds.instance.nameOfSound = PlayerSounds.SoundNames.DestructionBlock);
}
}
transform.position = endPos;
//makes the block move down back to its original position
elapsedTime = 0;
while (elapsedTime < waitTime)
{
this.transform.position = Vector3.Lerp(endPos, startPos, (elapsedTime / waitTime));
elapsedTime += Time.deltaTime;
yield return new WaitForEndOfFrame();
}
transform.position = startPos;
//disables object if its meant to be destructable
if (isDestructable)
{
this.transform.gameObject.SetActive(false);
}
}
isActive = false;
yield return null;
}
}
|
6dc6181b3759a552eece9466f704658114891f50
|
C#
|
SuperAndyHero/Shazzam
|
/KaxamlPlugins/Controls/DoubleDragBox.cs
| 2.734375
| 3
|
namespace KaxamlPlugins.Controls
{
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
public class DoubleDragBox : Control
{
/// <summary>
/// Indicates the number of digits that are displayed (beyond 0).
/// </summary>
public static readonly DependencyProperty PrecisionProperty = DependencyProperty.Register(
nameof(Precision),
typeof(int),
typeof(DoubleDragBox),
new UIPropertyMetadata(2));
/// <summary>
/// A string corresponding to the value of the Current property.
/// </summary>
public static readonly DependencyProperty CurrentTextProperty = DependencyProperty.Register(
nameof(CurrentText),
typeof(string),
typeof(DoubleDragBox),
new UIPropertyMetadata(string.Empty));
/// <summary>
/// The current value.
/// </summary>
public static readonly DependencyProperty CurrentProperty = DependencyProperty.Register(
nameof(Current),
typeof(double),
typeof(DoubleDragBox),
new FrameworkPropertyMetadata(double.MinValue, OnCurrentChanged, CoerceCurrent));
public static readonly DependencyProperty IntervalProperty = DependencyProperty.Register(
nameof(Interval),
typeof(double),
typeof(DoubleDragBox),
new UIPropertyMetadata(0.05));
public static readonly DependencyProperty SensitivityProperty = DependencyProperty.Register(
nameof(Sensitivity),
typeof(double),
typeof(DoubleDragBox),
new UIPropertyMetadata(20.0));
public static readonly DependencyProperty MinimumProperty = DependencyProperty.Register(
nameof(Minimum),
typeof(double),
typeof(DoubleDragBox),
new UIPropertyMetadata(0.0));
public static readonly DependencyProperty MaximumProperty = DependencyProperty.Register(
nameof(Maximum),
typeof(double),
typeof(DoubleDragBox),
new UIPropertyMetadata(1.0));
private Point beginPoint;
private bool isPointValid;
static DoubleDragBox()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(DoubleDragBox), new FrameworkPropertyMetadata(typeof(DoubleDragBox)));
}
public int Precision
{
get => (int)this.GetValue(PrecisionProperty);
set => this.SetValue(PrecisionProperty, value);
}
public string CurrentText
{
get => (string)this.GetValue(CurrentTextProperty);
set => this.SetValue(CurrentTextProperty, value);
}
public double Current
{
get => (double)this.GetValue(CurrentProperty);
set => this.SetValue(CurrentProperty, value);
}
public double Interval
{
get => (double)this.GetValue(IntervalProperty);
set => this.SetValue(IntervalProperty, value);
}
public double Sensitivity
{
get => (double)this.GetValue(SensitivityProperty);
set => this.SetValue(SensitivityProperty, value);
}
public double Minimum
{
get => (double)this.GetValue(MinimumProperty);
set => this.SetValue(MinimumProperty, value);
}
public double Maximum
{
get => (double)this.GetValue(MaximumProperty);
set => this.SetValue(MaximumProperty, value);
}
protected override void OnPreviewMouseDown(MouseButtonEventArgs e)
{
this.CaptureMouse();
this.beginPoint = e.GetPosition(this);
this.isPointValid = true;
base.OnPreviewMouseDown(e);
}
protected override void OnPreviewMouseUp(MouseButtonEventArgs e)
{
this.isPointValid = false;
this.ReleaseMouseCapture();
base.OnPreviewMouseUp(e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
if (this.isPointValid)
{
if (e.GetPosition(this).Y - this.beginPoint.Y > this.Sensitivity)
{
this.Current -= this.Interval;
this.beginPoint.Y = e.GetPosition(this).Y;
}
else if (e.GetPosition(this).Y - this.beginPoint.Y < (-1 * this.Sensitivity))
{
this.Current += this.Interval;
this.beginPoint.Y = e.GetPosition(this).Y;
}
}
}
base.OnMouseMove(e);
}
private static void OnCurrentChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
var ddb = (DoubleDragBox)o;
var d = (double)e.NewValue;
ddb.SetCurrentValue(CurrentTextProperty, Math.Round(d, ddb.Precision).ToString(CultureInfo.InvariantCulture));
}
private static object CoerceCurrent(DependencyObject o, object value)
{
var ddb = (DoubleDragBox)o;
var v = (double)value;
if (ddb != null)
{
if (v > ddb.Maximum)
{
return ddb.Maximum;
}
if (v < ddb.Minimum)
{
return ddb.Minimum;
}
}
return v;
}
}
}
|
08f2022ca34d0fef880a37ad45249935c109deaf
|
C#
|
rajubabub84/DotNetPractice
|
/DesignPatterns/FacadeDemo/ShoppingFacade/UserOrder.cs
| 2.828125
| 3
|
using ShoppingCart.Implementation;
using ShoppingCart.Interfaces;
using ShoppingCart.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShoppingFacade
{
public class UserOrder : IUserOrder
{
public int AddToCart(int itemID, int quantity)
{
Console.WriteLine("Start Add to cart");
ICart userCart = new ShoppingCartDetails();
int cartID = 0;
//Step 1: GetItem
Product product = userCart.GetItemDetails(itemID);
//Step 2: CheckAvailability
if(userCart.CheckItemAvailability(product))
{
//Step 3: LockItemInStock
userCart.LockItemInStock(itemID, quantity);
//Step 4: AddItenToCart
cartID = userCart.AddItemToCart(itemID, quantity);
}
Console.WriteLine("EndAddToCart");
return cartID;
}
public int PlaceOrder(int cartID, int userID)
{
Console.WriteLine("Start Place Order Details");
int orderID = -1;
IWallet wallet = new Wallet();
ITax tax = new Tax();
ICart userCart = new ShoppingCartDetails();
IAddress address = new AddressDetails();
IOrder order = new Order();
//Step 1: Get Tax Percentage by State
double stateTax = tax.GetTaxByState("ABC");
//Step 2: Apply Tax on Cart Items
tax.ApplyTax(cartID, stateTax);
//Step 3: Get User Wallet Balance
double userWalletBalance = wallet.GetUserBalance(userID);
//Step 4: Get Cart Items Price
double cartPrice = userCart.GetCartPrice(cartID);
//Step 5: Compare the balance and price
if (userWalletBalance > cartPrice)
{
//Step 6: Get User Address and set to Cart
Address userAddress = address.GetAddressDetails(userID);
//Step 7: Place the order
orderID = order.PlaceOrderDetails(cartID, userAddress.AddressID);
}
Console.WriteLine("End Place Order Details");
return orderID;
}
}
}
|
3bb9d930497294fbb7d126cc141ee86a616199df
|
C#
|
DynaStudios/Slaysher
|
/SlayerNetworking/Packets/Utils/PacketReader.cs
| 3.203125
| 3
|
using System;
using System.IO;
using System.Text;
namespace SlaysherNetworking.Packets.Utils
{
public class PacketReader
{
private readonly byte[] _data;
private readonly int _size;
private int _index;
private bool _failed;
public int Index
{
get { return _index; }
}
public int Size
{
get { return _size; }
}
public bool Failed
{
get { return _failed; }
set { _failed = value; }
}
public PacketReader(byte[] data, int size)
{
_data = data;
_size = size;
_index = 1;
_failed = false;
}
public bool CheckBoundaries(int size)
{
if ((_index + size) > _size)
_failed = true;
return !_failed;
}
public byte ReadByte()
{
if (!CheckBoundaries(1))
return 0;
int b = _data[_index++];
return (byte) b;
}
public byte[] ReadBytes(int count)
{
if (!CheckBoundaries(count))
return null;
byte[] input = new byte[count];
for (int i = count - 1; i >= 0; i--)
{
input[i] = ReadByte();
}
return input;
}
public sbyte ReadSByte()
{
return unchecked((sbyte) ReadByte());
}
public short ReadShort()
{
if (!CheckBoundaries(2))
return 0;
return unchecked((short) ((ReadByte() << 8) | ReadByte()));
}
public int ReadInt()
{
if (!CheckBoundaries(4))
return 0;
return unchecked((ReadByte() << 24) | (ReadByte() << 16) | (ReadByte() << 8) | ReadByte());
}
public long ReadLong()
{
if (!CheckBoundaries(8))
return 0;
return unchecked((ReadByte() << 56) | (ReadByte() << 48) | (ReadByte() << 40) | (ReadByte() << 32)
| (ReadByte() << 24) | (ReadByte() << 16) | (ReadByte() << 8) | ReadByte());
}
public unsafe float ReadFloat()
{
if (!CheckBoundaries(4))
return 0;
int i = ReadInt();
return *(float*) &i;
}
public double ReadDouble()
{
if (!CheckBoundaries(8))
return 0;
byte[] r = new byte[8];
for (int i = 7; i >= 0; i--)
{
r[i] = ReadByte();
}
return BitConverter.ToDouble(r, 0);
}
public string ReadString16(short maxLen)
{
int len = ReadShort();
if (len > maxLen)
throw new IOException("String field too long");
if (!CheckBoundaries(len*2))
return "";
byte[] b = new byte[len*2];
for (int i = 0; i < len*2; i++)
b[i] = ReadByte();
return Encoding.BigEndianUnicode.GetString(b);
}
public string ReadString8(short maxLen)
{
int len = ReadShort();
if (len > maxLen)
throw new IOException("String field too long");
if (!CheckBoundaries(len))
return "";
byte[] b = new byte[len];
for (int i = 0; i < len; i++)
b[i] = ReadByte();
return Encoding.UTF8.GetString(b);
}
public bool ReadBool()
{
return ReadByte() == 1;
}
public double ReadDoublePacked()
{
return ReadInt()/32.0;
}
}
}
|
6f28e934820e5790671375eb08d759d76f84a7d0
|
C#
|
adm244/CC98Unpacker
|
/CropCirclesUnpacker/Storages/Resources/TextureStorage.cs
| 2.84375
| 3
|
using System;
using System.Diagnostics;
using System.IO;
using CropCirclesUnpacker.Assets;
namespace CropCirclesUnpacker.Storages.Resources
{
public class TextureStorage : ImageResourceStorage
{
private Int32 Pitch;
public TextureStorage()
: this(string.Empty)
{
}
public TextureStorage(string libraryPath)
: base(libraryPath)
{
Pitch = 0;
}
public TextureStorage(string libraryPath, Texture texture)
: base(libraryPath, texture, ResourceType.Texture)
{
int modulo = (Width % 4);
int padding = (modulo > 0) ? (4 - modulo) : 0;
Pitch = Width + padding;
}
public static Texture LoadFromFile(string filePath)
{
TextureStorage storage = new TextureStorage(filePath);
using (FileStream inputStream = new FileStream(storage.LibraryPath, FileMode.Open, FileAccess.Read))
{
using (BinaryReader inputReader = new BinaryReader(inputStream, storage.Encoding))
{
if (!storage.Parse(inputReader))
return null;
}
}
string name = Path.GetFileNameWithoutExtension(filePath);
return new Texture(name, storage.Pixels, storage.Width, storage.Height);
}
public static bool SaveToFile(string filePath, Texture texture)
{
TextureStorage storage = new TextureStorage(filePath, texture);
using (FileStream outputStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
using (BinaryWriter outputWriter = new BinaryWriter(outputStream, storage.Encoding))
{
if (!storage.Write(outputWriter))
{
Debug.Assert(false, "Cannot write a texture file!");
return false;
}
}
}
return true;
}
public static Texture LoadFromStream(BinaryReader inputReader, string name)
{
TextureStorage storage = new TextureStorage();
if (!storage.Parse(inputReader))
return null;
return new Texture(name, storage.Pixels, storage.Width, storage.Height);
}
public static bool SaveToStream(BinaryWriter outputWriter, Texture texture)
{
TextureStorage storage = new TextureStorage(string.Empty, texture);
if (!storage.Write(outputWriter))
{
Debug.Assert(false, "Cannot write a texture file!");
return false;
}
return true;
}
protected override bool Write(BinaryWriter outputWriter)
{
SectionType[] types = new SectionType[] {
SectionType.INFO,
SectionType.DATA,
SectionType.RBYT
};
if (!base.Write(outputWriter, types))
return false;
return true;
}
protected override bool ParseSections(BinaryReader inputReader)
{
if (!base.ParseSections(inputReader))
return false;
if (!ParseSectionType(inputReader, SectionType.RBYT))
return false;
return true;
}
protected override bool ParseSection(BinaryReader inputReader, Section section)
{
bool result = false;
switch (section.Type)
{
case SectionType.RBYT:
result = ParseRBYTSection(inputReader, section);
break;
default:
result = base.ParseSection(inputReader, section);
break;
}
return result;
}
protected override bool WriteSection(BinaryWriter outputWriter, SectionType type)
{
bool result = false;
switch (type)
{
case SectionType.RBYT:
result = WriteRBYTSection(outputWriter);
break;
default:
result = base.WriteSection(outputWriter, type);
break;
}
return result;
}
private bool ParseRBYTSection(BinaryReader inputReader, Section section)
{
//NOTE(adm244): game's resource loader doesn't use this
Pitch = inputReader.ReadInt32();
return true;
}
private bool WriteRBYTSection(BinaryWriter outputWriter)
{
outputWriter.Write((Int32)Pitch);
return true;
}
}
}
|
bc3e0e20080915f2c2886ce5ac10daefd7bdf7b3
|
C#
|
AftianSpheres/conflagration
|
/Assets/Scripts/Battle/Core/ActionExecutionSubsystem.cs
| 2.890625
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace CnfBattleSys
{
/// <summary>
/// Battle overseer subsystem processing that handles the action we're currently executing.
/// This is sort of fiddly, so I've taken the liberty of docstringing the hell out of it.
/// </summary>
public class ActionExecutionSubsystem
{
/// <summary>
/// Object created when a BattleAction is processed.
/// </summary>
public class ActionHandle
{
/// <summary>
/// The handle of the subaction that we're currently working on.
/// </summary>
public SubactionHandle currentSubactionHandle { get { if (currentSubactionIndex < subactionHandles.Length) return subactionHandles[currentSubactionIndex]; else return null; } }
/// <summary>
/// The BattleAction that this handle belongs to.
/// </summary>
public readonly BattleAction battleAction;
/// <summary>
/// The Battler using this action.
/// </summary>
public readonly Battler user;
/// <summary>
/// An array containing subaction handles for each of this action's subactions.
/// </summary>
public readonly SubactionHandle[] subactionHandles;
/// <summary>
/// The primary targets acquired for this action.
/// </summary>
public readonly List<Battler> primaryTargetSet;
/// <summary>
/// The secondary targets acquired for this action.
/// </summary>
public readonly List<Battler> alternateTargetSet;
/// <summary>
/// If true, we skip all subaction or effect package
/// event blocks. We'll handle only the animSkip block.
/// </summary>
public bool skipMostEventBlocks { get; private set; }
/// <summary>
/// The callback that'll run after all of this action's subactions have been executed and its event blocks have finished processing.
/// </summary>
private readonly Action callback;
/// <summary>
/// Index that tracks which subaction handle we're currently processing.
/// </summary>
private int currentSubactionIndex;
public ActionHandle (BattleAction _battleAction, Battler _user, List<Battler> _primaryTargetSet, List<Battler> _alternateTargetSet, Action _callback)
{
battleAction = _battleAction;
user = _user;
primaryTargetSet = _primaryTargetSet;
alternateTargetSet = _alternateTargetSet;
callback = _callback;
subactionHandles = new SubactionHandle[battleAction.subactions.Length];
for (int i = 0; i < battleAction.subactions.Length; i++) subactionHandles[i] = new SubactionHandle(this, battleAction.subactions[i], SubactionFinished);
if (battleAction.onStart != null && !skipMostEventBlocks)
{
BattleStage.instance.Dispatch(battleAction.onStart);
BattleStage.instance.onAllEventBlocksFinished += currentSubactionHandle.Process;
}
else currentSubactionHandle.Process(); // Kickstart action processing
}
/// <summary>
/// Called by each of this action's subactions
/// as a callback, after they finish processing.
/// </summary>
private void SubactionFinished ()
{
currentSubactionIndex++;
// There's a much faster way to do dead target pruning but it's really, really ugly and kinda shits all over any pretensions to object-oriented design you have.
for (int i = primaryTargetSet.Count; i > -1; i--) if (primaryTargetSet[i].isDead) primaryTargetSet.RemoveAt(i);
for (int i = alternateTargetSet.Count; i > -1; i--) if (alternateTargetSet[i].isDead) alternateTargetSet.RemoveAt(i);
for (int i = 0; i < subactionHandles.Length; i++) subactionHandles[i].PruneDeadTargets();
if (currentSubactionIndex < subactionHandles.Length && !user.isDead) currentSubactionHandle.Process();
else OutOfSubactions();
}
/// <summary>
/// Skip any remaining event blocks and finish this action immediately.
/// </summary>
public void EndPrematurely ()
{
// Each time you EndPrematurely with subactions left to process, you immedaitely get the next handle in line.
// So this loop will continue aborting those until you run out of subactions.
while (currentSubactionHandle != null) currentSubactionHandle.EndPrematurely();
skipMostEventBlocks = true;
}
/// <summary>
/// Gets the handle corresponding to the given subaction.
/// </summary>
public SubactionHandle GetHandleFor (BattleAction.Subaction subaction)
{
for (int i = 0; i < subactionHandles.Length; i++)
{
if (subactionHandles[i].subaction == subaction) return subactionHandles[i];
}
return null;
}
/// <summary>
/// Called when we finish our subactions.
/// </summary>
private void OutOfSubactions ()
{
if (!user.isDead)
{
EventBlockHandle eventBlockHandle = null;
if (!skipMostEventBlocks)
{
if (battleAction.onConclusion != null) eventBlockHandle = BattleStage.instance.Dispatch(battleAction.onConclusion, callback);
}
else if (battleAction.animSkip != null) eventBlockHandle = BattleStage.instance.Dispatch(battleAction.animSkip, callback);
if (eventBlockHandle == null) callback();
}
else callback();
}
}
/// <summary>
/// Object created when an effect package is processed.
/// Keeps track of the state of any event blocks
/// this effect dispatched, and the results of
/// processing it.
/// </summary>
public class EffectPackageHandle
{
/// <summary>
/// The outcome of processing this effect package.
/// </summary>
public enum Result
{
/// <summary>
/// The effect hasn't actually been processed yet.
/// </summary>
Undetermined,
/// <summary>
/// Didn't do shit.
/// </summary>
Failure,
/// <summary>
/// The effects this package handles were applied
/// to some targets, but not all of them.
/// (This should never be used as the result for
/// a single target!)
/// </summary>
PartialSuccess,
/// <summary>
/// The effect was applied successfully to all targets.
/// </summary>
Success
}
/// <summary>
/// The base handle for tha BattleAction this effect package is attached to.
/// </summary>
public readonly ActionHandle actionHandle;
/// <summary>
/// The handle for the subaction this effect package is attached to.
/// </summary>
public readonly SubactionHandle subactionHandle;
/// <summary>
/// The effect package that this handle is attached to.
/// </summary>
public readonly BattleAction.Subaction.EffectPackage effectPackage;
/// <summary>
/// The overall result of processing the effect package.
/// </summary>
public readonly Result result;
/// <summary>
/// The individual results of processing the effect package,
/// matched to indices in parent.targets.
/// </summary>
public readonly Result[] resultsByTarget;
/// <summary>
/// Constructor: Fires off the effect package and sets up the handle's state based on that.
/// Fires off callback when the event block tied to this effect package has been handled,
/// or immediately if there's no event block.
/// </summary>
public EffectPackageHandle (SubactionHandle _subactionHandle, BattleAction.Subaction.EffectPackage _effectPackage)
{
subactionHandle = _subactionHandle;
actionHandle = subactionHandle.actionHandle;
effectPackage = _effectPackage;
resultsByTarget = new Result[subactionHandle.targets.Count];
// We don't worry about whether or not to handle event blocks based on anim skipping or anything
// until we actually dispatch them to the BattleStage. BattleStage.Dispatch does the lifting there.
// This is a minor efficiency loss but keeps this code much simpler.
if (effectPackage.eventBlock != null) subactionHandle.eventBlocksQueue.Enqueue(effectPackage.eventBlock);
if (effectPackage.tieSuccessToEffectIndex > -1)
{
result = subactionHandle.effectPackageHandles[effectPackage.tieSuccessToEffectIndex].result;
resultsByTarget = subactionHandle.effectPackageHandles[effectPackage.tieSuccessToEffectIndex].resultsByTarget;
}
else
{
bool overallSucceeded = true;
bool overallFailed = true;
for (int i = 0; i < subactionHandle.targets.Count; i++)
{
resultsByTarget[i] = ApplyToTargetIndex(i);
if (resultsByTarget[i] == Result.Success) overallFailed = false;
else if (resultsByTarget[i] == Result.Failure) overallSucceeded = false;
}
// Either these are both false or there are no targets, in which case our result doesn't matter because this is just a battle scripting thing.
if (overallSucceeded == overallFailed) result = Result.PartialSuccess;
else if (overallSucceeded) result = Result.Success;
else result = Result.Failure;
}
}
/// <summary>
/// Applies this effect package to target at index.
/// </summary>
private Result ApplyToTargetIndex (int targetIndex)
{
Func<Result> hitConfirmed = () =>
{
subactionHandle.targets[targetIndex].ApplyEffect(effectPackage);
return Result.Success;
};
if (!effectPackage.applyEvenIfSubactionMisses && subactionHandle.resultsByTarget[targetIndex] == SubactionHandle.TargetResult.Miss) return Result.Failure;
else
{
if (effectPackage.baseSuccessRate < 1.0f)
{
if (subactionHandle.targets[targetIndex].TryToLandFXAgainstMe(actionHandle.user, effectPackage)) return hitConfirmed();
else return Result.Failure;
}
else return hitConfirmed();
}
}
}
/// <summary>
/// Object created when a subaction is processed.
/// Keeps track of the state of any effect packages
/// or event blocks that this subaction dispatched,
/// and the results of processing it.
public class SubactionHandle
{
/// <summary>
/// The outcome of processing this subaction.
/// </summary>
public enum Result
{
/// <summary>
/// The subaction hasn't actually been processed yet.
/// </summary>
Undetermined,
/// <summary>
/// Didn't do shit.
/// </summary>
Failure,
/// <summary>
/// This subaction applied to a subset of its targets.
/// </summary>
PartialSuccess,
/// <summary>
/// The subaction was applied successfully to all targets.
/// </summary>
Success
}
/// <summary>
/// The outcome of processing this subaction
/// for a single target.
/// </summary>
public enum TargetResult
{
/// <summary>
/// The subaction hasn't actually been processed yet.
/// </summary>
Undetermined,
/// <summary>
/// This subaction doesn't do damage or perform
/// standard accuracy calculations.
/// </summary>
NotApplicable,
/// <summary>
/// Failed to hit.
/// </summary>
Miss,
/// <summary>
/// Landed a hit, touched target HP.
/// (Whether this is considered hit or
/// heal is based on whether we did
/// positive or negative dmg.)
/// </summary>
HitOrHealed,
/// <summary>
/// Landed a hit but dealt no damage.
/// </summary>
NoSell
}
/// <summary>
/// The base handle for tha BattleAction this subaction is attached to.
/// </summary>
public readonly ActionHandle actionHandle;
/// <summary>
/// Handles for each of this subaction's effect packages.
/// </summary>
public readonly EffectPackageHandle[] effectPackageHandles;
/// <summary>
/// The subaction that this handle is attached to.
/// </summary>
public readonly BattleAction.Subaction subaction;
/// <summary>
/// The target list this handle should point to.
/// </summary>
public readonly List<Battler> targets;
/// <summary>
/// Queue of event blocks tied to this subaction that it should
/// dispatch before firing callback.
/// </summary>
public readonly Queue<EventBlock> eventBlocksQueue = new Queue<EventBlock>(16);
/// <summary>
/// The overall result of processing the subaction.
/// </summary>
public Result result { get; private set; }
/// <summary>
/// The individual results of processing the subaction,
/// matched to indices in the target list.
/// </summary>
public readonly TargetResult[] resultsByTarget;
/// <summary>
/// Individual final damage figures, matched
/// to indices in the target list.
/// </summary>
public readonly int[] damageFiguresByTarget;
/// <summary>
/// Handle for the subaction that determines
/// damage figures for this one.
/// </summary>
private readonly SubactionHandle damageDeterminant;
/// <summary>
/// Handle for the subaction that determines
/// success/failure for this one.
/// </summary>
private readonly SubactionHandle successDeterminant;
/// <summary>
/// Callback that will be fired after the subaction has finished and
/// all event blocks are done.
/// </summary>
private Action callback;
/// <summary>
/// Constructor: Prepare a subaction handle. This doesn't execute the subaction until Process() is called.
/// </summary>
public SubactionHandle (ActionHandle _actionHandle, BattleAction.Subaction _subaction, Action _callback)
{
actionHandle = _actionHandle;
subaction = _subaction;
if (subaction.useAlternateTargetSet) targets = actionHandle.alternateTargetSet;
else targets = actionHandle.primaryTargetSet;
damageDeterminant = actionHandle.GetHandleFor(subaction.damageDeterminant);
successDeterminant = actionHandle.GetHandleFor(subaction.successDeterminant);
callback = _callback;
effectPackageHandles = new EffectPackageHandle[subaction.effectPackages.Length];
damageFiguresByTarget = new int[targets.Count];
resultsByTarget = new TargetResult[targets.Count];
}
/// <summary>
/// Process the subaction tied to this handle.
/// </summary>
public void Process ()
{
if (subaction.eventBlock != null) eventBlocksQueue.Enqueue(subaction.eventBlock);
if (damageDeterminant != null)
{
if (targets == damageDeterminant.targets)
{
for (int i = 0; i < damageFiguresByTarget.Length; i++)
{
damageFiguresByTarget[i] = damageDeterminant.damageFiguresByTarget[i];
if (subaction.baseDamage < 0 && damageDeterminant.subaction.baseDamage > 0 || subaction.baseDamage > 0 && damageDeterminant.subaction.baseDamage < 0)
damageFiguresByTarget[i] = -damageFiguresByTarget[i];
}
}
else
{
int d = Util.Mean(damageDeterminant.damageFiguresByTarget);
if (subaction.baseDamage < 0 && damageDeterminant.subaction.baseDamage > 0 || subaction.baseDamage > 0 && damageDeterminant.subaction.baseDamage < 0) d = -d;
for (int i = 0; i < damageFiguresByTarget.Length; i++) damageFiguresByTarget[i] = d;
}
}
else
{
for (int i = 0; i < targets.Count; i++) damageFiguresByTarget[i] = targets[i].CalcDamageAgainstMe(actionHandle.user, subaction, true, true, true);
}
if (successDeterminant != null)
{
if (targets == successDeterminant.targets)
{
for (int i = 0; i < resultsByTarget.Length; i++) resultsByTarget[i] = successDeterminant.resultsByTarget[i];
}
else
{
TargetResult bestTargetResult = TargetResult.NoSell;
for (int i = 0; i < successDeterminant.resultsByTarget.Length; i++)
{
if (successDeterminant.resultsByTarget[i] == TargetResult.NotApplicable)
{
bestTargetResult = TargetResult.NotApplicable;
break;
}
else if (successDeterminant.resultsByTarget[i] == TargetResult.Miss)
{
if (bestTargetResult != TargetResult.HitOrHealed) bestTargetResult = TargetResult.Miss;
}
else if (successDeterminant.resultsByTarget[i] == TargetResult.HitOrHealed) bestTargetResult = TargetResult.HitOrHealed;
}
for (int i = 0; i < resultsByTarget.Length; i++) resultsByTarget[i] = bestTargetResult;
}
result = successDeterminant.result;
}
else
{
bool anySucceeded = false;
bool anyFailed = false;
for (int i = 0; i < resultsByTarget.Length; i++)
{
if (subaction.baseDamage == 0 && subaction.baseAccuracy == 0)
{
resultsByTarget[i] = TargetResult.NotApplicable;
result = Result.Success;
}
else if (targets[i].TryToLandAttackAgainstMe(actionHandle.user, subaction))
{
if (damageFiguresByTarget[i] != 0)
{
resultsByTarget[i] = TargetResult.HitOrHealed;
anySucceeded = true;
}
else
{
resultsByTarget[i] = TargetResult.NoSell;
anyFailed = true;
}
}
else
{
resultsByTarget[i] = TargetResult.Miss;
anyFailed = true;
damageFiguresByTarget[i] = 0; // Lose whatever figure you had determined if you miss.
}
}
if (result != Result.Success)
{
if (anySucceeded && !anyFailed) result = Result.Success;
else if (anySucceeded && anyFailed) result = Result.PartialSuccess;
else result = Result.Failure;
}
}
for (int i = 0; i < targets.Count; i++) targets[i].DealOrHealDamage(damageFiguresByTarget[i]);
for (int i = 0; i < effectPackageHandles.Length; i++)
{
effectPackageHandles[i] = new EffectPackageHandle(this, subaction.effectPackages[i]);
if (subaction.effectPackages[i].eventBlock != null) eventBlocksQueue.Enqueue(subaction.effectPackages[i].eventBlock);
}
if (eventBlocksQueue.Count > 0)
{
while (eventBlocksQueue.Count > 0) BattleStage.instance.Dispatch(eventBlocksQueue.Dequeue());
BattleStage.instance.onAllEventBlocksFinished += callback;
}
else callback();
}
/// <summary>
/// Remove dead targets from target list.
/// </summary>
public void PruneDeadTargets ()
{
for (int i = targets.Count; i > -1; i--) if (targets[i].isDead) targets.RemoveAt(i);
}
/// <summary>
/// End processing of this subaction early.
/// </summary>
public void EndPrematurely ()
{
BattleStage.instance.CancelEventBlocks();
}
}
/// <summary>
/// The BattleData object to which this action execution subsystem belongs.
/// </summary>
private readonly BattleData battleData;
/// <summary>
/// The action that we're working on right now.
/// </summary>
public ActionHandle currentAction { get; private set; }
/// <summary>
/// Constructor: This ActionExecutionSystem belongs to the BattleData object given.
/// </summary>
public ActionExecutionSubsystem (BattleData _battleData)
{
battleData = _battleData;
}
/// <summary>
/// Start handling the given BattleActiom, given the selected user and target sets.
/// Callback will be executed upon completion of the action.
/// </summary>
public void BeginAction (BattleAction _battleAction, Battler _user, Battler[] _primaryTargetSet, Battler[] _alternateTargetSet, Action _callback)
{
if (currentAction != null) Util.Crash("Attempted to start executing " + _battleAction.actionID + " while holding a live handle for " + currentAction.battleAction.actionID);
else
{
Action callback = () =>
{
currentAction = null;
_callback();
};
currentAction = new ActionHandle(_battleAction, _user, new List<Battler>(_primaryTargetSet), new List<Battler>(_alternateTargetSet), callback);
}
}
}
}
|
bbf333687581536d776f864ccc6852425e4cb03f
|
C#
|
luotyzl/TodoList
|
/TodoList/Models/DataManager/TaskManager.cs
| 2.828125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TodoList.Models.Repository;
namespace TodoList.Models.DataManager
{
public class TaskManager:IDataRepository<Task>
{
private readonly TodoContext _todoContext;
public TaskManager(TodoContext context)
{
_todoContext = context;
}
public IQueryable<Task> GetAll()
{
return _todoContext.Tasks.AsQueryable();
}
public void Add(Task entity)
{
_todoContext.Tasks.Add(entity);
_todoContext.SaveChanges();
}
public void Update(Task dbEntity, Task entity)
{
dbEntity.CompleteAt = entity.CompleteAt;
dbEntity.IsComplete = entity.IsComplete;
_todoContext.SaveChanges();
}
}
}
|
1b7230cb3f0f6f99f1f023204fbe948617d94056
|
C#
|
AtricoSoftware/Atrico.Lib.Common
|
/Atrico.Lib.Common/Console/ConsoleUtils.cs
| 3
| 3
|
using System;
using System.Text;
namespace Atrico.Lib.Common.Console
{
public static class ConsoleUtils
{
public static string ReadPassword()
{
var sb = new StringBuilder();
while (true)
{
var cki = System.Console.ReadKey(true);
if (cki.Key == ConsoleKey.Enter)
{
System.Console.WriteLine();
break;
}
if (cki.Key == ConsoleKey.Backspace)
{
if (sb.Length > 0)
{
System.Console.Write("\b\0\b");
sb.Length--;
}
continue;
}
System.Console.Write('*');
sb.Append(cki.KeyChar);
}
return sb.ToString();
}
}
}
|
f1b0fce7229691621c22693c81dbe35111be7bd5
|
C#
|
isukces/AutoUml
|
/app/AutoUml/_features/Symbols/SymbolLineUmlMember.cs
| 2.734375
| 3
|
using System.Collections.Generic;
using System.Reflection;
namespace AutoUml.Symbols
{
public class SymbolLineUmlMember : UmlMember
{
public void AddSymbol(PlantUmlText symbol)
{
Symbols.Add(symbol);
}
public override MemberInfo GetMemberInfo()
{
return null;
}
public override void WriteTo(CodeWriter cf, UmlDiagram diagram)
{
var txt = string.Join(" ", Symbols);
if (string.IsNullOrEmpty(txt))
return;
cf.Writeln(txt);
cf.Writeln("==");
}
public List<PlantUmlText> Symbols { get; } = new List<PlantUmlText>();
}
}
|
0d9947f942290076fce1c6328a5f32dab4fb5337
|
C#
|
ITFriends/School
|
/C# - Beginner (Denis)/Lesson 74/lesson_74.cs
| 3.421875
| 3
|
Dictionary<int, string> countries = new Dictionary<int, string>(5);
countries.Add(1, "Russia");
countries.Add(3, "Great Britain");
countries.Add(2, "USA");
countries.Add(4, "France");
countries.Add(5, "China");
foreach (KeyValuePair<int, string> keyValue in countries)
{
Console.WriteLine(keyValue.Key + " - " + keyValue.Value);
}
// получение элемента по ключу
string country = countries[4];
// изменение объекта
countries[4] = "Spain";
// удаление по ключу
countries.Remove(2);
Dictionary<char, Person> people = new Dictionary<char, Person>();
people.Add('b', new Person() { Name = "Bill" });
people.Add('t', new Person() { Name = "Tom" });
people.Add('j', new Person() { Name = "John" });
foreach (KeyValuePair<char, Person> keyValue in people)
{
// keyValue.Value представляет класс Person
Console.WriteLine(keyValue.Key + " - " + keyValue.Value.Name);
}
// перебор ключей
foreach (char c in people.Keys)
{
Console.WriteLine(c);
}
// перебор по значениям
foreach (Person p in people.Values)
{
Console.WriteLine(p.Name);
}
Dictionary<char, Person> people = new Dictionary<char, Person>();
people.Add('b', new Person() { Name = "Bill" });
people['a'] = new Person() { Name = "Alice" };
Dictionary<string, string> countries = new Dictionary<string, string>
{
{"Франция", "Париж"},
{"Германия", "Берлин"},
{"Великобритания", "Лондон"}
};
foreach (var pair in countries)
Console.WriteLine("{0} - {1}", pair.Key, pair.Value);
Dictionary<string, string> countries = new Dictionary<string, string>
{
["Франция"] = "Париж",
["Германия"] = "Берлин",
["Великобритания"] = "Лондон"
};
|
6734908822ce70faa2deb6d761ccdfa4e244b7bd
|
C#
|
max-ieremenko/ThirdPartyLibraries
|
/Sources/ThirdPartyLibraries.Suite/Internal/NameCombiners/Name.cs
| 3.203125
| 3
|
using System;
namespace ThirdPartyLibraries.Suite.Internal.NameCombiners;
internal sealed class Name : IEquatable<Name>, IComparable<Name>
{
public Name(string first, string second)
{
First = first.ToLowerInvariant();
Second = second.ToLowerInvariant();
}
public string First { get; }
public string Second { get; }
public bool Equals(Name other)
{
if (other == null)
{
return false;
}
return StringComparer.OrdinalIgnoreCase.Equals(First, other.First)
&& StringComparer.OrdinalIgnoreCase.Equals(Second, other.Second);
}
public int CompareTo(Name other)
{
if (other == null)
{
return 1;
}
var c = StringComparer.OrdinalIgnoreCase.Compare(First, other.First);
if (c == 0)
{
c = StringComparer.OrdinalIgnoreCase.Compare(Second, other.Second);
}
return c;
}
public override bool Equals(object obj) => Equals(obj as Name);
public override int GetHashCode()
{
return HashCode.Combine(
StringComparer.OrdinalIgnoreCase.GetHashCode(First),
StringComparer.OrdinalIgnoreCase.GetHashCode(Second));
}
public override string ToString() => First + " - " + Second;
}
|
47cafe4287a07a02f07f73840045593d9ac9276b
|
C#
|
arkinfescioglu/turbot-dotnet
|
/OliWorkshop.Turbo.Abstractions/LinqExtension.cs
| 3.265625
| 3
|
using System;
using System.Linq;
using System.ComponentModel.Design;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Reflection;
namespace OliWorkshop.Turbo.Abstractions
{
/// <summary>
/// Extensiones comunes para todo proyecto basadas en Linq
/// que ayudan a la semticidad del codigo, la fluidez y la lucidez
/// de la codificacion
/// Ayuda a la reutilizacion y hacer operaciones bien recurrentes
/// para mejor la arquitectura y codificacion del sistema
/// </summary>
public static class LinqExtension
{
/// <summary>
/// Delegado que apunta a metodos y expreisones lambdas capaces
/// que ser manejas procesos de reducion
/// </summary>
/// <typeparam name="TValue"></typeparam>
/// <typeparam name="TR"></typeparam>
/// <param name="value"></param>
/// <param name="result"></param>
/// <returns></returns>
public delegate TR Reducer<TValue, TR>(TValue value, TR result);
/// <summary>
/// Delegado que apunta a metodos y expreisones lambdas capaces
/// de generar valores al azar
/// </summary>
/// <typeparam name="TResult">Tipo del resultado genrado</typeparam>
/// <returns></returns>
public delegate TResult Seeder<TResult>();
/// <summary>
/// Agrega una clasura where si se pasa un valor true como condicion
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="query"></param>
/// <param name="condition"></param>
/// <param name="predicate"></param>
/// <returns></returns>
public static IQueryable<T> FilterIf<T>(this IQueryable<T> query, bool condition, Predicate<T> predicate)
{
if (condition)
{
return query.Where(x => predicate.Invoke(x));
}
else
{
return query;
}
}
/// <summary>
/// Metodo de extension para diccionario
/// que posean una lista como valor
/// Este metodo ayuda a introducir valores
/// a la lista de los diccionario de forma mas directa
/// y facil
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="X"></typeparam>
/// <param name="keyValuePairs"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public static IDictionary<X, IList<T>> AddToList<T, X>(
this IDictionary<X, IList<T>> keyValuePairs,
X key,
T value )
{
// de debe comprobar que exista la llave
if (keyValuePairs.ContainsKey(key))
{
keyValuePairs.Add(key, new List<T> { value });
}
else
{
keyValuePairs[key].Add(value);
}
return keyValuePairs;
}
/// <summary>
/// Ayuda a trabajar con diccionarios de listas
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="X"></typeparam>
/// <param name="dic"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public static Dictionary<X,List<T>> AddToList<T, X>(
this Dictionary<X, List<T>> dic,
X key,
T value)
{
dic.AddToList(key, value);
return dic;
}
/// <summary>
/// Simple iteracion para los diccionarios
/// que posean lista como valores
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="X"></typeparam>
/// <param name="keyValuePairs"></param>
/// <param name="key"></param>
/// <param name="action"></param>
/// <returns></returns>
public static IDictionary<X, IList<T>> ForEach<T, X>(
this IDictionary<X, IList<T>> keyValuePairs,
X key,
Action<T> action)
{
foreach (T item in keyValuePairs[key])
{
action(item);
}
return keyValuePairs;
}
/// <summary>
/// Este curioso metodo ayuda a cuidar la fluidez de la consultas
/// mediante una ingeniosa tecnica
/// En concreto permite hacer where anidados pasado primeramente
/// una funcion que recibe como parametro el valor objetivo de la consulta
/// y dicha funcion devolvera algun valor de la propiedad, campo o metodo
/// que despues podra ser pasado por otro criterio que se encargue
/// de filtarlo finalmente para el resultado de la consulta engenrar
/// </summary>
/// <typeparam name="T">Objetivo de la consulta</typeparam>
/// <typeparam name="X">Valor de campo, propiedad o retorno de un metodo de T</typeparam>
/// <param name="enumerable">Extiende el IEnumerable</param>
/// <param name="func">Funcion para buscar un valor de T</param>
/// <param name="criteria">Criterio de consulta</param>
/// <returns></returns>
public static IEnumerable<T> In<T, X>(this IEnumerable<T> enumerable, Func<T, X> func, Func<X, bool> criteria)
{
return enumerable.Where(x => criteria(func(x)));
}
/// <summary>
/// Lanza una excepcion que se le pasa como arguemnto de tipo
/// si se encuentra al menos un elemento que coincida con el predicado
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TErr"></typeparam>
/// <param name="enumerable"></param>
/// <param name="criteria"></param>
/// <returns></returns>
public static IEnumerable<T> ThrowIf<T, TErr>(this IEnumerable<T> enumerable, Func<T, bool> criteria)
where TErr: Exception, new()
{
var subq = enumerable.Where(x => criteria(x)).Count();
if (subq > 0)
{
throw new TErr();
}
return enumerable;
}
/// <summary>
/// Lanza una excepcion que se establece como mediante una accion
/// si se encuentra al menos un elemento que coincida con el predicado
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="enumerable"></param>
/// <param name="criteria"></param>
/// <param name="action"></param>
/// <returns></returns>
public static IEnumerable<T> ThrowIf<T>(this IEnumerable<T> enumerable, Func<T, bool> criteria, Action action)
{
var subq = enumerable.Where(x => criteria(x)).Count();
if (subq > 0)
{
action();
}
return enumerable;
}
/// <summary>
/// Lanza una excepcion que se establece como mediante una accion
/// si se encuentra al menos un elemento que coincida con el predicado
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="enumerable"></param>
/// <param name="criteria"></param>
/// <param name="action"></param>
/// <returns></returns>
public static IEnumerable<T> ThrowIf<T>(this IEnumerable<T> enumerable, Func<T, bool> criteria, Action<T> action)
{
var subq = enumerable
.Where(x => criteria(x))
.Count();
if (subq > 0)
{
action(
enumerable
.Where(x => criteria(x))
.First()
);
}
return enumerable;
}
/// <summary>
/// Ayuda a filtrar por varios criterios end ependecia del tipo
/// que evalue el criterio
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="enumerable"></param>
/// <param name="predicate"></param>
/// <returns></returns>
/*public static IEnumerable<T> WhereCast<T, X>
(this IEnumerable<T> enumerable, Predicate<X> predicate)
{
return enumerable.Where(x => (x) );
}*/
/// <summary>
/// Ayuda a saber si una instancia de delegado es un predicate
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public static bool IsPredicate(this Delegate x)
{
MethodInfo methodInfo = x.GetMethodInfo();
return methodInfo.GetParameters().Length == 1
&&
methodInfo.ReturnParameter.ParameterType.Name == nameof(Boolean);
}
/// <summary>
/// Meto de ayuda privado que permite saber si un Tipo se le puede pasar
/// como primer parametro a un delegado
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="x"></param>
/// <returns></returns>
private static bool CastParameter<T>(Delegate x)
{
var parameter = x.GetMethodInfo()
.GetParameters()
.First()
.ParameterType;
Type target = typeof(T);
return target.Equals(parameter) || parameter.IsSubclassOf(target) || parameter.IsAssignableFrom(target);
}
/// <summary>
/// Soporte del where clasico de linq pero
/// para consultas predicados asincronos que
/// devuelven una tarea
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="enumerable"></param>
/// <param name="predicate"></param>
/// <returns></returns>
public static IEnumerable<T> WhereAsync<T>(this IEnumerable<T> enumerable, Func<T, Task<bool>> predicate)
{
return enumerable.Where(x => {
Task<bool> result = predicate(x);
result.Wait();
return result.Result;
});
}
/// <summary>
/// Mediante un criterio evalua que elementos se deben eliminar en una lista
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <param name="predicate"></param>
public static void Delete<T>(this IList<T> list, Predicate<T> predicate)
{
list
.Where((x) => predicate(x))
.Execute(x => list.Remove(x));
}
/// <summary>
/// Iteracion sencilla sobre un numero de elementos
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="enumerable"></param>
/// <param name="action"></param>
public static IEnumerable<T> Execute<T>(this IEnumerable<T> enumerable, Action<T> action)
{
foreach (T item in enumerable)
{
action(item);
}
return enumerable;
}
/// <summary>
/// Crea un diccionario a partir de un enumerable
/// tomando una propiedad, campo o valor de metodo
/// como la llave del diccionario
/// Nota: sebe tomar en el predicado un valor que se entienda unico sino falla
/// la creacion del diccionario
/// </summary>
/// <typeparam name="X">Tipo inferido por la devolucion del predicado
/// que establece la llave</typeparam>
/// <typeparam name="T">Objetivo de la consulta</typeparam>
/// <param name="query">Extender IEnumerable</param>
/// <param name="predicate">Funcion que define la llave de cada valor</param>
/// <returns></returns>
public static IDictionary<X, T> ToDictionary<X, T>(this IEnumerable<T> query, Func<T, X> predicate)
{
var result = new Dictionary<X, T>();
foreach (T item in query)
{
/// aqui lo se hace es simple para convertir un resultado enumerable de ona consulta
/// a un diccionario, lo hace es definir en el predicado cual es la propiedad,
/// campo o valor derivado del objetivo que va a ser la llave del diccionario
/// entonces procedemos a iterar sobre los resultados agregandolos al diccionario
/// y estableciendo como su llave el valor correspondiente
/// luego el compilador prodra inferir el tipado del diccionario
result.Add(predicate(item), item);
}
return result;
}
/// <summary>
/// Es similar a IDictionary con una diferencia sutil
/// los valores por llave pueden estar repetidos y en vez
/// de asiciar una llave con un valor se asocia con una lista de valores
/// Es un metodo util para estructurar listas clasificadas y colleciones
/// bien complejas
/// </summary>
/// <typeparam name="X"></typeparam>
/// <typeparam name="T"></typeparam>
/// <param name="query"></param>
/// <param name="predicate"></param>
/// <returns></returns>
public static IDictionary<X, IList<T>> ToDictionaryOfLists<X, T>(this IEnumerable<T> query, Func<T, X> predicate)
{
var result = new Dictionary<X, IList<T>>();
foreach (T item in query)
{
// se toma referencia d ela llave para no repetir la llamada
X key = predicate(item);
/// hay detalles de esta implementacion se comentan en el body
/// de ToDictionary
/// Mientras que hay un cambio importante, se espera que el predicado mas
/// que devolver una llave devuelva un valor que
/// clasifique dentro de otra collecion
/// los resultados objetivos
if (result.ContainsKey(key))
{
result[key].Add(item);
}
else
{
result.Add(predicate(item), new List<T> { item });
}
}
return result;
}
/// <summary>
/// Este metodo de ayuda para los tipos string es util para obtener
/// a partir de cadenas con cierto patron de formato
/// un diccionario de llave valor
/// tipo un archivo .ini simple
/// o el siguiente formato de ejemplo: key: value, key2: value2
/// formato para el cual se puede
/// efectuar una llamada asi: raw.ParseToKeyPairs(',',':') o
/// para archvos con formatos de configuracion: raw.ParseToKeyPairs('\n','=')
/// </summary>
/// <param name="str">Se extiende los tipos cadenas</param>
/// <param name="seg">token que separa lo segmentos</param>
/// <param name="pairs">token que separa las llaves y los valores</param>
/// <returns></returns>
public static Dictionary<string, string> ParseKeyPairs(this string str, char seg, char pairs)
{
var result = new Dictionary<string, string>();
// se itera sobre cada trozo divido por el primer token
foreach (string item in str.Split(seg))
{
// se divide entonces cada trozo obtenido del segumento
string[] chunks = item.Split(pairs);
/// se comprueba que solo haya dos string tras la division
if (chunks.Length != 2)
{
/// importante es como emitir un error de sintaxis
throw new Exception("Bad error to parse of pairs separator token");
}
/// se agrega el resultado de la division del separador de los pares
/// llave y valor
result.Add(chunks[0], chunks[1]);
}
return result;
}
/// <summary>
/// Este metodo sirve para generar un valor escalar a partir del resultado de
/// una consulta
/// </summary>
/// <typeparam name="TCurrent"></typeparam>
/// <typeparam name="TResult"></typeparam>
/// <param name="enumerable"></param>
/// <param name="reducer"></param>
/// <param name="initial"></param>
/// <returns></returns>
public static TResult Reduce<TCurrent, TResult>(
this IEnumerable<TCurrent> enumerable,
Reducer<TCurrent, TResult> reducer,
TResult initial
)
{
TResult result = initial;
foreach (TCurrent current in enumerable)
{
result = reducer(current, result);
}
return result;
}
/// <summary>
/// Este metodo de extension se agrega a todos los objetos de la biblioteca base .Net
/// y devuelve true si el valor de la instancia aparece en alguno de los valores
/// pasados como argumento
/// En fin simplifica condicionales de este tipo:
/// manera estandar => if(value == 3 || value == 5 || value == 7)
/// con este metodo => if(value.IsHere(3, 5, 7))
/// </summary>
/// <param name="element"></param>
/// <param name="values"></param>
/// <returns></returns>
public static bool IsHere(this object element, params object[] values)
{
return values.Contains(element);
}
/// <summary>
/// Utilidad simple que ayuda a cualquier objeto
/// a devolver el valor de una propiedad si se conoce su
/// nombre de propiedad
/// </summary>
/// <param name="value"></param>
/// <param name="key"></param>
/// <returns></returns>
public static object GetPropertyValue(this object value, string key)
{
return value.GetType().GetProperty(key).GetValue(value);
}
/// <summary>
/// Version de IsHere pero en un IQueryable
/// es decir agrega un filtro IsHere a la consulta
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="element"></param>
/// <param name="values"></param>
/// <returns></returns>
public static IQueryable<T> WhereIn<T>(this IQueryable<T> element, params object[] values)
{
return element.Where(x => values.Contains(x));
}
/// <summary>
/// Nombre mas semantico para Substring
/// </summary>
/// <param name="str"></param>
/// <param name="limit"></param>
/// <param name="offset"></param>
/// <returns></returns>
public static string TakeUntil(this string str, int limit, int offset = 0)
{
return string.IsNullOrEmpty(str) ? str : str.Substring(offset, limit);
}
/// <summary>
/// Este metodo es un simpel helper que ayuda
/// a generar sequencia tanto al azar o basadas en
/// alguna clase de patron atravez de un delgado o
/// expresion lambda que se le pase como argumento
/// </summary>
/// <typeparam name="TCurrent"></typeparam>
/// <param name="count"></param>
/// <param name="seeder"></param>
/// <returns></returns>
public static TCurrent[] Generate<TCurrent>(
int count,
Seeder<TCurrent> seeder)
{
// se genra un arreglo con la dimesion requerida por el parametro
TCurrent[] currents = new TCurrent[count];
/// luego se itera sobre el arreglo completo
/// para que el delago genere los valores
for (int i = 0; i < count; i++)
{
currents[i] = seeder();
}
return currents;
}
}
}
|
38328efef82febb67bfe061d1c076d4131476a26
|
C#
|
camilolrangel/BlogPwa
|
/pwa-blog-master/PWABlog/Models/Blog/Etiqueta/EtiquetaOrmService.cs
| 2.796875
| 3
|
using Microsoft.EntityFrameworkCore;
using PWABlog.Models.Blog.Categoria;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PWABlog.Models.Blog.Etiqueta
{
public class EtiquetaOrmService
{
private readonly DatabaseContext _databaseContext;
public EtiquetaOrmService(DatabaseContext databaseContext)
{
_databaseContext = databaseContext;
}
public List<EtiquetaEntity> ObterEtiqueta()
{
// INÍCIO DOS EXEMPLOS
/**********************************************************************************************************/
/*** OBTER UM ÚNICO OBJETO */
/**********************************************************************************************************/
// First = Obter a primeira categoria retornada pela consulta
//var primeiraCategoria = _databaseContext.Categorias.First();
// FirstOrDefault = Mesmo do First, porém retorna nulo caso não encontre nenhuma
var primeiraEtiquetaOuNulo = _databaseContext.Etiquetas.FirstOrDefault();
// Single = Obter um único registro do banco de dados
// var algumaCategoriaEspecifica = _databaseContext.Categorias.Single(c => c.Id == 3);
// SingleOrDefault = Mesmo do Sigle, porém retorna nulo caso não encontre nenhuma
var algumaEtiquetaOuNulo = _databaseContext.Etiquetas.SingleOrDefault(c => c.Id == 3);
// Find = Equivalente ao SingleOrDefault, porém fazendo uma busca por uma propriedade chave
var encontrarEtiqueta = _databaseContext.Etiquetas.Find(3);
/**********************************************************************************************************/
/*** OBTER MÚLTIPLOS OBJETOS */
/**********************************************************************************************************/
// ToList
var todasEtiquetas = _databaseContext.Etiquetas.ToList();
/***********/
/* FILTROS */
/***********/
var etiquetasComALetraG = _databaseContext.Etiquetas.Where(c => c.Nome.StartsWith("G")).ToList();
var etiquetasComALetraMouL = _databaseContext.Etiquetas
.Where(c => c.Nome.StartsWith("M") || c.Nome.StartsWith("L"))
.ToList();
/*************/
/* ORDENAÇÃO */
/*************/
var etiquetasEmOrdemAlfabetica = _databaseContext.Etiquetas.OrderBy(c => c.Nome).ToList();
var etiquetasEmOrdemAlfabeticaInversa = _databaseContext.Etiquetas.OrderByDescending(c => c.Nome).ToList();
/**************************/
/* ENTIDADES RELACIONADAS */
/**************************/
var etiquetasESuaCategoria = _databaseContext.Etiquetas
.Include(c => c.Categoria);
// FIM DOS EXEMPLOS
// Código de fato necessário para o método
return _databaseContext.Etiquetas
.Include(c => c.Categoria)
.ToList();
}
public EtiquetaEntity ObterEtiquetaPorId(int idEtiqueta)
{
var etiqueta = _databaseContext.Etiquetas.Find(idEtiqueta);
return etiqueta;
}
public List<EtiquetaEntity> PesquisarEtiquetaPorNome(string nomeEtiqueta)
{
return _databaseContext.Etiquetas.Where(c => c.Nome.Contains(nomeEtiqueta)).ToList();
}
public EtiquetaEntity CriarEtiqueta(string nome, CategoriaEntity idCategoria)
{
// Verificar se um nome foi passado
if (nome == null)
{
throw new Exception("A Etiqueta precisa de um nome!");
}
// Verificar existência da Categoria da Etiqueta
var categoria = _databaseContext.Categorias.Find(idCategoria);
if (categoria == null)
{
throw new Exception("A Categoria informada para a Etiqueta não foi encontrada!");
}
// Criar nova Etiqueta
var novaEtiqueta = new EtiquetaEntity { Nome = nome, Categoria = categoria };
_databaseContext.Etiquetas.Add(novaEtiqueta);
_databaseContext.SaveChanges();
return novaEtiqueta;
}
public EtiquetaEntity EditarEtiqueta(int id, string nome, CategoriaEntity idCategoria)
{
// Obter Etiqueta a Editar
var etiqueta = _databaseContext.Etiquetas.Find(id);
if (etiqueta == null)
{
throw new Exception("Etiqueta não encontrada!");
}
// Verificar existência da Categoria da Etiqueta
var categoria = _databaseContext.Categorias.Find(idCategoria);
if (categoria == null)
{
throw new Exception("A Categoria informada para a Etiqueta não foi encontrada!");
}
// Atualizar dados da Etiqueta
etiqueta.Nome = nome;
etiqueta.Categoria = categoria;
_databaseContext.SaveChanges();
return etiqueta;
}
public bool RemoverEtiqueta(int id)
{
var etiqueta = _databaseContext.Etiquetas.Find(id);
if (etiqueta == null)
{
throw new Exception("Etiqueta não encontrada!");
}
_databaseContext.Etiquetas.Remove(etiqueta);
_databaseContext.SaveChanges();
return true;
}
}
}
|
92f71131bd191e8b379fb491cfe3af3a8027aa2d
|
C#
|
Thirrash/UntitledAwesomeGame
|
/Unity/Assets/Scripts/UtilityMgmt/DictionaryExtension.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using UnityEngine;
public static class DictionaryExtension
{
public static Dictionary<TKey, TValue> CloneDictionaryCloningValues<TKey, TValue> ( this Dictionary<TKey, TValue> original ) where TValue : ICloneable {
Dictionary<TKey, TValue> ret = new Dictionary<TKey, TValue>( original.Count, original.Comparer );
foreach( KeyValuePair<TKey, TValue> entry in original )
ret.Add( entry.Key, (TValue)entry.Value.Clone( ) );
return ret;
}
public static Dictionary<TKey, TValue> CloneCertainValues<TKey, TValue> ( this Dictionary<TKey, TValue> original, List<TKey> selectiveList ) {
Dictionary<TKey, TValue> ret = new Dictionary<TKey, TValue>( );
foreach( TKey k in selectiveList ) {
TValue val;
if( original.TryGetValue( k, out val ) )
ret.Add( k, val );
}
return ret;
}
}
|
561bd24d451e3fee2cde058c2af1f63baa1a1543
|
C#
|
adikanike85/performance_dashboard
|
/Source/kCura.PDB.Core/Extensions/RetryExtensions.cs
| 2.78125
| 3
|
namespace kCura.PDB.Core.Extensions
{
using System;
using System.Threading.Tasks;
using kCura.PDB.Core.Exception;
using kCura.PDB.Core.Interfaces.Services;
public static class RetryExtensions
{
public static async Task<T> RetryCall<T>(this TimeSpan delay, int times, ILogger logger, Func<Task<T>> operation)
{
var attempts = 0;
do
{
try
{
attempts++;
return await operation();
}
catch (RetryException ex)
{
if (attempts == times)
{
throw ex.InnerException;
}
logger.WithClassName().LogVerbose($"Exception caught on attempt {attempts} - will retry after delay {delay} -- Exception Details: {ex}");
await Task.Delay(delay);
}
}
while (true);
}
}
}
|
79d8d248a7cb09db25c2f11ffb04ec686701c26a
|
C#
|
y1024866464/WeihanLi.Common
|
/samples/DotNetFxSample/ExtensionsTest.cs
| 2.765625
| 3
|
using System;
using WeihanLi.Extensions;
namespace DotNetFxSample
{
public class ExtensionsTest
{
public static void IsPrimaryTest()
{
var types = new[]
{
typeof(bool),
typeof(sbyte),
typeof(byte),
typeof(int),
typeof(uint),
typeof(short),
typeof(ushort),
typeof(long),
typeof(ulong),
typeof(float),
typeof(double),
typeof(decimal),
typeof(DateTime),// IsPrimitive:False
typeof(TimeSpan),// IsPrimitive:False
typeof(char),
typeof(string),// IsPrimitive:False
//typeof(object),// IsPrimitive:False
};
types.ForEach(t =>
{
Console.WriteLine($"{t.FullName}");
Console.WriteLine($"IsPrimitive:{t.IsPrimitive}");
Console.WriteLine($"DefaultValue:{t.GetDefaultValue()}");
Console.WriteLine($"Serilize Result:{t.GetDefaultValue().ToJson()}");
Console.WriteLine($"IsBasicType:{t.IsBasicType()}");
Console.WriteLine();
});
}
}
}
|
8d46604acd98d5243a6956c31536dc0316f18919
|
C#
|
NanaseRuri/Algorithms
|
/Algorithms/Chapter4_Graph/ConnectedComponent.cs
| 3.359375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Algorithms.Chapter4_Graph
{
class ConnectedComponent
{
private bool[] marked;
private int[] id;
public int Count { get; private set; }
public ConnectedComponent(Graph g)
{
marked=new bool[g.VertexSize];
id=new int[g.VertexSize];
for (int i = 0; i < g.VertexSize; i++)
{
if (!marked[i])
{
Dfs(g, i);
Count++;
}
}
}
void Dfs(Graph g, int v)
{
marked[v] = true;
id[v] = Count;
foreach(var i in g.Adj(v))
{
if (!marked[i])
{
Dfs(g, i);
}
}
}
public bool Connected(int v1, int v2)
{
return id[v1] == id[v2];
}
public int Id(int i)
{
return id[i];
}
}
}
|
2f4de7106c0bb81c2dfc40f6fb370cfa9e89d7cd
|
C#
|
BBraunRussia/MT940
|
/MT940/Classes/Invoice.cs
| 3.265625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MT940
{
public class Invoice
{
private string _number;
private bool _isRub;
private static Invoice _uniqueInstance;
private Invoice()
{
string day;
if (DateTime.Now.DayOfYear / 10 == 0)
day = "00" + DateTime.Now.DayOfYear.ToString();
else if (DateTime.Now.DayOfYear / 100 == 0)
day = "0" + DateTime.Now.DayOfYear.ToString();
else
day = DateTime.Now.DayOfYear.ToString();
Number = day + "." + "001";
}
public static Invoice GetUniqueInstance()
{
if (_uniqueInstance == null)
_uniqueInstance = new Invoice();
return _uniqueInstance;
}
public string Number
{
get { return _number; }
set { _number = value; }
}
public bool IsRub
{
get { return _isRub; }
set { _isRub = value; }
}
public string Currency { get { return (_isRub) ? "RUB" : "EUR"; } }
public string GetNumberFormated()
{
string number = Number;
while (number[0] == '0')
number = number.Remove(0, 1);
number = number.Replace('.', '/');
return number;
}
}
}
|
a6d1a8e709b84fb1d2487c50253d5ccf191d0746
|
C#
|
sprakash1993/ABC-Company-E-Recruitment
|
/sample/DB/EmployeeDB.cs
| 2.890625
| 3
|
using BOFactory;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Types;
namespace DB
{
public class EmployeeDB : IEmployeeDB
{
/// <summary>
///
/// </summary>
/// <returns></returns>
public SortedList<int, IEmployee> GetEmpList()
{
SortedList<int, IEmployee> employees=new SortedList<int,IEmployee>();
SqlConnection connection = DBUtility.getConnection();
connection.Open();
SqlCommand command = new SqlCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "sp_displayEmp";
command.Connection = connection;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string empname = (string)reader["EmployeeName"];
int empId = Convert.ToInt32(reader["EmployeeID"]);
DateTime dob = Convert.ToDateTime(reader["DOB"]);
DateTime doj = Convert.ToDateTime(reader["DOJ"]);
string gender = (string)reader["Gender"];
string divison = (string)reader["Division"];
float ctc = Convert.ToInt32(reader["CTC"]);
string designation = (string)reader["Designation"];
int unitheadid = Convert.ToInt32(reader["UnitHeadID"]);
int projectid = Convert.ToInt32(reader["ProjectID"]);
bool ishr = Convert.ToBoolean(reader["IsHR"]);
bool isnew = Convert.ToBoolean(reader["IsNew"]);
IEmployee emp = new EmployeeFactory().CreateEmployee(empId,empname,dob,doj,gender,divison,ctc,designation,unitheadid,projectid,ishr,isnew);
employees.Add(emp.EmployeeId,emp);
}
connection.Close();
return employees;
}
/// <summary>
///
/// </summary>
/// <param name="emp"></param>
/// <returns></returns>
public int AddEmployee(IEmployee emp )
{
SqlConnection connection = DBUtility.getConnection();
connection.Open();
SqlCommand command = new SqlCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "sp_AddEmployee";
command.Parameters.AddWithValue("@EmployeeName", emp.EmployeeName);
command.Parameters.AddWithValue("@DOB", emp.DOB);
command.Parameters.AddWithValue("@DOJ", emp.DOJ);
command.Parameters.AddWithValue("@Designation", emp.Designation);
command.Parameters.AddWithValue("@UnitHeadID", emp.UnitHeadID);
command.Parameters.AddWithValue("@ProjectID", emp.ProjectID);
command.Parameters.AddWithValue("@Gender", emp.Gender);
command.Parameters.AddWithValue("@Division", emp.Division);
command.Parameters.AddWithValue("@IsNew", emp.IsNew);
command.Parameters.AddWithValue("@IsHR", emp.IsHR);
command.Parameters.AddWithValue("@CTC", emp.CTC);
command.Parameters.AddWithValue("@EmployeeID", 0);
command.Parameters["@EmployeeID"].Direction = ParameterDirection.Output;
command.Connection = connection;
int row = command.ExecuteNonQuery();
connection.Close();
if (row > 0)
{
return Convert.ToInt32(command.Parameters["@EmployeeID"].Value);
}
else
return row;
}
/// <summary>
///
/// </summary>
/// <param name="empID"></param>
/// <param name="ctc"></param>
/// <param name="desigantion"></param>
/// <returns></returns>
public int UpdateEmployee(int empID, float ctc, string desigantion)
{
SqlConnection connection = DBUtility.getConnection();
connection.Open();
SqlCommand command = new SqlCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "sp_UpdateEmployee1";
command.Parameters.AddWithValue("@EmployeeID", empID);
command.Parameters.AddWithValue("@CTC", ctc);
command.Parameters.AddWithValue("@Designation", desigantion);
command.Connection = connection;
int row = command.ExecuteNonQuery();
connection.Close();
return row;
}
/// <summary>
///
/// </summary>
/// <param name="empID"></param>
/// <returns></returns>
public int CheckHr(int empID)
{
SqlConnection connection = DBUtility.getConnection();
connection.Open();
SqlCommand command = new SqlCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "sp_displayEmp";
command.Connection = connection;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (Convert.ToInt32(reader["EmployeeID"]) == empID)
{
return Convert.ToInt32(reader["IsHR"]);
}
}
connection.Close();
return 0;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public List<int> GetEmployeeIDList()
{
SqlConnection connection = DBUtility.getConnection();
connection.Open();
SqlCommand command = new SqlCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "sp_displayEmp";
command.Connection = connection;
List<int> empIDList = new List<int>();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int empId = Convert.ToInt32(reader["EmployeeID"]);
empIDList.Add(empId);
}
connection.Close();
return empIDList;
}
}
}
|
90c4a437b1e0b1a6915408f9c62d52b322cb5de1
|
C#
|
teddysot/VFS
|
/Portfolio/AIPrototype/Assets/Scripts/AI/StateMachine.cs
| 2.75
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StateMachine : MonoBehaviour
{
private IState _currentState;
public void ChangeState(IState newState)
{
if(_currentState != null)
{
_currentState.Exit();
}
#if UNITY_EDITOR
Debug.Log("[StateMachine] ChangeState: " + newState.ToString());
#endif
_currentState = newState;
}
public void ExecuteState()
{
IState runningState = _currentState;
if(runningState != null)
{
#if UNITY_EDITOR
Debug.Log("[StateMachine] ExecuteState: " + runningState.ToString());
#endif
runningState.Execute();
}
}
}
|
db38d5366fe8fb4d5b2f031ceb658f79f5b11c53
|
C#
|
dystudio/EasyCNTK
|
/Source/EasyCNTK/Learning/Reinforcement/PolicyGradientsTeacher.cs
| 2.640625
| 3
|
//
// Copyright (c) Stanislav Grigoriev. All rights reserved.
// grigorievstas9@gmail.com
// https://github.com/StanislavGrigoriev/EasyCNTK
//
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//
using CNTK;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EasyCNTK.Learning.Reinforcement
{
/// <summary>
/// Реализует механизм обучения методом Policy Gradients
/// </summary>
/// <typeparam name="T"></typeparam>
public class PolicyGradientsTeacher<T> : AgentTeacher<T> where T : IConvertible
{
public PolicyGradientsTeacher(Environment environment, DeviceDescriptor device) : base(environment, device) { }
/// <summary>
/// Обучает агента, модель которого представлена сетью прямого распространения (не рекуррентной). Используется в случае когда модель оперирует только текущим состоянием среды, не учитывая предыдущие состояния.
/// </summary>
/// <param name="agent">Агент для обучения, сеть заданной архитектуры</param>
/// <param name="iterationCount">Количество итераций обучения (эпох)</param>
/// <param name="rolloutCount">Количество прогонов(в случае игры - прохождений уровня до окончания игры <seealso cref="Environment.IsTerminated"/>), которое будет пройдено прежде чем обновятся веса.
/// Можно интерпретировать как количество обучающих данных на одну эпоху.</param>
/// <param name="minibatchSize">Размер минибатча для обучения</param>
/// <param name="actionPerIteration">Произвольное действие, которое требуется выполнять каждую эпоху. Позволяет прервать процесс тренировки. Входные параметры: эпоха, loss-ошибка, evaluation-ошибка.
/// Выходные: true - прервать процесс тренировки, false - продолжить тренировку.
/// Используется для осуществления логирования, отображения процесса обучения, сохранения промежуточных чекпоинтов модели и т.п.</param>
/// <param name="gamma">Коэффициент затухания награды(reward), при вычислении Discounted reward</param>
/// <returns></returns>
public Sequential<T> Teach(Sequential<T> agent, int iterationCount, int rolloutCount, int minibatchSize, Func<int, double, double, bool> actionPerIteration = null, double gamma = 0.99)
{
for (int iteration = 0; iteration < iterationCount; iteration++)
{
var data = new LinkedList<(int rollout, int actionNumber, T[] state, T[] action, T reward)>();
for (int rolloutNumber = 0; rolloutNumber < rolloutCount; rolloutNumber++)
{
int actionNumber = 0;
while (!Environment.IsTerminated)
{
var currentState = Environment.GetCurrentState<T>();
var action = agent.Predict(currentState, Device);
var reward = Environment.PerformAction(action);
data.AddLast((rolloutNumber, ++actionNumber, currentState, action, reward));
}
Environment.Reset();
}
var discountedRewards = new T[data.Count];
foreach (var rollout in data.GroupBy(p => p.rollout))
{
var steps = rollout.ToList();
steps.Sort((a, b) => a.actionNumber > b.actionNumber ? 1 : a.actionNumber < b.actionNumber ? -1 : 0); //во возрастанию actionNumber
for (int i = 0; i < steps.Count; i++)
{
var remainingRewards = steps.GetRange(i, steps.Count - i)
.Select(p => Environment.HasRewardOnlyForRollout ? steps[steps.Count - 1].reward : p.reward)
.ToArray();
discountedRewards[i] = CalculateDiscountedReward(remainingRewards, gamma);
}
}
var features = data.Select(p => p.state);
var labels = data.Zip(discountedRewards, (d, reward) => Multiply(d.action, reward));
var dataset = features.Zip(labels, (f, l) => f.Concat(l).ToArray()).ToArray();
var inputDim = features.FirstOrDefault().Length;
var fitResult = agent.Fit(dataset,
inputDim,
minibatchSize,
GetLoss()[0],
GetEvalLoss()[0],
GetOptimizer()[0],
1,
false,
Device);
data.Clear();
var needStop = actionPerIteration?.Invoke(iteration, fitResult.LossError, fitResult.EvaluationError);
if (needStop.HasValue && needStop.Value)
break;
}
return agent;
}
/// <summary>
/// Обучает агента, модель которого представлена рекуррентной сетью. Используется в случае когда модель оперирует цепочкой состояний среды.
/// </summary>
/// <param name="agent">Агент для обучения, сеть заданной архитектуры</param>
/// <param name="iterationCount">Количество итераций обучения (эпох)</param>
/// <param name="rolloutCount">Количество прогонов(в случае игры - прохождений уровня до окончания игры <seealso cref="Environment.IsTerminated"/>), которое будет пройдено прежде чем обновятся веса.
/// Можно интерпретировать как количество обучающих данных на одну эпоху.</param>
/// <param name="minibatchSize">Размер минибатча для обучения</param>
/// <param name="sequenceLength">Длина последовательности: цепочка из предыдущих состояних среды на каждом действии.</param>
/// <param name="actionPerIteration">Произвольное действие, которое требуется выполнять каждую эпоху. Позволяет прервать процесс тренировки. Входные параметры: эпоха, loss-ошибка, evaluation-ошибка.
/// Выходные: true - прервать процесс тренировки, false - продолжить тренировку.
/// Используется для осуществления логирования, отображения процесса обучения, сохранения промежуточных чекпоинтов модели и т.п.</param>
/// <param name="gamma">Коэффициент затухания награды(reward), при вычислении Discounted reward</param>
/// <returns></returns>
public Sequential<T> Teach(Sequential<T> agent, int iterationCount, int rolloutCount, int minibatchSize, int sequenceLength, Func<int, double, double, bool> actionPerIteration = null, double gamma = 0.99)
{
for (int iteration = 0; iteration < iterationCount; iteration++)
{
var data = new List<(int rollout, int actionNumber, T[] state, T[] action, T reward)>();
for (int rolloutNumber = 0; rolloutNumber < rolloutCount; rolloutNumber++)
{
int actionNumber = 0;
while (!Environment.IsTerminated)
{
var currentState = Environment.GetCurrentState<T>();
var sequence = actionNumber < sequenceLength
? data.GetRange(data.Count - actionNumber, actionNumber)
: data.GetRange(data.Count - sequenceLength - 1, sequenceLength - 1);
var sequenceStates = sequence
.Select(p => p.state)
.ToList();
sequenceStates.Add(currentState);
var action = agent.Predict(sequenceStates, Device);
var reward = Environment.PerformAction(action);
data.Add((rolloutNumber, ++actionNumber, currentState, action, reward));
}
Environment.Reset();
}
var discountedRewards = new T[data.Count];
foreach (var rollout in data.GroupBy(p => p.rollout))
{
var steps = rollout.ToList();
for (int i = 0; i < steps.Count; i++)
{
var remainingRewards = steps.GetRange(i, steps.Count - i)
.Select(p => Environment.HasRewardOnlyForRollout ? steps[steps.Count - 1].reward : p.reward)
.ToArray();
discountedRewards[i] = CalculateDiscountedReward(remainingRewards, gamma);
}
}
var features = new List<IList<T[]>>();
var labels = new List<T[]>();
var dataWithDiscountedReward = data.Zip(discountedRewards, (dat, reward) => (dat, reward)).GroupBy(p => p.dat.rollout);
foreach (var rollout in dataWithDiscountedReward)
{
var steps = rollout.ToList();
steps.Sort((a, b) => a.dat.actionNumber > b.dat.actionNumber ? 1 : a.dat.actionNumber < b.dat.actionNumber ? -1 : 0); //во возрастанию actionNumber
for (int i = 0; i < steps.Count; i++)
{
if (i < sequenceLength)
{
features.Add(steps.GetRange(0, i + 1).Select(p => p.dat.state).ToArray());
}
else
{
features.Add(steps.GetRange(i - sequenceLength, sequenceLength).Select(p => p.dat.state).ToArray());
}
labels.Add(Multiply(steps[i].dat.action, steps[i].reward));
}
}
var fitResult = agent.Fit(features,
labels,
minibatchSize,
GetLoss()[0],
GetEvalLoss()[0],
GetOptimizer()[0],
1,
Device);
data.Clear();
var needStop = actionPerIteration?.Invoke(iteration, fitResult.LossError, fitResult.EvaluationError);
if (needStop.HasValue && needStop.Value)
break;
}
return agent;
}
}
}
|
1094f23ef0493de25a5135cedd0949a1e98748be
|
C#
|
frobro98/School-Projects
|
/Omega Race Multiplayer/OmegaRace_2.0/OmegaRace/OmegaRace/OmegaRace/Manager/Manager.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using SpriteAnimation;
namespace OmegaRace
{
abstract class Manager
{
// public methods: -----------------------------------------------------------------------
protected Manager()
{
this.active = null;
this.reserve = null;
this.initalized = false;
this.totalNum = 0;
this.reserveGrow = 0;
}
// private: (reusable for other classes, just change types0: ------------------------------------
private void privReserveAddToFront(ManLink node, ref ManLink head)
{
Debug.Assert(node != null);
if (head == null)
{
head = node;
node.next = null;
node.prev = null;
}
else
{
node.next = head;
head.prev = node;
head = node;
}
}
private ManLink privReserveGetNodeFromFront(ref ManLink head)
{
Debug.Assert(head != null);
ManLink node = head;
head = node.next;
if (node.next != null)
{
node.next.prev = node.prev;
}
return node;
}
protected void privActiveRemoveNode(ManLink node, ref ManLink head)
{
if (node.prev != null)
{ // middle or last node
node.prev.next = node.next;
}
else
{ // first
head = node.next;
}
if (node.next != null)
{ // middle node
node.next.prev = node.prev;
}
}
protected void privActiveAddToFront(ManLink node, ref ManLink head)
{
Debug.Assert(node != null);
if (head == null)
{
head = node;
node.next = null;
node.prev = null;
}
else
{
node.next = head;
head.prev = node;
head = node;
}
}
// private methods ------------------------------------------------------------------------------
protected object privFind(Enum _enumName)
{
// // Do we need to get more Images?
ManLink pLink = this.active;
while (pLink != null)
{
if (pLink.getName().Equals(_enumName))
{
break;
}
pLink = pLink.next;
}
//return pImage;
return pLink;
}
protected object privGetReserveObject()
{
if (this.reserve == null)
{
// fill pool with more nodes
// OK now preload the timeEvents
this.privFillPool(this.reserveGrow);
}
// make sure we have TimeEvents
Debug.Assert(this.reserve != null);
// Detach 1 Image from the pool
object pObj = (object)this.privReserveGetNodeFromFront(ref this.reserve);
return pObj;
}
protected void privFillPool(int count)
{
// add to the count
this.totalNum += count;
// allocate Objects
for (int i = 0; i < count; i++)
{
// create a new Object
object pObj = privGetNewObj();
// move it to InActive list
privReserveAddToFront((ManLink)pObj, ref this.reserve);
}
}
protected void privCreate(int _numReserve, int _reserveGrow)
{
Debug.WriteLine("{0}:Create(): reserve:{1} delta:{2}", this, _numReserve, _reserveGrow);
// only initialize once
Debug.Assert(this.initalized == false);
// Set variables
this.initalized = true;
this.reserveGrow = _reserveGrow;
// OK now preload Nodes
this.privFillPool(_numReserve);
}
// private: Data --------------------------------------------------------------------------------
abstract protected object privGetNewObj();
// private: links
protected ManLink active;
protected ManLink reserve;
protected bool initalized;
// private: stats -------------------------------------------------------------------------------
protected int totalNum;
protected int reserveGrow;
}
abstract class CopyOfMan
{
// public methods: -----------------------------------------------------------------------
protected CopyOfMan()
{
this.active = null;
this.reserve = null;
this.initalized = false;
this.totalNum = 0;
this.reserveGrow = 0;
}
// private: (reusable for other classes, just change types0: ------------------------------------
private void privReserveAddToFront(ManLink node, ref ManLink head)
{
Debug.Assert(node != null);
if (head == null)
{
head = node;
node.next = null;
node.prev = null;
}
else
{
node.next = head;
head.prev = node;
head = node;
}
}
private ManLink privReserveGetNodeFromFront(ref ManLink head)
{
Debug.Assert(head != null);
ManLink node = head;
head = node.next;
if (node.next != null)
{
node.next.prev = node.prev;
}
return node;
}
protected void privActiveRemoveNode(ManLink node, ref ManLink head)
{
if (node.prev != null)
{ // middle or last node
node.prev.next = node.next;
}
else
{ // first
head = node.next;
}
if (node.next != null)
{ // middle node
node.next.prev = node.prev;
}
}
protected void privActiveAddToFront(ManLink node, ref ManLink head)
{
Debug.Assert(node != null);
if (head == null)
{
head = node;
node.next = null;
node.prev = null;
}
else
{
node.next = head;
head.prev = node;
head = node;
}
}
// private methods ------------------------------------------------------------------------------
protected object privFind(Enum _enumName)
{
// // Do we need to get more Images?
ManLink pLink = this.active;
while (pLink != null)
{
if (pLink.getName().Equals(_enumName))
{
break;
}
pLink = pLink.next;
}
//return pImage;
return pLink;
}
protected object privGetReserveObject()
{
if (this.reserve == null)
{
// fill pool with more nodes
// OK now preload the timeEvents
this.privFillPool(this.reserveGrow);
}
// make sure we have TimeEvents
Debug.Assert(this.reserve != null);
// Detach 1 Image from the pool
object pObj = (object)this.privReserveGetNodeFromFront(ref this.reserve);
return pObj;
}
protected void privFillPool(int count)
{
// add to the count
this.totalNum += count;
// allocate timeEvents
for (int i = 0; i < count; i++)
{
// create a new timeEvent
object pObj = privGetNewObj();
// move it to InActive list
privReserveAddToFront((ManLink)pObj, ref this.reserve);
}
}
protected void privCreate(int _numReserve, int _reserveGrow)
{
Debug.WriteLine("{0}:Create(): reserve:{1} delta:{2}", this, _numReserve, _reserveGrow);
// only initialize once
Debug.Assert(this.initalized == false);
// Set variables
this.initalized = true;
this.reserveGrow = _reserveGrow;
// OK now preload Nodes
this.privFillPool(_numReserve);
}
// private: Data --------------------------------------------------------------------------------
abstract protected object privGetNewObj();
// private: links
protected ManLink active;
protected ManLink reserve;
protected bool initalized;
// private: stats -------------------------------------------------------------------------------
protected int totalNum;
protected int reserveGrow;
}
}
|
689991ded97d911692ddfa97f8f3bdca89a5433f
|
C#
|
schultyy/blackMagic
|
/blackMagic/libMagic/IO/NativeModule.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Jurassic;
using Jurassic.Library;
namespace libMagic.IO
{
public class NativeModuleInstance : ObjectInstance
{
public NativeModuleInstance(ScriptEngine engine)
: base(engine)
{
this.PopulateFunctions();
}
[JSFunction(Name = "readFileSync")]
public string ReadFileSync(string filename)
{
return System.IO.File.ReadAllText(filename);
}
[JSFunction(Name = "writeFileSync")]
public void WriteFileSync(string filename, string content)
{
System.IO.File.WriteAllText(filename, content);
}
[JSFunction(Name = "directoryExists")]
public bool DirectoryExists(string path)
{
return System.IO.Directory.Exists(path);
}
[JSFunction(Name = "fileExists")]
public bool FileExists(string path)
{
return System.IO.File.Exists(path);
}
[JSFunction(Name = "combine")]
public string Combine(ArrayInstance pathParts)
{
var str = pathParts.ElementValues
.Select(c => c.ToString())
.ToArray();
return System.IO.Path.Combine(str);
}
[JSFunction(Name = "createDirectory")]
public void CreateDirectory(string directoryName)
{
System.IO.Directory.CreateDirectory(directoryName);
}
}
}
|
c7c4e8318d3acf0eb98c68c28eea92e373ad42e4
|
C#
|
zidad/dotnet-version
|
/src/dotnet-version/Program.cs
| 2.9375
| 3
|
using System;
using System.IO;
using Microsoft.DotNet.ProjectModel;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace dotnet_version
{
public class Program
{
private static readonly ILogger Logger = new LoggerFactory().AddConsole().CreateLogger<Program>();
public static void Main(string[] args)
{
if (args.Length == 0 || string.Equals(args[0], "-help", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("Usage: dotnet version <VERSION_STRING>");
return;
}
try
{
var projectFilePath =
$"{Directory.GetCurrentDirectory()}{Path.DirectorySeparatorChar}{Project.FileName}";
Logger.LogInformation($"Loading project from {projectFilePath}...");
dynamic projectFile = JsonConvert.DeserializeObject(File.ReadAllText(projectFilePath));
Logger.LogInformation($"Project loaded.");
projectFile.version = args[0];
Logger.LogInformation($"Version set to {args[0]}");
File.WriteAllText(projectFilePath, JsonConvert.SerializeObject(projectFile, Formatting.Indented));
Logger.LogInformation($"Project saved.");
}
catch (FileNotFoundException e)
{
Logger.LogError(new EventId(1, "Project file not found"), e, "The project file was not found. Make sure you are running this command from the project root.");
}
catch (Exception e)
{
Logger.LogError(new EventId(-1, "Unknown Error"), e, "Unexpected exception occurred.");
}
}
}
}
|
f804feb4472b87dd2682dba12d0ad220f8918869
|
C#
|
DomoYao/EnterpriseLibary
|
/Enterprises.Framework.Business/Plugin/Email/SmtpMail.cs
| 2.609375
| 3
|
using System;
using System.Text;
using System.Collections;
using System.Net.Sockets;
namespace Enterprises.Framework.Email
{
#region 邮件发送程序
/// <summary>
/// 邮件发送程序
/// </summary>
[SmtpEmail("邮件发送程序", Version = "2.0", Author = "姚立峰", DllFileName = "Enterprises.Framework.dll")]
public class SmtpMail: ISmtpMail
{
private const string Enter = "\r\n";
/// <summary>
/// 设定语言代码,默认设定为GB2312,如不需要可设置为""
/// </summary>
private string _charset = "GB2312";
/// <summary>
/// 发件人姓名
/// </summary>
private string _fromName = "";
/// <summary>
/// 回复邮件地址
/// </summary>
///public string ReplyTo="";
/// <summary>
/// 收件人姓名
/// </summary>
private string _recipientName = "";
/// <summary>
/// 收件人列表
/// </summary>
private readonly Hashtable _recipient = new Hashtable();
/// <summary>
/// 邮件服务器域名
/// </summary>
private string _mailserver = "";
/// <summary>
/// 邮件服务器端口号
/// </summary>
private int _mailserverport = 25;
/// <summary>
/// SMTP认证时使用的用户名
/// </summary>
private string _username = "";
/// <summary>
/// SMTP认证时使用的密码
/// </summary>
private string _password = "";
/// <summary>
/// 是否需要SMTP验证
/// </summary>
private bool _eSmtp;
/// <summary>
/// 邮件附件列表
/// </summary>
private readonly IList _attachments;
/// <summary>
/// 邮件发送优先级,可设置为"High","Normal","Low"或"1","3","5"
/// </summary>
private string _priority = "Normal";
/// <summary>
/// 密送收件人列表
/// </summary>
///private Hashtable RecipientBCC=new Hashtable();
/// <summary>
/// 收件人数量
/// </summary>
private int _recipientNum;
/// <summary>
/// 最多收件人数量
/// </summary>
private int _recipientmaxnum = 5;
/// <summary>
/// 密件收件人数量
/// </summary>
///private int RecipientBCCNum=0;
/// <summary>
/// 错误消息反馈
/// </summary>
private string _errmsg;
/// <summary>
/// TcpClient对象,用于连接服务器
/// </summary>
private TcpClient _tc;
/// <summary>
/// NetworkStream对象
/// </summary>
private NetworkStream _ns;
/// <summary>
/// 服务器交互记录
/// </summary>
private string _logs = "";
/// <summary>
/// SMTP错误代码哈希表
/// </summary>
private readonly Hashtable _errCodeHt = new Hashtable();
/// <summary>
/// SMTP正确代码哈希表
/// </summary>
private readonly Hashtable _rightCodeHt = new Hashtable();
/// <summary>
/// </summary>
public SmtpMail()
{
From = "";
_attachments = new ArrayList();
SmtpCodeAdd();
}
#region Properties
/// <summary>
/// 邮件主题
/// </summary>
public string Subject { get; set; }
/// <summary>
/// 邮件正文
/// </summary>
public string Body { get; set; }
/// <summary>
/// 发件人地址
/// </summary>
public string From { get; set; }
/// <summary>
/// 设定语言代码,默认设定为GB2312,如不需要可设置为""
/// </summary>
public string Charset
{
get
{
return _charset;
}
set
{
_charset = value;
}
}
/// <summary>
/// 发件人姓名
/// </summary>
public string FromName
{
get
{
return _fromName;
}
set
{
_fromName = value;
}
}
/// <summary>
/// 收件人姓名
/// </summary>
public string RecipientName
{
get
{
return _recipientName;
}
set
{
_recipientName = value;
}
}
/// <summary>
/// 邮件服务器域名和验证信息
/// 形如:"user:pass@www.server.com:25",也可省略次要信息。如"user:pass@www.server.com"或"www.server.com"
/// </summary>
public string MailDomain
{
set
{
string maidomain = value.Trim();
if(maidomain != "")
{
int tempint = maidomain.IndexOf("@", StringComparison.Ordinal);
if(tempint != -1)
{
string str = maidomain.Substring(0,tempint);
MailServerUserName = str.Substring(0,str.IndexOf(":", StringComparison.Ordinal));
MailServerPassWord = str.Substring(str.IndexOf(":", StringComparison.Ordinal) + 1,str.Length - str.IndexOf(":", StringComparison.Ordinal) - 1);
maidomain = maidomain.Substring(tempint + 1,maidomain.Length - tempint - 1);
}
tempint = maidomain.IndexOf(":", StringComparison.Ordinal);
if(tempint != -1)
{
_mailserver = maidomain.Substring(0,tempint);
_mailserverport = Convert.ToInt32(maidomain.Substring(tempint + 1,maidomain.Length - tempint - 1));
}
else
{
_mailserver = maidomain;
}
}
}
}
/// <summary>
/// 邮件服务器端口号
/// </summary>
public int MailDomainPort
{
set
{
_mailserverport = value;
}
}
/// <summary>
/// SMTP认证时使用的用户名
/// </summary>
public string MailServerUserName
{
set
{
if(value.Trim() != "")
{
_username = value.Trim();
_eSmtp = true;
}
else
{
_username = "";
_eSmtp = false;
}
}
}
/// <summary>
/// SMTP认证时使用的密码
/// </summary>
public string MailServerPassWord
{
set
{
_password = value;
}
}
/// <summary>
///
/// </summary>
/// <param name="code"></param>
/// <returns></returns>
public string ErrCodeHtMessage(string code)
{
return _errCodeHt[code].ToString();
}
/// <summary>
/// 邮件发送优先级,可设置为"High","Normal","Low"或"1","3","5"
/// </summary>
public string Priority
{
set
{
switch(value.ToLower())
{
case "high":
_priority = "High";
break;
case "1":
_priority = "High";
break;
case "normal":
_priority = "Normal";
break;
case "3":
_priority = "Normal";
break;
case "low":
_priority = "Low";
break;
case "5":
_priority = "Low";
break;
default:
_priority = "High";
break;
}
}
}
/// <summary>
/// 是否Html邮件
/// </summary>
public bool Html { get; set; }
/// <summary>
/// 错误消息反馈
/// </summary>
public string ErrorMessage
{
get
{
return _errmsg;
}
}
/// <summary>
/// 服务器交互记录
/// </summary>
public string Logs
{
get
{
return _logs;
}
}
/// <summary>
/// 最多收件人数量
/// </summary>
public int RecipientMaxNum
{
set
{
_recipientmaxnum = value;
}
}
#endregion
#region Methods
/// <summary>
/// 添加邮件附件
/// </summary>
/// <param name="filePath">附件绝对路径</param>
public void AddAttachment(params string[] filePath)
{
if(filePath == null)
{
throw(new ArgumentNullException("filePath"));
}
for(int i = 0; i < filePath.Length; i++)
{
_attachments.Add(filePath[i]);
}
}
/// <summary>
/// 添加一组收件人(不超过recipientmaxnum个),参数为字符串数组
/// </summary>
/// <param name="recipients">保存有收件人地址的字符串数组(不超过recipientmaxnum个)</param>
public bool AddRecipient(params string[] recipients)
{
if(_recipient == null)
{
Dispose();
throw(new ArgumentNullException("recipients"));
}
for(int i = 0; i < recipients.Length; i++)
{
string recipient = recipients[i].Trim();
if(recipient == String.Empty)
{
Dispose();
throw new ArgumentNullException("Recipients["+ i +"]");
}
if(recipient.IndexOf("@", StringComparison.Ordinal) == -1)
{
Dispose();
throw new ArgumentException("Recipients.IndexOf(\"@\")==-1","recipients");
}
if(!AddRecipient(recipient))
{
return false;
}
}
return true;
}
/// <summary>
/// 发送邮件方法,所有参数均通过属性设置。
/// </summary>
public bool Send()
{
if(_mailserver.Trim() == "")
{
throw (new ArgumentNullException("_mailserver", "必须指定SMTP服务器"));
}
return SendEmail();
}
/// <summary>
/// 发送邮件方法
/// </summary>
/// <param name="smtpserver">smtp服务器信息,如"username:password@www.smtpserver.com:25",也可去掉部分次要信息,如"www.smtpserver.com"</param>
public bool Send(string smtpserver)
{
MailDomain = smtpserver;
return Send();
}
/// <summary>
/// 发送邮件方法
/// </summary>
/// <param name="smtpserver">smtp服务器信息,如"username:password@www.smtpserver.com:25",也可去掉部分次要信息,如"www.smtpserver.com"</param>
/// <param name="from">发件人mail地址</param>
/// <param name="fromname">发件人姓名</param>
/// <param name="to">收件人地址</param>
/// <param name="toname">收件人姓名</param>
/// <param name="html">是否HTML邮件</param>
/// <param name="subject">邮件主题</param>
/// <param name="body">邮件正文</param>
public bool Send(string smtpserver,string from,string fromname,string to,string toname,bool html,string subject,string body)
{
MailDomain = smtpserver;
From = from;
FromName = fromname;
AddRecipient(to);
RecipientName = toname;
Html = html;
Subject = subject;
Body = body;
return Send();
}
#endregion
#region Private Helper Functions
/// <summary>
/// 添加一个收件人
/// </summary>
/// <param name="recipients">收件人地址</param>
private bool AddRecipient(string recipients)
{
//修改等待邮件验证的用户重复发送的问题
_recipient.Clear();
_recipientNum = 0;
if(_recipientNum<_recipientmaxnum)
{
_recipient.Add(_recipientNum, recipients);
_recipientNum++;
return true;
}
Dispose();
throw(new ArgumentOutOfRangeException("recipients","收件人过多不可多于 "+ _recipientmaxnum +" 个"));
}
void Dispose()
{
if(_ns != null)
_ns.Close();
if(_tc != null)
_tc.Close();
}
/// <summary>
/// SMTP回应代码哈希表
/// </summary>
private void SmtpCodeAdd()
{
_errCodeHt.Add("500","邮箱地址错误");
_errCodeHt.Add("501","参数格式错误");
_errCodeHt.Add("502","命令不可实现");
_errCodeHt.Add("503","服务器需要SMTP验证");
_errCodeHt.Add("504","命令参数不可实现");
_errCodeHt.Add("421","服务未就绪,关闭传输信道");
_errCodeHt.Add("450","要求的邮件操作未完成,邮箱不可用(例如,邮箱忙)");
_errCodeHt.Add("550","要求的邮件操作未完成,邮箱不可用(例如,邮箱未找到,或不可访问)");
_errCodeHt.Add("451","放弃要求的操作;处理过程中出错");
_errCodeHt.Add("551","用户非本地,请尝试<forward-path>");
_errCodeHt.Add("452","系统存储不足, 要求的操作未执行");
_errCodeHt.Add("552","过量的存储分配, 要求的操作未执行");
_errCodeHt.Add("553","邮箱名不可用, 要求的操作未执行(例如邮箱格式错误)");
_errCodeHt.Add("432","需要一个密码转换");
_errCodeHt.Add("534","认证机制过于简单");
_errCodeHt.Add("538","当前请求的认证机制需要加密");
_errCodeHt.Add("454","临时认证失败");
_errCodeHt.Add("530","需要认证");
_rightCodeHt.Add("220","服务就绪");
_rightCodeHt.Add("250","要求的邮件操作完成");
_rightCodeHt.Add("251","用户非本地, 将转发向<forward-path>");
_rightCodeHt.Add("354","开始邮件输入, 以<enter>.<enter>结束");
_rightCodeHt.Add("221","服务关闭传输信道");
_rightCodeHt.Add("334","服务器响应验证Base64字符串");
_rightCodeHt.Add("235","验证成功");
}
/// <summary>
/// 将字符串编码为Base64字符串
/// </summary>
/// <param name="str">要编码的字符串</param>
private string Base64Encode(string str)
{
byte[] barray = Encoding.Default.GetBytes(str);
return Convert.ToBase64String(barray);
}
/// <summary>
/// 将Base64字符串解码为普通字符串
/// </summary>
/// <param name="str">要解码的字符串</param>
private string Base64Decode(string str)
{
byte[] barray = Convert.FromBase64String(str);
return Encoding.Default.GetString(barray);
}
/// <summary>
/// 得到上传附件的文件流
/// </summary>
/// <param name="filePath">附件的绝对路径</param>
private string GetStream(string filePath)
{
//建立文件流对象
var fileStr = new System.IO.FileStream(filePath,System.IO.FileMode.Open);
var by = new byte[Convert.ToInt32(fileStr.Length)];
fileStr.Read(by,0,by.Length);
fileStr.Close();
return(Convert.ToBase64String(by));
}
/// <summary>
/// 发送SMTP命令
/// </summary>
private bool SendCommand(string str)
{
if(str == null || str.Trim() == String.Empty)
{
return true;
}
_logs += str;
byte[] writeBuffer = Encoding.Default.GetBytes(str);
try
{
_ns.Write(writeBuffer,0,writeBuffer.Length);
}
catch
{
_errmsg = "网络连接错误";
return false;
}
return true;
}
/// <summary>
/// 接收SMTP服务器回应
/// </summary>
private string RecvResponse()
{
int streamSize;
string returnValue = String.Empty;
var readBuffer = new byte[1024] ;
try
{
streamSize = _ns.Read(readBuffer,0,readBuffer.Length);
}
catch
{
_errmsg = "网络连接错误";
return "false";
}
if (streamSize == 0)
{
return returnValue ;
}
returnValue = Encoding.Default.GetString(readBuffer).Substring(0,streamSize);
_logs += returnValue + Enter;
return returnValue;
}
/// <summary>
/// 与服务器交互,发送一条命令并接收回应。
/// </summary>
/// <param name="str">一个要发送的命令</param>
/// <param name="errstr">如果错误,要反馈的信息</param>
private bool Dialog(string str,string errstr)
{
if(str == null||str.Trim() == "")
{
return true;
}
if(SendCommand(str))
{
string rr = RecvResponse();
if(rr == "false")
{
return false;
}
string rrCode = rr.Substring(0,3);
if(_rightCodeHt[rrCode] != null)
{
return true;
}
if(_errCodeHt[rrCode] != null)
{
_errmsg += (rrCode+_errCodeHt[rrCode]);
_errmsg += Enter;
}
else
{
_errmsg += rr;
}
_errmsg += errstr;
return false;
}
return false;
}
/// <summary>
/// 与服务器交互,发送一组命令并接收回应。
/// </summary>
private bool Dialog(string[] str,string errstr)
{
for(int i = 0; i < str.Length; i++)
{
if(!Dialog(str[i],""))
{
_errmsg += Enter;
_errmsg += errstr;
return false;
}
}
return true;
}
/// <summary>
/// SendEmail
/// </summary>
/// <returns></returns>
private bool SendEmail()
{
//连接网络
try
{
_tc = new TcpClient(_mailserver,_mailserverport);
}
catch(Exception e)
{
_errmsg = e.ToString();
return false;
}
_ns = _tc.GetStream();
//验证网络连接是否正确
if(_rightCodeHt[RecvResponse().Substring(0,3)] == null)
{
_errmsg = "网络连接失败";
return false;
}
string[] sendBuffer;
string sendBufferstr;
//进行SMTP验证
if(_eSmtp)
{
sendBuffer = new String[4];
sendBuffer[0] = "EHLO " + _mailserver + Enter;
sendBuffer[1] = "AUTH LOGIN" + Enter;
sendBuffer[2] = Base64Encode(_username) + Enter;
sendBuffer[3] = Base64Encode(_password) + Enter;
if(!Dialog(sendBuffer,"SMTP服务器验证失败,请核对用户名和密码。"))
return false;
}
else
{
sendBufferstr = "HELO " + _mailserver + Enter;
if(!Dialog(sendBufferstr,""))
return false;
}
//
sendBufferstr = "MAIL FROM:<" + From + ">" + Enter;
if(!Dialog(sendBufferstr,"发件人地址错误,或不能为空"))
return false;
//
sendBuffer = new string[_recipientmaxnum];
for(int i = 0; i < _recipient.Count; i++)
{
sendBuffer[i] = "RCPT TO:<" + _recipient[i] + ">" + Enter;
}
if(!Dialog(sendBuffer,"收件人地址有误"))
return false;
/*
SendBuffer=new string[10];
for(int i=0;i<RecipientBCC.Count;i++)
{
SendBuffer[i]="RCPT TO:<" + RecipientBCC[i].ToString() +">" + enter;
}
if(!Dialog(SendBuffer,"密件收件人地址有误"))
return false;
*/
sendBufferstr = "DATA" + Enter;
if(!Dialog(sendBufferstr,""))
return false;
sendBufferstr = "From:" + FromName + "<" + From + ">" +Enter;
//if(ReplyTo.Trim()!="")
//{
// SendBufferstr+="Reply-To: " + ReplyTo + enter;
//}
//SendBufferstr += "To:" + (Discuz.Common.Utils.StrIsNullOrEmpty(RecipientName)?"":Base64Encode(RecipientName)) + "<" + Recipient[0] + ">" + enter;
sendBufferstr += "To:=?" + Charset.ToUpper() + "?B?" + (string.IsNullOrEmpty(RecipientName) ? "" : Base64Encode(RecipientName)) + "?=" + "<" + _recipient[0] + ">" + Enter;
//注释掉抄送代码
sendBufferstr += "CC:";
for (int i = 1; i < _recipient.Count; i++)
{
sendBufferstr += _recipient[i] + "<" + _recipient[i] + ">,";
}
sendBufferstr += Enter;
sendBufferstr += (string.IsNullOrEmpty(Subject)?"Subject:":((Charset=="")?("Subject:" + Subject):("Subject:" + "=?" + Charset.ToUpper() + "?B?" + Base64Encode(Subject) +"?="))) + Enter;
sendBufferstr += "X-Priority:" + _priority + Enter;
sendBufferstr += "X-MSMail-Priority:" + _priority + Enter;
sendBufferstr += "Importance:" + _priority + Enter;
sendBufferstr += "X-Mailer: Lion.Web.Mail.SmtpMail Pubclass [cn]" + Enter;
sendBufferstr += "MIME-Version: 1.0" + Enter;
if(_attachments.Count != 0)
{
sendBufferstr += "Content-Type: multipart/mixed;" + Enter;
sendBufferstr += " boundary=\"=====" + (Html?"001_Dragon520636771063_":"001_Dragon303406132050_") + "=====\"" + Enter + Enter;
}
if(Html)
{
if(_attachments.Count == 0)
{
sendBufferstr += "Content-Type: multipart/alternative;" + Enter;//内容格式和分隔符
sendBufferstr += " boundary=\"=====003_Dragon520636771063_=====\"" + Enter + Enter;
sendBufferstr += "This is a multi-part message in MIME format." + Enter + Enter;
}
else
{
sendBufferstr += "This is a multi-part message in MIME format." + Enter + Enter;
sendBufferstr += "--=====001_Dragon520636771063_=====" + Enter;
sendBufferstr += "Content-Type: multipart/alternative;" + Enter;//内容格式和分隔符
sendBufferstr += " boundary=\"=====003_Dragon520636771063_=====\"" + Enter + Enter;
}
sendBufferstr += "--=====003_Dragon520636771063_=====" + Enter;
sendBufferstr += "Content-Type: text/plain;" + Enter;
sendBufferstr += ((Charset=="")?(" charset=\"iso-8859-1\""):(" charset=\"" + Charset.ToLower() + "\"")) + Enter;
sendBufferstr += "Content-Transfer-Encoding: base64" + Enter + Enter;
sendBufferstr += Base64Encode("邮件内容为HTML格式,请选择HTML方式查看") + Enter + Enter;
sendBufferstr += "--=====003_Dragon520636771063_=====" + Enter;
sendBufferstr += "Content-Type: text/html;" + Enter;
sendBufferstr += ((Charset=="")?(" charset=\"iso-8859-1\""):(" charset=\"" + Charset.ToLower() + "\"")) + Enter;
sendBufferstr += "Content-Transfer-Encoding: base64" + Enter + Enter;
sendBufferstr += Base64Encode(Body) + Enter + Enter;
sendBufferstr += "--=====003_Dragon520636771063_=====--" + Enter;
}
else
{
if(_attachments.Count!=0)
{
sendBufferstr += "--=====001_Dragon303406132050_=====" + Enter;
}
sendBufferstr += "Content-Type: text/plain;" + Enter;
sendBufferstr += ((Charset=="")?(" charset=\"iso-8859-1\""):(" charset=\"" + Charset.ToLower() + "\"")) + Enter;
sendBufferstr += "Content-Transfer-Encoding: base64" + Enter + Enter;
sendBufferstr += Base64Encode(Body) + Enter;
}
//SendBufferstr += "Content-Transfer-Encoding: base64"+enter;
if(_attachments.Count != 0)
{
for(int i = 0; i < _attachments.Count; i++)
{
var filepath = (string)_attachments[i];
sendBufferstr += "--=====" + (Html?"001_Dragon520636771063_":"001_Dragon303406132050_") + "=====" + Enter;
//SendBufferstr += "Content-Type: application/octet-stream"+enter;
sendBufferstr += "Content-Type: text/plain;" + Enter;
sendBufferstr += " name=\"=?" + Charset.ToUpper() + "?B?" + Base64Encode(filepath.Substring(filepath.LastIndexOf("\\", StringComparison.Ordinal)+1)) + "?=\"" + Enter;
sendBufferstr += "Content-Transfer-Encoding: base64" + Enter;
sendBufferstr += "Content-Disposition: attachment;" + Enter;
sendBufferstr += " filename=\"=?" + Charset.ToUpper() + "?B?" + Base64Encode(filepath.Substring(filepath.LastIndexOf("\\", StringComparison.Ordinal)+1)) + "?=\"" + Enter + Enter;
sendBufferstr += GetStream(filepath) + Enter + Enter;
}
sendBufferstr += "--=====" + (Html?"001_Dragon520636771063_":"001_Dragon303406132050_") + "=====--" + Enter + Enter;
}
sendBufferstr += Enter + "." + Enter;
if(!Dialog(sendBufferstr,"错误信件信息"))
return false;
sendBufferstr = "QUIT" + Enter;
if(!Dialog(sendBufferstr,"断开连接时错误"))
return false;
_ns.Close();
_tc.Close();
return true;
}
#endregion
#region
/*
/// <summary>
/// 添加一个密件收件人
/// </summary>
/// <param name="str">收件人地址</param>
public bool AddRecipientBCC(string str)
{
if(str==null||str.Trim()=="")
return true;
if(RecipientBCCNum<10)
{
RecipientBCC.Add(RecipientBCCNum,str);
RecipientBCCNum++;
return true;
}
else
{
errmsg+="收件人过多";
return false;
}
}
/// <summary>
/// 添加一组密件收件人(不超过10个),参数为字符串数组
/// </summary>
/// <param name="str">保存有收件人地址的字符串数组(不超过10个)</param>
public bool AddRecipientBCC(string[] str)
{
for(int i=0;i<str.Length;i++)
{
if(!AddRecipientBCC(str[i]))
{
return false;
}
}
return true;
}
*/
#endregion
}
#endregion
}
|
22e93b2b219ab63a6715edba58a247c4d49ad654
|
C#
|
coderudit/GreedyMethod
|
/GreedyMethod/_3_ActivitySelectionProblem.cs
| 3.640625
| 4
|
using System;
using System.Diagnostics.CodeAnalysis;
namespace GreedyMethod
{
class _3_ActivitySelectionProblem
{
public void SelectActivity(int[] start, int[] end, int n)
{
var activities = new Activity[n];
for (int index = 0; index < n; index++)
{
activities[index] = new Activity(start[index], end[index]);
}
Array.Sort(activities);
int prevEndTime = activities[0].EndTime;
int count = 1;
for (int index = 1; index < n; index++)
{
var activity = activities[index];
if (activity.StartTime >= prevEndTime)
{
count++;
prevEndTime = activity.EndTime;
}
}
}
}
struct Activity : IComparable<Activity>
{
public int StartTime { get; set; }
public int EndTime { get; set; }
public Activity(int startTime, int endTime)
{
StartTime = startTime;
EndTime = endTime;
}
public int CompareTo([AllowNull] Activity other)
{
if (this.EndTime < other.EndTime)
return -1;
else if (this.EndTime > other.EndTime)
return 1;
else
return 0;
}
}
}
|
bd36524a66eeddb280846eb540c5436c3b14b2d1
|
C#
|
MarktW86/dotnet.docs
|
/samples/snippets/csharp/VS_Snippets_Remoting/System.Net.Dns/CS/dnsnewmethods.cs
| 3.421875
| 3
|
using System;
using System.Net;
using System.Threading;
namespace DNSChanges
{
class DNS
{
//<Snippet1>
public static void DoGetHostEntry(string hostname)
{
IPHostEntry host;
host = Dns.GetHostEntry(hostname);
Console.WriteLine("GetHostEntry({0}) returns:", hostname);
foreach (IPAddress ip in host.AddressList)
{
Console.WriteLine(" {0}", ip);
}
}
//</Snippet1>
//<Snippet3>
public static void DoGetHostAddresses(string hostname)
{
IPAddress[] ips;
ips = Dns.GetHostAddresses(hostname);
Console.WriteLine("GetHostAddresses({0}) returns:", hostname);
foreach (IPAddress ip in ips)
{
Console.WriteLine(" {0}", ip);
}
}
//</Snippet3>
//<Snippet2>
// Signals when the resolve has finished.
public static ManualResetEvent GetHostEntryFinished =
new ManualResetEvent(false);
// Define the state object for the callback.
// Use hostName to correlate calls with the proper result.
public class ResolveState
{
string hostName;
IPHostEntry resolvedIPs;
public ResolveState(string host)
{
hostName = host;
}
public IPHostEntry IPs
{
get { return resolvedIPs; }
set {resolvedIPs = value;}}
public string host {get {return hostName;}
set {hostName = value;}}
}
// Record the IPs in the state object for later use.
public static void GetHostEntryCallback(IAsyncResult ar)
{
ResolveState ioContext = (ResolveState)ar.AsyncState;
ioContext.IPs = Dns.EndGetHostEntry(ar);
GetHostEntryFinished.Set();
}
// Determine the Internet Protocol (IP) addresses for
// this host asynchronously.
public static void DoGetHostEntryAsync(string hostname)
{
GetHostEntryFinished.Reset();
ResolveState ioContext= new ResolveState(hostname);
Dns.BeginGetHostEntry(ioContext.host,
new AsyncCallback(GetHostEntryCallback), ioContext);
// Wait here until the resolve completes (the callback
// calls .Set())
GetHostEntryFinished.WaitOne();
Console.WriteLine("EndGetHostEntry({0}) returns:", ioContext.host);
foreach (IPAddress ip in ioContext.IPs.AddressList)
{
Console.WriteLine(" {0}", ip);
}
}
//</Snippet2>
[STAThread]
static void Main(string[] args)
{
DoGetHostEntry("www.contoso.com");
DoGetHostAddresses("www.contoso.com");
DoGetHostEntryAsync("www.contoso.com");
}
}
}
|
248e86959465a5bd38d6544d64cbddad152b2631
|
C#
|
Agilefreaks/WinOmni
|
/Code/Omnipaste/Framework/Helpers/TextParser.cs
| 3
| 3
|
namespace Omnipaste.Framework.Helpers
{
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class TextParser
{
private List<Tuple<TextPartTypeEnum, string>> _result;
public List<Tuple<TextPartTypeEnum, string>> Parse(string text)
{
_result = new List<Tuple<TextPartTypeEnum, string>>();
int previousPlainTextPartStartIndex;
int previousPlainTextPartEndIndex;
var regularExpression =
new Regex(
@"((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)",
RegexOptions.IgnoreCase);
var matches = regularExpression.Matches(text);
for (var index = 0; index < matches.Count; index++)
{
var match = matches[index];
previousPlainTextPartStartIndex = index > 0 ? matches[index - 1].Index + matches[index - 1].Length : 0;
previousPlainTextPartEndIndex = match.Index;
AddPlainTextPart(text, previousPlainTextPartStartIndex, previousPlainTextPartEndIndex);
_result.Add(new Tuple<TextPartTypeEnum, string>(TextPartTypeEnum.Hyperlink, match.Captures[0].Value));
}
previousPlainTextPartStartIndex = matches.Count > 0
? matches[matches.Count - 1].Index + matches[matches.Count - 1].Length
: 0;
previousPlainTextPartEndIndex = text.Length;
AddPlainTextPart(text, previousPlainTextPartStartIndex, previousPlainTextPartEndIndex);
return _result;
}
private void AddPlainTextPart(string text, int startIndex, int endIndex)
{
var previousTextPart = text.Substring(startIndex, endIndex - startIndex);
if (!string.IsNullOrWhiteSpace(previousTextPart))
{
_result.Add(new Tuple<TextPartTypeEnum, string>(TextPartTypeEnum.PlainText, previousTextPart));
}
}
}
}
|
75c1f50e30cb46302b38936201084a74141ef1aa
|
C#
|
curiouslearning/Norad-Eduapp4syria
|
/Antura/EA4S_Antura_U3D/Assets/_games/_common/_scripts/_mustbeimplementedbyhub/SampleQuestionPack.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
namespace EA4S
{
class SampleQuestionPack : IQuestionPack
{
ILivingLetterData questionSentence;
IEnumerable<ILivingLetterData> wrongAnswersSentence;
IEnumerable<ILivingLetterData> correctAnswersSentence;
public SampleQuestionPack(ILivingLetterData questionSentence, IEnumerable<ILivingLetterData> wrongAnswersSentence, IEnumerable<ILivingLetterData> correctAnswersSentence)
{
this.questionSentence = questionSentence;
this.wrongAnswersSentence = wrongAnswersSentence;
this.correctAnswersSentence = correctAnswersSentence;
}
ILivingLetterData IQuestionPack.GetQuestion()
{
return questionSentence;
}
IEnumerable<ILivingLetterData> IQuestionPack.GetWrongAnswers()
{
return wrongAnswersSentence;
}
public IEnumerable<ILivingLetterData> GetCorrectAnswers()
{
return correctAnswersSentence;
}
public IEnumerable<ILivingLetterData> GetQuestions() {
throw new Exception("This provider can not use this method");
}
}
}
|
eb5c6a6d9530968b2af390ac12b2d53e7ec0396d
|
C#
|
IVSoftware/wpf-window-ex
|
/wpf-window-ex/Console.cs
| 3.046875
| 3
|
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Input;
namespace IVSoftware
{
public class Console : TextBox, IConsole
{
public void ReadKey()
{
_waiting = true;
AppendText("Press any key to continue..." + Environment.NewLine);
while (_waiting)
{
Thread.Sleep(0); // Pump Message Queue
Task.Delay(100).Wait();
}
AppendText("Execution has resumed.");
}
public void WriteLine(string text = "")
{
AppendText(text + Environment.NewLine);
}
public void Write(string text = "")
{
AppendText(text);
}
protected override void OnKeyDown(
KeyEventArgs e
)
{
if (_waiting) _waiting = false;
}
bool _waiting = false;
}
public interface IConsole
{
void Write(string text = "");
void WriteLine(string text = "");
void ReadKey();
}
}
|
569cb1f93c31d5063bf5a96d80ce992cfaa829ef
|
C#
|
MyLab-InventoryManagementTool/MyLab-Backend
|
/myLabDockerAPI/Models/Relation_Category_ItemAttribute.cs
| 2.5625
| 3
|
using System.ComponentModel.DataAnnotations;
namespace myLabDockerAPI.Models
{
/// <summary>
/// Datatable for m : n Relation between Category and Item Attribute.
/// </summary>
public class Relation_Category_ItemAttribute
{
/// <summary>
///
/// </summary>
[Key]
public long Id { get; set; }
/// <summary>
///
/// </summary>
public Category Category { get; set; }
/// <summary>
///
/// </summary>
public ItemAttribute ItemAttribute { get; set; }
}
}
|
73d56c69d53430e6b78864f73c27ef338a8d8bc4
|
C#
|
Pavel-Durov/Design-Patterns
|
/BehavioralDesignPatterns/State/States/HasCardState.cs
| 2.984375
| 3
|
using BehavioralDesignPatterns.State.States.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BehavioralDesignPatterns.State.Model;
namespace BehavioralDesignPatterns.State.States
{
class HasCardState : AtmMachineState
{
public HasCardState(AtmMachine context) : base(context)
{
}
public override void EjectCard()
{
Console.WriteLine("Ejecting Card");
_context.SetState(new NoCardState(_context));
}
public override void EnterPinCode(int pinCode)
{
if (pinCode == 123)
{
Console.WriteLine("Correct PIN");
_context.SetState(new HasPinState(_context));
}
else
{
Console.WriteLine("Wrong pin - try again");
}
}
public override void InsertCard()
{
Console.WriteLine("Cannot accept multiple cards at the same time..");
}
public override void RequestCash(int amount)
{
Console.WriteLine("Please enter PIN first");
}
}
}
|
b867060fa6cfefe26ea475725e46155736892954
|
C#
|
Raikiri62/projects-assignments
|
/Dot Net OOP course assigments/EX3/C19_Ex03/TheReferredVehicleByLicenseNumberIsNotElectricException.cs
| 2.71875
| 3
|
namespace C19_Ex03_GarageLogic
{
using System;
internal class TheReferredVehicleByLicenseNumberIsNotElectricException : ArgumentException
{
internal TheReferredVehicleByLicenseNumberIsNotElectricException(string i_NumberOfLicense, string i_NameOfArgument)
: base("The referred vehicle by license number " + i_NumberOfLicense + " is not electric.", i_NameOfArgument)
{
}
}
}
|
3486ebb8769bfaf9097336c1a04b41928d20b8c6
|
C#
|
alienown/Left4Dead
|
/src/Left4Dead/Difficulty/HardDifficulty.cs
| 2.6875
| 3
|
namespace Left4Dead
{
public class HardDifficulty : IDifficulty
{
public void PlanNextSpawn(ZombieMaker z)
{
int interval;
double scorePerMinute = (z.PlayerScore * 60) / z.GameTime;
if (z.ZombieCount < 10)
{
if (scorePerMinute <= 20)
{
z.WhichZombie = "NormalZombie";
}
else if (scorePerMinute <= GameData.GenerateRandomNumber(0, z.PlayerHealth))
{
z.WhichZombie = "TankZombie";
}
else
{
z.WhichZombie = "HunterZombie";
}
interval = (GameData.GenerateRandomNumber(1000, 2501) - z.PlayerScore * 10);
if (interval < 0)
{
z.SleepInterval = 0;
}
else
{
z.SleepInterval = interval;
}
}
else
{
z.SleepInterval = 0;
z.WhichZombie = "None";
}
}
public override string ToString()
{
return "Hard";
}
}
}
|
7ca462f2e0532abb46de88cf0d9e6e1141809870
|
C#
|
RauhoferE/SnakeInSignalR
|
/Snake_V_0_3/EventArgs/DirectionEventArgs.cs
| 2.828125
| 3
|
//-----------------------------------------------------------------------
// <copyright file="DirectionEventArgs.cs" company="FH Wiener Neustadt">
// Copyright (c) Emre Rauhofer. All rights reserved.
// </copyright>
// <author>Emre Rauhofer</author>
// <summary>
// This is a network library.
// </summary>
//-----------------------------------------------------------------------
namespace Snake_V_0_3
{
using System;
/// <summary>
/// The <see cref="DirectionEventArgs"/> class.
/// </summary>
public class DirectionEventArgs : EventArgs
{
/// <summary>
/// Initializes a new instance of the <see cref="DirectionEventArgs"/> class.
/// </summary>
/// <param name="e"> The current <see cref="IDirection"/>. </param>
public DirectionEventArgs(IDirection e)
{
this.Direction = e;
}
/// <summary>
/// Gets the new direction.
/// </summary>
/// <value> A normal <see cref="IDirection"/> object. </value>
public IDirection Direction
{
get;
}
}
}
|
9e5070e46851de61792b9df08a2fdd98850bb8d3
|
C#
|
minhchauss/cmchau_mf863
|
/MISA.Application.Core/Enum/MISAEnum.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MISA.CukCuk.Core.Enum
{
/// <summary>
/// Trạng thái của object
/// </summary>
/// Created by CMChau 22/05/2021
public enum EntityState
{
/// <summary>
/// Lấy dữ liệu
/// </summary>
GET,
/// <summary>
/// Thêm mới dữ liệu
/// </summary>
INSERT,
/// <summary>
/// Sửa dữ liệu
/// </summary>
UPDATE,
/// <summary>
/// Xóa dữ liệu
/// </summary>
DELETE
}
/// <summary>
/// Giới tính
/// </summary>
/// Created by CMChau 22/05/2021
public enum Gender
{
/// <summary>
/// Nam
/// </summary>
Male =0,
/// <summary>
/// Nữ
/// </summary>
Female = 1,
/// <summary>
/// Khác
/// </summary>
Other = 2
}
}
|
a122dcb8dab36325c3e8fa83ae00153e65637d5e
|
C#
|
akangbang/SymbioticSurvival---CutieHack2021
|
/betterTogether-v.0.1/betterTogether-v.0.1/betterTogether/Assets/Scripts/Boundary.cs
| 2.703125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Boundary : MonoBehaviour
{
private float minX, maxX, minY, maxY;
void Start()
{
float camDistance = Vector3.Distance(transform.position, Camera.main.transform.position);
Vector2 bottomCorner = Camera.main.ViewportToWorldPoint(new Vector3(0,0, camDistance));
Vector2 topCorner = Camera.main.ViewportToWorldPoint(new Vector3(1,1, camDistance));
minX = bottomCorner.x;
maxX = topCorner.x;
minY = bottomCorner.y;
maxY = topCorner.y;
}
void Update()
{
// Get current position
Vector3 pos = transform.position;
if(pos.x < minX) pos.x = minX;
if(pos.x > maxX) pos.x = maxX;
if(pos.y < minY) pos.y = minY;
if(pos.y > maxY) pos.y = maxY;
transform.position = pos;
}
}
|
693b3913cc05ca1f880c90c1988b361378693390
|
C#
|
cristhyanc/DemoTodoList
|
/src/DemoTodoList.Entities/TodoItemEntity.cs
| 2.859375
| 3
|
using SQLite;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace DemoTodoList.Entities
{
public class TodoItemEntity
{
[PrimaryKey]
public Guid TodoId { get; set; }
public Guid ListId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public bool IsCompleted { get; set; }
public async Task<bool> Save(IRepository<TodoItemEntity> repository)
{
if (repository == null)
{
throw new ArgumentNullException(nameof(repository));
}
if (string.IsNullOrWhiteSpace(this.Title))
{
throw new ArgumentException("The Todo Title is required");
}
if (string.IsNullOrWhiteSpace(this.Description ))
{
throw new ArgumentException("The Todo description is required");
}
if (TodoId == Guid.Empty)
{
this.TodoId = Guid.NewGuid();
return await repository.Insert(this);
}
else
{
return await repository.Update(this);
}
}
}
}
|
158c114ee5b58f22e1955f28fc275cc50b4aad7c
|
C#
|
JustD4nTe/AoC2020
|
/Day6/PartTwo.cs
| 3.21875
| 3
|
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace AoC2020.Day6
{
public static class PartTwo
{
public static int Solve()
{
using var sr = new StreamReader("Day6/data.txt");
var answers = sr.ReadToEnd().Split("\r\n");
var sum = 0;
var singleAnswers = new Dictionary<char, int>();
var numberOfAnswers = 0;
foreach (var groupAnswers in answers)
{
if (string.IsNullOrWhiteSpace(groupAnswers))
{
sum += singleAnswers.Count(d => d.Value == numberOfAnswers);
numberOfAnswers = 0;
singleAnswers.Clear();
}
else
{
foreach (var answer in groupAnswers)
{
if (singleAnswers.ContainsKey(answer))
{
singleAnswers[answer]++;
}
else
{
singleAnswers[answer] = 1;
}
}
numberOfAnswers++;
}
}
sum += singleAnswers.Count(d => d.Value == numberOfAnswers);
return sum;
}
}
}
|
b08fd2a3a290897b9b8fef4efdc2c7addf7aef29
|
C#
|
shendongnian/download4
|
/latest_version_download2/210296-44946898-150965116-2.cs
| 2.953125
| 3
|
private void LV1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selected = (sender as ListView).SelectedItem as string;
int index = -1;
for (int i = 0; i < LV2.Items.Count(); i++)
{
if (LV2.Items[i] as string == selected){
index = i;
break;
}
}
// The if becomes obsolete here, it could be replaced by
// if(index >= 0)
if (LV2.Items.ToList().Contains(selected))
{
LV2.SelectedIndex = index;
}
}
|
dccf1a4880970042fd1e00ece91157a186b8eca8
|
C#
|
Goolyio/auth0.net
|
/src/Auth0.AuthenticationApi/Models/RefreshTokenRequest.cs
| 2.71875
| 3
|
namespace Auth0.AuthenticationApi.Models
{
/// <summary>
/// Represents a request to get new tokens based on a previously obtained refresh token.
/// </summary>
public class RefreshTokenRequest
{
/// <summary>
/// Optional audience used for refreshing the access token token.
/// </summary>
public string Audience { get; set; }
/// <summary>
/// A valid refresh token previously issued to the client.
/// </summary>
public string RefreshToken { get; set; }
/// <summary>
/// Optional scope for the access request.
/// </summary>
/// <remarks>
/// The requested scope must not include any scope not originally granted
/// by the resource owner, and if omitted is treated as equal to the scope
/// originally granted by the resource owner.
/// </remarks>
public string Scope { get; set; }
/// <summary>
/// Client ID for which the refresh token was issued.
/// </summary>
public string ClientId { get; set; }
/// <summary>
/// Client secret for which the refresh token was issued.
/// </summary>
public string ClientSecret { get; set; }
/// <summary>
/// What <see cref="JwtSignatureAlgorithm"/> is used to verify the signature
/// of Id Tokens.
/// </summary>
public JwtSignatureAlgorithm SigningAlgorithm { get; set; }
/// <summary>
/// Organization for Id Token verification.
/// </summary>
public string Organization { get; set; }
}
}
|
c3f35a92b9bfe6bc3d7c768969c2884e566e9e08
|
C#
|
bwhoffmann/Stealth
|
/Stealth/Assets/Scripts/Player.cs
| 2.625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
private Transform tf;
public float turnSpeed = 110f; //sets base turn speed, can be changed
public float moveSpeed = 5f; //sets base move speed, can be changed
// Start is called before the first frame update
void Start()
{
GameManager.Instance.player = this.gameObject;
tf = gameObject.GetComponent<Transform>();
}
// Update is called once per frame
void Update()
{
HandleRotation();
if (Input.GetKey(KeyCode.UpArrow))
{
tf.Translate(Vector3.right * moveSpeed * Time.deltaTime, Space.Self); //Moves player forward in the direction faced
}
else if (Input.GetKey(KeyCode.DownArrow))
{
tf.Translate(Vector3.left * moveSpeed * Time.deltaTime / 2, Space.Self); //Moves player forward in the direction faced
}
}
public void HandleRotation()
{
if (Input.GetKey(KeyCode.LeftArrow))
{
tf.Rotate(0, 0, turnSpeed * Time.deltaTime); //Rotates player left when pressing left arrow
}
if (Input.GetKey(KeyCode.RightArrow))
{
tf.Rotate(0, 0, -turnSpeed * Time.deltaTime); //Rotates player right when pressing right arrow
}
}
}
|
e21cc209051fc514ce844a1d12a3b662180e67db
|
C#
|
gyx9208/sweep
|
/sweep/SweepLogic/SweepCommon.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace sweep.SweepLogic
{
public class SweepCommon
{
public static object SyncObj = new object();
private static IDictionary<string, SweepState> ProcessStatus { get; set; }
public SweepCommon()
{
if (ProcessStatus == null)
{
ProcessStatus = new Dictionary<string, SweepState>();
}
}
public void AddStatus(string id,SweepState ss)
{
lock (SyncObj)
{
ProcessStatus.Add(id, ss);
}
}
public void RemoveStatus(string id)
{
lock (SyncObj)
{
ProcessStatus.Remove(id);
}
}
public SweepState GetStatus(string id)
{
lock (SyncObj)
{
if (ProcessStatus.Keys.Count(p => p == id) == 1)
{
return ProcessStatus[id];
}
return null;
}
}
}
}
|
24ba94afb2ceddaf0d9763e9629d589d974a2d70
|
C#
|
FabioZumbi12/drywetmidi
|
/DryWetMidi.Tests/Smf.Interaction/ChordsManager/ChordTests.cs
| 2.65625
| 3
|
using Melanchall.DryWetMidi.Common;
using Melanchall.DryWetMidi.Smf;
using Melanchall.DryWetMidi.Smf.Interaction;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace Melanchall.DryWetMidi.Tests.Smf.Interaction
{
[TestClass]
public class ChordTests
{
#region Nested classes
public abstract class NotesPropertyTester<TValue>
{
#region Fields
private readonly Expression<Func<Chord, TValue>> _chordPropertySelector;
private readonly Expression<Func<Note, TValue>> _notePropertySelector;
private readonly TValue _value1;
private readonly TValue _value2;
private readonly TValue _value;
#endregion
#region Constructor
public NotesPropertyTester(Expression<Func<Chord, TValue>> chordPropertySelector,
Expression<Func<Note, TValue>> notePropertySelector,
TValue value1,
TValue value2,
TValue value)
{
_chordPropertySelector = chordPropertySelector;
_notePropertySelector = notePropertySelector;
_value1 = value1;
_value2 = value2;
_value = value;
}
#endregion
#region Test methods
[TestMethod]
[Description("Get property value of a chord without notes.")]
public void Get_NoNotes()
{
var chord = new Chord();
Assert.ThrowsException<InvalidOperationException>(() => GetPropertyValue(_chordPropertySelector, chord));
}
[TestMethod]
[Description("Get property value of a chord containing notes with the same value of the specified property.")]
public void Get_SameValues()
{
var chord = GetChord(_notePropertySelector, _value1, _value1);
Assert.AreEqual(_value1, GetPropertyValue(_chordPropertySelector, chord));
}
[TestMethod]
[Description("Get property value of a chord containing notes with different values of the specified property.")]
public void Get_DifferentValues()
{
var chord = GetChord(_notePropertySelector, _value1, _value2);
Assert.ThrowsException<InvalidOperationException>(() => GetPropertyValue(_chordPropertySelector, chord));
}
[TestMethod]
[Description("Set a chord's property value.")]
public void Set()
{
var chord = GetChord(_notePropertySelector, _value1, _value2);
SetPropertyValue(_chordPropertySelector, chord, _value);
Assert.AreEqual(_value, GetPropertyValue(_chordPropertySelector, chord));
}
#endregion
#region Private methods
private static Chord GetChord(Expression<Func<Note, TValue>> notePropertySelector, TValue value1, TValue value2)
{
var firstNote = new Note(NoteName.A, 1);
SetPropertyValue(notePropertySelector, firstNote, value1);
var secondNote = new Note(NoteName.B, 1);
SetPropertyValue(notePropertySelector, secondNote, value2);
return new Chord(firstNote, secondNote);
}
private static TValue GetPropertyValue<TObj>(Expression<Func<TObj, TValue>> propertySelector, TObj obj)
{
var propertyInfo = GetPropertyInfo(propertySelector);
try
{
return (TValue)propertyInfo?.GetValue(obj);
}
catch (TargetInvocationException ex)
{
throw ex.InnerException;
}
}
private static void SetPropertyValue<TObj>(Expression<Func<TObj, TValue>> propertySelector, TObj obj, TValue value)
{
var propertyInfo = GetPropertyInfo(propertySelector);
try
{
propertyInfo?.SetValue(obj, value);
}
catch (TargetInvocationException ex)
{
throw ex.InnerException;
}
}
private static PropertyInfo GetPropertyInfo<TObj>(Expression<Func<TObj, TValue>> propertySelector)
{
var propertySelectorExpression = propertySelector.Body as MemberExpression;
if (propertySelectorExpression == null)
return null;
return propertySelectorExpression.Member as PropertyInfo;
}
#endregion
}
[TestClass]
public sealed class ChannelTester : NotesPropertyTester<FourBitNumber>
{
public ChannelTester()
: base(c => c.Channel,
n => n.Channel,
FourBitNumber.MaxValue,
FourBitNumber.MinValue,
(FourBitNumber)5)
{
}
}
[TestClass]
public sealed class VelocityTester : NotesPropertyTester<SevenBitNumber>
{
public VelocityTester()
: base(c => c.Velocity,
n => n.Velocity,
SevenBitNumber.MaxValue,
SevenBitNumber.MinValue,
(SevenBitNumber)5)
{
}
}
[TestClass]
public sealed class OffVelocityTester : NotesPropertyTester<SevenBitNumber>
{
public OffVelocityTester()
: base(c => c.OffVelocity,
n => n.OffVelocity,
SevenBitNumber.MaxValue,
SevenBitNumber.MinValue,
(SevenBitNumber)5)
{
}
}
#endregion
#region Test methods
[TestMethod]
[Description("Get length of Chord without notes.")]
public void Length_Get_NoNotes()
{
Assert.AreEqual(0, GetChord_NoNotes().Length);
}
[TestMethod]
[Description("Get length of Chord with time of zero.")]
public void Length_Get_ZeroTime()
{
Assert.AreEqual(200, GetChord_ZeroTime().Length);
}
[TestMethod]
[Description("Get length of Chord with time of nonzero number.")]
public void Length_Get_NonzeroTime()
{
Assert.AreEqual(200, GetChord_NonzeroTime().Length);
}
[TestMethod]
[Description("Set length of Chord without notes.")]
public void Length_Set_NoNotes()
{
var chord = GetChord_NoNotes();
chord.Length = 100;
Assert.AreEqual(0, chord.Length);
}
[TestMethod]
[Description("Set length of Chord with time of zero.")]
public void Length_Set_ZeroTime()
{
var chord = GetChord_ZeroTime();
chord.Length = 500;
Assert.AreEqual(500, chord.Length);
}
[TestMethod]
[Description("Set length of Chord with time of nonzero number.")]
public void Length_Set_NonzeroTime()
{
var chord = GetChord_NonzeroTime();
chord.Length = 500;
Assert.AreEqual(500, chord.Length);
}
#endregion
#region Private methods
private static Chord GetChord_NoNotes()
{
return new Chord();
}
private static Chord GetChord_ZeroTime()
{
return new Chord(new Note(SevenBitNumber.MaxValue, 100),
new Note(SevenBitNumber.MaxValue, 100, 50),
new Note(SevenBitNumber.MaxValue, 100, 100));
}
private static Chord GetChord_NonzeroTime()
{
return new Chord(new Note(SevenBitNumber.MaxValue, 100, 50),
new Note(SevenBitNumber.MaxValue, 100, 100),
new Note(SevenBitNumber.MaxValue, 100, 150));
}
#endregion
}
}
|
8b850cdd76c47dcd0fe5a449e808844970e926c5
|
C#
|
connorlevesque/FunFactory
|
/Assets/Scripts/Crates.cs
| 2.90625
| 3
|
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
public class Crates : GridOf<Crate> {
public Crates(int h, int w) : base(h,w) {}
public static List<CrateGroup> Groups() {
List<CrateGroup> groups = new List<CrateGroup>();
Action<Crate> addGroup = (crate) => {
bool alreadyAdded = groups.Contains(crate.group);
if (!alreadyAdded) groups.Add(crate.group);
};
ForEach(addGroup);
return groups;
}
public static void ForEachGroup(Action<CrateGroup> action) {
foreach (CrateGroup group in Groups()) {
action(group);
}
}
}
|
8b75d875d446e67ad1971f42e1d22b0dffb86acb
|
C#
|
srscrls/payroll-calculator
|
/tax.cs
| 3.359375
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PAYECalcWin
{
class Tax
{
public Tax(string name, OrderedDictionary taxRates)
{
this.Name = name;
this.TaxRates = taxRates;
}
public string Name { get; private set; }
public OrderedDictionary TaxRates { get; private set; }
//Method to calculate the tax by looping through the thresholds (the key of the dictionary).
//Calculate the tax and add it to the accumulated amount
//Stopping when the threshold is above the salary.
public virtual decimal CalculateTax(decimal amount)
{
decimal AccumulatedTax = 0;
for (int i = this.TaxRates.Count-1; i >=0 ; i--)
{
decimal LowerBound = Convert.ToDecimal(this.TaxRates.Cast<DictionaryEntry>().ElementAt(i).Key);
if (amount > LowerBound)
{
AccumulatedTax += (amount - LowerBound) * Convert.ToDecimal(this.TaxRates[i]);
amount = LowerBound;
}
}
return AccumulatedTax;
}
}
}
|
b56e90839a414db976343f66db02c9e0291acbc5
|
C#
|
androidZ200/snake-game
|
/Field.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.Drawing;
namespace змейка
{
class Field
{
private Random rand = new Random();
public Snake<int> snake { get; set; }
public HashSet<int> wall { get; private set; }
public int eat { get; private set; }
public int Width { get; private set; }
public int WidthImage { get; private set; }
public bool isLive { get; private set; } = true;
private Bitmap image;
private bool isChangeField = true;
private object DrawingLock = new object();
private Color _Background = Color.White;
private Color _EatColor = Color.DarkRed;
private Color _WallColor = Color.Black;
public Color Background { get { return _Background; } set { lock (DrawingLock) _Background = value; isChangeField = true; } }
public Color EatColor { get { return _EatColor; } set { lock (DrawingLock) _EatColor = value; isChangeField = true; } }
public Color WallColor { get { return _WallColor; } set { lock (DrawingLock) _WallColor = value; isChangeField = true; } }
public event Action Eat;
public event Action Die;
public Field(int Width, int startLength)
{
this.Width = Width;
snake = new Snake<int>(rand.Next(Width * Width),
(Snake<int>.Rotate)rand.Next(4), startLength, NextCell, GetRotate);
WidthImage = Width * 20;
wall = new HashSet<int>();
GenerateEat();
}
public Field(int Width, int startLength, Func<int, Color> SkinSnake) : this(Width, startLength)
{
snake.NewSkin(SkinSnake);
}
public void Move()
{
int coordinate = NextCell(snake.Body.Head, snake.angle);
if (eat == coordinate) { snake.MoveAndEat(); GenerateEat(); Eat(); }
else if (snake.Body.Find(coordinate, Comparison)) { isLive = false; Die(); }
else if (wall.Contains(coordinate)) { isLive = false; Die(); }
else snake.Move(coordinate);
lock (DrawingLock)
isChangeField = true;
}
public void ReverseAndMove()
{
snake.ReversAndMove();
if (eat == snake.Body.Head) { GenerateEat(); Eat(); }
lock (DrawingLock)
isChangeField = true;
}
public void Restart(int startLength)
{
snake = new Snake<int>(rand.Next(Width * Width),
(Snake<int>.Rotate)rand.Next(4), startLength, NextCell, GetRotate);
wall.Clear();
GenerateEat();
_Background = Color.White;
_EatColor = Color.DarkRed;
_WallColor = Color.Black;
isLive = true;
isChangeField = true;
}
public void NewSnakeSkin(Func<int, Color> skin)
{
snake.NewSkin(skin);
}
public void AddWall()
{
for (int i = 0; i < 100; i++)
{
int t = rand.Next(Width * Width);
if (!snake.Body.Find(t, Comparison) && GetLength(t, snake.Body.Head) > 10 && t != eat)
{
wall.Add(t);
break;
}
}
}
public Bitmap Image()
{
lock (DrawingLock)
if (isChangeField)
{
image = new Bitmap(Width * 20, Width * 20);
Graphics g = Graphics.FromImage(image);
g.Clear(Background);
Deque<int>.Iiterator curr = snake.Body.GetHead();
int index = 0;
do
{
g.FillRectangle(new SolidBrush(snake.GetColor(index++)), curr.Value % Width * 20,
curr.Value / Width * 20, 19, 19);
} while (curr.Next() != null);
g.FillRectangle(new SolidBrush(EatColor), eat % Width * 20, eat / Width * 20, 19, 19);
foreach (var x in wall)
g.FillRectangle(new SolidBrush(WallColor), x % Width * 20, x / Width * 20, 19, 19);
isChangeField = false;
return image;
}
else return image;
}
private int NextCell(int currenCell, Snake<int>.Rotate rotate)
{
switch (rotate)
{
case Snake<int>.Rotate.Up:
currenCell -= Width;
if (currenCell < 0) currenCell += Width * Width;
return currenCell;
case Snake<int>.Rotate.Right:
if (currenCell % Width == Width - 1) return currenCell - Width + 1;
else return currenCell + 1;
case Snake<int>.Rotate.Down:
currenCell += Width;
if (currenCell >= Width * Width) currenCell -= Width * Width;
return currenCell;
case Snake<int>.Rotate.Left:
if (currenCell % Width == 0) return currenCell + Width - 1;
else return currenCell - 1;
default:
return currenCell;
}
}
private Snake<int>.Rotate GetRotate(int currentCell, int nextCell)
{
int delta = nextCell - currentCell;
if (delta == 1 || delta == -Width + 1) return Snake<int>.Rotate.Right;
else if (delta == -1 || delta == Width - 1) return Snake<int>.Rotate.Left;
else if (delta == Width || delta == Width * (Width - 1)) return Snake<int>.Rotate.Down;
else return Snake<int>.Rotate.Up;
}
private bool Comparison(int a, int b)
{
return a == b;
}
private int GetLength(int a, int b)
{
int a1 = a % Width;
int b1 = b % Width;
int length = Math.Abs(a1 - b1) > Width - Math.Abs(a1 - b1) ?
Width - Math.Abs(a1 - b1) : Math.Abs(a1 - b1);
a1 = a / Width;
b1 = b / Width;
length += Math.Abs(a1 - b1) > Width - Math.Abs(a1 - b1) ?
Width - Math.Abs(a1 - b1) : Math.Abs(a1 - b1);
return length;
}
private void GenerateEat()
{
for (int i = 2; ; i++)
{
int t = rand.Next(Width * Width);
if (!snake.Body.Find(t, Comparison) && GetLength(t, snake.Body.Head) < i && !wall.Contains(t))
{
eat = t;
break;
}
}
}
}
}
|
f5f2588996e54dc755f901987985b1ac4ae5f9b1
|
C#
|
orontamir/1272_GOODIES_ZAHAL
|
/1272_GOODIES_ZAHAL/DataBase/DBParser.cs
| 2.859375
| 3
|
using _1272_GOODIES_ZAHAL.DataModel;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.OracleClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _1272_GOODIES_ZAHAL.DataBase
{
public class DBParser
{
/// <summary>
/// The singleton instance
/// </summary>
private static DBParser m_ins;
/// <summary>
/// select command
/// </summary>
private SelectCmd m_selsctCmd;
/// <summary>
/// update command
/// </summary>
private UpdateCmd m_updateCmd;
private readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(DBParser));
readonly string m_connectionString = ConfigurationManager.ConnectionStrings["testos"].ConnectionString;
/// <summary>
/// constructor
/// </summary>
private DBParser()
{
m_selsctCmd = new SelectCmd();
m_updateCmd = new UpdateCmd();
}
/// <summary>
/// Get the singleton instance
/// </summary>
/// <returns>The singleton instance</returns>
public static DBParser Instance()
{
if (m_ins == null)
{
m_ins = new DBParser();
}
return m_ins;
}
/// <summary>
/// read string that must not be empty - if it is emty - set the valid data flag to be false
/// </summary>
/// <param name="curReader">the current reader</param>
/// <param name="clmName">the coulumn name</param>
/// <returns>the string</returns>
private string ReadString(OracleDataReader curReader, string clmName)
{
string str = ReadNotValidString(curReader, clmName);
return str;
}
/// <summary>
/// read string that can be empty
/// </summary>
/// <param name="curReader">the current reader</param>
/// <param name="clmName">the coulumn name</param>
/// <returns>the string</returns>
private string ReadNotValidString(OracleDataReader curReader, string clmName)
{
string val = null;
try
{
if (curReader[clmName] != null)
{
val = curReader[clmName].ToString();
}
}
catch
{
string errMsg = "Error: Invalid colum name: " + clmName;
throw new Exception(errMsg);
}
return val;
}
/// <summary>
/// read int that must not be empty - if it is emty - set the valid data flag to be false
/// </summary>
/// <param name="curReader">the current reader</param>
/// <param name="clmName">the coulumn name</param>
/// <returns>the int</returns>
private int ReadInt(OracleDataReader curReader, string clmName)
{
int val = 0;
string str = ReadString(curReader, clmName);
val = Convert.ToInt32(str);
return val;
}
/// <summary>
/// read double that must not be empty - if it is emty - set the valid data flag to be false
/// </summary>
/// <param name="curReader">the current reader</param>
/// <param name="clmName">the coulumn name</param>
/// <returns>the int</returns>
private double ReadDouble(OracleDataReader curReader, string clmName)
{
double val = 0;
string str = ReadString(curReader, clmName);
val = Convert.ToDouble(str);
return val;
}
/// <summary>
/// read date time that must not be empty - if it is emty - set the valid data flag to be false
/// </summary>
/// <param name="curReader">the current reader</param>
/// <param name="clmName">the coulumn name</param>
/// <returns>the int</returns>
private DateTime ReadDateTime(OracleDataReader curReader, string clmName)
{
DateTime val = DateTime.Now;
string str = ReadString(curReader, clmName);
val = Convert.ToDateTime(str);
return val;
}
/// <summary>
/// read time that must not be empty - if it is emty - set the valid data flag to be false
/// </summary>
/// <param name="curReader">the current reader</param>
/// <param name="clmName">the coulumn name</param>
/// <returns>date in string</returns>
public string ReadTime(OracleDataReader curReader, string clmName)
{
DateTime val = DateTime.Now;
string str = ReadString(curReader, clmName);
val = Convert.ToDateTime(str);
return val.ToString("HH-mm-ss");
}
/// <summary>
/// read date that must not be empty - if it is emty - set the valid data flag to be false
/// </summary>
/// <param name="curReader">the current reader</param>
/// <param name="clmName">the coulumn name</param>
/// <returns>date in string</returns>
public string ReadDate(OracleDataReader curReader, string clmName)
{
DateTime val = DateTime.Now;
string str = ReadString(curReader, clmName);
val = Convert.ToDateTime(str);
return val.ToString("yyyy-MM-dd");
}
public Token GetToken()
{
using (OracleConnection connection = new OracleConnection(m_connectionString))
{
try
{
connection.Open();
m_selsctCmd.TblName = "TBL_GOODI_TOKEN_1272";
using (OracleCommand command = new OracleCommand(m_selsctCmd.GetCmd(), connection))
{
command.CommandTimeout = 5000;
OracleDataReader reader = command.ExecuteReader();
if (reader.Read())
{
Token token = new Token
{
TokenNumber = ReadString(reader, "TOKEN"),
Stemp_Tar = ReadDateTime(reader, "STAMP_TAR")
};
return token;
}
}
}
catch (Exception ex)
{
//insert log error message
log.Error($"Exception when try to get token, error message: {ex.Message}");
}
finally
{
connection.Close();
}
}
return null;
}
[Obsolete("Message")]
public IEnumerable<ExecuteTransaction> GetAllTransactions()
{
ExecuteTransaction transaction = null;
List<ExecuteTransaction> transactions = new List<ExecuteTransaction>();
using (OracleConnection connection = new OracleConnection(m_connectionString))
{
try
{
connection.Open();
m_selsctCmd.TblName = "V_TBL_GOODIES_ZAHAL_1272";
using (OracleCommand command = new OracleCommand(m_selsctCmd.GetCmd(), connection))
{
command.CommandTimeout = 5000;
OracleDataReader reader = command.ExecuteReader();
while (reader.Read())
{
transaction = new ExecuteTransaction
{
ID = ReadInt(reader, "ROW_ID"),
PRICE = ReadDouble(reader, "PRICE"),
AMOUNT = ReadDouble(reader, "AMOUNT"),
KOD_MAKOR = ReadInt(reader, "KOD_MAKOR"),
KOD_STATION = ReadInt(reader, "KOD_STATION"),
KOD_HETKEN = ReadInt(reader, "KOD_HETKEN"),
MISPAR_HETKEN = ReadString(reader, "MISPAR_HETKEN"),
TIDLUK_DATE = ReadString(reader, "TIDLUK_DATE"),
TIDLUK_TIME = ReadString(reader, "TIDLUK_TIME"),
KOD_TAZKIK = ReadInt(reader, "KOD_TAZKIK"),
STATION_ORDER = ReadString(reader, "STATION_ORDER"),
};
transactions.Add(transaction);
}
reader.Close();
}
}
catch (Exception ex)
{
//insert log error message
log.Error($"Exception when try to get all transactions, error message: {ex.Message}");
}
finally
{
connection.Close();
}
}
return transactions;
}
public bool UpdateToken(Token token)
{
using (OracleConnection connection = new OracleConnection(m_connectionString))
{
try
{
connection.Open();
m_updateCmd.TblName = "TBL_GOODI_TOKEN_1272";
m_updateCmd.AddTextVal("TOKEN", token.TokenNumber);
m_updateCmd.AddTextVal("STAMP_TAR", token.Stemp_Tar.ToString());
using (OracleCommand command = new OracleCommand(m_updateCmd.GetCmd(), connection))
{
command.CommandTimeout = 5000;
int result = command.ExecuteNonQuery();
if (result > 0) return true;
}
}
catch (Exception ex)
{
//insert log error message
log.Error($"Exception when try to update Token number, error message: {ex.Message}");
return false;
}
finally
{
connection.Close();
}
return false;
}
}
[Obsolete("Message")]
public bool UpdateTransaction(int id,string errorMessage = null , string errorCode = null, ExecuteTransactionResponse transactionResponse = null)
{
using (OracleConnection connection = new OracleConnection(m_connectionString))
{
try
{
connection.Open();
m_updateCmd.TblName = "TBL_GOODIES_ZAHAL_1272";
m_updateCmd.AddIntKeyVal("ID", id);
if (errorCode == null && errorMessage == null)
{
m_updateCmd.AddIntVal("STATUS", 1);
m_updateCmd.AddTextVal("BALANCE", transactionResponse.Balance);
m_updateCmd.AddTextVal("ORDERID", transactionResponse.orderId);
}
else
{
m_updateCmd.AddIntVal("STATUS", 2);
m_updateCmd.AddTextVal("ERROR_MESSAGE", errorMessage);
m_updateCmd.AddTextVal("ERROR_CODE", errorCode);
}
using (OracleCommand command = new OracleCommand(m_updateCmd.GetCmd(), connection))
{
command.CommandTimeout = 5000;
int result = command.ExecuteNonQuery();
if (result > 0) return true;
}
}
catch (Exception ex)
{
//log.Error($"Exception when try to update seler status, error message: {ex.Message}");
return false;
}
finally
{
connection.Close();
}
}
return false;
}
}
}
|
21676cb33514c930452caf1580015decae30975f
|
C#
|
rockiesmagicnumber/Odds-N-Ends
|
/ObjectUpdater.cs
| 2.953125
| 3
|
namespace Andrew.OddsNEnds
{
public class GeneralFunctions
{
public T UpdateObject<T>(T target, T source, bool overWriteWithNull)
{
Type t = typeof(T);
var properties = t.GetProperties().Where(prop => prop.CanRead && prop.CanWrite);
foreach (var prop in properties)
{
var value = prop.GetValue(source, null);
var existingValue = prop.GetValue(target, null);
if ((value != null || overWriteWithNull) && value is IComparable && !value.Equals(existingValue))
{
// I picked IList because I can directly apply indexing to IList, but not to ICollection or IEnumerable
if (value is IList iLvalue)
{
IList exILvalue = (IList)existingValue;
// Initial use case assumed any IList objects would have an equal number of entries
// This assumption is stupid.
// TODO: Add "Insert/Delete" functionality
for (int i = 0; i < iLvalue.Count; i++)
{
var v = iLvalue[i];
var e = exILvalue[i];
Type typeArgument = v.GetType();
MethodInfo method = typeof(ReportBuilder).GetMethod(nameof(ReportBuilder.UpdateObject));
MethodInfo generic = method.MakeGenericMethod(typeArgument);
generic.Invoke(this, new[] { e, v });
}
}
prop.SetValue(target, value, null);
}
}
return target;
}
}
}
|
85a0c1947c28c0d908111577709df456e5e824a9
|
C#
|
aroder/heatmap
|
/HeatMap/CoordinateConverter.cs
| 2.984375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AdamRoderick.HeatMap
{
//with help from http://groups.google.com/group/Google-Maps-API/browse_thread/thread/278923f0aad4811a
public class CoordinateConverter
{
public const int OFFSET = 268435456;
public const double RADIUS = OFFSET/Math.PI;
public static int LonToX(double lon)
{
return (int)Math.Round(OFFSET + RADIUS * lon * Math.PI / 180);
}
public static int LatToY(double lat)
{
return
(int)Math.Round(OFFSET - RADIUS*Math.Log((1 + Math.Sin(lat*Math.PI/180))/(1 - Math.Sin(lat*Math.PI/180)))/2);
}
public static double YToLat(int y)
{
return (Math.PI / 2 - 2 * Math.Atan(Math.Exp((y - OFFSET) / RADIUS)))*180/Math.PI;
}
public static double XToLon(int x)
{
return ((x - OFFSET)/RADIUS)*180/Math.PI;
}
public static double AdjustLonByPixels(double lon, int delta, int zoom)
{
return XToLon(LonToX(lon) + (delta << (21 - zoom)));
}
public static double AdjustLatByPixels(double lat, int delta, int zoom)
{
return YToLat(LatToY(lat) + (delta << (21 - zoom)));
}
}
}
|
bec8d9c94160212ea5a2e7362fde5678bc16995b
|
C#
|
FelicePollano/Metsys.Bson
|
/Metsys.Bson.VStest/UnitTest1.cs
| 2.671875
| 3
|
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Metsys.Bson.VStest
{
/// <summary>
/// Summary description for UnitTest1
/// </summary>
[TestClass]
public class UnitTest1
{
public UnitTest1()
{
//
// TODO: Add constructor logic here
//
}
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
// You can use the following additional attributes as you write your tests:
//
// Use ClassInitialize to run code before running the first test in the class
// [ClassInitialize()]
// public static void MyClassInitialize(TestContext testContext) { }
//
// Use ClassCleanup to run code after all tests in a class have run
// [ClassCleanup()]
// public static void MyClassCleanup() { }
//
// Use TestInitialize to run code before running each test
// [TestInitialize()]
// public void MyTestInitialize() { }
//
// Use TestCleanup to run code after each test has run
// [TestCleanup()]
// public void MyTestCleanup() { }
//
#endregion
public class Simple
{
public string Name { get; set; }
public double Value { get; set; }
}
[TestMethod]
public void ArrayOrig()
{
var array = new byte[] { 1, 2, 3, 100, 94 };
var input = Serializer.Serialize(array);
var o = Deserializer.Deserialize<byte[]>(input);
Assert.AreEqual(array, o);
}
[TestMethod]
public void TestMethod1()
{
var x = new Simple() { Name = "Pasta", Value = 5 };
var q = new Simple[] { x,x,x,x,x,x,x,x};
var bytes = Bson.Serializer.Serialize(q);
var z = Bson.Deserializer.Deserialize<Simple[]>(bytes);
}
}
}
|
1243c2a376fb7c9f02c1dec94a128764c00a5cef
|
C#
|
moserarthur/Exercises
|
/ExercicioBancoDados/DAO/ProdutoDAO.cs
| 3.171875
| 3
|
using ExercicioBancoDados.Model;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
namespace ExercicioBancoDados.DAO
{
public class ProdutoDAO
{
private SqlConnection _conn;
private SqlTransaction _trans;
public ProdutoDAO(SqlConnection conn, SqlTransaction trans)
{
this._conn = conn;
this._trans = trans;
}
public void InserirProduto(string descricao, double preco)
{
string sqlInsert = @"INSERT INTO PRODUTOS (DESCRICAO,PRECO) VALUES (@descricao,@preco)";
SqlCommand cmd = new SqlCommand(sqlInsert,_conn,_trans);
cmd.Parameters.AddWithValue("@descricao",descricao);
cmd.Parameters.AddWithValue("@preco",preco);
cmd.ExecuteNonQuery();
}
public List<Produto> RetornaProdutos()
{
string sql = @"SELECT
DESCRICAO,
PRECO
FROM PRODUTOS";
var lista = new List<Produto>();
SqlCommand cmd = new SqlCommand(sql,_conn,_trans);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Produto p = new Produto()
{
Descricao = reader["DESCRICAO"].ToString(),
Preco = Convert.ToDouble(reader["PRECO"])
};
lista.Add(p);
}
}
return lista;
}
}
}
|
ae3600013396ced1c49abd8b7a5ba5acfb65c5ef
|
C#
|
Harvey1214/Website-Finder
|
/WebsiteFinder/Handlers/ActionsManager.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using System.Threading;
using System.Text.RegularExpressions;
namespace WebsiteFinder
{
class ActionsManager
{
private Bot bot = new Bot();
public string KeyWords { get; set; } = "Hi there it works!";
public string MinDate { get; set; } = "2000";
public string MaxDate { get; set; } = "2005";
public List<Website> Websites { get; set; } = new List<Website>();
public int MinPages { get; set; }
public int Pages { get; set; } = 4;
public void StartProcess(bool maximized = true, bool headless = false)
{
ScrapeSearchResults(maximized, headless);
}
private void ScrapeSearchResults(bool maximized, bool headless)
{
bot.OpenChrome(maximized, headless);
// search using keywords
{
bot.GoToURL("https://www.google.com");
try { bot.ClickElement(By.Id("L2AGLb")); } catch { } // "Agree with ToS" button
// type keywords
By byForSearchAndConfirm;
try
{
byForSearchAndConfirm = By.XPath("//input[@placeholder='Search Google or type a URL']");
bot.SendKeysToElement(byForSearchAndConfirm, KeyWords);
}
catch
{
try
{
byForSearchAndConfirm = By.XPath("//input[@type='text']");
bot.SendKeysToElement(byForSearchAndConfirm, KeyWords);
}
catch
{
try
{
byForSearchAndConfirm = By.XPath("//input[@type='search']");
bot.SendKeysToElement(byForSearchAndConfirm, KeyWords);
}
catch
{
byForSearchAndConfirm = By.ClassName("gLFyf");
bot.SendKeysToElement(byForSearchAndConfirm, KeyWords);
}
}
}
// confirm
try { bot.SendKeysToElement(byForSearchAndConfirm, Keys.Enter); } catch { }
}
// filter by date
{
try
{
bot.ClickElement(By.Id("hdtb-tls")); // "Tools" button
Thread.Sleep(250);
bot.ClickElement(By.XPath("//*[@class=\"hdtb-mn-hd\"]")); // "Any time" dropdown
var timeDropdownItems = bot.driver.FindElements(By.XPath("//*[contains(@class, 'znKVS') and contains(@class, 'tnhqA')]")); // get all items from the time filter dropdown
timeDropdownItems.Last().Click(); // click "Custom range..." item in the dropdown
}
catch
{
}
try { bot.SendKeysToElement(By.Id("OouJcb"), MinDate); } catch { }
try { bot.SendKeysToElement(By.Id("rzG2be"), MaxDate); } catch { }
try { bot.ClickElement(By.XPath("/html/body/div[7]/div/div[4]/div[2]/div[2]/div[3]/form/g-button")); } catch { } // "Go" button
}
// read URLs
{
for (int i = 0; i < Pages; i++)
{
// reading search results
if (i + 1 >= MinPages) // if the page isn't in the specified range, skip it
{
try
{
string html = bot.GetElementInnerHTML(By.Id("center_col"));
MatchCollection matches = Regex.Matches(html, @"https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b");
foreach (Match match in matches)
{
Websites.Add(new() { Link = match.Value, Page = i + 1 });
}
}
catch
{
}
}
// go to next page of search results
try
{
By nextPageButton = By.XPath("//*[contains(@style, 'display:block;margin-left:53px')]");
bot.ScrollToElement(nextPageButton);
Thread.Sleep(1000);
bot.ClickElement(nextPageButton); // go to the next page of search results
Thread.Sleep(1000);
}
catch
{
break; // no more pages of search results, so continue onto another process
}
}
RemoveDuplicateWebsites();
}
// driver action ends
{
EndProcess();
}
}
private void RemoveDuplicateWebsites()
{
List<string> links = new List<string>();
List<int> pages = new List<int>();
foreach (Website website in Websites)
{
bool duplicate = false;
foreach (string link in links)
{
if (website.Link == link)
{
duplicate = true;
break;
}
}
if (duplicate) continue;
links.Add(website.Link);
pages.Add(website.Page);
}
Websites.Clear();
for (int i = 0; i < links.Count; i++)
{
Websites.Add(new() { Link = links[i], Page = pages[i] });
}
}
public void EndProcess()
{
bot.CloseDriver();
}
}
}
|
d603eb95ede388f82bc83db6d723468ee7fde1b3
|
C#
|
dojo87/microservicesoverview
|
/Gateway/Service/DefaultAuthService.cs
| 2.6875
| 3
|
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using UserApi.Model;
namespace Gateway.Service
{
public class DefaultAuthService : IAuthService
{
private IOptions<AuthenticationSettings> settings;
public DefaultAuthService(IOptions<AuthenticationSettings> settings)
{
this.settings = settings;
}
public User Authenticate(HttpContext context)
{
User result = FindUser(context.User.Identity.Name);
if (result != null)
{
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
SecurityTokenDescriptor tokenDetails = new SecurityTokenDescriptor()
{
Subject = new System.Security.Claims.ClaimsIdentity(
new Claim[]{
new Claim(ClaimTypes.Name, result.Name),
new Claim(ClaimTypes.Role, result.Claims)
}),
Expires = DateTime.UtcNow.AddMilliseconds(this.settings.Value.JWTExpirationMiliseconds),
SigningCredentials = GetSecurityCredentials()
};
Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true;
result.Token = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDetails));
}
return result;
}
protected User FindUser(string user)
{
if (user == null) return null;
return USERS_MOCK.FirstOrDefault(u => user.EndsWith(u.Name))?.CloneWithoutSensitiveData();
}
protected SigningCredentials GetSecurityCredentials()
{
var jwtKey = Convert.FromBase64String(this.settings.Value.JWTKey);
return new SigningCredentials(new SymmetricSecurityKey(jwtKey), SecurityAlgorithms.HmacSha256Signature);
}
private static List<User> USERS_MOCK = new List<User>()
{
new User()
{
Name = "a305477",
Claims = "some additional info like roles and such"
}
};
}
}
|
6e660b0c4f793617eb4de259577503d6f21f60f1
|
C#
|
eniga/LagosHealthReminderApi
|
/LagosHealthReminderApi/Repositories/RoleRepo.cs
| 2.625
| 3
|
using Dapper;
using LagosHealthReminderApi.DbContext;
using LagosHealthReminderApi.Models;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
namespace LagosHealthReminderApi.Repositories
{
public class RoleRepo
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
public string ConnectionString { get; set; }
public RoleRepo(IConfiguration Configuration)
{
this.ConnectionString = Configuration.GetConnectionString("DefaultConnection");
}
private SqlConnection GetConnection()
{
return new SqlConnection(ConnectionString);
}
public List<RoleContext> Read()
{
List<RoleContext> list = new List<RoleContext>();
string sql = "SELECT * FROM ROLES";
try
{
using (IDbConnection conn = GetConnection())
{
list = conn.Query<RoleContext>(sql).ToList();
}
}
catch (Exception ex)
{
logger.Error(ex);
}
return list;
}
public Response Create(RoleContext context)
{
Response response = new Response();
string sql = "INSERT INTO ROLES (ROLENAME) VALUES (@RoleName)";
try
{
using (IDbConnection conn = GetConnection())
{
conn.Execute(sql, context);
response.Status = true;
response.StatusMessage = "Approved and completed successfully";
}
}
catch (Exception ex)
{
response.Status = false;
response.StatusMessage = "System Malfunction";
logger.Error(ex);
}
return response;
}
public Response Update(RoleContext context)
{
Response response = new Response();
string sql = "UPDATE ROLES SET ROLENAME = @RoleName WHERE ROLEID = @RoleId";
try
{
using (IDbConnection conn = GetConnection())
{
conn.Execute(sql, context);
response.Status = true;
response.StatusMessage = "Approved and completed successfully";
}
}
catch (Exception ex)
{
response.Status = false;
response.StatusMessage = "System Malfunction";
logger.Error(ex);
}
return response;
}
public Response Delete(int RoleId)
{
Response response = new Response();
string sql = "DELETE FROM ROLES WHERE ROLEID = @RoleId";
try
{
using (IDbConnection conn = GetConnection())
{
conn.Execute(sql, new { RoleId });
response.Status = true;
response.StatusMessage = "Approved and completed successfully";
}
}
catch (Exception ex)
{
response.Status = false;
response.StatusMessage = "System Malfunction";
logger.Error(ex);
}
return response;
}
}
}
|
ba5010edb76be6dd3f79a0ea94eca0f0040ab5f4
|
C#
|
DerLando/PolycurveEditingTools
|
/PolycurveEditingTools/Core/CurveTypes.cs
| 2.796875
| 3
|
using Rhino.Geometry;
namespace PolycurveEditingTools.Core
{
public enum CurveType
{
LineCurve,
ArcCurve,
NurbsCurve,
PolylineCurve,
Undefined,
}
public static class CurveTypes
{
public static CurveType CurveType(this Curve crv)
{
var type = crv.GetType();
if (type == typeof(LineCurve)) return Core.CurveType.LineCurve;
if (type == typeof(ArcCurve)) return Core.CurveType.ArcCurve;
if (type == typeof(PolylineCurve)) return Core.CurveType.PolylineCurve;
if (type == typeof(NurbsCurve)) return Core.CurveType.NurbsCurve;
return Core.CurveType.Undefined;
}
}
}
|