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
|
|---|---|---|---|---|---|---|
fe42cd6e5675597d439424dbb259facbf2cdbbb2
|
C#
|
asgerhallas/DomFx
|
/DomFx.Tests/Units/Layouters/Sectioning/simple.cs
| 2.609375
| 3
|
using DomFx.Layouters;
using Xunit;
namespace DomFx.Tests.Units.Layouters.Sectioning
{
public class simple : sectioning_tests
{
[Fact]
public void single_element_is_layouted()
{
Section(content: Content(border: 1.cm(), elements: new[]
{
Element(innerWidth: 2.cm(), innerHeight: 2.cm())
}));
LayoutWithPage(10.cm(), 15.cm());
Element(1).ShouldBeAt(page: 1, left: 1.cm(), top: 1.cm(), height: 2.cm());
}
[Fact]
public void header_content_and_footer_are_all_layouted()
{
Section(header: Content(border: 1.cm(), elements: new[]
{
Element(innerWidth: 2.cm(), innerHeight: 2.cm())
}),
content: Content(border: 1.cm(), elements: new[]
{
Element(innerWidth: 2.cm(), innerHeight: 2.cm())
}),
footer: Content(border: 1.cm(), elements: new[]
{
Element(innerWidth: 2.cm(), innerHeight: 2.cm())
}));
LayoutWithPage(10.cm(), 15.cm());
Element(1).ShouldBeAt(page: 1, left: 1.cm(), top: 1.cm(), height: 2.cm());
Element(2).ShouldBeAt(page: 1, left: 1.cm(), top: 5.cm(), height: 2.cm());
Element(3).ShouldBeAt(page: 1, left: 1.cm(), top: 11.cm(), height: 2.cm());
}
[Fact]
public void content_page_height_respects_header_and_footer()
{
Section(header: Content(border: 1.cm(), elements: new[]
{
Element(innerWidth: 2.cm(), innerHeight: 2.cm())
}),
content: Content(border: 1.cm(), elements: new[]
{
Element(innerWidth: 2.cm(), innerHeight: 10.cm(), breakable: true)
}),
footer: Content(border: 1.cm(), elements: new[]
{
Element(innerWidth: 2.cm(), innerHeight: 2.cm())
}));
LayoutWithPage(10.cm(), 15.cm());
Element(2, 1).ShouldBeAt(page: 1, left: 1.cm(), top: 5.cm(), height: 5.cm());
Element(2, 2).ShouldBeAt(page: 2, left: 1.cm(), top: 5.cm(), height: 5.cm());
}
[Fact]
public void section_begins_on_new_page()
{
Section(content: Content(border: 1.cm(), elements: new[]
{
Element(innerWidth: 2.cm(), innerHeight: 5.cm())
}));
Section(content: Content(border: 1.cm(), elements: new[]
{
Element(innerWidth: 2.cm(), innerHeight: 5.cm())
}));
LayoutWithPage(10.cm(), 15.cm());
Element(1).ShouldBeAt(page: 1, left: 1.cm(), top: 1.cm(), height: 5.cm());
Element(2).ShouldBeAt(page: 2, left: 1.cm(), top: 1.cm(), height: 5.cm());
}
}
}
|
54b985642e8b9b5c2e4a6583812aa935f03d3361
|
C#
|
ashishanand25/cloudclaims
|
/CloudClaims.Data/Portal/EverythingToDoWith_CCClaims.cs
| 2.65625
| 3
|
using CloudClaims.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace CloudClaims.Data.Portal {
public static class EverythingToDoWith_CCClaims {
public static CCClaim getClaimByGuid(Guid id, int clientID) {
var db = new CCPortalEntities();
return db.CCClaims.Where(c => c.claimGUID == id && c.clientID == clientID).SingleOrDefault();
}
public static CCClaim getClaimByID(int id, int clientID) {
try {
var db = new CCPortalEntities();
return db.CCClaims.Where(c => c.claimID == id && c.clientID == clientID).SingleOrDefault();
} catch {
throw new Exception();
}
}
public static IEnumerable<CCClaim> getAllClaimsFor(int clientID) {
try {
var db = new CCPortalEntities();
return db.CCClaims.Where(c => c.clientID == clientID);
} catch {
throw new Exception();
}
}
public static Guid addClaim(CCClaim c) {
try {
var db = new CCPortalEntities();
c.claimGUID = Guid.NewGuid();
db.CCClaims.Add(c);
db.SaveChanges();
return c.claimGUID;
} catch {
throw new Exception();
}
}
public static void updateClaim(CCClaim c) {
var db = new CCPortalEntities();
db.Entry(c).State = EntityState.Modified;
db.SaveChanges();
}
public static void deleteClaim(CCClaim c) {
var db = new CCPortalEntities();
db.CCClaims.Remove(db.CCClaims.Find(c.claimID));
db.SaveChanges();
}
}
}
|
3538524eece259945aca1e17c4b25a7800dd2111
|
C#
|
PillowIsGod/BasketballManager
|
/BasketballManadger/ClassesImportExport/XMLteamsProcessing.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Xml;
namespace BasketballManadger
{
public class XMLTeamsProcessing : FileTypesProcessing
{
public XMLTeamsProcessing(string filePath) : base(filePath)
{
}
public override BindingList<BasketballPlayers> GetPlayersFromFile()
{
throw new NotImplementedException();
}
public override BindingList<Teams> GetTeamFromFIle()
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load(FileProcessingPath);
XmlElement root = xdoc.DocumentElement;
BindingList<Teams> teamsToReturn = new BindingList<Teams>();
foreach (XmlNode item in root)
{
Teams team = new Teams();
foreach (XmlNode node in item.ChildNodes)
{
if (node.Name == "teamName")
{
team.TeamName = node.InnerText;
}
if (node.Name == "city")
{
team.City = node.InnerText;
}
if (node.Name == "logo")
{
team.Logo = node.InnerText;
}
}
teamsToReturn.Add(team);
}
return teamsToReturn;
}
public override void ImportPlayersData(params BasketballPlayers[] playersToImport)
{
throw new NotImplementedException();
}
public override void ImportTeamData(params Teams [] teamsToImport)
{
XmlDocument xdoc = new XmlDocument();
XmlElement xmlTeam = xdoc.CreateElement("teams");
xdoc.AppendChild(xmlTeam);
foreach (var item in teamsToImport)
{
var xmlTeamGot = GetXMLTeam(item, xdoc);
xmlTeam.AppendChild(xmlTeamGot);
}
xdoc.Save(FileProcessingPath);
}
public XmlElement GetXMLTeam(Teams team, XmlDocument xdoc)
{
XmlElement xmlTeam = xdoc.CreateElement("team");
XmlElement cityElem = xdoc.CreateElement("city");
xmlTeam.AppendChild(cityElem);
XmlElement nameElem = xdoc.CreateElement("teamName");
xmlTeam.AppendChild(nameElem);
XmlElement logoElem = xdoc.CreateElement("logo");
xmlTeam.AppendChild(logoElem);
XmlText cityText = xdoc.CreateTextNode(team.City);
XmlText nameText = xdoc.CreateTextNode(team.TeamName);
XmlText logoText = xdoc.CreateTextNode(team.Logo);
cityElem.AppendChild(cityText);
nameElem.AppendChild(nameText);
logoElem.AppendChild(logoText);
return xmlTeam;
}
}
}
|
e294c502711562b405cc3c3f286774e180bc681c
|
C#
|
freepc2/WPFSample
|
/WPFSample/LINQ.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WPFSample
{
//public class LINQ : ViewModel.ViewModelBase
//{
// private List<Student> _DataList;
// public List<Student> DataList
// {
// get => _DataList;
// set => Set(ref _DataList, value);
// }
// public LINQ()
// {
// _DataList = new List<Student>()
// {
// new Student("김철수", 78.5f),
// new Student("김영희", 91.2f),
// new Student("홍길동", 77.3f),
// new Student("김길수", 80.8f),
// new Student("김진수", 90.8f),
// new Student("아이유", 60.8f),
// new Student("지드래곤", 50.8f),
// new Student("박명수", 20.8f),
// };
// }
// public IEnumerable<Student> GetStudentListOfAverage(float Average)
// {
// // 쿼리 식
// var queryStudent = from Student in DataList
// orderby Student.Average
// where Student.Average < Average
// select Student;
// return queryStudent;
// }
// public IEnumerable<Student> GetStudentsOrderby()
// {
// return DataList.OrderBy(x=> x.Average);
// }
//}
}
|
6663c3e725f2912065e216cbe23cec500cc2d2c5
|
C#
|
JamesRuwart/Lab_8_GetToKnowYourClassmatesUsingSwitch
|
/Program.cs
| 3.96875
| 4
|
using System;
namespace Switch_Statements
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to C# January 2020.");
//start of while-loop for userContinue
string userContinue = "y";
while (userContinue != "n")
{
//Prompt user to select a classmate and uses the Switch-Case method
Console.WriteLine("Pick a classmate from below to get to know them.");
Console.WriteLine(" 1. James \n 2. Matt \n 3. Sean \n 4. Blake");
Console.WriteLine();
//Start of while-loop to only accept valid case
string name = "";
bool tryAgain = true;
while (tryAgain)
{
string userInput = Console.ReadLine().ToLower();
tryAgain = false;
switch (userInput)
{
case "1":
case "james":
name = "James";
break;
case "2":
case "matt":
name = "Matt";
break;
case "3":
case "sean":
name = "Sean";
break;
case "4":
case "blake":
name = "Blake";
break;
default:
tryAgain = true;
Console.WriteLine("Invalid. Try another option");
break;
}
}
//diplays the classmate's name
Console.WriteLine();
Console.WriteLine($"You've entered {name}! Excellent choice!");
Console.WriteLine();
//Prompts user what they would like to know next
Console.WriteLine("What would you like to know next?");
Console.WriteLine();
//give user list to choose from
Console.WriteLine(" 1. Hometown \n 2. Favorite food \n");
//Another while-loop to validate case number inputs
bool tryAgain2 = true;
while (tryAgain2)
{
string moreInfo = Console.ReadLine().ToLower();
tryAgain2 = false;
switch (moreInfo)
{
case "1":
case "hometown":
Console.WriteLine($"{name} is from Detroit!");
break;
case "2":
case "favorite food":
Console.WriteLine($"{name}'s favorite food is pizza!");
break;
default:
tryAgain = true;
Console.WriteLine("Invalid. Try another option");
break;
}
//The while-loop at the top comes full circle
//ask user if they want to try again
//Validation to make sure they enter y or n
userContinue = "";
while (userContinue != "y" && userContinue != "n")
{
Console.WriteLine();
Console.WriteLine("Would you like to try again? y/n");
userContinue = Console.ReadLine().ToLower();
}
}
}
}
}
}
|
6f9d6689f165ba15e3ec03418a047caf1930deb7
|
C#
|
Demdiran/PuzzleGame
|
/PuzzleGameMigrations/DatabaseCreator.cs
| 2.609375
| 3
|
using System;
using System.Configuration;
using System.Data.SqlClient;
namespace PuzzleGameMigrations
{
public class DatabaseCreator
{
public static void CreateDatabaseIfNotExists(string connectionString)
{
var databaseName = ConfigurationManager.AppSettings["DatabaseName"];
try
{
ExecuteSql(connectionString, DatabaseCreationString(databaseName));
}
catch (Exception e)
{
Console.WriteLine("There was a problem creating the database: " + e);
throw;
}
}
private static void ExecuteSql(string connectionString, string sql)
{
using (var connection = new SqlConnection(GetConnectionStringToMasterDb(connectionString)))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = sql;
command.ExecuteNonQuery();
}
}
}
private static string GetConnectionStringToMasterDb(string connectionString)
{
var builder = new SqlConnectionStringBuilder(connectionString) { InitialCatalog = "master" };
return builder.ConnectionString;
}
private static string DatabaseCreationString(string databaseName)
{
return $@"
USE [master]
IF DB_ID('{databaseName}') IS NULL
CREATE DATABASE [{databaseName}]
CONTAINMENT = NONE
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [{databaseName}].[dbo].[sp_fulltext_database] @action = 'enable'
end
ALTER DATABASE [{databaseName}] SET ANSI_NULL_DEFAULT OFF
ALTER DATABASE [{databaseName}] SET ANSI_WARNINGS OFF
ALTER DATABASE [{databaseName}] SET ARITHABORT OFF
ALTER DATABASE [{databaseName}] SET AUTO_CLOSE OFF
ALTER DATABASE [{databaseName}] SET AUTO_SHRINK OFF
ALTER DATABASE [{databaseName}] SET AUTO_UPDATE_STATISTICS ON
ALTER DATABASE [{databaseName}] SET CURSOR_CLOSE_ON_COMMIT OFF
ALTER DATABASE [{databaseName}] SET CURSOR_DEFAULT GLOBAL
ALTER DATABASE [{databaseName}] SET CONCAT_NULL_YIELDS_NULL OFF
ALTER DATABASE [{databaseName}] SET NUMERIC_ROUNDABORT OFF
ALTER DATABASE [{databaseName}] SET QUOTED_IDENTIFIER OFF
ALTER DATABASE [{databaseName}] SET RECURSIVE_TRIGGERS OFF
ALTER DATABASE [{databaseName}] SET DISABLE_BROKER
ALTER DATABASE [{databaseName}] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
ALTER DATABASE [{databaseName}] SET DATE_CORRELATION_OPTIMIZATION OFF
ALTER DATABASE [{databaseName}] SET TRUSTWORTHY OFF
ALTER DATABASE [{databaseName}] SET ALLOW_SNAPSHOT_ISOLATION OFF
ALTER DATABASE [{databaseName}] SET PARAMETERIZATION SIMPLE
ALTER DATABASE [{databaseName}] SET READ_COMMITTED_SNAPSHOT OFF
ALTER DATABASE [{databaseName}] SET HONOR_BROKER_PRIORITY OFF
ALTER DATABASE [{databaseName}] SET RECOVERY FULL
ALTER DATABASE [{databaseName}] SET MULTI_USER
ALTER DATABASE [{databaseName}] SET PAGE_VERIFY CHECKSUM
ALTER DATABASE [{databaseName}] SET DB_CHAINING OFF
ALTER DATABASE [{databaseName}] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )
ALTER DATABASE [{databaseName}] SET TARGET_RECOVERY_TIME = 60 SECONDS
ALTER DATABASE [{databaseName}] SET READ_WRITE
";
}
}
}
|
368a9d4bc8204872f252ee88fc8da4bc7816554f
|
C#
|
andreasstove/MicrowaveOven
|
/Microwave.Test.Integration/Output/PowerTubeAndOutput.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using Microwave.Classes.Boundary;
using Microwave.Classes.Interfaces;
using NSubstitute;
namespace Microwave.Test.Integration
{
class PowerTubeAndOutput
{
private Output output;
private PowerTube power;
private System.IO.StringWriter stringWriter;
[SetUp]
public void Setup()
{
output = new Output();
power = new PowerTube(output);
stringWriter = new System.IO.StringWriter();
Console.SetOut(stringWriter);
}
[Test]
public void TestForTurnOn()
{
power.TurnOn(50);
StringAssert.Contains("PowerTube works with 50", stringWriter.ToString());
}
[Test]
public void TestForTurnOnTurnOff()
{
power.TurnOn(50);
power.TurnOff();
StringAssert.Contains("PowerTube turned off", stringWriter.ToString());
}
[Test]
public void TurnOff()
{
power.TurnOff();
StringAssert.DoesNotContain("PowerTube turned off", stringWriter.ToString());
}
}
}
|
fe0506db080a68e0216ff9945e2636d5cd901f53
|
C#
|
JesusErnestoBg/POO
|
/UNIDAD4/FigurasGeometricas1/Trianguloisosceles.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FigurasGeometricas1
{
class Trianguloisosceles:Triangulo
{
public override double Perimetro()
{
Perimetro1 = Lado + (Lado2 * 2);
return base.Perimetro1;
}
public override double Area()
{
Area1 = (Lado * Altura) / 2;
return base.Area1;
}
}
}
|
6eec369a6e93484b9db3b7c81ccc9a50e00dfd77
|
C#
|
miraDask/CSarp-OOP-Feb-2019
|
/05.POLYMORPHISM/Exercise/Polymorphism-Exarcise/p01.Vehicles/Models/Truck.cs
| 3.140625
| 3
|
namespace Vehicles
{
public class Truck : Vehicle
{
private const double fuelConsumptionIncreasment = 1.6;
private const double fuelQuantityDecreasment = 0.95;
public Truck(double fuelQuantity, double fuelConsumption)
: base(fuelQuantity, fuelConsumption)
{
this.FuelConsumption = fuelConsumption += fuelConsumptionIncreasment;
}
public override void Refuel(double fuel)
{
base.Refuel(fuel * fuelQuantityDecreasment);
}
}
}
|
b70758bbd7f921c365243bcac86dfd5658c2b4a8
|
C#
|
facetraro/school-solution
|
/ERPSchoolSolution/ERPSchoolUI/ConsultTeachers.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Module;
namespace ERPSchoolUI
{
public partial class ConsultTeachers : UserControl
{
private Panel mainPanel;
public ConsultTeachers(Panel mainPanel)
{
InitializeComponent();
try
{
LoadTeachers();
this.mainPanel = mainPanel;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
TeacherMenu backMenu = new TeacherMenu(mainPanel);
mainPanel.Controls.Add(backMenu);
}
}
private void backButton_Click(object sender, EventArgs e)
{
mainPanel.Controls.Clear();
TeacherMenu backMenu = new TeacherMenu(mainPanel);
mainPanel.Controls.Add(backMenu);
}
private bool IsListSelected(ListBox list)
{
int selectedIndex = list.SelectedIndex;
if (selectedIndex == -1)
{
MessageBox.Show("No se ha seleccionado ningun profesor", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
return true;
}
private void LoadTeachers()
{
TeacherModule module = new TeacherModule();
module.LoadAllTeacher(listTeachers);
}
private void LoadSubjects(Object selectedItem)
{
TeacherModule module = new TeacherModule();
try
{
module.LoadSubjectsByTeacher(selectedItem, listSubjects);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void buttonLookSubjects_Click(object sender, EventArgs e)
{
if (IsListSelected(listTeachers))
{
listSubjects.Items.Clear();
LoadSubjects(listTeachers.SelectedItem);
}
}
}
}
|
d1994b8b7b4d5cf617448f32954d60837025aded
|
C#
|
nurlan09/oyrenirem
|
/arrey/Form1.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace arrey
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int start = Convert.ToInt32(textBox1.Text);
int end = Convert.ToInt32(textBox2.Text);
int tekcem = 0;
int teksay = 0;
int cutcem = 0;
int cutsay = 0;
for (int i = start; i < end; i++)
{
if (i%2==0)
{
cutcem += i;
cutsay++;
}
else
{
tekcem += i;
teksay++;
}
label1.Text = tekcem.ToString();
label2.Text = teksay.ToString();
label3.Text = cutcem.ToString();
label4.Text = cutsay.ToString();
}
}
private void button3_Click(object sender, EventArgs e)
{
int start = Convert.ToInt32(textBox1.Text);
int end = Convert.ToInt32(textBox2.Text);
int bolunencem = 0;
int bolunensay = 0;
for (int i = start; i <=end; i++)
{
if (i % 4==0 || i % 6==0)
{
bolunencem += i;
bolunensay++;
}
label1.Text = bolunencem.ToString();
label4.Text = bolunensay.ToString();
}
{
}
}
}
}
|
5b2a1ad048b7d9db288fd8ff0e37bb6b6bf43b80
|
C#
|
GStanchev47/Automation-C-Homework
|
/Homework 8 - Inheritance/Program.cs
| 2.75
| 3
|
using System;
using Homework_8_Inheritance.Blocks;
namespace Homework_8_Inheritance
{
class Program
{
static void Main(string[] args)
{
Player player1 = new Player();
player1.PickUp(BlockType.Grass);
player1.BreakItem(BlockType.Grass);
player1.PickUp(BlockType.Charcoal);
player1.PickUp(BlockType.Junk);
player1.StoreInChest(BlockType.Charcoal);
player1.StoreInChest(BlockType.Junk);
player1.PickUp(BlockType.Wood);
player1.Smelt(BlockType.Wood);
player1.PickUp(BlockType.Stone);
player1.PickUp(BlockType.Grass);
player1.Smelt(BlockType.Stone, BlockType.Grass);
player1.PickUp(BlockType.Charcoal);
player1.Place(BlockType.Charcoal);
player1.PickUp(BlockType.Stone);
player1.BreakItem(BlockType.Stone);
player1.PickUp(BlockType.Pickaxe);
player1.PickUp(BlockType.Stone);
player1.BreakItem(BlockType.Stone);
player1.BreakItem(BlockType.Pickaxe);
}
}
}
|
89122f1d1cef63f0c27e07dda1f328456abbe417
|
C#
|
Doge815/MandelbroTCP
|
/source/MandelbroTCP.Base/PixelCollection.cs
| 3.21875
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Numerics;
using System.Diagnostics;
using MandelbroTCP.Base.Extensions;
namespace MandelbroTCP.Base
{
public class Color
{
//Todo: custom color depth
public uint Red, Green, Blue;
public override bool Equals(object obj)
{
return obj is Color color &&
Red == color.Red &&
Green == color.Green &&
Blue == color.Blue;
}
public string Serialize()
{
return (Red.ToString() + '|' + Green.ToString() + '|' + Blue.ToString());
}
private void Deserialize(string serializedColor)
{
uint[] vals = serializedColor.Split('|').Select(x => UInt32.Parse(x)).ToArray();
Red = vals[0];
Green = vals[1];
Blue = vals[2];
}
public Color()
{
}
public Color(string serializedColor)
{
Deserialize(serializedColor);
}
}
public class PixelCollection
{
private Color[,] Pixels;
public string Serialize()
{
StringBuilder sb = new StringBuilder();
sb.Append(Pixels.GetLength(0).ToString()).Append('|').Append(Pixels.GetLength(1).ToString()).Append('\n');
foreach (Color c in Pixels)
{
sb.Append(c.Serialize() + '#');
}
return sb.ToString();
}
private void Deserialize(string serializedPixelCollection)
{
string[] parts = serializedPixelCollection.Split('\n');
uint[] size = parts[0].Split('|').Select(x => UInt32.Parse(x)).ToArray();
Pixels = new Color[size[0], size[1]];
string[] colors = parts[1].Split('#', StringSplitOptions.RemoveEmptyEntries);
int x = 0, y = 0;
foreach (string s in colors)
{
Pixels[x, y] = new Color(s);
y++;
if (y == Pixels.GetLength(1))
{
y = 0;
x++;
}
}
}
public PixelCollection(string serializedPixelCollection)
{
Deserialize(serializedPixelCollection);
}
public PixelCollection(uint x, uint y)
{
Pixels = new Color[x, y];
for (int i = 0; i < x; i++)
for (int j = 0; j < y; j++)
Pixels[i, j] = new Color();
}
public Color this[int x, int y]
{
get => Pixels[x, y];
set => Pixels[x, y] = value;
}
public Color[,] GetColors() => Pixels;
public override bool Equals(object obj)
{
return obj is PixelCollection collection &&
Pixels.IsEqual(collection.Pixels);
}
public override int GetHashCode()
{
return 1;
}
}
}
|
00cd37a3abcbcbef50a1a941362f8f4f8ff3d159
|
C#
|
ScrubSandwich/Food-Flingin-VR
|
/Assets/ResetIfOnFloor2.cs
| 2.5625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ResetIfOnFloor2 : MonoBehaviour
{
Vector3 originalLocation;
Rigidbody rb;
int TIMER = 150;
void Start()
{
originalLocation = gameObject.transform.position;
rb = gameObject.GetComponent<Rigidbody>();
Debug.Log(gameObject.tag);
}
bool same(float a, float b)
{
if (Mathf.Abs(a - b) < 0.3)
{
return true;
}
return false;
}
// Update is called once per frame
void Update()
{
if (gameObject.tag.Equals("Leek")) {
Debug.Log("__________________");
Debug.Log((gameObject.transform.position.y));
Debug.Log((originalLocation.y));
}
// If laying on floor too long, reset position to back on the table
if (gameObject.transform.position.y <= 0.4 || rb.velocity.magnitude <= 0.4f)
{
if (!same(gameObject.transform.position.y, originalLocation.y) && !same(gameObject.transform.position.x, originalLocation.x) && !same(gameObject.transform.position.z,originalLocation.z)) {
if (TIMER <= 0)
{
gameObject.transform.position = originalLocation;
TIMER = 150;
}
TIMER--;
}
}
}
}
|
1015659eeaf766a102273538f701d79fd821888b
|
C#
|
Touqi634/OOD
|
/Application/Shelter/UnitTestProject/ShelterClassTest.cs
| 2.875
| 3
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ShelterManager;
namespace UnitTestProject
{
[TestClass]
public class ShelterClassTest
{
[TestMethod]
public void TestGettingAnimalByRFID()
{
//Arrange
Shelter s = new Shelter("TestShelter", "Test Address", "Test@Email", "TestPhone");
Dog d1 = new Dog(DateTime.Now, "TestLocation", "TestDescription", "1234abc");
Cat c1 = new Cat(DateTime.Now, "TestLocation2", "TestDescription2", "123abcd", "TestInfo");
s.AddAnimal(d1);
s.AddAnimal(c1);
//Act
Dog checkDog = (Dog)s.GetByRFID("1234abc");
Cat checkCat = (Cat)s.GetByRFID("123abcd");
Animal checkAnimal = s.GetByRFID("IDontExist");
//Assert
Assert.AreEqual(d1, checkDog);
Assert.AreEqual(c1, checkCat);
Assert.AreEqual(null, checkAnimal);
}
[TestMethod]
public void TestAddAnimal()
{
Shelter s = new Shelter("TestShelter", "Test Address", "Test@Email", "TestPhone");
Dog dog = new Dog(DateTime.Now, "TestL", "TestDesc", "1234abc");
Cat cat = new Cat(DateTime.Now, "TestLocation", "TestDescription", "123abcd", "TestInfo");
Dog dupeDog = new Dog(DateTime.Now, "TestLocation", "TestDesc", "1234abc"); //Duplicate RFID
//Act
bool checkDog = s.AddAnimal(dog);
bool checkCat = s.AddAnimal(cat);
bool checkDupe = s.AddAnimal(dupeDog);
//Assert
Assert.AreEqual(true, checkDog);
Assert.AreEqual(true, checkCat);
Assert.AreEqual(false, checkDupe);
Assert.AreEqual(dog, s.GetByRFID("1234abc")); //Check that the RFID is only for the first
}
[TestMethod]
public void TestGetOwner()
{
//Arrange
DateTime date1 = new DateTime(2019, 1, 1);
Shelter s = new Shelter("TestShelter", "Test Address", "Test@Email", "TestPhone");
Owner own1 = new Owner("1", "Stefans");
Dog animal1 = new Dog(DateTime.Now, "1234 playground stret", "Description", "1234abcd");
animal1.Adopt(own1);
Dog dog = new Dog(date1, "TestL", "TestDesc", "1234abc");
s.AddAnimal(dog);
s.AddOwner(own1);
dog.Adopt(own1);
//Act
Owner checkowner = dog.GetOwner();
//Assert
Assert.AreEqual(own1, checkowner);
}
[TestMethod]
public void TestClaimAnimal()
{
//Arrange
DateTime date1 = new DateTime(2019, 1, 1);
Shelter shelter = new Shelter("TestShelter", "Test Address", "Test@Email", "TestPhone");
Dog dog = new Dog(date1, "TestLocation", "TestDescription", "1234abc");
Dog dogfail = new Dog(DateTime.Now, "TestL", "TestD", "12ab");
Owner owner = new Owner("1", "TestOwner");
double amountDays = (DateTime.Today - dog.GetFoundDate()).TotalDays;
double payAmount = 10+2*amountDays;
shelter.AddAnimal(dog);
shelter.AddOwner(owner);
dog.Adopt(owner);
dog.checkIn();
//Act
double check = dog.Claim(owner);
double checkfail = dog.Claim(owner);
//Assert
Assert.AreEqual(payAmount, check);
Assert.AreEqual(-1, checkfail);
}
}
}
|
3ebd8cb49d483f34f86aed66483e4f4da3cb5b1c
|
C#
|
manojbhargavan/AzureSamples
|
/Storage/AzureStorageWrapper/Helper/TableHelper.cs
| 3.015625
| 3
|
using Microsoft.Azure.Cosmos.Table;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AzureStorageWrapper.Helper
{
public class TableHelper
{
private readonly CloudStorageAccount cloudStorageAccount;
public TableHelper()
{
cloudStorageAccount = CloudStorageAccount.Parse(Constants.StorageAccountConnectionString);
}
public CloudTable CreateTable(string tableName)
{
CloudTableClient tableClient = cloudStorageAccount.CreateCloudTableClient();
CloudTable tableReference = tableClient.GetTableReference(tableName);
if (tableReference.CreateIfNotExists())
Console.WriteLine("Table created");
else
Console.WriteLine("Table exits");
return tableReference;
}
public T InsertEntity<T>(CloudTable table, T entity) where T : TableEntity
{
TableOperation tableOperation = TableOperation.InsertOrMerge(entity);
TableResult tableResult = table.Execute(tableOperation);
T insertedT = tableResult.Result as T;
if (tableResult.RequestCharge.HasValue)
{
Console.WriteLine("Request Charge of InsertOrMerge Operation: " + tableResult.RequestCharge);
}
return insertedT;
}
}
}
|
01663226de5160c74442a083575235b952636553
|
C#
|
LimaGustav/SENAI_HROADS_WEBAPI
|
/Back-End/hroads/senai.hroads.WebApi/senai.hroads.WebApi/Interfaces/ITipoHabilidadeRepository.cs
| 2.734375
| 3
|
using senai.hroads.webApi.Domains;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace senai.hroads.webApi.Interfaces
{
interface ITipohabilidadeRepository
{
/// <summary>
/// Lista todos os Tipos de habilidades
/// </summary>
/// <returns>Uma lista de Tipos de habilidades</returns>
List<Tipohabilidade> Listar();
/// <summary>
/// Busca um Tipo de habilidade através do id
/// </summary>
/// <param name="idTipohabilidade">ID do Tipo de habilidade a ser buscado</param>
/// <returns>Um Tipo de habilidade buscado</returns>
Tipohabilidade BuscarPorId(int idTipohabilidade);
/// <summary>
/// Cadastrar um novo Tipohabilidade
/// </summary>
/// <param name="novoTipohabilidade">Objeto novaTipohabilidade com os dados que serão cadastrados</param>
void Cadastrar(Tipohabilidade novoTipohabilidade);
/// <summary>
/// Atualiza um Tipohabilidade existente
/// </summary>
/// <param name="idTipohabilidade">ID do Tipohabilidade que será atualizado</param>
/// <param name="TipohabilidadeAtualizada">Objeto TipohabilidadeAtualizada com as novas informações</param>
void Atualizar(int idTipohabilidade, Tipohabilidade TipohabilidadeAtualizada);
/// <summary>
/// Deleta um Tipo de habilidade existente
/// </summary>
/// <param name="idTipohabilidade">ID do Tipohabilidade que será deletado</param>
void Deletar(int idTipohabilidade);
}
}
|
66045a94c68f19ed28a83f050a90cd08438403c9
|
C#
|
kensh3/NWT
|
/AngularPractice/ActivityLibrary/CarCodeActivity/CreateCarCodeActivity.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using EntityModel;
using DataContract;
namespace ActivityLibrary.CarCodeActivity
{
public sealed class CreateCarCodeActivity : CodeActivity
{
private DatabaseEntities1 db = new DatabaseEntities1();
// Define an activity input argument of type string
public InArgument<CarRequest> CarReq { get; set; }
public OutArgument<int> CreatedCarId { get; set; }
// If your activity returns a value, derive from CodeActivity<TResult>
// and return the value from the Execute method.
protected override void Execute(CodeActivityContext context)
{
// Obtain the runtime value of the Text input argument
CarRequest carRequest = context.GetValue(this.CarReq);
Car car = new Car();
car.Id = carRequest.Id;
car.Name = carRequest.Name;
car.Type = carRequest.Type;
car.Year = carRequest.Year;
Car createdCar = db.Cars.Add(car);
db.SaveChanges();
CreatedCarId.Set(context, createdCar.Id);
}
}
}
|
39dacc844504fa53a2c32b29bbb8c8446c768179
|
C#
|
mattmc3/TSqlScriptExtractor
|
/TSqlScriptExtractor/RefreshSqlScripts.cs
| 2.5625
| 3
|
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common.Extensions;
namespace SqlScriptExtractor {
public class DbLocation {
public string ServerName {
get;
private set;
}
public string DbName {
get;
private set;
}
public DbLocation(string serverName, string dbName) {
this.ServerName = serverName;
this.DbName = dbName;
}
}
public class RefreshSqlScripts {
public IWriter Buffer {
get;
set;
}
private StringBuilder _buf = new StringBuilder();
public RefreshSqlScripts() {
this.Buffer = new StringBuilderWriter(_buf);
}
public void Run(string outpath, IEnumerable<DbLocation> dbs) {
foreach (var db in dbs) {
var scripter = new Scripter(db.ServerName, db.DbName);
RefreshScripts(outpath, scripter.GetTables(), db.DbName, "Tables");
RefreshScripts(outpath, scripter.GetViews(), db.DbName, "Views");
RefreshScripts(outpath, scripter.GetStoredProcedures(), db.DbName, "Stored Procedures");
RefreshScripts(outpath, scripter.GetUserDefinedFunctions(), db.DbName, "Functions");
}
}
private void RefreshScripts(string outpath, IEnumerable<SqlObject> objects, string db, string objectType) {
var scripts = new List<string>();
var basePath = Path.Combine(outpath, @"{0}\Create Scripts".FormatWith(db));
var scriptDir = Path.Combine(basePath, objectType);
if (!Directory.Exists(scriptDir)) {
Directory.CreateDirectory(scriptDir);
}
foreach (var item in objects) {
this.Buffer.WriteLine("Writing {0}: {1}", objectType, item.Name);
var filePath = Path.Combine(scriptDir, item.Schema.Replace("\\", "_") + "." + item.Name + ".sql");
if (item.Name.StartsWith("_")) {
if (File.Exists(filePath)) File.Delete(filePath);
continue;
}
scripts.Add(filePath);
File.WriteAllText(filePath, item.SqlDefinition);
}
var deletedScripts = (from fp in Directory.GetFiles(scriptDir, "*.sql") where !scripts.Contains(fp) select fp);
if (deletedScripts.Count() > 0) {
this.Buffer.WriteLine("---- DELETED SCRIPTS -----");
this.Buffer.WriteLine(String.Join(Environment.NewLine, deletedScripts));
}
}
}
}
|
d7cc16575dc015c13d125bf173f32fcdcabf0e1d
|
C#
|
FreekDS/Portforward-tool
|
/PortForwardTool/FirewallDevice.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Security.Policy;
using NetFwTypeLib;
namespace PortForwardTool
{
class FirewallDevice
{
readonly INetFwPolicy2 firewallPolicy;
List<INetFwRule> createdRules = new List<INetFwRule>();
readonly Dictionary<int, INetFwRule> createdRules2 = new Dictionary<int, INetFwRule>();
public FirewallDevice()
{
firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(
Type.GetTypeFromProgID("HNetCfg.FwPolicy2")
);
}
public void AllowPort(int port)
{
if(createdRules2.ContainsKey(port)) return;
INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(
Type.GetTypeFromProgID("HNetCfg.FWRule")
);
firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
firewallRule.Description = "Rule created by the portforwarding tool. Allows traffic on port " + port.ToString();
firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
firewallRule.Enabled = true;
firewallRule.InterfaceTypes = "All";
firewallRule.Name = "_Opened port " + port.ToString() + " by portforwarding tool";
firewallRule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
firewallRule.RemotePorts = port.ToString();
firewallRule.LocalPorts = port.ToString();
firewallPolicy.Rules.Add(firewallRule);
createdRules2[port] = firewallRule;
}
public void RemoveRule(int port)
{
if (!createdRules2.ContainsKey(port)) return;
INetFwRule rule = createdRules2[port];
firewallPolicy.Rules.Remove(rule.Name);
createdRules2.Remove(port);
}
~FirewallDevice()
{
foreach(int port in createdRules2.Keys)
{
RemoveRule(port);
}
}
}
}
|
f7fac8f423ea7edd3b53828778100f7bc50653eb
|
C#
|
dkhwang118/CIS575_Spring19_HW6
|
/CIS575_HW6/CIS575_HW6/Program.cs
| 3.09375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CIS575_HW6
{
class Program
{
static void Main(string[] args)
{
/// Main Run Begin
int[] PRI_array100 = GenerateRndArray(100);
int[] PRI_array1k = GenerateRndArray(1000);
int[] PRI_array10k = GenerateRndArray(10000);
int[] AOI_array100 = GenerateAlmstOrderedArray(100);
int[] AOI_array1k = GenerateAlmstOrderedArray(1000);
int[] AOI_array10k = GenerateAlmstOrderedArray(10000);
Console.WriteLine("PRI_100 = {0} swaps", InsertionSort(PRI_array100));
Console.WriteLine("PRI_1k = {0} swaps", InsertionSort(PRI_array1k));
Console.WriteLine("PRI_10k = {0} swaps", InsertionSort(PRI_array10k));
Console.WriteLine("AOI_100 = {0} swaps", InsertionSort(AOI_array100));
Console.WriteLine("AOI_1k = {0} swaps", InsertionSort(AOI_array1k));
Console.WriteLine("AOI_10k = {0} swaps\n", InsertionSort(AOI_array10k));
PRI_array100 = GenerateRndArray(100);
PRI_array1k = GenerateRndArray(1000);
PRI_array10k = GenerateRndArray(10000);
AOI_array100 = GenerateAlmstOrderedArray(100);
AOI_array1k = GenerateAlmstOrderedArray(1000);
AOI_array10k = GenerateAlmstOrderedArray(10000);
Console.WriteLine("PRI_100 = {0} swaps", HeapSortSift(PRI_array100));
Console.WriteLine("PRI_1k = {0} swaps", HeapSortSift(PRI_array1k));
Console.WriteLine("PRI_10k = {0} swaps", HeapSortSift(PRI_array10k));
Console.WriteLine("AOI_100 = {0} swaps", HeapSortSift(AOI_array100));
Console.WriteLine("AOI_1k = {0} swaps", HeapSortSift(AOI_array1k));
Console.WriteLine("AOI_10k = {0} swaps\n", HeapSortSift(AOI_array10k));
PRI_array100 = GenerateRndArray(100);
PRI_array1k = GenerateRndArray(1000);
PRI_array10k = GenerateRndArray(10000);
AOI_array100 = GenerateAlmstOrderedArray(100);
AOI_array1k = GenerateAlmstOrderedArray(1000);
AOI_array10k = GenerateAlmstOrderedArray(10000);
Console.WriteLine("PRI_100 = {0} swaps", HeapSortPercolate(PRI_array100));
Console.WriteLine("PRI_1k = {0} swaps", HeapSortPercolate(PRI_array1k));
Console.WriteLine("PRI_10k = {0} swaps", HeapSortPercolate(PRI_array10k));
Console.WriteLine("AOI_100 = {0} swaps", HeapSortPercolate(AOI_array100));
Console.WriteLine("AOI_1k = {0} swaps", HeapSortPercolate(AOI_array1k));
Console.WriteLine("AOI_10k = {0} swaps", HeapSortPercolate(AOI_array10k));
Console.ReadLine();
/// InsetionSort; Returns number of swaps performed on array
int InsertionSort(int[] arr)
{
int numOfSwaps = 0;
for (int i = 0; i < (arr.Length); i++)
{
int j = i;
while (j > 0 && (arr[j] < arr[j - 1]))
{
int temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
numOfSwaps++;
j--;
}
}
return numOfSwaps;
}
/// Generates a pseduo-random array of size size;
int[] GenerateRndArray(int size)
{
int[] returnArray = new int[size];
for (int i = 0; i < size; i++)
{
returnArray[i] = (13 * i) % size;
}
return returnArray;
}
int[] GenerateAlmstOrderedArray(int size)
{
int[] returnArray = new int[size];
for (int i = 0; i < size; i++)
{
if (i % 13 != 12)
{
returnArray[i] = i;
}
else
{
returnArray[i] = (i + 13) % size;
}
}
return returnArray;
}
/// HeapSort using SIFT on an integer array
int HeapSortSiftBasic(int[] arr)
{
int numOfSwaps = 0;
int lowestParent = (arr.Length - 2) / 2;
bool isEven = arr.Length % 2 == 0 ? true : false;
for (int i = 0; i < lowestParent + 1; i++)
{
int parentVal = arr[i];
int LCval = arr[(i * 2) + 1];
int RCval = (((i * 2) + 2) > arr.Length - 1) ? -1 : arr[(i * 2) + 2];
if (LCval > parentVal && RCval > parentVal)
{
if (LCval > RCval)
{
arr[i] = LCval;
arr[(i * 2) + 1] = parentVal;
}
else
{
arr[i] = RCval;
arr[(i * 2) + 2] = parentVal;
}
numOfSwaps++;
}
else
{
if (LCval > parentVal)
{
arr[i] = LCval;
arr[(i * 2) + 1] = parentVal;
numOfSwaps++;
}
else if (RCval > parentVal)
{
arr[i] = RCval;
arr[(i * 2) + 2] = parentVal;
numOfSwaps++;
}
}
}
return numOfSwaps;
}
int HeapSortSift(int[] arr)
{
int currentRunSwaps;
int totalSwaps = 0;
do
{
currentRunSwaps = HeapSortSiftBasic(arr);
totalSwaps += currentRunSwaps;
} while (currentRunSwaps > 0);
return totalSwaps;
}
/// HeapSort using PERCOLATE on an integer array
int HeapSortPercolateBasic(int[] arr)
{
int numOfSwaps = 0;
for (int i = arr.Length-1; i > 0; i--)
{
if (arr[i] > arr[(i - 1) / 2])
{
int temp = arr[i];
arr[i] = arr[(i - 1) / 2];
arr[(i - 1) / 2] = temp;
numOfSwaps++;
}
}
return numOfSwaps;
}
int HeapSortPercolate(int[] arr)
{
int currentRunSwaps;
int totalSwaps = 0;
do
{
currentRunSwaps = HeapSortPercolateBasic(arr);
totalSwaps += currentRunSwaps;
} while (currentRunSwaps > 0);
return totalSwaps;
}
}
}
}
|
6ffc4a08e905e4e576cfe26efc3bb85a92d75864
|
C#
|
pirocorp/Programming-Basics
|
/Loops/Histogram/Histogram.cs
| 3.53125
| 4
|
using System;
namespace Histogram
{
class Histogram
{
static void Main(string[] args)
{
double n = double.Parse(Console.ReadLine());
int p1 = 0;
int p2 = 0;
int p3 = 0;
int p4 = 0;
int p5 = 0;
int x;
for (int i = 0; i < n; i++)
{
x = int.Parse(Console.ReadLine());
if (x < 200) p1++;
else if (x >= 200 && x < 400) p2++;
else if (x >= 400 && x < 600) p3++;
else if (x >= 600 && x < 800) p4++;
else if (x >= 800 && x <= 1000) p5++;
}
double percent1 = p1 / n * 100;
double percent2 = p2 / n * 100;
double percent3 = p3 / n * 100;
double percent4 = p4 / n * 100;
double percent5 = p5 / n * 100;
Console.WriteLine($"{percent1:f2}%");
Console.WriteLine($"{percent2:f2}%");
Console.WriteLine($"{percent3:f2}%");
Console.WriteLine($"{percent4:f2}%");
Console.WriteLine($"{percent5:f2}%");
int l = 3, y = 4;
double z;
z = l * 100 / y ;
Console.WriteLine(z);
}
}
}
|
c770f5f6909766371d994a332c4ac65648b0f79d
|
C#
|
mattmemmesheimer/patience
|
/Solitaire/Solitaire.Common/Factories/SolitaireGameInstanceFactory.cs
| 2.9375
| 3
|
using Solitaire.Common.Models;
namespace Solitaire.Common.Factories
{
/// <summary>
/// Factory class used to create instances of <see cref="ISolitaireGameInstance"/>.
/// </summary>
public class SolitaireGameInstanceFactory : ISolitaireGameInstanceFactory
{
/// <summary>
/// Creates a concrete instance of <see cref="ISolitaireGameInstance"/>.
/// </summary>
/// <returns>Instance of a solitaire game.</returns>
public ISolitaireGameInstance CreateGameInstance()
{
IDeckFactory deckFactory = new StandardDeckFactory();
IDeck deck = deckFactory.CreateDeck();
ISolitaireGameInstance gameInstance = new SolitaireGameInstance(deck);
return gameInstance;
}
}
}
|
beb4b916c37b1a2287503fcc59832662a699e588
|
C#
|
k-o-t-n/SfwFootball
|
/Sfw.Football/Generators/TeamGenerator.cs
| 3.078125
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using Sfw.Football.DataAccess.Entities;
using Sfw.Football.ExtensionMethods;
using Sfw.Football.Helpers;
namespace Sfw.Football.Generators
{
public class TeamGenerator : ITeamGenerator
{
private readonly IShuffler _shuffler;
public TeamGenerator(IShuffler shuffler)
{
_shuffler = shuffler;
}
public Tuple<IEnumerable<Player>, IEnumerable<Player>> GenerateTeams(List<Player> selectedPlayers)
{
int halfCount = (int)Math.Ceiling((decimal)selectedPlayers.Count / 2);
decimal totalSum = selectedPlayers.Sum(p => (decimal)p.PointsPerGame);
decimal target = decimal.Divide(totalSum, 2);
List<IEnumerable<Player>> team1combinations = selectedPlayers.Combinations(halfCount).ToList();
List<Tuple<IEnumerable<Player>, IEnumerable<Player>>> solutions = new List<Tuple<IEnumerable<Player>, IEnumerable<Player>>>();
decimal bestDifferential = -1;
foreach (var team1 in team1combinations.Select(p => p.ToList()))
{
var team1Temp = team1;
decimal team1Score = team1Temp.Sum(p => (decimal)p.PointsPerGame);
var team2Temp = selectedPlayers.Except(team1Temp).ToList();
decimal team2Score = team2Temp.Sum(p => (decimal)p.PointsPerGame);
decimal totalDifferential = Math.Abs(team1Score - target) + Math.Abs(team2Score - target);
if (bestDifferential == -1 || totalDifferential <= bestDifferential)
{
if (totalDifferential < bestDifferential)
// Everything found so far is not a solution, so wipe the list
solutions = new List<Tuple<IEnumerable<Player>, IEnumerable<Player>>>();
solutions.Add(new Tuple<IEnumerable<Player>, IEnumerable<Player>>(team1Temp, team2Temp));
bestDifferential = totalDifferential;
}
}
_shuffler.Shuffle(solutions);
return solutions.First();
}
}
}
|
893aca4a758f342ede161ca0d9cd98acb663c919
|
C#
|
pablovdelrio/MaD-pr-cticas
|
/MaDPractica/Model/ProductDao/ProductDaoEntityFramework.cs
| 2.640625
| 3
|
using Es.Udc.DotNet.ModelUtil.Dao;
using Es.Udc.DotNet.ModelUtil.Exceptions;
using System;
using System.Data.Common;
using System.Linq;
namespace Es.Udc.DotNet.MaDPractica.Model.ProductDao
{
/// <summary>
/// Specific Operations for Product
/// </summary>
public class ProductDaoEntityFramework :
GenericDaoEntityFramework<Product, Decimal>, IProductDao
{
#region Public Constructors
/// <summary>
/// Public Constructor
/// </summary>
public ProductDaoEntityFramework()
{
}
#endregion Public Constructors
#region IUserProfileDao Members. Specific Operations
/// <summary>
/// Finds a Cosumer by his product_id
/// </summary>
/// <param product="product_id"></param>
/// <returns></returns>
/// <exception cref="InstanceNotFoundException"></exception>
public Product FindByProductId(Decimal product_id)
{
Product product = null;
#region Option 2: Using eSQL over dbSet
string sqlQuery = "Select * FROM Product where product_id=@product_id";
DbParameter product_idParameter =
new System.Data.SqlClient.SqlParameter("product_id", product_id);
product = Context.Database.SqlQuery<Product>(sqlQuery, product_idParameter).FirstOrDefault<Product>();
#endregion Option 2: Using eSQL over dbSet
if (product == null)
throw new InstanceNotFoundException(product_id,
typeof(Product).FullName);
return product;
}
#endregion IProductDao Members
}
}
|
a70ab309b8fef5604d07843ee631bf81f300f53e
|
C#
|
ogunsoladebayo/dotNET-C-Square-root-Web-Calculator
|
/Controllers/SquareRootController.cs
| 2.90625
| 3
|
using Microsoft.AspNetCore.Mvc;
using System;
namespace Task4.Controllers
{
public class SquareRootController : Controller
{
[HttpGet]
public ActionResult Sqroot()
{
return View();
}
[HttpPost]
public ActionResult Sqroot(string firstNumber, string secondNumber)
{
// string result = "";
int FirstNumber = int.Parse(firstNumber);
int SecondNumber = int.Parse(secondNumber);
if (FirstNumber > 0 && SecondNumber > 0)
{
double rootFirstNum = Math.Sqrt(FirstNumber);
double rootSecondNum = Math.Sqrt(SecondNumber);
ViewBag.firstRoot = rootFirstNum;
ViewBag.secondRoot = rootSecondNum;
}
else
{
ViewBag.Result = true;
}
// if(rootFirstNum > rootSecondNum){
// string result = ("The number " + FirstNumber + " with Square root " + rootFirstNum + " has a higher square root than the number " + SecondNumber + " with square root " + rootSecondNum);
// return result;
// }
// if(rootFirstNum < rootSecondNum){
// string result = ("The number " + SecondNumber + " with Square root " + rootSecondNum + " has a higher square root than the number " + FirstNumber + " with square root " + rootFirstNum);
// return result;
// }
ViewBag.firstNum = FirstNumber;
ViewBag.secondNum = SecondNumber;
return View();
}
}
}
|
6b482ddf7d06bb63c6aaeae753cb8d84c2b54e5c
|
C#
|
cwt-test/UnmanagedThreadUtils-fork
|
/examples/UnmanagedThreadUtils.Examples/Program.cs
| 3.171875
| 3
|
namespace UnmanagedThreadUtils.Examples
{
using System;
using System.Runtime.InteropServices;
using System.Threading;
/// <summary>
/// Example.
/// </summary>
public static class Program
{
private const int ThreadCount = 3;
// Use static field to make sure that delegate is alive.
private static readonly UnmanagedThread.ThreadExitCallback ThreadExitCallbackDelegate = OnThreadExit;
private static readonly CountdownEvent UnmanagedThreadsExitEvent = new CountdownEvent(ThreadCount);
/// <summary>
/// Entry point.
/// </summary>
public static void Main()
{
var threadExitCallbackDelegatePtr = Marshal.GetFunctionPointerForDelegate(ThreadExitCallbackDelegate);
var callbackId = UnmanagedThread.SetThreadExitCallback(threadExitCallbackDelegatePtr);
for (var i = 1; i <= ThreadCount; i++)
{
var threadLocalVal = i;
var thread = new Thread(_ =>
{
Console.WriteLine($"Managed thread #{threadLocalVal} started.");
UnmanagedThread.EnableCurrentThreadExitEvent(callbackId, new IntPtr(threadLocalVal));
Thread.Sleep(100);
Console.WriteLine($"Managed thread #{threadLocalVal} ended.");
});
thread.Start();
}
UnmanagedThreadsExitEvent.Wait();
Console.WriteLine("All unmanaged threads have exited.");
UnmanagedThread.RemoveThreadExitCallback(callbackId);
}
private static void OnThreadExit(IntPtr data)
{
Console.WriteLine($"Unmanaged thread #{data.ToInt64()} is exiting.");
UnmanagedThreadsExitEvent.Signal();
}
}
}
|
cbba11ea3ed1f89830f0034a5025d98c20363088
|
C#
|
SinaC/TetriNET
|
/TetriNET.Client.Achievements/Achievements/Base/SpecialCountBase.cs
| 2.671875
| 3
|
using TetriNET.Client.Interfaces;
using TetriNET.Common.DataContracts;
namespace TetriNET.Client.Achievements.Achievements.Base
{
internal abstract class SpecialCountBase : AchievementBase
{
private int _count;
public abstract Specials Special { get; }
public abstract int CountToAchieve { get; }
public override void Reset()
{
_count = 0;
base.Reset();
}
public override void OnUseSpecial(int playerId, string playerTeam, IReadOnlyBoard playerBoard, int targetId, string targetTeam, IReadOnlyBoard targetBoard, Specials special)
{
if (special == Special)
{
_count++;
if (_count == CountToAchieve)
Achieve();
}
}
}
}
|
6acd02b2a0aa91568a626caf01bd800295336fad
|
C#
|
sakaat/AtCoder
|
/abs/abc081_a.cs
| 2.5625
| 3
|
// https://atcoder.jp/contests/abs/submissions/7035193
using System;
using System.Linq;
class Program
{
static void Main()
{
var input = Console.ReadLine();
Console.WriteLine(input.Count(c => c == '1'));
}
}
|
c7ccc3da95ecf1d7210730f4303dd0ed944ee231
|
C#
|
mantunes27/UnitTestInJenkins
|
/GettingStarted/Calculator.Tests/Class1.cs
| 3.15625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace Calculator.Tests
{
[TestFixture]
public class SimpleCalculatorTests
{
[Test]
public void ShouldAddTwoNumbers()
{
var sut = new SimpleCalculator();
var result = sut.Add(1, 2);
Assert.That(result, Is.EqualTo(3));
}
[Test]
public void ShouldMultiplyTwoNumbers()
{
var sut = new SimpleCalculator();
var result = sut.Multiply(2, 10);
Assert.That(result, Is.EqualTo(20));
}
[Test]
public void ShouldAddDouble()
{
var sut = new SimpleCalculator();
var result = sut.AddDoubles(1.1, 2.2);
Assert.That(result, Is.EqualTo(3.3).Within(0.01));
}
[Test]
public void ShouldNotBeBiggerThan100()
{
var sut = new SimpleCalculator();
var result = sut.AddDoubles(1.1, 2.2);
Assert.That(result, Is.Not.GreaterThan(100));
}
[Test]
public void ShouldJoinNames()
{
var sut = new NameJoiner();
var result = sut.Join("Sarah", "Smith");
Assert.That(result, Is.EqualTo("Sarah Smith"));
}
[Test]
public void ShouldJoinName_CaseInsentitiveAssertDemo()
{
var sut = new NameJoiner();
var fullName = sut.Join("sarah", "smith");
Assert.That(fullName, Is.EqualTo("SARAH SMITH").IgnoreCase);
}
[Test]
public void ShouldJoinNames_NotEqualDemo()
{
var sut = new NameJoiner();
var fullName = sut.Join("Sarah", "Smith");
Assert.That(fullName, Is.Not.EqualTo("Gentry Smith"));
}
}
}
|
86ec2144dee9d08c389a14c54f57048d79a3ba29
|
C#
|
Rbatts/supportbank
|
/ConsoleApp8/supportbank.cs
| 2.609375
| 3
|
using Newtonsoft.Json;
using NLog;
using NLog.Config;
using NLog.Targets;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Threading;
using System.Text;
using System.Threading.Tasks;
using NLog.LayoutRenderers.Wrappers;
using System.Xml;
using System.IO;
namespace supportbank
{
class Program
{
private static readonly ILogger logger = LogManager.GetCurrentClassLogger();
public static void Main(string[] args)
{
var config = new LoggingConfiguration();
var target = new FileTarget { FileName = @"C:\Work\Logs\SupportBank.log", Layout = @"${longdate} ${level} - ${logger}: ${message}" };
config.AddTarget("File Logger", target);
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, target));
LogManager.Configuration = config;
logger.Log(LogLevel.Info, "Program starting");
string path = @"C:\Users\Rich\test\supportproject\Transactions2014.csv";
string textFromFile = System.IO.File.ReadAllText(path);
logger.Log(LogLevel.Info, "2014 transaction Files uploaded");
textFromFile = textFromFile.ToLower();
string path2 = @"C: \Users\Rich\Downloads\dodgy transactions.csv";
string textFromFile2 = System.IO.File.ReadAllText(path2);
logger.Log(LogLevel.Info, "Dodgy Files uploaded");
textFromFile2 = textFromFile2.ToLower();
string path3 = @"C: \Users\Rich\Downloads\Transactions2013.json";
string textFromFile3 = System.IO.File.ReadAllText(path3);
textFromFile3 = textFromFile3.ToLower();
var transactions = JsonConvert.DeserializeObject<List<Transaction>>(textFromFile3);
List<Person> employees = new List<Person>();
foreach (var transaction in transactions)
{
Console.WriteLine(transaction.date + " " + transaction.fromAccount + " " + transaction.toAccount + " " + transaction.narrative + " " + transaction.amount);
}
string[] lines = System.IO.File.ReadAllLines(path2);
for (int i = 1; i < lines.Length; i = i + 1)
{
try
{
string[] line = lines[i].Split(',');
string date = line[0];
string from = line[1];
string to = line[2];
string narrative = line[3];
decimal amount = decimal.Parse(line[4]);
var transaction = new Transaction { date = date, toAccount = to, amount = amount, narrative = narrative, fromAccount = from };
if (!employees.Any(worker => worker.name == from))
{
Person fromPerson = new Person { name = from, balance = -amount };
employees.Add(fromPerson);
fromPerson.transactions.Add(transaction);
}
else
{
Person fromPerson = employees.First(worker => worker.name == from);
fromPerson.balance = fromPerson.balance - amount;
fromPerson.transactions.Add(transaction);
}
if (!employees.Any(worker => worker.name == to))
{
Person toPerson = new Person { name = to, balance = amount };
employees.Add(toPerson);
toPerson.transactions.Add(transaction);
}
else
{
Person toPerson = employees.First(worker => worker.name == to);
toPerson.balance = toPerson.balance + amount;
toPerson.transactions.Add(transaction);
}
}
catch
{
logger.Log(LogLevel.Error, "Error with a line of data file");
logger.Log(LogLevel.Error, lines[i]);
Console.WriteLine("\nError detected. Please check the log file");
}
}
foreach (Person worker in employees)
{
Console.WriteLine(worker.name);
Console.WriteLine(worker.balance);
}
Console.WriteLine("Input employee");
var userInput = Console.ReadLine();
foreach (Person worker in employees)
{
if (userInput.ToLower() == worker.name.ToLower())
{
foreach (Transaction transaction in worker.transactions)
Console.WriteLine(transaction.date + " " + transaction.fromAccount + " " + transaction.toAccount + " " + transaction.narrative + " " + transaction.amount);
}
}
Console.ReadLine();
}
}
}
class Person
{
public string name;
public decimal balance;
public List<Transaction> transactions = new List<Transaction>();
}
class Transaction
{
public string toAccount;
public string fromAccount;
public string date;
public string narrative;
public decimal amount;
}
|
ba9bd57fcca783b0464aa3b660558626a97e5f12
|
C#
|
dyslexicanaboko/simple-class-creator
|
/SimpleClassCreator.Tests/Lib/Services/QueryToClassServiceTests.cs
| 2.6875
| 3
|
using Moq;
using NUnit.Framework;
using SimpleClassCreator.Lib;
using SimpleClassCreator.Lib.DataAccess;
using SimpleClassCreator.Lib.Models;
using SimpleClassCreator.Lib.Services;
using SimpleClassCreator.Tests.DummyObjects;
using System.Linq;
using System.Text.RegularExpressions;
namespace SimpleClassCreator.Tests.Lib.Services
{
[TestFixture]
public class QueryToClassServiceTests
: TestBase
{
[Test]
public void Providing_no_generation_elections_produces_null()
{
//Arrange
var p = new QueryToClassParameters
{
SourceSqlType = SourceSqlType.TableName,
LanguageType = CodeType.CSharp,
Namespace = "SimpleClassCreator.Tests.DummyObjects"
};
var repoQueryToClass = new Mock<IQueryToClassRepository>();
var repoGeneral = new Mock<IGeneralDatabaseQueries>();
var svc = new QueryToClassService(repoQueryToClass.Object, repoGeneral.Object);
//Act
var actual = svc.Generate(p);
//Assert
Assert.IsNull(actual);
}
/*
3. Need to create templates for whatever code it is that I am trying to create
A. Let's create a dummy object that is easy to understand and work off of that
like your rudimentary person object
B. I want templates to be plug and play meaning the user can provide whatever
templates they want so long as they use the appropriate tags
4. I don't like the if (tableName != null) clauses, need to abstract this, let's
pause and see what happens */
[Test]
public void Person_table_produces_person_class()
{
//Arrange
var expected = PersonUtil.PersonClass;
var sq = PersonUtil.GetPersonAsSchemaQuery();
var p = new QueryToClassParameters
{
SourceSqlType = SourceSqlType.TableName,
SourceSqlText = sq.TableQuery.Table,
LanguageType = CodeType.CSharp,
Namespace = "SimpleClassCreator.Tests.DummyObjects",
TableQuery = sq.TableQuery
};
p.ClassOptions.GenerateEntity = true;
p.ClassOptions.ClassEntityName = sq.TableQuery.Table;
var repoQueryToClass = new Mock<IQueryToClassRepository>();
repoQueryToClass.Setup(x => x.GetSchema(p.TableQuery, It.IsAny<string>())).Returns(sq); //TODO: Fix this later
var repoGeneral = new Mock<IGeneralDatabaseQueries>();
var svc = new QueryToClassService(repoQueryToClass.Object, repoGeneral.Object);
//Act
var actual = svc.Generate(p).Single().Contents;
//This is for debug only
//DumpFile("Expected.cs", expected);
//DumpFile("Actual.cs", actual);
//Assert
//Spacing is still an issue, so going to give it a pass for now
AssertAreEqualIgnoreWhiteSpace(expected, actual);
}
//This is for debug only
private void DumpFile(string fileName, string contents)
{
System.IO.File.WriteAllText(@"C:\Dump\" + fileName, contents);
}
private void AssertAreEqualIgnoreWhiteSpace(string expected, string actual)
{
var re = new Regex(@"\s+");
expected = re.Replace(expected, string.Empty);
actual = re.Replace(actual, string.Empty);
Assert.AreEqual(expected, actual);
}
}
}
|
368c00db866917464f55c1217c2c03f433fefecb
|
C#
|
ashyrokoriadov/Statistics
|
/Statistics/Implementations/BinominalDistribution/BinominalDistributionFloat.cs
| 2.953125
| 3
|
using System;
using System.Linq;
using Statistics.IntegralCalculus;
namespace Statistics.Implementations
{
class BinominalDistributionFloat : CalculationBinominalDistributionBase
{
float p;
public BinominalDistributionFloat(int n, int x, float p)
{
this.n = n;
this.x = x;
this.p = p;
}
public override object GetStandardDeviation()
{
return (float)Math.Sqrt(n * p * (1 - p));
}
public override object GetVariance()
{
return (float)(n * p * (1 - p));
}
public override object GetProbability()
{
float result = GetCombinationNumber(n, x) * (float)Math.Pow(p, x) * (float)Math.Pow((1 - p), (n - x));
return (float)Math.Round(result, 3);
}
public override object GetProbabilityRange(object range)
{
if (!IsFloatArray(range))
throw new ArgumentException(ERROR_ARGUMENT_FLOAT_ARRAY);
float[] array = (float[])range;
float result = array.Select(item =>
{
BinominalDistributionFloat bdf = new BinominalDistributionFloat(n, Convert.ToInt32(item), p);
return Convert.ToSingle(bdf.GetProbability());
}).ToArray().Sum();
return result;
}
public override object GetProbabilityReverse(double criterion)
{
double calculatedCriterion = 1;
int startPosition = n;
BinominalDistribution bd;
while (calculatedCriterion > criterion)
{
bd = new BinominalDistribution(n, n, p);
calculatedCriterion = Math.Round(Convert.ToDouble(bd.GetCumulativeDistribution(startPosition)), 2);
startPosition--;
}
return Convert.ToSingle(startPosition += 2);
}
public override object GetCumulativeDistribution(int criterion)
{
float sum = 0;
for (int i = 0; i <= criterion; i++)
{
BinominalDistribution bd = new BinominalDistribution(n, i, p);
sum += Convert.ToSingle(bd.GetProbability());
}
return sum;
}
public override object GetCombinationNumber()
{
return GetFactorial(n) / (GetFactorial(x) * GetFactorial(n - x));
}
public override object GetMean()
{
return n * p;
}
private float GetFactorial(float y)
{
float f = 1;
for (int i = 1; i <= y; i++)
{
f *= i;
}
return f;
}
private float GetCombinationNumber(float n, float x)
{
return GetFactorial(n) / (GetFactorial(x) * GetFactorial(n - x));
}
public override object GetHypothesisTestingForPercentage(object p0, out object lessThan, out object greaterThan)
{
if (!IsFloat(p0))
throw new ArgumentException(ERROR_ARGUMENT_FLOAT);
float z = ((float)p0 - p) / Convert.ToSingle(Math.Sqrt(p * (1 - p) / n));
SimpsonMethod sm1 = new SimpsonMethod(-3.6, Convert.ToDouble(z), 30000, zFunction);
lessThan = (1 / Math.Sqrt(2 * Math.PI)) * sm1.GetResult();
SimpsonMethod sm2 = new SimpsonMethod(Convert.ToDouble(z), 3.6, 30000, zFunction);
greaterThan = (1 / Math.Sqrt(2 * Math.PI)) * sm2.GetResult();
return z;
}
double zFunction(double x)
{
return Math.Pow(Math.E, -(Math.Pow(x, 2) / 2));
}
}
}
|
172f6f6fa6ff67841ea2c2641098bfb57d92146f
|
C#
|
yavorvasilev/CSharp-Advanced
|
/FunctionalProgrammingExercises/04FindEvensOrOdds/FindEvensOrOdds.cs
| 4.15625
| 4
|
namespace _04FindEvensOrOdds
{
using System;
public class FindEvensOrOdds
{
public static void Main()
{
var rangeOfNumbers = Console.ReadLine().Split();
var oddOrEven = Console.ReadLine();
var lowerBound = int.Parse(rangeOfNumbers[0]);
var upperBound = int.Parse(rangeOfNumbers[1]);
Predicate<int> isEven = delegate (int a) { return a % 2 == 0; };
Predicate<int> isOdd = delegate (int a) { return a % 2 != 0; };
if (oddOrEven == "even")
{
for (int i = lowerBound; i <= upperBound; i++)
{
var number = i;
if (isEven(number))
{
Console.Write("{0} ", number);
}
}
}
else if (oddOrEven == "odd")
{
for (int i = lowerBound; i <= upperBound; i++)
{
var number = i;
if (isOdd(number))
{
Console.Write("{0} ", number);
}
}
}
Console.WriteLine();
}
}
}
|
f936abb2b105c819cdc10b68672eb97a8e523906
|
C#
|
BluetextDC/vectornav
|
/WebApp/Common/GeneralFun.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
namespace SitefinityWebApp.Common
{
public static class GeneralFun
{
private static string cnnStr = System.Configuration.ConfigurationManager.ConnectionStrings["Sitefinity"].ToString();
public static void ExecQuery(string query)
{
SqlConnection cnn = new SqlConnection(cnnStr);
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnn;
cmd.CommandText = query;
cmd.ExecuteNonQuery();
cnn.Close();
}
public static DataTable GetData(string query)
{
DataTable dt= new DataTable();
SqlConnection cnn = new SqlConnection(cnnStr);
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnn;
cmd.CommandText = query;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
cmd.ExecuteNonQuery();
cnn.Close();
return dt;
}
}
}
|
1bae6896fe3896ce3b08835023eda6a42ed726f4
|
C#
|
ibrahimbilgic/Csharp-Examples
|
/Donusum/Program.cs
| 3.328125
| 3
|
using System;
namespace Donusum
{
class Program
{
static void Main(string[] args)
{
double a = 5.4;
int b = (int) a; // explicit donusum..
short s = 6;
b = s; //implicit donusum...
Console.WriteLine(sizeof(short) +"bit");
Console.WriteLine(sizeof(int)+"bit");
Console.WriteLine(sizeof(double)+"bit");
Console.WriteLine("\n");
Kesir k1 = new Kesir(5,4);
k1.yaz();
int a2 = (int)k1;
Console.WriteLine(a2);
Kesir k2 = 3;
k2.yaz();
}
}
}
|
5d658116074572d942cd32b91ed6e9a1c1f9bc12
|
C#
|
lkuznet/BBAssignment
|
/CatalogManager.Persistence/Repositories/UnitOfWork.cs
| 2.75
| 3
|
using CatalogManager.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CatalogManager.Persistence.Repositories
{
public class UnitOfWork : IUnitOfWork
{
private readonly IDataContext _db;
public UnitOfWork(IDataContext context)
{
_db = context;
}
public int SaveChanges()
{
return _db.SaveChanges();
}
public async Task<int> SaveChangesAsync()
{
return await _db.SaveChangesAsync();
}
#region Disposed
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
_db.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
|
196d52c86481da925a5f48fb55fefe6dff1c2c77
|
C#
|
kenemar/PDFPages
|
/App.xaml.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace PDFPages
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
string[] args = Environment.GetCommandLineArgs();
//first arg is executable path
if (args.Length > 1)
{
var action = args[1].ToLower();
switch (action)
{
case "merge":
Merge(args);
App.Current.Shutdown();
return;
case "split":
Split(args);
App.Current.Shutdown();
return;
}
}
}
private void Split(string[] args)
{
for (int i = 2; i < args.Length; i++)
{
if (File.Exists(args[i]))
{
var filePath = Path.GetFullPath(args[i]);
var doc = PdfSharp.Pdf.IO.PdfReader.Open(filePath, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Import);
int cnt = 1;
foreach (var page in doc.Pages)
{
var doc1 = new PdfSharp.Pdf.PdfDocument();
doc1.AddPage(page);
var newFile = filePath.Replace(".pdf", $" ({cnt}).pdf");
doc1.Save(newFile);
cnt++;
}
doc.Close();
}
}
}
private void Merge(string[] args)
{
var outputPath = "";
var doc1 = new PdfSharp.Pdf.PdfDocument();
for (int i = 2; i < args.Length; i++)
{
if (File.Exists(args[i]))
{
var filePath = Path.GetFullPath(args[i]);
if (outputPath == "") outputPath = filePath.Replace(".pdf", $" (Merged).pdf");
var doc = PdfSharp.Pdf.IO.PdfReader.Open(filePath, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Import);
foreach (var page in doc.Pages)
{
doc1.AddPage(page);
}
doc.Close();
}
}
if (outputPath != "") doc1.Save(outputPath);
}
}
}
|
0c8da9434804e2c11387a6c955dc71b26052b248
|
C#
|
yulianiindah96/Tugas-Akhir
|
/deteksi/KMeans.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Collections;
using System.Collections.Specialized;
using tugasakhir;
namespace tugasakhir.deteksi
{
public unsafe class KMeans
{
public class Distance
{
public Distance(float d) { _d = d; }
public float Measure
{
get { return _d; }
set { _d = value; }
}
private float _d;
}
public class Cluster
{
public Cluster(float R, float G, float B)
{
_centroid1 = R;
_centroid2 = G;
_centroid3 = B;
}
public float CentroidR
{
get { return _centroid1; }
set { _centroid1 = value; }
}
public float CentroidG
{
get { return _centroid2; }
set { _centroid2 = value; }
}
public float CentroidB
{
get { return _centroid3; }
set { _centroid3 = value; }
}
private float _centroid1;
private float _centroid2;
private float _centroid3;
}
public KMeans(Bitmap bmp, int numCluster, Colour.Types model)
{
_image = (Bitmap)bmp.Clone();
_processedImage = (Bitmap)bmp.Clone();
_model = model;
_previousCluster = new Dictionary<string, Cluster>();
_currentCluster = new Dictionary<string, Cluster>();
FindTopXColours(numCluster); //find top X colours in the image
//create clusters for top X colours
for (int i = 0; i < _topColours.Length; i++)
{
PixelData pd = Colour.GetPixelData(_topColours[i].R, _topColours[i].G, _topColours[i].B, model);
_previousCluster.Add(_topColours[i].Name, new Cluster(pd.Ch1, pd.Ch2, pd.Ch3));
_currentCluster.Add(_topColours[i].Name, new Cluster(pd.Ch1, pd.Ch2, pd.Ch3));
}
}
public Bitmap ProcessedImage { get { return _processedImage; } }
public bool Converged { get { return _converged; } }
public void Iterate()
{
_colourClusterAllocation = new Hashtable(); //for keeping track of colour<->cluster allocation
_pixelDataClusterAllocation = new Hashtable();
_clusterColours = new Hashtable();
UnsafeBitmap fastBitmap = new UnsafeBitmap(_image);
fastBitmap.LockBitmap();
Point size = fastBitmap.Size;
BGRA* pPixel;
for (int y = 0; y < size.Y; y++)
{
pPixel = fastBitmap[0, y];
for (int x = 0; x < size.X; x++)
{
PixelData pd = Colour.GetPixelData(pPixel, _model);
AllocateToCluster(pd);
//increment the pointer
pPixel++;
}
}
fastBitmap.UnlockBitmap();
CalculateClusterCentroids();
_processedImage = (Bitmap)_image.Clone();
//segment the image based on the cluster
fastBitmap = new UnsafeBitmap(_processedImage);
fastBitmap.LockBitmap();
for (int y = 0; y < size.Y; y++)
{
pPixel = fastBitmap[0, y];
for (int x = 0; x < size.X; x++)
{
PixelData pd = Colour.GetPixelData(pPixel, _model);
Color newClr = (Color)_clusterColours[pd.Name];
pPixel->red = newClr.R;
pPixel->green = newClr.G;
pPixel->blue = newClr.B;
//increment the pointer
pPixel++;
}
}
fastBitmap.UnlockBitmap();
CheckConvergence();
}
private void CheckConvergence()
{
//if current and previous cluster centroids are the same then converged
bool match = true;
foreach (KeyValuePair<string, Cluster> cluster in _currentCluster)
{
if (((int)cluster.Value.CentroidR != (int)_previousCluster[cluster.Key].CentroidR)
&& ((int)cluster.Value.CentroidG != (int)_previousCluster[cluster.Key].CentroidG)
&& ((int)cluster.Value.CentroidB != (int)_previousCluster[cluster.Key].CentroidB))
{
match = false;
break;
}
}
if (!match)
{
foreach (KeyValuePair<string, Cluster> cluster in _currentCluster)
{
_previousCluster[cluster.Key].CentroidR = cluster.Value.CentroidR;
_previousCluster[cluster.Key].CentroidG = cluster.Value.CentroidG;
_previousCluster[cluster.Key].CentroidB = cluster.Value.CentroidB;
}
}
_converged = match;
}
private void CalculateClusterCentroids()
{
foreach (KeyValuePair<string, Cluster> cluster in _currentCluster)
{
List<PixelData> clrList = (List<PixelData>)_pixelDataClusterAllocation[cluster.Key];
float cR = 0;
float cG = 0;
float cB = 0;
foreach (PixelData clr in clrList)
{
cR += clr.Ch1;
cG += clr.Ch2;
cB += clr.Ch3;
if (!_clusterColours.ContainsKey(clr.Name))
{
_clusterColours.Add(clr.Name, Color.FromArgb((int)cluster.Value.CentroidR, (int)cluster.Value.CentroidG, (int)cluster.Value.CentroidB));
}
}
float count = clrList.Count + 1; //total of colours plus 1 for the existing centroid
cluster.Value.CentroidR = (cluster.Value.CentroidR + cR) / count; //average to find new centroid
cluster.Value.CentroidG = (cluster.Value.CentroidG + cG) / count;
cluster.Value.CentroidB = (cluster.Value.CentroidB + cB) / count;
}
}
private void AllocateToCluster(PixelData pd)
{
//find distance of this colour from each cluster centroid
Dictionary<string, Distance> distances = new Dictionary<string, Distance>();
foreach (KeyValuePair<string, Cluster> c in _currentCluster)
{
float d = (float)Math.Sqrt(
(double)Math.Pow((c.Value.CentroidR - pd.Ch1), 2) +
(double)Math.Pow((c.Value.CentroidG - pd.Ch2), 2) +
(double)Math.Pow((c.Value.CentroidB - pd.Ch3), 2)
);
distances.Add(c.Key, new Distance(d));
}
//allocate this colour to the closest cluster based on distance
List<KeyValuePair<string, Distance>> list = new List<KeyValuePair<string, Distance>>();
list.AddRange(distances);
list.Sort(delegate(KeyValuePair<string, Distance> kvp1, KeyValuePair<string, Distance> kvp2)
{ return Comparer<float>.Default.Compare(kvp1.Value.Measure, kvp2.Value.Measure); });
//assign to closest cluster
if (_pixelDataClusterAllocation.ContainsKey(list[0].Key))
{
((List<PixelData>)_pixelDataClusterAllocation[list[0].Key]).Add(pd);
}
else
{
List<PixelData> clrList = new List<PixelData>();
clrList.Add(pd);
_pixelDataClusterAllocation.Add(list[0].Key, clrList);
}
}
private void FindTopXColours(int numColours)
{
Dictionary<string, ColourCount> colours = new Dictionary<string, ColourCount>();
UnsafeBitmap fastBitmap = new UnsafeBitmap(_image);
fastBitmap.LockBitmap();
Point size = fastBitmap.Size;
BGRA* pPixel;
for (int y = 0; y < size.Y; y++)
{
pPixel = fastBitmap[0, y];
for (int x = 0; x < size.X; x++)
{
//get the bin index for the current pixel colour
Color clr = Color.FromArgb(pPixel->red, pPixel->green, pPixel->blue);
if (colours.ContainsKey(clr.Name))
{
((ColourCount)colours[clr.Name]).Count++;
}
else
colours.Add(clr.Name, new ColourCount(clr, 1));
//increment the pointer
pPixel++;
}
}
fastBitmap.UnlockBitmap();
//instantiate using actual colours found - which might be less than numColours
if (colours.Count < numColours)
numColours = colours.Count;
_topColours = new Color[numColours];
List<KeyValuePair<string, ColourCount>> summaryList = new List<KeyValuePair<string, ColourCount>>();
summaryList.AddRange(colours);
summaryList.Sort(delegate(KeyValuePair<string, ColourCount> kvp1, KeyValuePair<string, ColourCount> kvp2)
{ return Comparer<int>.Default.Compare(kvp2.Value.Count, kvp1.Value.Count); });
for (int i = 0; i < _topColours.Length; i++)
{
_topColours[i] = Color.FromArgb(summaryList[i].Value.Colour.R, summaryList[i].Value.Colour.G, summaryList[i].Value.Colour.B);
}
}
private Color[] _topColours;
private Colour.Types _model;
private Dictionary<string, Cluster> _previousCluster;
private Dictionary<string, Cluster> _currentCluster;
private Hashtable _colourClusterAllocation;
private Hashtable _pixelDataClusterAllocation;
private Hashtable _clusterColours;
private bool _converged = false;
private Bitmap _image;
private Bitmap _processedImage;
}
}
|
e3eb264443b9a6c4fb5eefd968d949c40f2be0c1
|
C#
|
MaboUhha/TestTask_itpc
|
/ru.itpc.trial/Data/StorageDataContext.cs
| 2.78125
| 3
|
using ru.itpc.trial.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ru.itpc.trial.Data
{
public class StorageDataContext:DataContext
{
public List<PersonRecord> PersonRecords { get; set; }
public List<DriverLicenseRecord> DriversLicensesRecords { get; set; }
public List<string> Strings { get; set; }
public List<int> Integers { get; set; }
public DateTime LastChange { get; set; }
public StorageDataContext()
{
this.PersonRecords = new List<PersonRecord>();
this.DriversLicensesRecords = new List<DriverLicenseRecord>();
this.Strings = new List<string>();
this.Integers = new List<int>();
this.LastChange = DateTime.Now;
}
public T Get<T>()
{
foreach (PropertyInfo property in this.GetType().GetProperties())
{
if (typeof(T).IsAssignableFrom(property.PropertyType))
return (T)property.GetValue(this);
}
return default(T);
}
}
public class DefaultDataContext
{
static StorageDataContext dataContext = new StorageDataContext();
public static DataContext Instance { get { return dataContext; } }
private DefaultDataContext() { }
}
}
|
3378e5d1919ac6ea3c413be0771f30acf06b8fff
|
C#
|
KaptenJon/ComponentOne-WinForms-Samples
|
/NetFramework/Command/CS/MdiTabs/DirView.cs
| 2.546875
| 3
|
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
namespace MdiTabs
{
/// <summary>
/// Tree view with deferred directory listing
/// </summary>
public class DirView : TreeView
{
private System.Windows.Forms.ImageList imageList1;
private System.ComponentModel.IContainer components;
// filter: a list of file matching patterns
private string[] m_filter;
// used to identify 'placeholder' nodes
static object s_placeholderTag = new object();
// used to identify directories
static object s_directory = new object();
// used to identify files
static object s_file = new object();
// used to identify text files
static object s_document = new object();
// event to edit file
public class EditFileEventArgs : EventArgs
{
public string Path = string.Empty;
public EditFileEventArgs(string path)
{
Path = path;
}
}
public delegate void EditFileEventHandler(object sender, EditFileEventArgs e);
public event EditFileEventHandler EditFile;
public DirView()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(DirView));
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
//
// imageList1
//
this.imageList1.ColorDepth = System.Windows.Forms.ColorDepth.Depth24Bit;
this.imageList1.ImageSize = new System.Drawing.Size(16, 16);
this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
this.imageList1.TransparentColor = System.Drawing.Color.Magenta;
//
// DirView
//
this.ImageIndex = 0;
this.ImageList = this.imageList1;
this.SelectedImageIndex = 0;
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.DirView_KeyDown);
this.AfterCollapse += new System.Windows.Forms.TreeViewEventHandler(this.DirView_AfterCollapse);
this.DoubleClick += new System.EventHandler(this.DirView_DoubleClick);
this.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.DirView_AfterSelect);
this.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.DirView_BeforeExpand);
}
/// <summary>
/// A list of extensions (no dots) to list
/// </summary>
public string[] Filter
{
get { return m_filter; }
set { m_filter = value; }
}
protected override void OnVisibleChanged(EventArgs e)
{
base.OnVisibleChanged(e);
Nodes.Clear();
if (Visible)
{
string[] drives = Directory.GetLogicalDrives();
foreach (string drive in drives)
AddDirNode(Nodes, drive.Substring(0, 2));
}
}
private void AddDirNode(TreeNodeCollection nodes, string dir)
{
// string tstr = Path.GetDirectoryName(dir);
string tstr = Path.GetFileName(dir);
if (tstr != null && tstr.Length > 0)
dir = tstr;
TreeNode tn = new TreeNode(dir);
tn.Tag = s_directory;
tn.ImageIndex = 0;
tn.SelectedImageIndex = 4;
AddPlaceholder(tn);
nodes.Add(tn);
}
private void AddPlaceholder(TreeNode dirNode)
{
TreeNode placeholder = new TreeNode("...");
placeholder.Tag = s_placeholderTag;
dirNode.Nodes.Add(placeholder);
}
private void AddFileNode(TreeNodeCollection nodes, string file)
{
file = Path.GetFileName(file);
TreeNode tn = new TreeNode(file);
string tstr = file.ToLower();
// files matching filter are "documents"
bool doc = false;
foreach (string pattern in m_filter)
{
string pat = pattern;
if (pattern.StartsWith("*"))
pat = pat.Substring(1);
else if (!pattern.StartsWith("."))
pat = "." + pat;
if (tstr.EndsWith(pat))
{
doc = true;
break;
}
}
if (doc)
{
tn.Tag = s_document;
tn.ImageIndex = 3;
tn.SelectedImageIndex = 7;
}
else
{
tn.Tag = s_file;
tn.ImageIndex = 2;
tn.SelectedImageIndex = 6;
}
nodes.Add(tn);
}
private void ListDir(TreeNode parent)
{
try
{
string parentPath = parent.FullPath;
if (!parentPath.EndsWith(PathSeparator))
parentPath = parentPath + PathSeparator;
string[] dirs = Directory.GetDirectories(parentPath);
string path = parent.FullPath;
foreach (string dir in dirs)
{
AddDirNode(parent.Nodes, Path.Combine(path, dir));
}
foreach (string pattern in m_filter)
{
string tstr = pattern;
if (!pattern.StartsWith("*"))
tstr = "*." + pattern;
else if (!pattern.StartsWith("."))
tstr = "." + pattern;
string[] files = Directory.GetFiles(parentPath, pattern);
foreach (string file in files)
AddFileNode(parent.Nodes, file);
}
}
catch
{
// ignore file system access errors.
}
}
private void DirView_BeforeExpand(object sender, System.Windows.Forms.TreeViewCancelEventArgs e)
{
e.Node.Nodes.Clear();
ListDir(e.Node);
if (e.Node.Nodes.Count > 0)
{
e.Node.ImageIndex = 1;
e.Node.SelectedImageIndex = 5;
}
}
private void DirView_AfterCollapse(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
e.Node.ImageIndex = 0;
e.Node.SelectedImageIndex = 4;
}
private void DirView_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
}
private void EditSelectedFile()
{
if (EditFile != null)
{
TreeNode tn = SelectedNode;
if (tn == null || tn.Tag != s_document)
return;
string path = tn.FullPath;
EditFile(this, new EditFileEventArgs(path));
}
}
private void DirView_DoubleClick(object sender, System.EventArgs e)
{
EditSelectedFile();
}
private void DirView_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
TreeNode tn = SelectedNode;
if (tn != null)
if (tn.Tag == s_document)
EditSelectedFile();
else
tn.Expand();
e.Handled = true;
}
}
}
}
|
3526102d787e43b2c2c98159a0e951b43af950d2
|
C#
|
jerry0914/usi_shd1_tools
|
/PC_Tools/CSharp/StressTestGuide/CE_Process.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using OpenNETCF.Desktop.Communication;
using System.IO;
namespace com.usi.shd1_tools.TestGuide
{
class CE_Process
{
//public static readonly String ceCopyPath = System.AppDomain.CurrentDomain.BaseDirectory + "ce_tool\\cecopy.exe";
//public static readonly String workingDirectory = System.AppDomain.CurrentDomain.BaseDirectory + "ce_tool";
private static RAPI rapi = new RAPI();
// public static int CE_Copy(String sourcePath, String destinationPath)
//{
// //dev:/Application/
// int exitcode = -1;
// Process psCE_Copy = new Process();
// //String adbPath = System.AppDomain.CurrentDomain.BaseDirectory + "adb\\adb.exe";
// try
// {
// psCE_Copy.StartInfo = new ProcessStartInfo(ceCopyPath);
// psCE_Copy.StartInfo.WorkingDirectory = workingDirectory;
// psCE_Copy.StartInfo.Arguments = "\"" + sourcePath + " \" dev:" + destinationPath;
// psCE_Copy.StartInfo.CreateNoWindow = true;
// psCE_Copy.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
// psCE_Copy.StartInfo.RedirectStandardOutput = true;
// psCE_Copy.StartInfo.UseShellExecute = false;
// psCE_Copy.Start();
// psCE_Copy.WaitForExit();
// exitcode = psCE_Copy.ExitCode;
// }
// catch
// {
// }
// finally
// {
// if (psCE_Copy != null)
// {
// psCE_Copy.Close();
// }
// }
// return exitcode;
//}
public static bool Connected
{
get
{
if (rapi != null)
{
return rapi.DevicePresent;
}
else
{
return false;
}
}
}
public static void GetFileFormDevice(String SourcePath, String DestinationPath)
{
GetFileFormDevice(SourcePath, DestinationPath, true);
}
public static void GetFileFormDevice(String SourcePath, String DestinationPath, bool Overwrite)
{
if (rapi.DevicePresent)
{
if (!rapi.Connected)
{
rapi.Connect();
}
FileAttributes attr = File.GetAttributes(DestinationPath);
if ((attr & FileAttributes.Directory).Equals(FileAttributes.Directory)) //DestinationPath is a directory
{
DestinationPath = Path.Combine(DestinationPath , Path.GetFileName(SourcePath));
}
rapi.CopyFileFromDevice(DestinationPath, SourcePath, Overwrite);
if (rapi != null && rapi.Connected)
{
rapi.Disconnect();
}
}
}
public static void CopyFileToDevice(String SourcePath, String DestinationPath, bool Overwrite)
{
try
{
if (rapi.DevicePresent)
{
if (!rapi.Connected)
{
rapi.Connect();
}
try
{
RAPI.RAPIFileAttributes rattr = rapi.GetDeviceFileAttributes(DestinationPath);
if ((rattr & RAPI.RAPIFileAttributes.Directory).Equals(RAPI.RAPIFileAttributes.Directory)) //if destination path exist and it's a directory
{
FileAttributes attr = File.GetAttributes(SourcePath);
if (!(attr & FileAttributes.Directory).Equals(FileAttributes.Directory)) //if source path is not a directory.
{
DestinationPath = DestinationPath.TrimEnd('\\') + '\\' + Path.GetFileName(SourcePath); //Append the file name after the destination directory
}
}
}
catch
{
//if destination path is a non-existing file, it's a normal situation, do nothing.
}
rapi.CopyFileToDevice(SourcePath, DestinationPath, Overwrite);
if (rapi != null && rapi.Connected)
{
rapi.Disconnect();
}
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message + " ; \r\n" + ex.StackTrace);
}
}
public static List<String> GetFileList(String sourceFolder, String searchingCriteria)
{
List<String> lstFiles = new List<string>();
if (rapi.DevicePresent)
{
if (!rapi.Connected)
{
rapi.Connect();
}
IEnumerable<FileInformation> files = rapi.EnumerateFiles(Path.Combine(sourceFolder, searchingCriteria));
foreach (var file in files)
{
lstFiles.Add(Path.Combine(sourceFolder, file.FileName));
}
if (rapi != null && rapi.Connected)
{
rapi.Disconnect();
}
}
return lstFiles;
}
public static SYSTEM_INFO GetSystemInfo()
{
SYSTEM_INFO sys_info;
rapi.GetDeviceSystemInfo(out sys_info);
return sys_info;
}
//public static extern IntPtr CeCreateFile(string lpFileName, uint dwDesiredAccess, int dwShareMode, int lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, int hTemplateFile);
// private static void GetFileFromDevice(String SourcePath, String DestinationPath, bool Overwrite)
// {
// this.CheckConnection();
// IntPtr zero = IntPtr.Zero;
// int lpNumberOfbytesRead = 0;
// byte[] lpBuffer = new byte[0x1000];
// zero = CeCreateFile(DestinationPath, 0x80000000, 0, 0, 3, 0x80, 0);
// if (((int) zero) == -1)
// {
// throw new RAPIException("Could not open remote file");
// }
// FileStream stream = new FileStream(SourcePath, Overwrite ? FileMode.Create : FileMode.CreateNew, FileAccess.Write);
// CeReadFile(zero, lpBuffer, 0x1000, ref lpNumberOfbytesRead, 0);
// while (lpNumberOfbytesRead > 0)
// {
// stream.Write(lpBuffer, 0, lpNumberOfbytesRead);
// if (!Convert.ToBoolean(CeReadFile(zero, lpBuffer, 0x1000, ref lpNumberOfbytesRead, 0)))
// {
// CeCloseHandle(zero);
// stream.Close();
// throw new RAPIException("Failed to read device data");
// }
// }
// CeCloseHandle(zero);
// stream.Flush();
// stream.Close();
//}
}
}
|
236d8296ede295d246a3f9a29e0dd3f747e175fe
|
C#
|
lucca450/Devoir-2-ANALYSE
|
/Devoir 2 Analyse/Devoir 2 Analyse/Error.cs
| 3.125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Devoir_2_Analyse
{
public class Error
{
public readonly string errorOrigin = "", expected = "";
private readonly ErrorType errorType;
public Error(ErrorType errorType, string errorOrigin, string expected = "")
{
this.errorType = errorType;
this.errorOrigin = errorOrigin;
this.expected = expected;
}
public void DisplayError()
{
MyConsole.DisplayError(this);
}
public string GetErrorText()
{
switch (true)
{
case true when errorType == ErrorType.MissingCaracter:
return "Un caractère est manquant";
case true when errorType == ErrorType.UndeclaredVariable:
return "La variable n'est pas declarée";
case true when errorType == ErrorType.WrongIdenFormat:
return "Mauvais format d'identificateur";
case true when errorType == ErrorType.WrongKeyword:
return "Mauvais mot clef";
case true when errorType == ErrorType.WrongType:
return "Mauvais type de variable";
case true when errorType == ErrorType.ExpectedKeyword:
return "Mot clef attendu";
case true when errorType == ErrorType.DuplicateKeyword:
return "Mot clef dublique";
case true when errorType == ErrorType.WrongDeclarationFormat:
return "Mauvais format de declaration";
case true when errorType == ErrorType.CantUseReservedKeywords:
return "Vous ne pouvez utiliser de mots clefs reservés";
case true when errorType == ErrorType.VariableNotDeclared:
return "Aucune variable déclarée";
case true when errorType == ErrorType.WrongAssignationFortmat:
return "Mauvais format d'assignation";
case true when errorType == ErrorType.AlreadyDeclaredVariable:
return "Variable déjà déclarée";
}
return "";
}
}
}
|
22448bed0a8fe79bf9fc8aa5f8588bed9e264c7b
|
C#
|
NtreevSoft/CommandLineParser
|
/Ntreev.Library.Commands/TextWriterExtensions.cs
| 2.84375
| 3
|
//Released under the MIT License.
//
//Copyright (c) 2018 Ntreev Soft co., Ltd.
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
//documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
//rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
//persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
//Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
//COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
//OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Ntreev.Library.Commands
{
public static class TextWriterExtensions
{
public static void PrintItems<T>(this TextWriter writer, IEnumerable<T> items)
{
var properties = typeof(T).GetProperties();
var query = from item in properties
where item.PropertyType.IsArray == false
select item;
var headers = from item in query
let displayName = item.GetDisplayName()
select displayName != string.Empty ? displayName : item.Name;
var dataBuilder = new TableDataBuilder(headers.ToArray());
foreach (var item in items)
{
dataBuilder.Add(query.Select(i => i.GetValue(item, null)).ToArray());
}
writer.PrintTableData(dataBuilder.Data, true);
}
public static void Print(this TextWriter writer, TableDataBuilder tableData)
{
PrintTableData(writer, tableData.Data, tableData.HasHeader);
}
public static void PrintTableData(this TextWriter writer, string[][] itemsArray, bool hasHeader)
{
var count = itemsArray.First().Length;
var lengths = new int[count];
for (var x = 0; x < count; x++)
{
var len = 0;
for (var y = 0; y < itemsArray.Length; y++)
{
len = Math.Max(Terminal.GetLength(itemsArray[y][x]), len);
}
lengths[x] = len + (4 - (len % 4));
}
for (var y = 0; y < itemsArray.Length; y++)
{
for (var x = 0; x < itemsArray[y].Length; x++)
{
var pad = lengths[x] - Terminal.GetLength(itemsArray[y][x]);
writer.Write(itemsArray[y][x]);
writer.Write(string.Empty.PadRight(pad));
writer.Write(" ");
}
writer.WriteLine();
if (y != 0 || hasHeader == false)
continue;
for (var x = 0; x < itemsArray[y].Length; x++)
{
var pad = lengths[x];
writer.Write(string.Empty.PadRight(pad, '-'));
writer.Write(" ");
}
writer.WriteLine();
}
}
public static void Print<T>(this TextWriter writer, T[] items)
{
Print<T>(writer, items, (o, a) => a(), item => item.ToString());
}
public static void Print<T>(this TextWriter writer, T[] items, Action<T, Action> action)
{
Print<T>(writer, items, action, item => item.ToString());
}
/// <summary>
/// linux에 ls 명령처럼 단순 문자열을 위에서 아래로 좌에서 우로 정렬해서 출력하는 기능
/// </summary>
public static void Print<T>(this TextWriter writer, T[] items, Action<T, Action> action, Func<T, string> selector)
{
var maxWidth = Terminal.BufferWidth;
var lineCount = 4;
while (true)
{
var lines = new List<string>[lineCount];
var objs = new List<T>[lineCount];
var lengths = new int[lineCount];
var columns = new List<int>();
for (var i = 0; i < items.Length; i++)
{
var y = i % lineCount;
var item = selector(items[i]);
if (lines[y] == null)
{
lines[y] = new List<string>();
objs[y] = new List<T>();
lengths[y] = Terminal.GetLength(item) + 2;
}
else
{
lengths[y] += Terminal.GetLength(item) + 2;
}
var c = lines[y].Count;
lines[y].Add(item);
objs[y].Add(items[i]);
if (columns.Count < lines[y].Count)
columns.Add(0);
columns[c] = Math.Max(columns[c], Terminal.GetLength(item) + 2);
}
var canPrint = true;
for (var i = 0; i < lines.Length; i++)
{
if (lines[i] == null)
continue;
var c = 0;
for (var j = 0; j < lines[i].Count; j++)
{
c += columns[j];
}
if (c >= maxWidth)
canPrint = false;
}
if (canPrint == false)
{
lineCount++;
continue;
}
for (var i = 0; i < lines.Length; i++)
{
if (lines[i] == null)
continue;
for (var j = 0; j < lines[i].Count; j++)
{
var obj = objs[i][j];
var text = lines[i][j].PadRight(columns[j]);
action(obj, () => writer.Write(text));
}
writer.WriteLine();
}
break;
}
}
public static void Print<T>(this TextWriter writer, IDictionary<string, T> items)
{
Print<T>(writer, items, (o, a) => a(), item => $"{item}");
}
public static void Print<T>(this TextWriter writer, IDictionary<string, T> items, Action<T, Action> action)
{
Print<T>(writer, items, action, item => $"{item}");
}
/// <summary>
/// 라벨과 값이 존재하는 아이템을 {0} : {1} 형태로 출력하는 기능
/// </summary>
public static void Print<T>(this TextWriter writer, IDictionary<string, T> items, Action<T, Action> action, Func<T, string> selector)
{
var maxWidth = items.Keys.Max(item => item.Length);
foreach (var item in items)
{
var text = $"{item.Key.PadRight(maxWidth)} : {selector(item.Value)}";
action(item.Value, () => writer.WriteLine(text));
}
}
}
}
|
c1a95429c686180509b614409826ccebe46d81aa
|
C#
|
SiriusUnity3DGameEngine/MiniTrucks
|
/Scripts/Waypoint.cs
| 2.84375
| 3
|
using System;
using UnityEngine;
public class Waypoint : MonoBehaviour
{
[SerializeField] private Color wayColor = new Color(1,1,1,1);
public Transform[] Waypoints;
public float[] MaxSpeeds;
private void Awake()
{
int i = 0;
var points = gameObject.GetComponentsInChildren<Transform>();
Array.Resize(ref Waypoints, points.Length-1);
Array.Resize(ref MaxSpeeds, points.Length - 1);
foreach (Transform point in points)
{
if (point != transform)//чтобы не брал себя
{
Waypoints[i] = point;
MaxSpeeds[i] = point.GetComponent<MaxSpeed>().Speed/2;
i += 1;
}
}
}
void OnDrawGizmos ()
{
var points = gameObject.GetComponentsInChildren<Transform>();
if (!Application.isPlaying)
{
foreach (Transform point in points)
{
Gizmos.color = wayColor;
Gizmos.DrawSphere(point.position, 0.5f );
}
}
for (int i = 0; i < points.Length; i++)
{
if (i > 0)
Gizmos.DrawLine(points[i].position, points[Mathf.Min(i + 1, points.Length - 1)].position);
}
}
}
|
8baf872d330b6551d132c1a11cab0af54dd00ca0
|
C#
|
OneSesta/Squad47Bot
|
/TelegramBot.Interfaces/MenuItemViewModel.cs
| 3.125
| 3
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace TelegramBot.Common
{
/// <summary>
/// ViewModel associated with menu item in modular menu
/// </summary>
public class MenuItemViewModel : ObservableModelBase
{
#region Properties
/// <summary>
/// Text of MenuItem
/// </summary>
private string _text;
public string Text
{
get
{
return _text;
}
set
{
_text = value;
OnPropertyChanged();
}
}
/// <summary>
/// Icon of MenuItem
/// </summary>
private Uri _imageSource;
public Uri ImageSource
{
get
{
return _imageSource;
}
set
{
_imageSource = value;
OnPropertyChanged();
}
}
/// <summary>
/// Command to be associated with MenuItem
/// </summary>
private ICommand _command;
public ICommand Command
{
get
{
return _command;
}
set
{
_command = value;
OnPropertyChanged();
}
}
/// <summary>
/// Children MenuItems
/// </summary>
private ObservableCollection<MenuItemViewModel> _children;
public ObservableCollection<MenuItemViewModel> Children
{
get
{
return _children;
}
set
{
_children = value;
OnPropertyChanged();
}
}
#endregion
public MenuItemViewModel()
{
Children = new ObservableCollection<MenuItemViewModel>();
}
/// <summary>
/// Searching item in its children by given predivate.
/// </summary>
/// <param name="condition">Item should satisfy it</param>
/// <param name="searchInSubmenusAlso">Should the method search in submenus also?</param>
/// <returns>Menu item if found, null if not found</returns>
public MenuItemViewModel GetItem(Predicate<MenuItemViewModel> predicate, bool searchInSubmenusAlso = false)
{
foreach (MenuItemViewModel model in Children)
{
if (predicate(model))
{
return model;
}
}
if (searchInSubmenusAlso)
{
foreach (MenuItemViewModel model in Children)
{
MenuItemViewModel found = null;
found = model.GetItem(predicate, searchInSubmenusAlso);
if (found != null)
{
return found;
}
}
}
return null;
}
}
}
|
5bbcdc798d4d4fe4604e1b652354ff32e0eaeea5
|
C#
|
Cavcaliuc/LibraryManagement.Web
|
/LibraryManagement.Web/Encryption.cs
| 2.921875
| 3
|
using LibraryManagement.Web.Models;
using System;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
namespace LibraryManagement.Web
{
public static class Encryption
{
public static string Encrypt(string textData)
{
if( string.IsNullOrWhiteSpace(textData)) return textData;
var Encryptionkey = System.Configuration.ConfigurationManager.AppSettings["Encryptionkey"];
RijndaelManaged objrij = new RijndaelManaged();
//set the mode for operation of the algorithm
objrij.Mode = CipherMode.CBC;
//set the padding mode used in the algorithm.
objrij.Padding = PaddingMode.PKCS7;
//set the size, in bits, for the secret key.
objrij.KeySize = 0x80;
//set the block size in bits for the cryptographic operation.
objrij.BlockSize = 0x80;
//set the symmetric key that is used for encryption & decryption.
byte[] passBytes = Encoding.UTF8.GetBytes(Encryptionkey);
//set the initialization vector (IV) for the symmetric algorithm
byte[] EncryptionkeyBytes = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
int len = passBytes.Length;
if (len > EncryptionkeyBytes.Length)
{
len = EncryptionkeyBytes.Length;
}
Array.Copy(passBytes, EncryptionkeyBytes, len);
objrij.Key = EncryptionkeyBytes;
objrij.IV = EncryptionkeyBytes;
//Creates symmetric AES object with the current key and initialization vector IV.
ICryptoTransform objtransform = objrij.CreateEncryptor();
byte[] textDataByte = Encoding.UTF8.GetBytes(textData);
//Final transform the test string.
return Convert.ToBase64String(objtransform.TransformFinalBlock(textDataByte, 0, textDataByte.Length));
}
public static string Decrypt(string encryptedText)
{
if (string.IsNullOrWhiteSpace(encryptedText)) return encryptedText;
var Encryptionkey = System.Configuration.ConfigurationManager.AppSettings["Encryptionkey"];
RijndaelManaged objrij = new RijndaelManaged();
objrij.Mode = CipherMode.CBC;
objrij.Padding = PaddingMode.PKCS7;
objrij.KeySize = 0x80;
objrij.BlockSize = 0x80;
byte[] encryptedTextByte = Convert.FromBase64String(encryptedText);
byte[] passBytes = Encoding.UTF8.GetBytes(Encryptionkey);
byte[] EncryptionkeyBytes = new byte[0x10];
int len = passBytes.Length;
if (len > EncryptionkeyBytes.Length)
{
len = EncryptionkeyBytes.Length;
}
Array.Copy(passBytes, EncryptionkeyBytes, len);
objrij.Key = EncryptionkeyBytes;
objrij.IV = EncryptionkeyBytes;
byte[] TextByte = objrij.CreateDecryptor().TransformFinalBlock(encryptedTextByte, 0, encryptedTextByte.Length);
return Encoding.UTF8.GetString(TextByte); //it will return readable string
}
public static bool IsValidEmail(string strIn)
{
// Return true if strIn is in valid e-mail format.
return Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
}
public static string EncryptionForEmail(string textdata)
{
var isEmailValid = IsValidEmail(textdata);
if (isEmailValid)
{
// Require the user to have a confirmed email before they can log on.
return Encrypt(textdata);
}
return textdata;
}
public static string DecryptionForEmail(string textdata)
{
var isEmailValid = IsValidEmail(textdata);
if (isEmailValid)
{
// Require the user to have a confirmed email before they can log on.
return textdata;
}
return Decrypt(textdata);
}
}
}
|
a59a0d8c98a8762ff83909ddb23f627a5dbf1189
|
C#
|
ChrisTorng/GameOfLife
|
/GameOfLifeLibrary/BoardReaderBuilder.cs
| 3.390625
| 3
|
using System;
namespace GameOfLife.Library
{
public class BoardReaderBuilder
{
public BoardReaderType Type { get; }
public string Content { get; private set; }
public BoardReaderBuilder(BoardReaderType type)
{
if (!Enum.IsDefined(typeof(BoardReaderType), type) ||
type == BoardReaderType.Unknown)
{
throw new ArgumentOutOfRangeException(nameof(type));
}
this.Type = type;
}
public BoardReaderBuilder SetContent(string content)
{
this.Content = content;
return this;
}
public BoardReader Build()
{
#pragma warning disable IDE0010 // Add missing cases
switch (this.Type)
#pragma warning restore IDE0010 // Add missing cases
{
case BoardReaderType.Plaintext:
return new PlaintextBoardReader(this.Content);
default:
throw new NotImplementedException();
}
}
}
}
|
2a8ffce21aac0055eb568969733ec57065317514
|
C#
|
AmadeusW/vshelper
|
/helperapp.test/OperationFormatterTests.cs
| 3
| 3
|
using System;
using System.Collections.Generic;
using Xunit;
namespace helperapp.test
{
public class OperationFormatterTests
{
[Fact]
public void PlainStringIsUnchanged()
{
var properties = new Dictionary<string, string>();
var input = @"This\is\an(input)\string and it: will remain %unchanged%";
var output = OperationFormatter.Format(input, properties);
var target = input;
Assert.Equal(target, output);
}
[Fact]
public void EnvironmentVariableIsExpanded()
{
var properties = new Dictionary<string, string>();
var input = @"%temp% will expand only when it's in braces, like (%temp%).";
var output = OperationFormatter.Format(input, properties);
var target = $@"%temp% will expand only when it's in braces, like {Environment.ExpandEnvironmentVariables("%temp%")}.";
Assert.Equal(target, output);
}
[Fact]
public void KnownPropertyIsExpanded()
{
var properties = new Dictionary<string, string>() { { "sample", "I'm expanded!" } };
var input = @"sample will expand only when it's in braces, like (sample).";
var output = OperationFormatter.Format(input, properties);
var target = @"sample will expand only when it's in braces, like I'm expanded!.";
Assert.Equal(target, output);
}
[Fact]
public void UnknownPropertyIsSkipped()
{
var properties = new Dictionary<string, string>() { { "sample", "I'm expanded!" } };
var input = @"sample will expand only when it's known, (not like this).";
var output = OperationFormatter.Format(input, properties);
var target = input;
Assert.Equal(target, output);
}
[Fact]
public void MultiplePropertiesAreExpanded()
{
var properties = new Dictionary<string, string>() { { "sample", "I'm expanded!" }, { "bar", "baz"} };
var input = @"Here we have (%temp%), (sample), (foo) and (bar).";
var output = OperationFormatter.Format(input, properties);
var target = $@"Here we have {Environment.ExpandEnvironmentVariables("%temp%")}, I'm expanded!, (foo) and baz.";
Assert.Equal(target, output);
}
}
}
|
600ffe628f3784d591885fce1c5f3c85886d5a9d
|
C#
|
MartyIX/SoTh
|
/Lib/ProfileXmlServerResponse.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using Sokoban.Lib.Exceptions;
namespace Sokoban.Model.Profile
{
public class ProfileXmlServerResponse
{
private bool isLoggedIn = false;
private string sessionID = null;
private string ip = null;
public ProfileXmlServerResponse()
{
}
public string SessionID
{
get { return sessionID; }
}
public string IP
{
get { return ip; }
}
public bool IsLoggedIn
{
get { return isLoggedIn; }
}
public void Parse(string response)
{
XmlDocument xml = new XmlDocument(); //* create an xml document object.
XmlTextReader xmlTextReader = new XmlTextReader(new StringReader(response));
xml.Load(xmlTextReader);
//XmlNamespaceManager names = new XmlNamespaceManager(xml.NameTable);
//names.AddNamespace("x", "http://www.martinvseticka.eu/SoTh");
try
{
XmlNode login = (xml.GetElementsByTagName("Login"))[0];
isLoggedIn = (login["Successful"].InnerText == "1");
if (isLoggedIn == true)
{
sessionID = login["SessionID"].InnerText;
ip = login["IP"].InnerText;
}
}
catch
{
isLoggedIn = false;
throw new InvalidStateException("Answer from the server is not well-formed.");
}
}
}
}
|
b27fa999d1f7bfd5c73d63952cf4da7e4da8f656
|
C#
|
songgod/gEngine
|
/gEngine.View.Datatemplate/DataTemplateManager.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using static gEngine.Graph.Ge.Enums;
namespace gEngine.View.Datatemplate
{
/// <summary>
/// 模板管理类
/// </summary>
public class DataTemplateManager
{
/// <summary>
/// 按类型注册模板
/// </summary>
/// <typeparam name="TViewModel"></typeparam>
/// <typeparam name="TView"></typeparam>
public void RegisterDataTemplate<TViewModel, TView>() where TView : FrameworkElement
{
RegisterDataTemplate(typeof(TViewModel), typeof(TView));
}
public void RegisterDataTemplate(Type viewModelType, Type viewType)
{
var template = CreateTemplate(viewModelType, viewType);
var key = template.DataTemplateKey;
if (!Application.Current.Resources.Contains(key))
Application.Current.Resources.Add(key, template);
else
Application.Current.Resources[key] = template;
}
/// <summary>
/// 功能:创建数据模板方式1
/// </summary>
/// <param name="viewModelType"></param>
/// <param name="viewType"></param>
/// <returns></returns>
private DataTemplate CreateTemplate(Type viewModelType, Type viewType)
{
const string xamlTemplate = "<DataTemplate DataType=\"{{x:Type vm:{0}}}\"><v:{1} /></DataTemplate>";
var xaml = String.Format(xamlTemplate, viewModelType.Name, viewType.Name);
var context = new ParserContext();
context.XamlTypeMapper = new XamlTypeMapper(new string[0]);
context.XamlTypeMapper.AddMappingProcessingInstruction("vm", viewModelType.Namespace, viewModelType.Assembly.FullName);
context.XamlTypeMapper.AddMappingProcessingInstruction("v", viewType.Namespace, viewType.Assembly.FullName);
context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
context.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
context.XmlnsDictionary.Add("vm", "vm");
context.XmlnsDictionary.Add("v", "v");
var template = (DataTemplate)XamlReader.Parse(xaml, context);
return template;
}
/// <summary>
/// 按xaml文件名注册数据模板
/// </summary>
/// <typeparam name="TViewModel"></typeparam>
/// <param name="fileName">文件全路径</param>
public void RegDataTemplateByFile<TViewModel>(string type, string fileName)
{
string templateFolder = AppDomain.CurrentDomain.BaseDirectory + "DataTemplates\\" + type + "\\";
if (!Directory.Exists(templateFolder))
{
Directory.CreateDirectory(templateFolder);
}
string filePath = templateFolder + fileName;
StreamReader reader = new StreamReader(filePath, Encoding.Default);
string fileContent = reader.ReadToEnd();
var viewModelType = typeof(TViewModel);
var template = CreateTemplate(viewModelType, fileContent);
var key = template.DataTemplateKey;
if (!Application.Current.Resources.Contains(key))
Application.Current.Resources.Add(key, template);
else
Application.Current.Resources[key] = template;
}
/// <summary>
/// 功能:创建数据模板方式2
/// </summary>
/// <param name="viewModelType">viewModel类型</param>
/// <param name="fileContent">模板文件内容</param>
/// <returns></returns>
private DataTemplate CreateTemplate(Type viewModelType, string fileContent)
{
const string xamlTemplate = "<DataTemplate DataType=\"{{x:Type vm:{0}}}\">{1}</DataTemplate>";
var xaml = String.Format(xamlTemplate, viewModelType.Name, fileContent);
var context = new ParserContext();
context.XamlTypeMapper = new XamlTypeMapper(new string[0]);
context.XamlTypeMapper.AddMappingProcessingInstruction("vm", viewModelType.Namespace, viewModelType.Assembly.FullName);
context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
context.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
context.XmlnsDictionary.Add("vm", "vm");
var template = (DataTemplate)XamlReader.Load(new MemoryStream(Encoding.UTF8.GetBytes(xaml)), context);
return template;
}
public List<string> GetAllDataTemplates()
{
List<string> result = new List<string>();
string templateFolder = AppDomain.CurrentDomain.BaseDirectory + "DataTemplates\\";
if (!Directory.Exists(templateFolder))
{
Directory.CreateDirectory(templateFolder);
}
DirectoryInfo TheFolder = new DirectoryInfo(templateFolder);
foreach (FileInfo file in TheFolder.GetFiles())
{
if (file.Extension.Equals(".xaml"))
{
result.Add(file.Name);
}
}
return result;
}
public List<string> GetAllDataTemplatesByType(string type)
{
List<string> result = new List<string>();
string templateFolder = AppDomain.CurrentDomain.BaseDirectory + "DataTemplates\\" + type + "\\";
if (!Directory.Exists(templateFolder))
{
Directory.CreateDirectory(templateFolder);
}
DirectoryInfo TheFolder = new DirectoryInfo(templateFolder);
foreach (FileInfo file in TheFolder.GetFiles())
{
if (file.Extension.Equals(".xaml"))
{
result.Add(file.Name);
}
}
return result;
}
public List<string> GetDataTemplateTypes()
{
List<string> result = new List<string>();
result = Enum.GetNames(typeof(DataTemplateType)).ToList<string>();
return result;
}
}
}
|
e6393f2a1f7da9a6d61c74aee149fcf1aa0775ed
|
C#
|
b201lab/unity-top-down-workshop
|
/Assets/Scripts/SpriteRotation.cs
| 2.5625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpriteRotation : MonoBehaviour
{
SpriteRenderer spriteRenderer;
public Sprite[] sprites;
public float startDirection = 0;
public float rotation;
void Start()
{
spriteRenderer = GetComponent<SpriteRenderer>();
}
void Update()
{
startDirection = Mathf.Repeat(startDirection, 360);
float angle = Mathf.Repeat(rotation - startDirection, 360);
int index = (int)Mathf.Round(angle * sprites.Length / 360);
if (spriteRenderer != null) {
spriteRenderer.sprite = sprites[index % sprites.Length];
}
}
}
|
858d2cf7b93c66dedd92ccd5c16266bd857527c2
|
C#
|
Brandon-Smith-457/Education
|
/McGill University/COMP 521 - Modern Computer Games/Assignment2/MyRigidBody.cs
| 2.546875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyRigidBody : MonoBehaviour
{
public int id;
public static float gravity = -9.81f;
public static float windResistance = 0.0f;
public static float coefficientOfRestitution = 0.5f;
public Vector3 velocity;
public bool isStatic = false;
public bool isVerlet = false;
public bool isWater = false;
public float stationaryCutoff = 0.01f;
private int deathCounter = 0;
private float stationaryDeathTime = 5.0f; //Seconds
private float fixedCallsUntilDeath;
private float screenWidth;
void Start()
{
fixedCallsUntilDeath = stationaryDeathTime / Time.fixedDeltaTime;
screenWidth = Camera.main.aspect * Camera.main.orthographicSize * 2;
}
// This function is called indepently of frame-rate at Time.fixedDeltaTime second intervals
void FixedUpdate()
{
if (isStatic || isVerlet) return;
velocity.x = velocity.x + windResistance * Time.deltaTime;
velocity.y = velocity.y + gravity * Time.deltaTime;
// Checking if the body has remained stationary for "stationaryDeathTime" amount of time.
if (velocity.magnitude < stationaryCutoff)
{
if (++deathCounter >= fixedCallsUntilDeath)
PhysicsManager.instance.removeId(id);
}
else deathCounter = 0;
Vector3 pos = transform.position;
pos.x = pos.x + velocity.x * Time.deltaTime;
pos.y = pos.y + velocity.y * Time.deltaTime;
transform.position = pos;
if (transform.position.x < 0 || transform.position.x > screenWidth)
{
PhysicsManager.instance.removeId(id);
Destroy(gameObject);
return;
}
}
// A helper function for when we need to binary search backup
public void updatePosition(float deltaTime)
{
Vector3 pos = transform.position;
pos.x = pos.x + velocity.x * deltaTime;
pos.y = pos.y + velocity.y * deltaTime;
transform.position = pos;
}
}
|
87e06de1e0f0a92396ad18d2c53ad620e9bd9fee
|
C#
|
mutuware/WiffWaff
|
/waf/Renderer.cs
| 3.0625
| 3
|
using System;
using System.Collections.ObjectModel;
using System.Text;
using WiffWaff.Pages;
namespace WiffWaff
{
public class Renderer
{
public string Do(Page page, Type type, ReadOnlyDictionary<string, Type> routes)
{
var masterPage =
"<HTML><HEAD><link rel=\"stylesheet\" type=\"text/css\" href=\"/style.css\"><TITLE>{{title}}</TITLE></HEAD><BODY><div class=\"navbar\">{{navbar}}</div><div class=\"container\">{{content}}</div></BODY></HTML>";
var html = masterPage
.Replace("{{title}}", type.FullName)
.Replace("{{navbar}}", Navbar(routes))
.Replace("{{content}}", page.GetContents());
return html;
}
private string Navbar(ReadOnlyDictionary<string, Type> routes)
{
var sb = new StringBuilder();
sb.Append("<ul>");
foreach (var route in routes)
{
sb.Append($"<li><a href=\"{route.Key}\">{route.Value}</a></li>");
}
sb.Append("</ul>");
return sb.ToString();
}
}
}
|
24690f40e13470fb68be29722bd36fef3a932118
|
C#
|
DigitalPacificSolutions/AussieDivers
|
/AussieDivers/Models/DataModels/Mapping/EquipmentTypeMap.cs
| 2.734375
| 3
|
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
namespace AussieDivers.Models.Mapping
{
public class EquipmentTypeMap : EntityTypeConfiguration<EquipmentType>
{
public EquipmentTypeMap()
{
// Primary Key
this.HasKey(t => t.EquipmentTypeID);
// Properties
this.Property(t => t.EquipmentType1)
.IsRequired()
.HasMaxLength(20);
// Table & Column Mappings
this.ToTable("EquipmentType");
this.Property(t => t.EquipmentTypeID).HasColumnName("EquipmentTypeID");
this.Property(t => t.EquipmentID).HasColumnName("EquipmentID");
this.Property(t => t.EquipmentType1).HasColumnName("EquipmentType");
// Relationships
this.HasRequired(t => t.Equipment)
.WithMany(t => t.EquipmentTypes)
.HasForeignKey(d => d.EquipmentID);
}
}
}
|
304bd7619ba6b02f8e07427efc6b8a7074fe8299
|
C#
|
VimleshS/csharp_advance_features
|
/advanceFeatures/Nullable.cs
| 3.09375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Linq
{
public class Nullable
{
public void TestNullables()
{
Nullable<int> index = null;
//ShortHand for above syntax
int? indexAgain = null;
Nullable<DateTime> date1 = new Nullable<DateTime>(new DateTime(2001, 1, 1));
DateTime? date2 = new DateTime(2001, 1, 1);
DateTime dt;
//DateTime date2 = date1.GetValueOrDefault();
//Null Coalsing operator.
dt = date2 ?? DateTime.Today;
//Ternary Operator
var dt2 = date2 != null ? date2.GetValueOrDefault() : DateTime.Today;
}
}
}
|
c403c2af4077d1019676f361cc5672dbad8ab2a4
|
C#
|
davemateer/GildedRose
|
/src/GildedRose.Tests/GildedRose.Domain/InventoryItemBuilderTests.cs
| 2.625
| 3
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace GildedRose.Domain.Tests
{
[TestClass]
public class InventoryItemBuilderTests
{
private static readonly Guid TestId = Guid.NewGuid();
[TestMethod]
public void Build_AgedBrie()
{
var builder = new InventoryItemBuilder();
IInventoryItem item = builder.Build(TestId, "Aged Brie", "Food", 50, 10);
Assert.IsInstanceOfType(item, typeof(BetterWithAgeInventoryItem));
Assert.AreEqual(TestId, item.Id);
Assert.AreEqual("Aged Brie", item.Name);
Assert.AreEqual("Food", item.Category);
Assert.AreEqual(50, item.Quality);
Assert.IsNull(item.SellIn);
}
[TestMethod]
public void Build_BackstagePasses()
{
var builder = new InventoryItemBuilder();
IInventoryItem item = builder.Build(TestId, "Raging Ogre", "Backstage Passes", 10, 10);
Assert.IsInstanceOfType(item, typeof(BackstagePassInventoryItem));
Assert.AreEqual(TestId, item.Id);
Assert.AreEqual("Raging Ogre", item.Name);
Assert.AreEqual("Backstage Passes", item.Category);
Assert.AreEqual(10, item.Quality);
Assert.AreEqual(10, item.SellIn);
}
[TestMethod]
public void Build_Conjured()
{
var builder = new InventoryItemBuilder();
IInventoryItem item = builder.Build(TestId, "Giant Slayer", "Conjured", 15, 50);
Assert.IsInstanceOfType(item, typeof(ConjuredInventoryItem));
Assert.AreEqual(TestId, item.Id);
Assert.AreEqual("Giant Slayer", item.Name);
Assert.AreEqual("Conjured", item.Category);
Assert.AreEqual(15, item.Quality);
Assert.AreEqual(50, item.SellIn);
}
[TestMethod]
public void Build_StandardItem()
{
var builder = new InventoryItemBuilder();
IInventoryItem item = builder.Build(TestId, "Sword", "Weapon", 50, 30);
Assert.IsInstanceOfType(item, typeof(StandardInventoryItem));
Assert.AreEqual(TestId, item.Id);
Assert.AreEqual("Sword", item.Name);
Assert.AreEqual("Weapon", item.Category);
Assert.AreEqual(50, item.Quality);
Assert.AreEqual(30, item.SellIn);
}
[TestMethod]
public void Build_Sulfuras()
{
var builder = new InventoryItemBuilder();
IInventoryItem item = builder.Build(TestId, "Hand of Ragnaros", "Sulfuras", 80, 80);
Assert.IsInstanceOfType(item, typeof(LegendaryInventoryItem));
Assert.AreEqual(TestId, item.Id);
Assert.AreEqual("Hand of Ragnaros", item.Name);
Assert.AreEqual("Sulfuras", item.Category);
Assert.AreEqual(80, item.Quality);
Assert.IsNull(item.SellIn);
}
}
}
|
31bb66c8d095eab394d91cb15c3ad4d344b0e8df
|
C#
|
MatiasHamie/UTN_Laboratorio_2
|
/Parciales de practica/20181122-SP/Alumno/Entidades/PatenteStringExtension.cs
| 2.96875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Entidades
{
public static class PatenteStringExtension
{
public const string patente_vieja = "^[A-Z]{3}[0-9]{3}$";
public const string patente_mercosur = "^[A-Z]{2}[0-9]{3}[A-Z]{2}$";
public static Patente ValidarPatente(this string str)
{
Patente p;
Regex rgx_v = new Regex(PatenteStringExtension.patente_vieja);
Regex rgx_n = new Regex(PatenteStringExtension.patente_mercosur);
if (rgx_v.IsMatch(str))
{
p = new Patente(str, Patente.Tipo.Vieja);
}
else if (rgx_n.IsMatch(str))
{
p = new Patente(str, Patente.Tipo.Mercosur);
}
else
{
string s = string.Format("{0} no cumple el formato.", str);
throw new PatenteInvalidaException(s);
}
return p;
}
}
}
|
f1083d173b6f57ff02072e685e1033c4faa8c28d
|
C#
|
Nconflux/Conflux.net.SDK
|
/src/Conflux.Contracts/Extensions/ContractMessageHexBigIntegerExtensions.cs
| 2.53125
| 3
|
using System.Numerics;
using Conflux.Contracts.CQS;
using Conflux.Hex.HexTypes;
using Conflux.Util;
namespace Conflux.Contracts
{
public static class ContractMessageHexBigIntegerExtensions
{
/// <summary>
/// Convert BigInteger to HexBigInteger, if input is null, return null;
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static HexBigInteger ToHexBigInteger(this BigInteger? input) => input?.ToHexBigInteger();
/// <summary>
/// Convert BigInteger to HexBigInteger
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static HexBigInteger ToHexBigInteger(this BigInteger input) => new HexBigInteger(input);
public static string SetDefaultFromAddressIfNotSet(this ContractMessageBase contractMessage, string defaultFromAdddress)
{
if (string.IsNullOrEmpty(contractMessage.FromAddress))
{
contractMessage.FromAddress = defaultFromAdddress;
}
return contractMessage.FromAddress;
}
}
}
|
ce93253734b8f2b523673c2b5927cc3e28920cae
|
C#
|
codearchive/c-sharp-path
|
/asynchronous-programming-dotnet/module_02/StockAnalyzer.Windows/Services/StockService.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using StockAnalyzer.Core.Domain;
namespace StockAnalyzer.Windows.Services
{
public class StockService
{
public async Task<IEnumerable<StockPrice>> GetStockPricesFor(string ticker)
{
using (var client = new HttpClient())
{
var result = await client.GetAsync($"http://localhost:61363/api/stocks/{ticker}");
result.EnsureSuccessStatusCode();
var content = await result.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<IEnumerable<StockPrice>>(content);
}
}
}
}
|
78c12575f9a738840b3e251bac36171373fc8d54
|
C#
|
tormaroe/mist
|
/src/Marosoft.Mist/Evaluation/FormalParameters.cs
| 2.90625
| 3
|
using System.Linq;
using System.Collections.Generic;
using Marosoft.Mist.Parsing;
using Marosoft.Mist.Lexing;
namespace Marosoft.Mist.Evaluation
{
public class FormalParameters
{
private ListExpression _parameters;
public FormalParameters(Expression expr)
{
if (!(expr is ListExpression))
throw new MistException("Formal parameters must be a list, not " + expr);
if (!expr.Elements.All(p => p.Token.Type == Tokens.SYMBOL))
throw new MistException("Only symbols allowed in formal paremeters. " + expr);
_parameters = (ListExpression)expr;
}
public int Count
{
get
{
return _parameters.Elements.Count;
}
}
public Bindings BindArguments(Bindings scope, IEnumerable<Expression> args)
{
var invocationScope = new Bindings { ParentScope = scope };
// TODO: enhance when optional parameter length added
if (_parameters != null && _parameters.Elements.Count != args.Count())
throw new MistException(string.Format("Wrong number of arguments ({0} instead of {1})",
args.Count(), _parameters.Elements.Count));
if (_parameters != null)
for (int i = 0; i < Count; i++)
invocationScope.AddBinding(
_parameters.Elements[i],
args.ElementAt(i));
return invocationScope;
}
}
}
|
62a6fdb824ca6181d4b3889d18554e7d37233362
|
C#
|
lautaromedeiros98/tp_laboratorio_2
|
/TrabajoPracticoN°1/Entidades/Calculadora.cs
| 3.890625
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entidades
{
public static class Calculadora
{
/// <summary>
/// Realiza la operacion aritmetica con los parametros recibidos
/// </summary>
/// <param name="num1"></param>
/// <param name="num2"></param>
/// <param name="operador"></param>
/// <returns></returns>El resultado de dicha operacion
public static double Operar(Numero num1,Numero num2,string operador)
{
switch(ValidarOperador(operador))
{
case "*":
return num1 * num2;
case "/":
return num1 / num2;
case "-":
return num1 - num2;
case "+":
return num1 + num2;
}
return num1 + num2;
}
/// <summary>
/// Valida que el dato ingresado sea "+","-","*" o "/"
/// </summary>
/// <param name="operador"></param>
/// <returns></returns> si es un operador valido retorna el mismo , caso contrario retornará "+"
private static string ValidarOperador(string operador)
{
switch(operador)
{
case "*":
return "*";
case "/":
return "/";
case "-":
return "-";
default:
return "+";
}
}
}
}
|
dc7173f8dfd8425a80f4ed95a1233ebae57e59bf
|
C#
|
Xigi/elementary
|
/src/PersonHello/AdulthoodMessageStrategy.cs
| 3.21875
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace PersonHello
{
public class AdulthoodMessageStrategy : IMessageStrategy
{
public string Message { get; private set; }
public bool Execute(Person p)
{
if (p.IsAdult() && !p.IsPensioner())
{
Message = $"Hello { p.FirstName } you already enjoy your adulthood";
return true;
}
return false;
}
}
}
|
bc4d6f9d892f59b2d5409817743425b9101de773
|
C#
|
luiseduardohdbackup/SafeILGenerator
|
/SafeILGenerator/Ast/AstLabel.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
namespace SafeILGenerator.Ast
{
public class AstLabel
{
public string Name;
protected AstLabel(string Name)
{
this.Name = Name;
}
static public AstLabel CreateLabel(string Name = "<Unknown>")
{
return new AstLabel(Name);
}
//static public AstLabel CreateNewLabelFromILGenerator(ILGenerator ILGenerator, string Name = "<Unknown>")
//{
// return new AstLabel((ILGenerator != null) ? ILGenerator.DefineLabel() : default(Label), Name);
//}
public override string ToString()
{
return String.Format("AstLabel({0})", Name);
}
}
}
|
4b12fa525dba065e5c1aab7ea549a517ae097659
|
C#
|
gkudel/mvc-for-net
|
/MVCEngineLibrary/Engine/Model/Attributes/Formatter/Formatter.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MVCEngine.Model.Attributes.Formatter
{
[System.AttributeUsage(System.AttributeTargets.Property)]
public abstract class Formatter : System.Attribute
{
#region Constructor
public Formatter()
{
PropertyName = string.Empty;
}
#endregion Constructor
#region Format
public abstract object Format(object value);
#endregion Format
#region Properties
public string PropertyName { get; set; }
#endregion Properties
}
}
|
e9e0fb93a307b6b14012db6364bc0dabf83e4e54
|
C#
|
kentays/girls-with-swords-ggpo
|
/Player/AnimationPlayer.cs
| 2.578125
| 3
|
using Godot;
using System;
public class AnimationPlayer : Godot.AnimationPlayer
{
[Signal]
public delegate void AnimationFinished();
private int animationLength;
public int cursor;
public void NewAnimation(string animName)
{
if (animName == AssignedAnimation)
{
Seek(0, true);
cursor = 0;
}
else
{
Play(animName);
cursor = 0;
animationLength = (int)CurrentAnimationLength; //Bad idea?
Stop();
Seek(0, true);
}
}
public void SetAnimationAndFrame(string animName, int frame)
{
Play(animName);
animationLength = (int)CurrentAnimationLength;
Stop();
cursor = frame;
Seek(cursor, true);
GD.Print($"Setting animation to {animName} and frame to {frame}");
}
public void FrameAdvance()
{
if (cursor < animationLength)
{
cursor++;
Seek(cursor, true);
}
else
{
EmitSignal(nameof(AnimationFinished), CurrentAnimation);
}
if (IsPlaying())
{
GD.Print("This SHOULD NOT BE CALLED");
}
}
public void Restart()
{
Seek(0, true);
cursor = 0;
}
}
|
f757d65ab311de0c73e68b9f15dc8698b6e7bba7
|
C#
|
AlexanderChernykh/LibraryHh
|
/LibraryHh/Triangle.cs
| 3.734375
| 4
|
using System;
using System.Collections.Generic;
using System.Text;
namespace LibraryHh
{
public class Triangle : Shape
{
public double SideA { get; set; }
public double SideB { get; set; }
public double SideC { get; set; }
public Triangle(string nameShape, double sideA, double sideB, double sideC) : base(nameShape)
{
if (IsExist(sideA,sideB,sideC))
{
SideA = sideA;
SideB = sideB;
SideC = sideC;
}
}
public override double Area()
{
double semiPerimeter = (SideA + SideB + SideC) / 2;
return Math.Sqrt(semiPerimeter * (semiPerimeter - SideA) * (semiPerimeter - SideB) * (semiPerimeter - SideC));
}
private bool IsExist(double sideA, double sideB, double sideC)
{
if (sideA > sideB + sideC || sideB > sideA + sideC || sideC > sideA + sideB)
{
throw new ArgumentException("Такого треугольника не существует");
}
if (sideA <= 0 || sideB <= 0 || sideC <= 0)
{
throw new ArgumentException("Стороны треугольника не могут быть меньше или равны 0");
}
return true;
}
public bool IsRightAngledTriangle()
{
bool isRightAngledTriangle = Math.Pow(SideA, 2) == Math.Pow(SideB, 2) + Math.Pow(SideC, 2)
|| Math.Pow(SideB, 2) == Math.Pow(SideA, 2) + Math.Pow(SideC, 2)
|| Math.Pow(SideC, 2) == Math.Pow(SideB, 2) + Math.Pow(SideA, 2);
return isRightAngledTriangle;
}
public override string ToString()
{
string message = $"{base.NameShape} имеет стороны A={SideA} B={SideB} C={SideC}, площадь {Area()}";
if (IsRightAngledTriangle())
{
return message + " и является прямоугольным";
}
return message;
}
}
}
|
ad206992bee9e7eced5177f35feb89900303f08e
|
C#
|
Awdesh/Algorithmic
|
/LinkedList/DeleteItemFromLinkedList.cs
| 3.28125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinkedList
{
class DeleteItemFromLinkedList
{
public LinkedListNode DeleteNode(LinkedListNode node, int value)
{
if(node == null)
{
return node;
}
if(node.getData() == value)
{
node = node.getNext();
}
LinkedListNode current;
LinkedListNode prev = new LinkedListNode();
current = node;
while(current != null)
{
if(current.getData() == value)
{
prev.setNext(current.getNext());
}
else
{
prev = current;
}
current = current.getNext();
}
prev.setNext(null);
return prev;
}
}
}
|
1fc3a8956430c4eb620e5e56349bcde8ed984dc7
|
C#
|
gsaurus/back_to_the_streets
|
/data-model/storage-model/Scripts/Character/Character.cs
| 2.53125
| 3
|
using System;
using ProtoBuf;
namespace RetroBread.Storage{
// A character contains all the animations data,
// including data that may be duplicated between events and animations
// So hitboxes, collision boxes point to boxes in the character,
// animations point to events in the character,
// and events point to conditions in the character model
[ProtoContract]
public sealed class Character{
// Logical character name
[ProtoMember(1)]
public string name;
[ProtoMember(2, OverwriteList=true)]
public GenericParameter[] genericParameters;
[ProtoMember(3, OverwriteList=true)]
public Box[] boxes;
[ProtoMember(4, OverwriteList=true)]
public CharacterAnimation[] animations;
// Names of transforms in model used as anchors for attached objects
[ProtoMember(5, OverwriteList=true)]
public string[] viewAnchors;
// Name of the 2D or 3D model(s) of the character (may have multiple skins)
[ProtoMember(6, OverwriteList=true)]
public string[] viewModels;
// Name of the portrait sprite assets, one for each skin
[ProtoMember(7, OverwriteList=true)]
public string[] portraits;
[ProtoMember(8)]
public string shadowName;
// Default Constructor
public Character(){
// Nothing to do
}
// Constructor
public Character(string name){
this.name = name;
}
}
} // namespace RetroBread.Storage
|
818ce0088d0b14911e752d3aac39f802b06422a7
|
C#
|
annahita/Code-Reviewer
|
/clean_code/Strategies/Name/NameConvention.cs
| 2.8125
| 3
|
using System.Linq;
using CleanCode.Metrics;
using CleanCode.Utils.Name;
using CleanCode.Utils.WordNet;
namespace CleanCode.Strategies.Name
{
public class NamingConvention : INamingConvention
{
private readonly int _nameMinLength;
private readonly INameSplitter _nameSplitter;
private readonly IWordLookUp _wordLookUp;
public NamingConvention(IWordLookUp wordLookUp, INameSplitter nameSplitter, IMetric metric)
{
_nameSplitter = nameSplitter;
_wordLookUp = wordLookUp;
_nameMinLength = metric.MinimumLengthOfName;
}
public bool IsPronounceable(string name)
{
var nameParts = _nameSplitter.Split(name);
return nameParts.All(IsNamePartPronounceable);
}
public bool IsSearchable(string name)
{
var hasMinimumLength = name.Length >= _nameMinLength;
return hasMinimumLength;
}
public bool HasWritePartOfSpeech(string name, PartsOfSpeech partsOfSpeech)
{
var firstPartOfName = _nameSplitter.Split(name).FirstOrDefault();
var partOfSpeeches = _wordLookUp.FindWordPartOfSpeeches(firstPartOfName.ToLower());
return partOfSpeeches.Contains(partsOfSpeech);
}
private bool IsNamePartPronounceable(string name)
{
return _wordLookUp.FindWordPartOfSpeeches(name.ToLower()).Any();
}
}
}
|
25d2618f89f6c22e7a5fb05d037416af08371a73
|
C#
|
ealux/TKZ
|
/Shared/Model/Grid/GridGraph.cs
| 2.875
| 3
|
using System.Collections.Generic;
using System.Linq;
using TKZ.Shared.Model;
namespace TKZ.Shared
{
public partial class Grid
{
/// <summary>
/// Finds branches from a given bus.
/// </summary>
/// <param name="BusId"> Id start Bus.</param>
/// <param name="numBelt"> Count belt for find branch.</param>
/// <returns>Branch Id</returns>
public List<int> FindBranchBelt(int BusId, int numBelt)
{
if (this.Branches.Count() < 1 || this.Buses.Count() < 2) return new List<int>();
if (numBelt < 1) numBelt = 1;
Dictionary<int, bool> dicBranches = new Dictionary<int, bool>();
Dictionary<int, bool> dicBuses = new Dictionary<int, bool>();
foreach (Branch b in this.Branches.Values.ToList()) dicBranches.Add(b.Id, false);
foreach (Bus b in this.Buses.Values.ToList()) dicBuses.Add(b.Id, false);
RecursiveFindBeltBranch(dicBranches, dicBuses, BusId, numBelt);
List<int> res = new List<int>();
foreach (int i in dicBranches.Keys) if (dicBranches[i] == true) res.Add(i);
return res;
}
private void RecursiveFindBeltBranch(Dictionary<int, bool> dicBranches, Dictionary<int, bool> dicBuses, int BusId, int Belt)
{
dicBuses[BusId] = true;
if (Belt < 1 || BusId == 0) return; //must not worked, if bus is ground
List<int> l = FindAllBranchOnBusID(BusId);
for (int ind = 0; ind < l.Count; ind++)
{
int cur = l[ind];
dicBranches[cur] = true;
if (this.Branches[cur].StartBusId == BusId)
{
if (dicBuses[Branches[cur].FinalBusId] == false) RecursiveFindBeltBranch(dicBranches, dicBuses, Branches[cur].FinalBusId, Belt - 1);
continue;
}
if (this.Branches[cur].FinalBusId == BusId)
{
if (dicBuses[Branches[cur].StartBusId] == false) RecursiveFindBeltBranch(dicBranches, dicBuses, Branches[cur].StartBusId, Belt - 1);
continue;
}
}
}
/// <summary>
/// Find all branch connectivity given bus.
/// </summary>
/// <param name="BusId"> Start Bus Id for find branch.</param>
/// <returns>Branch ID</returns>
public List<int> FindAllBranchOnBusID(int BusId)
{
List<int> res = new List<int>();
foreach (Branch b in this.Branches.Values)
{
if (b.StartBusId == BusId | b.FinalBusId == BusId) res.Add(b.Id);
}
return res;
}
/// <summary>
/// Find all neighbors bus.
/// </summary>
/// <param name="BusId">The bus for which to look for neighbors</param>
/// <returns>Bus Id</returns>
public List<int> FindNeighbourBus(int BusId)
{
List<int> res = new List<int>();
List<int> br = FindAllBranchOnBusID(BusId);
for (int ind = 0; ind < br.Count(); ind++)
{
if (this.Branches[br[ind]].StartBusId != BusId | this.Branches[br[ind]].FinalBusId != BusId) res.Add(BusId);
}
return res;
}
/// <summary>
/// Check grid connectivity
/// </summary>
/// <returns>/// true - 1 island; false - many island.</returns>
public bool CheckConnectivityGrid()
{
if (this.Buses.Count() < 2) return true;
if (this.Branches.Count() < 1) return false;
Dictionary<int, int> dicBuses = FindIslandGrid();
int numIsland = dicBuses.Values.ToArray().Distinct().ToArray().Count();
if (numIsland == 1) return true;
else return false;
}
/// <summary>
/// Find all island grid.
/// </summary>
/// <returns></returns>
public Dictionary<int, int> FindIslandGrid()
{
if (this.Buses.Count() < 2 || this.Branches.Count() < 1) return new Dictionary<int, int>();
Dictionary<int, int> dicBuses = new Dictionary<int, int>();
int ind = 0;
foreach (int busId in this.Buses.Keys.ToList()) dicBuses.Add(busId, ind++);
bool FlagChange = true;
int[] keys = this.Branches.Keys.ToArray();
while (FlagChange)
{
FlagChange = false;
for (ind = 0; ind < keys.Count(); ind++)
{
int s = this.Branches[keys[ind]].StartBusId;
int f = this.Branches[keys[ind]].FinalBusId;
if (dicBuses[s] < dicBuses[f]) { dicBuses[f] = dicBuses[s]; FlagChange = true; continue; }
if (dicBuses[f] < dicBuses[s]) { dicBuses[s] = dicBuses[f]; FlagChange = true; continue; }
}
}
return dicBuses;
}
/// <summary>
/// Check contains bus Id all Branches in Buses.
/// </summary>
/// <returns>true - there is a missing bus; flase - all rigth </returns>
public bool CheckContainsBusId()
{
if (FindMissingBusId().Count() > 0) return true;
else return false;
}
/// <summary>
/// Find in Branches to all missing bus Id.
/// </summary>
/// <returns>List missing bus Id</returns>
public List<int> FindMissingBusId()
{
List<int> res = new List<int>();
int[] keys = this.Branches.Keys.ToArray();
for (int ind = 0; ind < keys.Length; ind++)
{
if (!this.Buses.ContainsKey(this.Branches[keys[ind]].StartBusId)) res.Add(this.Branches[keys[ind]].StartBusId);
if (!this.Buses.ContainsKey(this.Branches[keys[ind]].FinalBusId)) res.Add(this.Branches[keys[ind]].FinalBusId);
}
return res.Distinct().ToList();
}
/// <summary>
/// Search for grounded transformer branches
/// </summary>
/// <returns>Problem branch Id</returns>
public List<int> FindBranchTransformerGround()
{
List<int> res = new List<int>();
int[] keys = this.Branches.Keys.ToArray();
for (int ind = 0; ind < keys.Count(); ind++)
{
if (this.Branches[keys[ind]].Ratio > 0)
{
//if (this.Branches[keys[ind]].StartBusId == this.BusGround.Id) res.Add(keys[ind]);
//if (this.Branches[keys[ind]].FinalBusId == this.BusGround.Id) res.Add(keys[ind]);
}
}
return res;
}
/// <summary>
/// Search generator between two buses (not ground)
/// </summary>
/// <returns>Problem branch Id</returns>
public List<int> FindGeneratorBetweenBuses()
{
List<int> res = new List<int>();
int[] keys = this.Branches.Keys.ToArray();
for (int ind = 0; ind < keys.Count(); ind++)
{
if (//(this.Branches[keys[ind]].E > 0) &&
(this.Branches[keys[ind]].StartBusId > 0) &&
(this.Branches[keys[ind]].FinalBusId > 0))
{
res.Add(keys[ind]);
}
}
return res;
}
}
}
|
f1db06df66114a83d3f8abfa858f5d94f24580a9
|
C#
|
PersephonyAPI/csharp-sdk
|
/persy-cs-sdk/api/application/ApplicationsRequester.cs
| 2.78125
| 3
|
using com.persephony.api;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace com.persephony.api.application
{
/// <summary>
/// This class represents the set of wrappers around the Persephony Application API.
/// It provides methods to handle all the operations supported by the Persephony
/// Application API.
/// </summary>
public class ApplicationsRequester : APIRequester
{
private readonly string path;
/// <summary>
/// Creates an ApplicationsRequester. For most SDK users ApplicationsRequester will be
/// created automatically by the PersyClient but is available for more
/// users who only require the features in this specific requester and not
/// the rest of the features of the PersyClient.
/// </summary>
/// <param name="credAccountId">The accountId to use as authentication credentials in the HTTP Basic Auth header for requests made by this requester.</param>
/// <param name="credAuthToken">The authToken to use as authentication credentials in the HTTP Basic Auth header for requests made by this requester.</param>
/// <param name="accountId">The accountId to act as. This can be the same as the credAccountId or the accountId of a subaccount of the credAccountId.</param>
public ApplicationsRequester(string credAccountId, string credAuthToken, string accountId) : base(credAccountId, credAuthToken)
{
this.path = "/Accounts/" + accountId + "/Applications";
}
/// <summary>
/// Retrieve path object value.
/// </summary>
/// <returns>The base path used for the Persephony API.</returns>
public string getPath { get { return this.path; } }
/// <summary>
/// Retrieve a single application from Persephony.
/// </summary>
/// <param name="appId">The applicationId of the target application.</param>
/// <returns>The application matching the appId provided.</returns>
/// <exception cref="PersyException">Thrown upon failed request.</exception>
public Application get(string appId)
{
string json = base.GET(String.Format("{0}/{1}", this.path, appId));
if (string.IsNullOrEmpty(json) == true)
{
throw new PersyException(String.Format("Failed to get application {0} information", appId ?? ""));
}
return Application.fromJson(json);
}
/// <summary>
/// Retrieve a list of applications from Persephony.
/// </summary>
/// <param name="filters">Optional ApplicationsSearchFilters instance to filter list of applications.</param>
/// <returns>
/// An in-language representation of Persephony's paginated list response.This will be a paginated list
/// of application instances as returned by the Persephony API.
/// </returns>
/// <exception cref="PersyException">Thrown upon failed request.</exception>
/// <see cref="ApplicationsSearchFilters">ApplicationsSearchFilters class.</see>
public ApplicationList get(ApplicationsSearchFilters filters = null)
{
string json = base.GET(this.path, ((filters != null) ? filters.toDict() : null));
if (string.IsNullOrEmpty(json) == true)
{
throw new PersyException("Failed to get application list");
}
ApplicationList list = new ApplicationList(this.getAccountId, this.getAuthToken, json);
return list;
}
/// <summary>
/// Create a new application through the Persephony API
/// </summary>
/// <param name="options">Optional ApplicationOptions instance to be used when creating an application.</param>
/// <returns>An Application object returned by Persephony that represents the application that was created.</returns>
/// <exception cref="PersyException">Thrown upon failed request.</exception>
/// <see cref="ApplicationOptions">ApplicationOptions class.</see>
public Application create(ApplicationOptions options = null)
{
string json = base.POST(this.path, ((options != null) ? options.toJson() : null));
if (string.IsNullOrEmpty(json) == true)
{
throw new PersyException(String.Format("Failed to create application with options {0}", ((options != null) ? options.toJson() : string.Empty)));
}
return Application.fromJson(json);
}
/// <summary>
/// Update a single application.
/// </summary>
/// <param name="applicationId">The applicationId of the target application.</param>
/// <param name="options">Optional ApplicationOptions instance to be used when updating an application.</param>
/// <returns>The updated application matching the applicationId provided.</returns>
/// <exception cref="PersyException">Thrown upon failed request.</exception>
public Application update(string applicationId, ApplicationOptions options = null)
{
string json = base.POST(String.Format("{0}/{1}", this.path, applicationId), ((options != null) ? options.toJson() : null));
if (string.IsNullOrEmpty(json) == true)
{
throw new PersyException(String.Format("Failed to update application {0} information", applicationId ?? ""));
}
return Application.fromJson(json);
}
/// <summary>
/// Delete a Persephony application.
/// </summary>
/// <param name="applicationId">The applicationId of the target application.</param>
/// <exception cref="PersyException">Thrown upon failed request.</exception>
public void delete(string applicationId)
{
base.DELETE(String.Format("{0}/{1}", this.path, applicationId));
}
}
}
|
3f753d96c0a45cb00a803379ddd794e4c3b6d618
|
C#
|
nareshkumar66675/AutoBuild
|
/AutoBuild/Tasks/CopyInstallerBuildTask.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoBuild.Helper;
using System.Configuration;
using System.IO;
using BMC.Common.LogManagement;
using BMC.Common.ExceptionManagement;
namespace AutoBuild.Tasks
{
class CopyInstallerBuildTask:BuildTask
{
public override int Execute(TaskInfo TaskInfo)
{
string installerSourceFolder = ConfigurationManager.AppSettings["InstallerSourceFolder"];
string installerDestinationFolder = ConfigurationManager.AppSettings["InstallerDestinationFolder"];
int daysToRetain ;
if (int.TryParse(ConfigurationManager.AppSettings["DaysToRetain"], out daysToRetain) == false)
{
daysToRetain = 2;
LogManager.WriteLog("Error in DaysToRetain Setting. Configuring it to Default Value - " +daysToRetain,LogManager.enumLogLevel.Warning);
}
try
{
if (Directory.Exists(installerSourceFolder))
{
if (!Directory.Exists(installerDestinationFolder))
Directory.CreateDirectory(installerDestinationFolder);
DirectoryInfo info = new DirectoryInfo(installerDestinationFolder);
foreach (DirectoryInfo dir in info.EnumerateDirectories("*", SearchOption.TopDirectoryOnly))
{
if (dir.CreationTime < DateTime.Now.AddDays(-daysToRetain))
DeleteDirectory(dir.FullName,true);//Directory.Delete(dir.FullName, true);
}
string buildPath = Path.Combine(installerDestinationFolder, "BMC Nightly Build - " + DateTime.Now.ToString("dd-MM-yyyy"));
if (Directory.Exists(buildPath))
DeleteDirectory(buildPath, true);
CopyDirectory(installerSourceFolder, buildPath);
return 1;
}
else
return -1;
}
catch (Exception ex)
{
ExceptionManager.Publish(ex);
LogManager.WriteLog("Error Occured while Copying installer files", LogManager.enumLogLevel.Error);
return -1;
}
}
private void CopyDirectory(string Source, string Destination)
{
if (!Directory.Exists(Destination))
{
Directory.CreateDirectory(Destination);
}
DirectoryInfo dirInfo = new DirectoryInfo(Source);
FileInfo[] files = dirInfo.GetFiles();
foreach (FileInfo tempfile in files)
{
tempfile.CopyTo(Path.Combine(Destination, tempfile.Name));
}
DirectoryInfo[] directories = dirInfo.GetDirectories();
foreach (DirectoryInfo tempdir in directories)
{
CopyDirectory(Path.Combine(Source, tempdir.Name), Path.Combine(Destination, tempdir.Name));
}
}
private static void DeleteDirectory(string path, bool recursive)
{
if (recursive)
{
var subfolders = Directory.GetDirectories(path);
foreach (var s in subfolders)
{
DeleteDirectory(s, recursive);
}
}
var files = Directory.GetFiles(path);
foreach (var f in files)
{
var attr = File.GetAttributes(f);
if ((attr & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
File.SetAttributes(f, attr ^ FileAttributes.ReadOnly);
}
File.Delete(f);
}
Directory.Delete(path);
}
}
}
|
85c18e48073a7db6c11b80949b9aea9ec83d2a76
|
C#
|
Kingefosa/QuickGenerate
|
/QuickGenerate.Tests/EntityGeneratorTests/PluggableFunctionsTests.cs
| 2.796875
| 3
|
using Xunit;
namespace QuickGenerate.Tests.EntityGeneratorTests
{
public class PluggableFunctionsTests
{
[Fact]
public void GeneratorIsApplied()
{
var generator =
new EntityGenerator<SomethingToGenerate>()
.For(e => e.MyProperty,
0, val => ++val,
val => string.Format("SomeString{0}", val));
Assert.Equal("SomeString1", generator.One().MyProperty);
Assert.Equal("SomeString2", generator.One().MyProperty);
Assert.Equal("SomeString3", generator.One().MyProperty);
Assert.Equal("SomeString4", generator.One().MyProperty);
Assert.Equal("SomeString5", generator.One().MyProperty);
Assert.Equal("SomeString6", generator.One().MyProperty);
}
public class SomethingToGenerate
{
public string MyProperty { get; set; }
}
}
}
|
aa940109f4804cdde725ad9c0bc7a4d1dd27763a
|
C#
|
afrasier02/MartiniGlassApp
|
/MartiniGlassApp/MartiniProgram.cs
| 3.453125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MartiniGlassApp
{
class MartiniProgram
{
static char GlassSymbol = '0';
static char SpaceSymbol = ' ';
static char HandleSymbol = '|';
static char BottomSymbol = '=';
static void Main(string[] args)
{
Console.WriteLine("\nHow big would you like your Martini glass? ");
var size = Convert.ToInt32(Console.ReadLine());
//Set the size of the top of the glass
var topGlassSize = (size * 2) - 1;
//Keep track of side spacing for handle
int sideSpacing = 0;
for (int i = 0; i < size; i++)
{
var glassRow = new string(GlassSymbol, topGlassSize);
//Add Spacing after first row
if (i != 0)
{
var spacing = new string(SpaceSymbol, i);
glassRow = (spacing + glassRow + spacing);
}
Console.WriteLine(glassRow);
topGlassSize = topGlassSize - 2;
sideSpacing = i;
}
AddMartiniGlassBottom((size * 2) - 1, size, sideSpacing);
Console.Write("\nPress any key to exit...");
Console.ReadKey(true);
}
/// <summary>
/// Loop through and add handle and bottom of Martini Glass
/// </summary>
/// <param name="glassBottomSize">Size of Bottom of Martini Glass</param>
/// <param name="holdCount">Size of Handle</param>
/// <param name="sideSpacing">Line handle in center of glass</param>
static void AddMartiniGlassBottom(int glassBottomSize, int holdCount, int sideSpacing)
{
for (int i = 0; i < holdCount; i++)
{
var spacing = new string(SpaceSymbol, sideSpacing);
Console.WriteLine(spacing + new string(HandleSymbol, 1) + spacing);
}
Console.WriteLine(new string(BottomSymbol, glassBottomSize));
}
}
}
|
2ac47825773154fb27a458bee593edaaae886854
|
C#
|
anhellwig/BibTeXLibrary
|
/BibTeXLibrary/BibEntry.cs
| 3.40625
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
namespace BibTeXLibrary
{
public class BibEntry : IEnumerable<KeyValuePair<string, string>>
{
private readonly Dictionary<string, string> tags = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
public string Key { get; set; }
public string Type { get; set; }
/// <summary>
/// Get value by given tagname(index) or create new tag by index and value.
/// </summary>
/// <param name="index"></param>
/// <returns>The value if the key exists, otherwise `null`.</returns>
public string this[string index]
{
get
{
return this.tags.TryGetValue(index.ToLowerInvariant(), out var value) ? value : null;
}
set
{
if (string.IsNullOrWhiteSpace(value))
{
if (this.ContainsKey(index))
{
this.tags.Remove(index);
}
}
else
{
this.tags[index.ToLowerInvariant()] = value;
}
}
}
public bool ContainsKey(string key) => this.tags.ContainsKey(key);
public IEnumerator<KeyValuePair<string, string>> GetEnumerator() => this.tags.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => this.tags.GetEnumerator();
}
}
|
27c98cc86ad4ec8f700d98de18122aa39bc1f5d0
|
C#
|
archyyu/cyberServer
|
/ClassLibrary/Util/Config.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
namespace CashierLibrary.Util
{
public class Config
{
private static Config config;
public static void initConfig()
{
StreamReader sr = new StreamReader("config.json", Encoding.Default);
String line = "";
String content = "";
while ((line = sr.ReadLine()) != null)
{
content += line;
}
config = JsonUtil.DeserializeJsonToObject<Config>(content);
}
public static Config get()
{
return config;
}
public String host { get; set; }
public String port { get; set; }
public String version { get; set; }
}
}
|
009050e9f55379b0acfce4171a7579d1dc7c1a7e
|
C#
|
namelessbliss/TussanStorageAdm
|
/CAPA_DATOS/ClassAdo.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.OleDb;
using System.Data;
namespace CAPA_DATOS {
/// <summary>
/// Descripción breve de ClassAdo
/// </summary>
public class ClassAdo {
protected OleDbConnection con = new OleDbConnection();
protected OleDbCommand cmd;
public ClassAdo() {
}
public void conexion(ObjConexion obj) //msn mensaje de retorno
{
con.ConnectionString = "Provider=SQLNCLI11;Data Source=" + obj.Server + ";Persist Security Info=True;User ID=" + obj.User + ";password=" + obj.Pass + ";Initial Catalog=" + obj.DB;
con.Open();
}
public void transaccion(string sql) //1.- exito, 0 fallo
{
cmd.Connection = con;
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
public int login(string sql) //1.- exito, 0 fallo
{
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = sql;
int resultado = (Int32)cmd.ExecuteScalar();
return resultado;
}
public int selectEscalar(string sql) //1.- exito, 0 fallo
{
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = sql;
int resultado = (Int32)cmd.ExecuteScalar();
return resultado;
}
public DataSet consultasql(string sql) //retorna datos
{
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(sql, con);
da.Fill(ds, "tabla");
con.Close();
return ds;
}
public DataTable consultasqlDataTable(string sql) //retorna datos
{
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(sql, con);
da.Fill(dt);
con.Close();
return dt;
}
public void closeConexion() {
if (cmd != null)
cmd.Dispose();
con.Close();
}
}
}
|
180a2ec1ac074cd9eddcbfed82a07517eae03647
|
C#
|
EobanZ/GameOfLife
|
/Game of Life/Assets/Scripts/GameManager.cs
| 2.59375
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class GameManager : GenericSingletonClass<GameManager> {
private static float timer = 0;
private bool fieldIsReady = false;
private Cell[,] cells; //refs to the instantiated cells will be stored here
private Camera camera;
private int fieldSizeY;
private int fieldSizeX;
private bool simulate = false;
private float refreshTime; //fps
[SerializeField] private GameObject toolPanel; //ref to the Tool Panel
[SerializeField] private TMPro.TMP_Text fpsText; //ref to the FPS text
[SerializeField] private GameObject field; //ref to the field
[SerializeField] private GameObject cellPrefab; //the Prefab used for the Cells
[SerializeField] private MapContainerSO maps; //ref to the MapContainer ScriptableObject
[SerializeField] private CellSO cellProperties; //ref tho the Cell Properties ScriptableObject
public Sprite PlayButtonIcon, PauseButtonIcon;
public Image PlayPauseButtonImage;
public GameObject CellPrefab { get { return cellPrefab; } }
public GameObject Field { get { return field; } }
public Cell[,] Cells { get { return cells; } }
public Vector2Int FieldSize { get { return new Vector2Int(fieldSizeX, fieldSizeY); } }
#region Private Methods
private void Start ()
{
//If a Map was chosen, get the Maps settings. Else use the randomWith and calculate Y Cells
if(maps.ChosenMap != null)
{
fieldSizeX = maps.ChosenMap.Width;
fieldSizeY = maps.ChosenMap.Height;
}
else
{
fieldSizeX = maps.randomWidth;
fieldSizeY = Mathf.RoundToInt(fieldSizeX * (1 / Camera.main.aspect));
}
camera = Camera.main;
cells = new Cell[fieldSizeX,fieldSizeY];
refreshTime = cellProperties.fps;
fpsText.text = "FPS: " + refreshTime.ToString();
PositionCamera();
StartCoroutine(BuildFieldCR());
}
private void Update () {
timer += Time.deltaTime;
//updates the field depending on the framerate. field has to be ready and simulate flag has to be true
if(timer > (float)1/refreshTime && fieldIsReady && simulate)
{
UpdateField();
timer = 0;
}
}
/// <summary>
/// Positions the camera depending on the width and height of the field
/// </summary>
void PositionCamera()
{
camera.transform.position = new Vector3((float)fieldSizeX / 2 - 0.5f, (float)fieldSizeY / 2 - 0.5f, -1);
camera.orthographicSize = fieldSizeX >= fieldSizeY? fieldSizeY/2 : fieldSizeX/2 ;
}
/// <summary>
/// Coroutine to build the field from a map or random
/// </summary>
/// <returns></returns>
IEnumerator BuildFieldCR()
{
for (int y = 0; y < fieldSizeY; y++)
{
for (int x = 0; x < fieldSizeX; x++)
{
GameObject go = (GameObject)Instantiate(cellPrefab, new Vector3(x, y, 0), Quaternion.identity, field.transform); //create cell gameobject in the scene as child of the field
Cell c = go.GetComponent<Cell>(); //get the Cell Script
c.SetFieldPosition(x, y); //tell the cell its position
cells[x, y] = c; //write a reference to the created cell in our array
if (maps.ChosenMap == null) //If no map is chosen, build a random field
{
int i = (int)Random.Range(0, 1.99f);
bool b = i == 0 ? false : true;
go.GetComponent<Cell>().SetAlive(b);
}
else //Build the chosen Map
{
go.GetComponent<Cell>().SetAlive(maps.ChosenMap.Field[x, y]);
}
}
}
fieldIsReady = true;
yield return null;
}
/// <summary>
/// Updates each cell in the Field
/// </summary>
void UpdateField()
{
//Get the next state for each cell
for (int y = 0; y < fieldSizeY; y++)
{
for (int x = 0; x < fieldSizeX; x++)
{
cells[x, y].GetNextState();
}
}
//Apply the next state
for (int y = 0; y < fieldSizeY; y++)
{
for (int x = 0; x < fieldSizeX; x++)
{
cells[x, y].ApplyNextGeneration();
}
}
}
#endregion
#region public Methods
public void ToggleSimulate()
{
simulate = !simulate;
if (simulate)
{
toolPanel.SetActive(false);
PlayPauseButtonImage.sprite = PauseButtonIcon;
}
else
{
toolPanel.SetActive(true);
PlayPauseButtonImage.sprite = PlayButtonIcon;
}
}
public void LoadLauncher()
{
SceneManager.LoadScene(0);
}
public void IncrementFPS()
{
if (refreshTime == cellProperties.maxFPS)
return;
refreshTime++;
fpsText.text = "FPS: "+ refreshTime.ToString();
}
public void DecrementFPS()
{
if (refreshTime == cellProperties.minFPS)
return;
refreshTime--;
fpsText.text = "FPS: " + refreshTime.ToString();
}
#endregion
}
|
27dabdbe2801f6aac32edc3c74ad889b435cfa97
|
C#
|
genie30/TRPGTool
|
/Assets/Scripts/Tile/ZoomController.cs
| 2.53125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ZoomController : MonoBehaviour
{
[SerializeField]
Camera cam;
[SerializeField]
float min, max, zoom, movestep;
Vector3 startpos;
private void Update()
{
if(Input.GetAxis("Mouse ScrollWheel") != 0)
{
var scr = Input.GetAxis("Mouse ScrollWheel");
var tmp = cam.orthographicSize + scr * zoom;
if (tmp < 3f)
{
cam.orthographicSize = 3f;
}
else if (tmp > 12)
{
cam.orthographicSize = 12f;
}
else
{
cam.orthographicSize = tmp;
}
}
if (Input.GetMouseButtonDown(1))
{
startpos = Input.mousePosition;
}
if (Input.GetMouseButton(1))
{
float x = (startpos.x - Input.mousePosition.x) / Screen.width;
float y = (startpos.y - Input.mousePosition.y) / Screen.height;
x *= movestep;
y *= movestep;
var movepos = cam.transform.position + new Vector3(x, y, 0);
cam.transform.position = movepos;
}
}
}
|
1587d014276bc8b3250c5f18b8f766beb2e676da
|
C#
|
BarryAustin1993/WhiteBoardChallengesRepo
|
/WhiteBoardChallenges/ChallengeFour_CurrentComboNeededCombo_FastestTurnsToReachNeededCombo.cs
| 3.640625
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WhiteBoardChallenges
{
class ChallengeFour_CurrentComboNeededCombo_FastestTurnsToReachNeededCombo
{
//Member Variables (HAS A)
readonly string currentLock = "3893";
readonly string targetLock = "5296";
int currentLockInt;
int targetLockInt;
int leftTurn;
int rightTurn;
string message;
int totalTurns;
//Constructor
//Member Methods (CAN DO)
public void RunChallengeFour()
{
DetermineTheCorrectTurn();
Console.WriteLine($"Minimum turns to hit target: {totalTurns}");
Console.ReadLine();
}
void DetermineTheCorrectTurn()
{
for (int i = 0; i < currentLock.Length; i++)
{
Int32.TryParse(currentLock[i].ToString(), out currentLockInt);
Int32.TryParse(targetLock[i].ToString(), out targetLockInt);
CompareCurrentAndTargetInts();
Console.WriteLine($"{i}. {message}");
}
}
void CompareCurrentAndTargetInts()
{
if (currentLockInt > targetLockInt)
{
DetermineAmountOfTurnsWhenCurrentLockIsLarger();
}
else if (currentLockInt < targetLockInt)
{
DetermineAmountOfTurnsWhenCurrentLockIsSmaller();
}
else if (currentLockInt == targetLockInt)
{
message = "Do not change the lock it is already correct";
}
}
void DetermineAmountOfTurnsWhenCurrentLockIsLarger()
{
leftTurn = currentLockInt - targetLockInt;
rightTurn = 10 - leftTurn;
TellUserWhichWayAndHowMuchToTurn();
}
void DetermineAmountOfTurnsWhenCurrentLockIsSmaller()
{
rightTurn = targetLockInt - currentLockInt;
leftTurn = 10 - rightTurn;
TellUserWhichWayAndHowMuchToTurn();
}
void TellUserWhichWayAndHowMuchToTurn()
{
if (leftTurn < rightTurn)
{
totalTurns += leftTurn;
message = $"Turn left {leftTurn} times.";
}
else if (rightTurn < leftTurn)
{
totalTurns += rightTurn;
message = $"Turn right {rightTurn} times.";
}
else
{
totalTurns += rightTurn;
message = $"Turn either way {rightTurn} times.";
}
}
}
}
|
065103525d1af122830021d9363f4d0713ffdc1e
|
C#
|
cyrsis/LearnCSharp
|
/TDD/14-Moq'ing-a-Database/ShoppingCart/ShppingCart.Common/CartItem.cs
| 3.078125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShoppingCart.Common
{
public class CartItem
{
public int Quantity { get; set; }
public string Description { get; private set; }
public decimal UnitPrice { get; private set; }
public decimal Discount { get; private set; }
public CartItem(int quantity, string description, decimal unitPrice)
{
Quantity = quantity;
Description = description;
UnitPrice = unitPrice;
}
public decimal GetItemPrice()
{
var price = (Quantity * UnitPrice) - Discount;
return price < 0m ? 0m : price;
}
public void ApplyDiscount(decimal discountAmount)
{
Discount = discountAmount;
}
}
}
|
87fb2a7121dcfcacaad99d9ab77da12f8639eb74
|
C#
|
VivekReddy92/devops-days
|
/NET_Service/SimpleRest/SimpleRest/CloudConnectionHelper.cs
| 2.703125
| 3
|
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace OrderRest
{
public class CloudConnectionHelper
{
//Look up connection from either vCaps sevice or local
public static string connectionString()
{
//if running outside PCF this will be NULL
if (Environment.GetEnvironmentVariable("VCAP_SERVICES") != null)
{
Dictionary<string, object> vcapServices = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(
Environment.GetEnvironmentVariable("VCAP_SERVICES"));
if (vcapServices != null)
{
// this is the dumb way - this is the smart way https://github.com/dmikusa-pivotal/cf-ex-phpmyadmin/blob/master/htdocs/config.inc.php
var credentials = ((Newtonsoft.Json.Linq.JArray)vcapServices["p-mysql"]).First()["credentials"];
if (credentials != null)
{
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = (String)credentials["hostname"];
conn_string.Port = (uint)Int32.Parse((String)credentials["port"]);
conn_string.UserID = (String)credentials["username"];
conn_string.Password = (String)credentials["password"];
conn_string.Database = (String)credentials["name"];
//Note that the DB is not listed. This is supplied by the service
Console.WriteLine("We are using the following to connect to the DB: " + conn_string.ToString());
return conn_string.ToString();
}
}
}
//this is the local connection
return "Server=localhost;Uid=root;Pwd=password;Database=orderdb";
}
}
}
|
e3b1b4f85fde412c7638ada078b9c81034879e1c
|
C#
|
emscape2/Unity-Renderering-Extension
|
/Scripts/Interactivity/Interactions/TimedTrigger.cs
| 2.53125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TimedTrigger : Interaction
{
bool triggered;
public bool disengage;
public float timedDelay;
private bool started;
public override bool? TryInteract(GameObject gameObject)
{
if (this.gameObject.transform.position.x > -0.01)
{
started = false;
}
if (!started)
{
if (this.gameObject.transform.position.x > -timedDelay)
{
return null;
}
started = true;
}
if (!triggered)
{
triggered = true;
return true;
}
if (disengage) return false;
return true;
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
|
322fc50b1a87fcaaa56194395cb5b267342d1a93
|
C#
|
tefkros777/breakout
|
/Assets/Scripts/Commands/BounceCommand.cs
| 2.625
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class BounceCommand : Command
{
// All data that defines this command
Vector2 mIncomingVelocity;
ContactPoint2D mCollisionPoint;
private float mSpeed;
// For optimization
private Vector2 newDirection;
public BounceCommand(IEntity entity, float time, Vector2 incomingVelocity, ContactPoint2D collisionPoint, float speed) : base (entity, time)
{
mIncomingVelocity = incomingVelocity;
mCollisionPoint = collisionPoint;
mSpeed = speed;
}
public override void Execute()
{
newDirection = Vector2.Reflect(mIncomingVelocity.normalized, mCollisionPoint.normal);
mEntity.SetVelocity(newDirection * mSpeed);
}
public override void Undo()
{
throw new System.NotImplementedException();
}
}
|
358729f642f470eb62f4457ca3847d191bf0b18a
|
C#
|
lesya-tishencko/TestSQLite
|
/SQLite_ya_test_proj/Program.cs
| 2.984375
| 3
|
using System;
namespace SQLite_ya_test_proj
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine("Don't set name of source file");
return;
}
string path = args[0];
Console.WriteLine(path);
DBHandler.DBCreateStructure();
DBHandler.DBFillOrders(path);
int commandNum = -1;
while (commandNum != 0)
{
Console.WriteLine("Put query number(1,2,3): ");
if (!int.TryParse(Console.ReadLine(), out commandNum))
{
commandNum = -1;
continue;
}
switch (commandNum)
{
case 1:
DBHandler.DBCountSumQuery();
break;
case 2:
DBHandler.DBQueryDiffCurrMonth();
break;
case 3:
DBHandler.DBQueryMonthStatistics();
break;
default:
Console.WriteLine("Invalid number of query");
break;
}
}
}
}
}
|
fb797761c3149c56657b353b2b94a2decd9e1373
|
C#
|
BIMobileApp/BIWebService
|
/BILibraryBLL/OldBarAllTaxSQL.cs
| 2.65625
| 3
|
using ClassLib;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Web;
namespace BILibraryBLL
{
public class OldBarAllTaxSQL
{ //get connectionString to connect Database
Conn con = new Conn();
//query out in dataTable
public DataTable SQL1()
{
//create datatable format in 'dt'
DataTable dt = new DataTable();
//create connection to access database by OleDbConnection
using (OleDbConnection thisConnection = new OleDbConnection(con.connection()))
{
//string q = "select * from Ic_Sum_Allday_Cube";
string q = "select b.sort as no, b.group_name as grp_name" +
" ,nvl(sum(a.tax_nettax_amt), 0) as tax" +
" ,nvl(sum(a.last_tax_nettax_amt), 0) as tax_ly" +
" ,nvl(sum(a.estimate), 0) as est "+
" from ic_sum_allday_cube a, ic_product_grp_dim b" +
" where a.product_grp_cd = b.group_id" +
" and a.product_grp_cd in (0101, 0501, 7001, 8001, 7002, 0201, 1690)" +
" and a.time_id between 20180501 and 20180531" +
" group by b.sort, b.group_name" +
" order by b.sort";
//prepare get q to use with thisconnection by command
OleDbCommand cmd = new OleDbCommand(q, thisConnection);
thisConnection.Open();
//Execute q
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
//get result to fill in 'dt'
adapter.Fill(dt);
thisConnection.Close();
return dt;
}
}
}
}
|
5ca28ebd080e6416d1842f5436f8381adb06f41f
|
C#
|
abdelrahman-abdelhameed/play-with-gmail-API-
|
/GmailWittMVC/Utilities/EmailConverterHelper.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;
namespace GmailWittMVC.Utilities
{
public static class EmailConverterHelper
{
public static byte[] Base64UrlDecode(string arg)
{
// Convert from base64url string to base64 string
string s = arg;
s = s.Replace('-', '+').Replace('_', '/');
switch (s.Length % 4)
{
case 0:
break; // No pad chars in this case
case 2:
s += "==";
break; // Two pad chars
case 3:
s += "=";
break; // One pad char
default:
throw new Exception("Illegal base64url string!");
}
return Convert.FromBase64String(s);
}
public static string GetUntilOrEmpty(this string text, string stopAt = "<html")
{
if (!String.IsNullOrWhiteSpace(text))
{
int charLocation = text.IndexOf(stopAt, StringComparison.Ordinal);
if (charLocation > 0)
{
return text.Substring(charLocation);
}
}
return String.Empty;
}
public static string MsgNestedParts(IList<MessagePart> Parts)
{
string str = string.Empty;
if (Parts.Count() < 0)
{
return string.Empty;
}
else
{
IList<MessagePart> PlainTestMail = Parts.Where(x => x.MimeType == "text/plain").ToList();
IList<MessagePart> AttachmentMail = Parts.Where(x => x.MimeType == "multipart/alternative").ToList();
if (PlainTestMail.Count() > 0)
{
foreach (MessagePart EachPart in PlainTestMail)
{
if (EachPart.Parts == null)
{
if (EachPart.Body != null && EachPart.Body.Data != null)
{
str += EachPart.Body.Data;
}
}
else
{
return MsgNestedParts(EachPart.Parts);
}
}
}
if (AttachmentMail.Count() > 0)
{
foreach (MessagePart EachPart in AttachmentMail)
{
if (EachPart.Parts == null)
{
if (EachPart.Body != null && EachPart.Body.Data != null)
{
str += EachPart.Body.Data;
}
}
else
{
return MsgNestedParts(EachPart.Parts);
}
}
}
return str;
}
}
public static string Base64Decode(string Base64Test)
{
string EncodTxt = string.Empty;
//STEP-1: Replace all special Character of Base64Test
EncodTxt = Base64Test.Replace("-", "+");
EncodTxt = EncodTxt.Replace("_", "/");
EncodTxt = EncodTxt.Replace(" ", "+");
EncodTxt = EncodTxt.Replace("=", "+");
//STEP-2: Fixed invalid length of Base64Test
if (EncodTxt.Length % 4 > 0) { EncodTxt += new string('=', 4 - EncodTxt.Length % 4); }
else if (EncodTxt.Length % 4 == 0)
{
EncodTxt = EncodTxt.Substring(0, EncodTxt.Length - 1);
if (EncodTxt.Length % 4 > 0) { EncodTxt += new string('+', 4 - EncodTxt.Length % 4); }
}
//STEP-3: Convert to Byte array
byte[] ByteArray = Convert.FromBase64String(EncodTxt);
//STEP-4: Encoding to UTF8 Format
return Encoding.UTF8.GetString(ByteArray);
}
public static byte[] Base64ToByte(string Base64Test)
{
string EncodTxt = string.Empty;
//STEP-1: Replace all special Character of Base64Test
EncodTxt = Base64Test.Replace("-", "+");
EncodTxt = EncodTxt.Replace("_", "/");
EncodTxt = EncodTxt.Replace(" ", "+");
EncodTxt = EncodTxt.Replace("=", "+");
//STEP-2: Fixed invalid length of Base64Test
if (EncodTxt.Length % 4 > 0) { EncodTxt += new string('=', 4 - EncodTxt.Length % 4); }
else if (EncodTxt.Length % 4 == 0)
{
EncodTxt = EncodTxt.Substring(0, EncodTxt.Length - 1);
if (EncodTxt.Length % 4 > 0) { EncodTxt += new string('+', 4 - EncodTxt.Length % 4); }
}
//STEP-3: Convert to Byte array
return Convert.FromBase64String(EncodTxt);
}
}
}
|
a7c00657cf32d601edf8f4c95130bfac90559d85
|
C#
|
Nickose777/SportBets
|
/SportBet/LoginWindow.xaml.cs
| 2.546875
| 3
|
using System;
using System.Windows;
using SportBet.Services.Contracts;
using SportBet.Services.Contracts.Services;
using SportBet.Services.DTOModels;
using SportBet.Services.Providers;
using SportBet.Services.ResultTypes;
using SportBet.ControllerFactories;
using SportBet.Contracts;
using SportBet.Logs;
namespace SportBet
{
/// <summary>
/// Interaction logic for LoginWindow.xaml
/// </summary>
public partial class LoginWindow : Window
{
private bool shouldBeClosed = true;
public LoginWindow()
{
InitializeComponent();
this.loginTxt.Focus();
}
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
using (IAuthService service = new AuthService())
{
bool connectionEstablished = service.EstablishConnection();
if (!connectionEstablished)
{
MessageBox.Show("Cannot establish connection to database! The program will be closed");
this.Close();
}
}
}
private void Login_Click(object sender, RoutedEventArgs e)
{
Login();
}
private void Login()
{
using (IAuthService authService = new AuthService())
{
string login = loginTxt.Text;
string password = passwordTxt.Password;
UserLoginDTO userLogin = new UserLoginDTO
{
Login = login,
Password = password
};
LoginServiceMessage result = authService.Login(userLogin);
if (result.IsSuccessful)
{
loginTxt.Clear();
passwordTxt.Clear();
LoginType loginType = result.LoginType;
ServiceFactory factory = result.Factory;
ControllerFactory controllerFactory = new ControllerFactory(factory, loginType, login);
ILogger logger = new Logger();
SignOutWindowBase window = Create(controllerFactory, logger, loginType, login);
window.SignedOut += (s, e) =>
{
this.Show();
shouldBeClosed = false;
window.Close();
};
window.Closed += (s, e) => this.Close();
window.Show();
this.Hide();
}
else
{
MessageBox.Show("Could not login: " + result.Message);
}
}
}
private SignOutWindowBase Create(ControllerFactory controllerFactory, ILogger logger, LoginType loginType, string login)
{
SignOutWindowBase window = null;
switch (loginType)
{
case LoginType.Superuser:
window = new SuperuserControls.SuperuserMainWindow(controllerFactory, logger);
break;
case LoginType.Admin:
window = new AdminControls.AdminMainWindow(controllerFactory, logger);
break;
case LoginType.Analytic:
window = new AnalyticControls.AnalyticMainWindow(controllerFactory, logger);
break;
case LoginType.Bookmaker:
window = new BookmakerControls.BookmakerMainWindow(controllerFactory, logger);
break;
case LoginType.Client:
window = new ClientControls.ClientMainWindow(controllerFactory, logger);
break;
case LoginType.NoLogin:
MessageBox.Show("Your role wasn't recognized! The program will be closed");
this.Close();
break;
default:
break;
}
window.WindowState = System.Windows.WindowState.Maximized;
window.Title = String.Format("Welcome, {0}!", login);
return window;
}
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
e.Cancel = !shouldBeClosed;
shouldBeClosed = true;
base.OnClosing(e);
}
}
}
|
a6f166097ad7eadc16a02886853b9630410910aa
|
C#
|
pivovard/ZCU
|
/PIA_BankWebsite/Bank/Bank/Data/BankContext.User.cs
| 3.25
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Bank.Models
{
public partial class BankContext
{
/// <summary>
/// Generate unique login and hash pin.
/// Set it to the given user.
/// Returns pin in no hash.
/// </summary>
/// <param name="user">User</param>
/// <returns>Pin in no hash</returns>
public int GenerateLogin(User user)
{
Random r = new Random();
string login;
do
{
login = r.Next(10000000, 100000000).ToString();
} while (this.User.Any(a => a.Login == login));
user.Login = login;
int pin = r.Next(1000, 10000);
user.Pin = user.HashPin(pin);
return pin;
}
/// <summary>
/// Generate unique account number
/// </summary>
/// <returns>account number</returns>
public long GenerateAccountNumber()
{
Random r = new Random();
long n;
do
{
n = r.Next(10000000, 100000000) * 100000000L + r.Next(10000000, 100000000);
} while (this.User.Any(a => a.AccountNumber == n));
return n;
}
/// <summary>
/// Generate unique card number
/// </summary>
/// <returns>card number</returns>
public long GenerateCardNumber()
{
Random r = new Random();
long n;
do
{
n = r.Next(10000000, 100000000) * 100000000L + r.Next(10000000, 100000000);
} while (this.User.Any(a => a.CardNumber == n));
return n;
}
/// <summary>
/// Returns if account number is unique
/// </summary>
/// <param name="acc">account number</param>
/// <returns>True if unique, false if not</returns>
public bool IsAccountUnique(long acc)
{
return !this.User.Any(a => a.AccountNumber == acc);
}
/// <summary>
/// Returns if card number is unique
/// </summary>
/// <param name="acc">card number</param>
/// <returns>True if unique, false if not</returns>
public bool IsCardUnique(long card)
{
return !this.User.Any(a => a.CardNumber == card);
}
}
}
|
dc2ccd824b1c0239fcffec8e3d0ed75027e1e597
|
C#
|
TheodorLindberg/Mindstorm-controller
|
/ManagedCSharp/ManagedClass.cs
| 2.953125
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
using EV3MessengerLib;
namespace ManagedCSharp
{
public static class ManagedClass
{
public static List<EV3Message> messages = new List<EV3Message>();
public static int Value;
private static EV3Messenger messenger = new EV3Messenger();
public static SerialPort port;
public static int ShowValue()
{
DialogResult result = MessageBox.Show("C# Message Box", "C# Message Box", MessageBoxButtons.OKCancel);
if (result == DialogResult.OK)
return 1;
else
return 2;
}
public static int GetValue()
{
return Value;
}
public static void ChangeValue(int newvalue)
{
Value = newvalue;
}
public static bool UpdateMessageReciving()
{
if (messenger.IsConnected)
{
EV3Message message = messenger.ReadMessage();
if (message != null)
{
messages.Add(message);
return true;
}
}
return false;
}
//EV3 messanger function lib
public static void Connect(int port)
{
messenger.Connect("COM" + port.ToString());
}
public static void Disconnect()
{
messenger.Disconnect();
}
public static bool IsConnected()
{
return messenger.IsConnected;
}
public static void SendMessage(string title, string value)
{
messenger.SendMessage(title, value);
}
public static void SendMessage(string title, float value)
{
messenger.SendMessage(title.ToString(), value);
}
public static void SendMessage(string title, bool value)
{
messenger.SendMessage(title.ToString(), value);
}
public static int GetAvilableMessages()
{
return messages.Count;
}
public static bool AvilableMessage()
{
return messages.Count > 0;
}
public static string ReadMessageTitle()
{
return messages[0].MailboxTitle;
}
public static string ReadMessageText()
{
return messages[0].ValueAsText;
}
public static float ReadMessageNumber()
{
return messages[0].ValueAsNumber;
}
public static bool ReadMessageLogic()
{
bool message = messages[0].ValueAsLogic;
messages.RemoveAt(0);
return message;
}
}
}
|
423d001a33b366b153ba1b0ef4945a12519598ec
|
C#
|
dotnet/iot
|
/src/devices/Ssd13xx/Commands/Ssd1306Commands/SetMemoryAddressingMode.cs
| 2.8125
| 3
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace Iot.Device.Ssd13xx.Commands.Ssd1306Commands
{
/// <summary>
/// Represents SetMemoryAddressingMode command
/// </summary>
public class SetMemoryAddressingMode : ISsd1306Command
{
/// <summary>
/// This command sets the memory addressing mode.
/// </summary>
/// <param name="memoryAddressingMode">Memory addressing mode.</param>
public SetMemoryAddressingMode(AddressingMode memoryAddressingMode = AddressingMode.Page)
{
MemoryAddressingMode = memoryAddressingMode;
}
/// <summary>
/// The value that represents the command.
/// </summary>
public byte Id => 0x20;
/// <summary>
/// Memory addressing mode.
/// </summary>
public AddressingMode MemoryAddressingMode { get; }
/// <summary>
/// Gets the bytes that represent the command.
/// </summary>
/// <returns>The bytes that represent the command.</returns>
public byte[] GetBytes()
{
return new byte[] { Id, (byte)MemoryAddressingMode };
}
/// <summary>
/// Addressing mode
/// </summary>
public enum AddressingMode
{
/// <summary>
/// In horizontal addressing mode, after the display RAM is read/written, the column address
/// pointer is increased automatically by 1. If the column address pointer reaches column end
/// address, the column address pointer is reset to column start address and page address
/// pointer is increased by 1. When both column and page address pointers reach the end address,
/// the pointers are reset to column start address and page start address.
/// </summary>
Horizontal = 0x00,
/// <summary>
/// In vertical addressing mode, after the display RAM is read/written, the page address pointer
/// is increased automatically by 1. If the page address pointer reaches the page end address,
/// the page address pointer is reset to page start address and column address pointer is
/// increased by 1. When both column and page address pointers reach the end address, the
/// pointers are reset to column start address and page start address.
/// </summary>
Vertical = 0x01,
/// <summary>
/// In page addressing mode, after the display RAM is read/written, the column address pointer
/// is increased automatically by 1. If the column address pointer reaches column end address,
/// the column address pointer is reset to column start address and page address pointer is not
/// changed. Users have to set the new page and column addresses in order to access the next
/// page RAM content.
/// </summary>
Page = 0x02,
}
}
}
|
89836c1a1e362bdff0de2d709bd1a75f3c7f7fc5
|
C#
|
LeszekBlazewski/ReportGenerator
|
/ReportGenerator.UnitTests/OrderCreator.cs
| 3.3125
| 3
|
using ReportGenerator.Utilities;
using System.Collections.Generic;
namespace ReportGenerator.UnitTests
{
/// <summary>
/// Class contains methods which create specific data to fill the database for various unit tests.
/// </summary>
class OrderCreator
{
/// <summary>
/// Creates list of three orders where two orders refer to same request id.
/// Used in tests to check if order aggregation based on request id works.
/// </summary>
/// <returns>list of orders </returns>
public static List<Order> CreateOrders_TwoOrdersWithSameReuquestId()
{
List<Order> orders = new List<Order>();
// Add two orders to list
for (int i = 1; i < 3; i++)
{
orders.Add(new Order
{
ClientId = "id" + i,
RequestId = i,
Name = "Roll",
Quantity = i * 12,
Price = 12.2m,
});
}
// Add next order with same request id to database to check whether orders will be aggregated
orders.Add(new Order
{
ClientId = "id",
RequestId = 1,
Name = "Roll",
Quantity = 10,
Price = 10.0m,
});
return orders;
}
/// <summary>
/// Creates list of three orders.
/// Two orders refere to same clientId and two orders refere to same request id.
/// Used to check if aggregation of orders for specific client works.
/// </summary>
/// <returns>list of orders</returns>
public static List<Order> CreateOrders_ForSpecificCLient_TwoOrdersWithSameRequestId(string clientId)
{
List<Order> orders = new List<Order>();
// Create two orders
for (int i = 1; i < 3; i++)
{
orders.Add(new Order
{
ClientId = "id" + i,
RequestId = i,
Name = "Roll",
Quantity = i * 12,
Price = 12.2m,
});
}
// Add order for client with same request id and clientId to database to check whether orders will be aggregated
orders.Add(new Order
{
ClientId = clientId,
RequestId = 1,
Name = "Roll",
Quantity = 10,
Price = 10.0m,
});
return orders;
}
/// <summary>
/// Creates single order for client based on parameters.
/// </summary>
/// <param name="clientId"></param>
/// <param name="requestId"></param>
/// <param name="name"></param>
/// <param name="quantity"></param>
/// <param name="price"></param>
/// <returns></returns>
public static Order CreateOrder(string clientId, long requestId, string name, int quantity, decimal price)
{
Order order = new Order
{
ClientId = clientId,
RequestId = requestId,
Name = name,
Quantity = quantity,
Price = price
};
return order;
}
/// <summary>
/// Creates four orders.
/// Two orders have the same name, so they should be aggregated durning tests.
/// </summary>
/// <returns></returns>
public static List<Order> CreateOrdersForGroupByNameTest()
{
List<Order> orders = new List<Order>();
// Add two orders to database
for (int i = 1; i < 3; i++)
{
orders.Add(new Order
{
ClientId = "id" + i,
RequestId = i,
Name = "Roll",
Quantity = i,
Price = 1.5m + i,
});
}
// add order with same request id but different name
orders.Add(new Order
{
ClientId = "id",
RequestId = 1,
Name = "Stuck",
Quantity = 1,
Price = 1.5m,
});
// add order with same request id && client id but different name
orders.Add(new Order
{
ClientId = "id" + 1,
RequestId = 2,
Name = "Car",
Quantity = 1,
Price = 1.5m,
});
return orders;
}
}
}
|
0e626cbed29422ca928614d0383c8fe7e4006771
|
C#
|
TamilK92/Podstawy-C-Sharp
|
/for wypisz parzyste z podanego przedziału zapytanie logiczne z resztą if if warunki logiczne reszta procent.cs
| 2.96875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace trajning
{
class Program
{
static void Main(string[] args)
{
int i = 1;
double dlug = 80, zarobekJanka = 50, zarobekKarola = 40;
double splata = 0;
do
{
splata += 0.2 * zarobekJanka + 0.2 * zarobekKarola;
Console.WriteLine("Dzień = {0} Spłata = {1}", i++, splata);
} while (dlug > splata);
Console.ReadKey();
}
}
}
|
85177a82a55704596fdd762b42963db84de61daa
|
C#
|
JamieBickers/PersonalWebsite
|
/PersonalWebsite/Models/GifRequest.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace PersonalWebsite.Models
{
public class GifRequest : IPrivateApiRequest, IValidatableObject
{
public string Password { get; set; }
public IEnumerable<string> Tags { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Password == null)
{
yield return new ValidationResult("Must have authorization details.");
}
if (Tags == null || Tags.Count() == 0)
{
yield return new ValidationResult("Must have tags.");
}
}
}
}
|
8dd147fcbf514fcbb48b2627fc26f7b1e54bb99f
|
C#
|
AlehZakharau/My-Student-Projects
|
/Assets/2D Platformer/Scripts/NPC/EnemyMovement.cs
| 3.0625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Platformer
{
public class EnemyMovement : MonoBehaviour
{
public float speed;
private bool isFacingRight;
/// <summary>
/// Двигает спрайт в заданную точку
/// </summary>
/// <param name="target">Цель</param>
public void FollowTo(Vector2 target)
{
//Проверка в какую сторону повернуть спрайт
if (transform.position.x > target.x && isFacingRight)
{
Flip(false);
}
else if(transform.position.x < target.x && !isFacingRight)
{
Flip(true);
}
transform.position = Vector2.MoveTowards(transform.position, target, speed * Time.deltaTime);
}
/// <summary>
/// Поворачивает спрайт
/// </summary>
/// <param name="turn"></param>
private void Flip(bool turn)
{
isFacingRight = turn;
var scale = transform.localScale;
scale.x *= -1;
transform.localScale = scale;
}
}
}
|
2265c7d1f636a40e542452e1e4a99d99f6ec74a9
|
C#
|
igorsci/myRepoSEDC
|
/c # adv/CSharpAdvanced - Class7/LINQExercises/LINQExercises/Program.cs
| 3.3125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQExercises
{
class Program
{
public static void PrintDogs(List<Dog> dogs)
{
foreach (var dog in dogs)
{
Console.WriteLine(dog.Name);
}
}
public static bool CheckIfDogsSame(Person p)
{
bool allSame = false;
if (p.Dogs.Count > 0)
{
//var firstDog = p.Dogs[0];
for (var i = 0; i < p.Dogs.Count; i++)
{
for (var j = i+1; j < p.Dogs.Count; j++)
{
if (p.Dogs[i].Race == p.Dogs[j].Race)
{
allSame = true;
}
}
}
if (allSame ==true)
{
Console.WriteLine(p.FirstName + p.LastName + p.Occupation);
}
}
//Console.WriteLine(allSame);
return allSame;
}
public static void GroupBySinglePropertyDog(List<Dog>dogs)
{
Console.WriteLine("Group by a single property in an object:");
var queryDogs =
from dog in dogs
group dog by dog.Race into newGroup
orderby newGroup.Key
select newGroup;
foreach (var nameGroup in queryDogs)
{
Console.WriteLine($"Key: {nameGroup.Key}");
foreach (var dog in nameGroup)
{
Console.WriteLine($"\t{dog.Name}, {dog.Race}");
}
}
}
public static void GroupByColorDog(List<Dog> dogs)
{
Console.WriteLine("Group by a single property in an object:");
var queryDogs =
from dog in dogs
group dog by dog.Color into newGroup
orderby newGroup.Key
select newGroup;
foreach (var nameGroup in queryDogs)
{
Console.WriteLine($"Key: {nameGroup.Key}");
foreach (var dog in nameGroup.OrderBy(dog=>dog.Name))
{
Console.WriteLine($"\t{dog.Name}, {dog.Color}");
}
}
}
public static void GroupBySinglePropertyPerson(List<Person> persons)
{
Console.WriteLine("Group by a single property in an object:");
var queryPersons =
from person in persons
group person by person.Age into newGroup
orderby newGroup.Key
select newGroup;
foreach (var nameGroup in queryPersons)
{
Console.WriteLine($"Key: {nameGroup.Key}");
foreach (var person in nameGroup)
{
Console.WriteLine($"\t{person.FirstName}, {person.Age}");
}
}
}
static void Main(string[] args)
{
var people = new List<Person>()
{
new Person("Nathanael", "Holt", 20, Job.Choreographer),
new Person("Jabari", "Chapman", 35, Job.Designer),
new Person("Oswaldo", "Wilson", 19, Job.Developer),
new Person("Kody", "Walton", 43, Job.Sculptor),
new Person("Andreas", "Weeks", 17, Job.Developer),
new Person("Kayla", "Douglas", 28, Job.Designer),
new Person("Xander", "Campbell", 19, Job.Waiter),
new Person("Soren", "Velasquez", 33, Job.Interpreter),
new Person("August", "Rubio", 21, Job.Developer),
new Person("Malakai", "Mcgee", 57, Job.Barber),
new Person("Emerson", "Rollins", 42, Job.Choreographer),
new Person("Everett", "Parks", 39, Job.Sculptor),
new Person("Amelia", "Moody", 24, Job.Waiter),
new Person("Emilie", "Horn", 16, Job.Waiter),
new Person("Leroy", "Baker", 44, Job.Interpreter),
new Person("Nathen", "Higgins", 60, Job.Archivist),
new Person("Erin", "Rocha", 37, Job.Developer),
new Person("Freddy", "Gordon", 26, Job.Interpreter),
new Person("Valeria", "Reynolds", 26, Job.Dentist),
new Person("Cristofer", "Stanley", 22, Job.Dentist),
new Person("William", "Favorite", 29, Job.Waiter),
new Person("James", "Ferguson", 34, Job.Tattooist),
new Person("Julian", "Stanley", 47, Job.Auctioneer),
new Person("Tom", "Barnes", 19, Job.Barber),
new Person("James", "Rodriguez", 55, Job.Dentist),
new Person("Jean", "Gaylord", 23, Job.Archivist),
new Person("Erika", "Lawrence", 67, Job.Sculptor),
new Person("Vanessa", "Braman", 33, Job.Lecturer),
new Person("Donna", "Snider", 36, Job.Sculptor),
new Person("Larry", "Ellington", 41, Job.Dietician)
};
var dogs = new List<Dog>()
{
new Dog("Charlie", Color.Black, 3, Race.Collie),
new Dog("Buddy", Color.Brown, 1, Race.Doberman),
new Dog("Max", Color.Olive, 1, Race.Plott),
new Dog("Archie", Color.Black, 2, Race.Doberman),
new Dog("Oscar", Color.Mix, 1, Race.Mudi),
new Dog("Toby", Color.Silver, 3, Race.Bulldog),
new Dog("Ollie", Color.Golden, 4, Race.Husky),
new Dog("Bailey", Color.White, 4, Race.Pointer),
new Dog("Frankie", Color.Olive, 2, Race.Retriever),
new Dog("Jack", Color.Black, 5, Race.Dalmatian),
new Dog("Chanel", Color.White, 1, Race.Pug),
new Dog("Henry", Color.Black, 7, Race.Plott),
new Dog("Bo", Color.Maroon, 3, Race.Boxer),
new Dog("Scout", Color.Mix, 2, Race.Boxer),
new Dog("Ellie", Color.Brown, 6, Race.Doberman),
new Dog("Hank", Color.Silver, 2, Race.Collie),
new Dog("Shadow", Color.Brown, 3, Race.Mudi),
new Dog("Diesel", Color.Golden, 1, Race.Bulldog),
new Dog("Abby", Color.Mix, 1, Race.Dalmatian),
new Dog("Trixie", Color.Maroon, 6, Race.Mudi),
new Dog("Alfi", Color.Black, 3, Race.Chihuahua),
new Dog("Benji", Color.Brown, 2, Race.Cocker),
new Dog("Ava", Color.Golden, 4, Race.Bulldog),
new Dog("Chet", Color.Olive, 1, Race.Boxer),
new Dog("Rigby", Color.Mix, 5, Race.Collie),
new Dog("Sam", Color.Silver, 1, Race.Inu),
new Dog("Tilly", Color.White, 3, Race.Retriever),
new Dog("Yumi", Color.White, 4, Race.Retriever),
new Dog("Zoe", Color.Brown, 9, Race.Husky),
new Dog("Gonzo", Color.Mix, 1, Race.Doberman),
};
#region Exercises
//==============================
// TODO LINQ expressions :)
// Your turn guys...
//==============================
//PART 1
// 1. Structure the solution (create class library and move classes and enums accordingly)
//PART 2
// 1. Take person Cristofer and add Jack, Ellie, Hank and Tilly as his dogs.
// 2. Take person Freddy and add Oscar, Toby, Chanel, Bo and Scout as his dogs.
// 3. Add Trixie, Archie and Max as dogs from Erin.
// 4. Give Abby and Shadow to Amelia.
// 5. Take person Larry and Zoe, Ollie as his dogs.
// 6. Add all retrievers to Erika.
// 7. Erin has Chet and Ava and now give Diesel to August thah previously has just Rigby
//1.
var cristofer = people.Where(n => n.FirstName == "Cristofer").FirstOrDefault();
var CristoferDogs = dogs.Where(d => d.Name == "Jack" || d.Name == "Ellie" || d.Name == "Hank" || d.Name == "Tilly").ToList();
cristofer.Dogs.AddRange(CristoferDogs);
//foreach (var dog in cristofer.Dogs)
//{
// Console.WriteLine(dog.Name);
//}
//2.
var Freddy = people.Where(n => n.FirstName == "Freddy").FirstOrDefault();
var FreddyDogs = dogs.Where(d => d.Name == "Oscar" || d.Name == "Toby" || d.Name == "Chanel" || d.Name == "Bo" || d.Name == "Scout").ToList();
Freddy.Dogs.AddRange(FreddyDogs);
//3
var Erin = people.Where(n => n.FirstName == "Erin").FirstOrDefault();
var ErinDogs = dogs.Where(d => d.Name == "Trixie" || d.Name == "Max" || d.Name == "Archie").ToList();
Erin.Dogs.AddRange(ErinDogs);
//4
var Amelia = people.Where(n => n.FirstName == "Amelia").FirstOrDefault();
var AmeliaDogs = dogs.Where(d => d.Name == "Abby" || d.Name == "Shadow").ToList();
Amelia.Dogs.AddRange(AmeliaDogs);
//5
var Larry = people.Where(n => n.FirstName == "Larry").FirstOrDefault();
var LarryDogs = dogs.Where(d => d.Name == "Zoe" || d.Name == "Ollie").ToList();
Larry.Dogs.AddRange(LarryDogs);
// 6
var Erika = people.Where(n => n.FirstName == "Erika").FirstOrDefault();
var ErikaDogs = dogs.Where(d => d.Race == Race.Retriever).ToList();
Erika.Dogs.AddRange(ErikaDogs);
Console.WriteLine("erikas dogs check ");
foreach (var dog in Erika.Dogs)
{
Console.WriteLine(dog.Name + dog.Race);
}
Console.WriteLine("erikas dogs check ");
//7 // 7. Erin has Chet and Ava and now give Diesel to August thah previously has just Rigby
var ErinDogs2 = dogs.Where(d => d.Name == "Chet" || d.Name == "Ava").ToList();
var diseldog = dogs.Where(d => d.Name == "Diesel").ToList();
Erin.Dogs.AddRange(ErinDogs2);
Erin.Dogs.AddRange(diseldog);
Erin.Dogs.RemoveAll(r => r.Name == "Diesel");
Console.WriteLine("kucinjata na erin gledaj tuka dali e dizelo");
foreach (var dog in Erin.Dogs)
{
Console.WriteLine(dog.Name);
}
Console.WriteLine("kucinjata na august");
var August = people.Where(n => n.FirstName == "August").FirstOrDefault();
var AugustDogs = dogs.Where(d => d.Name == "Diesel" || d.Name == "Rigby").ToList();
August.Dogs.AddRange(AugustDogs);
foreach (var item in August.Dogs)
{
Console.WriteLine(item.Name);
}
//PART 3 - LINQ
// 1. Find and print all persons firstnames starting with 'R', ordered by age - DESCENDING ORDER.
var personStartWithR = people.Where(n => n.FirstName.StartsWith("E")).OrderByDescending(n => n.Age).ToList();
foreach (var item in personStartWithR)
{
Console.WriteLine(item.FirstName + item.Age);
}
// 2. Find and print all brown dogs names and ages older than 3 years, ordered by age - ASCENDING ORDER.
var brownDogs = dogs.Where(c => c.Color == Color.Brown || c.Age > 3).OrderBy(c => c.Age);
foreach (var dog in brownDogs)
{
Console.WriteLine(dog.Name + dog.Age);
}
// 3. Find and print all persons with more than 2 dogs, ordered by name - DESCENDING ORDER.
var personsWithMoreDogs = people.Where(n => n.Dogs.Count > 2).OrderByDescending(n => n.FirstName).ToList();
foreach (var item in personsWithMoreDogs)
{
Console.WriteLine(item.FirstName + item.Dogs.Count);
}
// 4. Find and print all persons names, last names and job positions that have just one race type dogs.
//another way
// using distinct method - metod sto gi trgnuva duplikatite i so selekt da se kreiran nov anonimen objekt so propertija sto ni trebat na nas
// another way
Console.WriteLine("gledaj tuka za kucinja so edna rasa");
foreach (var item in people)
{
CheckIfDogsSame(item);
}
Console.WriteLine("gledaj tuka za kucinja so edna rasa");
// 5. Find and print all Freddy`s dogs names older than 1 year, grouped by dogs race.
Console.WriteLine("printing task 5 part 3");
var fredyOlderDogs = Freddy.Dogs.Where(p => p.Age > 1).ToList();
GroupBySinglePropertyDog(fredyOlderDogs);
//var groupedFredyList = fredyOlderDogs
// .GroupBy(u => u.Race)
// .Select(grp => grp.ToList())
// .ToList();
//foreach (var group in groupedFredyList)
//{
// foreach (var user in group)
// {
// Console.WriteLine(" {0}", user.Name + "" + user.Race);
// }
//}
// 6. Find and print last 10 persons grouped by their age.
Console.WriteLine("Find and print last 10 persons grouped by their age");
var lastTen = people.Skip(20).ToList();
GroupBySinglePropertyPerson(lastTen);
// Pls hints da gi napravam genericki ovie funkcii
// 7. Find and print all dogs names from Cristofer, Freddy, Erin and Amelia, grouped by color and ordered by name - ASCENDING ORDER.
var allDogsFromSomePeop = people.Where(x => x.FirstName == "Freddy" || x.FirstName == "Cristofer" || x.FirstName == "Erin" || x.FirstName == "Amelia").Select(x => x.Dogs).ToList();
foreach (var item in allDogsFromSomePeop)
{
GroupByColorDog(item);
}
// 8. Find and persons that have same dogs races and order them by name length ASCENDING, then by age DESCENDING.
// try with intersec method i check the link query from the class ?????
// 9. Find the last dog of Amelia and print all dogs form other persons older than Amelia, ordered by dogs age DESCENDING.
// 10. Find all developers older than 20 with more than 1 dog that contains letter 'e' in the name and print their names and job positions.
Console.ReadLine();
#endregion
}
}
}
|
64306058750c66ddd7a9f04c0f3fbe72a186a9d6
|
C#
|
douglasforte/ThriveWebApp
|
/ThriveWebApp/Tools/SampleTemplateV6/SampleTemplateV6/SampleTemplateV6/SampleTemplate/Models/Book1.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SampleTemplate.Models
{
public class Book1
{
public string Title { get; set; }
public string ISBN { get; set; }
public string Publisher { get; set; }
public DateTime PublicationDate { get; set; }
public decimal Price { get; set; }
public byte[] BookImage { get; set; }
public Book1() { }
public Book1(string isbn, string title, string publisher, DateTime date, decimal price, byte[] image)
{
ISBN = isbn;
Title = title;
Publisher = publisher;
PublicationDate = date;
Price = price;
BookImage = image;
}
}
}
|
ecd988ca50c9cde27e7ed202236e1284fffeaccd
|
C#
|
DenisAkm/InnTech.SqlDataGenerator
|
/InnTech.SqlDataGenerator/InnTech.SqlDataGenerator/TypeGenerators/DecimalGenerator.cs
| 2.96875
| 3
|
namespace InnTech.SqlDataGenerator
{
public class DecimalGenerator : ITypeGenerator
{
public decimal MinValue { get; set; }
public decimal MaxValue { get; set; }
public DecimalGenerator(decimal minValue, decimal maxValue)
{
MinValue = minValue;
MaxValue = maxValue;
}
public object GetRandom(EntityProperty column)
{
return Randomize.NextDecimal(MinValue, MaxValue);
}
public string GetValue(EntityProperty column)
{
return $"{GetRandom(column)}".Replace(",", ".");
}
}
}
|
6f247818ab615710f4ef0f403022ea8aa9127ccc
|
C#
|
NeminiCZ/GildedRose-Refactoring-Kata
|
/csharp/GildedRose.cs
| 2.640625
| 3
|
using System.Collections.Generic;
namespace csharp
{
public class GildedRose
{
private readonly IList<Items.IItem> _items;
public GildedRose(IList<Items.IItem> items)
{
this._items = items;
}
public void UpdateQuality()
{
foreach (var item in _items)
{
item.UpdateQuality();
}
}
}
}
|