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
|
|---|---|---|---|---|---|---|
f43684bcda01fe05cb4ab0644201e3e4e9d11058
|
C#
|
sootie8/Serialise-Work
|
/Assets/JsonDotNet/Extras/CustomConverters/ResolutionFullConverter.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEngine;
namespace JsonDotNet.Extras.CustomConverters
{
public class ResolutionFullConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var res = (Resolution)value;
writer.WriteStartObject();
writer.WritePropertyName("height");
writer.WriteValue(res.height);
writer.WritePropertyName("width");
writer.WriteValue(res.width);
writer.WritePropertyName("refreshRate");
writer.WriteValue(res.refreshRate);
writer.WriteEndObject();
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Resolution);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var obj = JObject.Load(reader);
var props = obj.Properties().ToList();
var result = new Resolution();
if (props.Any(p => p.Name == "height"))
result.height = (int)obj["height"];
if (props.Any(p => p.Name == "width"))
result.width = (int)obj["width"];
if (props.Any(p => p.Name == "refreshRate"))
result.refreshRate = (int)obj["refreshRate"];
return result;
}
public override bool CanRead
{
get { return true; }
}
}
}
|
4603a816f5a33567b1f13b26515cc95ff7d37539
|
C#
|
masterpoi/scsharp
|
/tools/brute.cs
| 2.84375
| 3
|
using System;
using System.IO;
using System.Threading;
using MpqReader;
using System.Reflection;
public class Brute {
const int MAX_COUNT = 45;
static string allowable = "()\\/._0123456789abcdefghijklmnopqrstuvwxyz";
static StreamWriter sw;
static int entry_count = 0;
static object iolock = new object ();
static object consolelock = new object ();
static void TestStrings (MpqArchive mpq, string dot, int count, char[] test, int index) {
if (index == count) {
entry_count ++;
if (entry_count % 10000 == 0) {
lock (consolelock) {
Console.Write (dot);
Console.Out.Flush ();
}
}
String entry = new String (test, 0, count);
if (mpq.FileExists (entry)) {
lock (iolock) {
sw.WriteLine (entry);
}
}
return;
}
for (int j = 0; j < allowable.Length; j ++) {
test[index] = allowable[j];
TestStrings (mpq, dot, count, test, index + 1);
}
}
public static void Main (string[] args) {
if (args.Length < 2) {
Console.WriteLine ("usage: brute.exe <mpq-file> <output-list.txt>");
Environment.Exit (0);
}
MpqArchive mpq = new MpqArchive (args[0]);
sw = File.CreateText (args[1]);
Thread t = new Thread (delegate (object state) {
for (int count = 8; count < MAX_COUNT; count ++) {
if (count % 2 == 0)
continue;
char[] test = new char [count];
lock (consolelock) {
Console.Write ("T{0}", count);
Console.Out.Flush();
}
TestStrings (mpq, "t", count, test, 0);
}
});
t.Start();
for (int count = 8; count < MAX_COUNT; count ++) {
if (count % 2 == 1)
continue;
char[] test = new char [count];
lock (consolelock) {
Console.Write ("M{0}", count);
Console.Out.Flush ();
}
TestStrings (mpq, "m", count, test, 0);
}
}
}
|
42482eb7c207e1477f04f1cfeaacdf7f03bb9126
|
C#
|
webdude21/Homework
|
/C# part two/StringsAndTextProcessing/FillWithAsterisk/FillWithAsterisk.cs
| 4.59375
| 5
|
// Write a program that reads from the console a string of maximum 20 characters. If the length of the string
// is less than 20, the rest of the characters should be filled with '*'. Print the result string into the console.
namespace FillWithAsterisk
{
using System;
using System.Text;
internal class FillWithAsterisk
{
private static void Main()
{
try
{
var input = GetInput();
Console.WriteLine("The result is: {0}", AddAsterisks(input));
}
catch (ArgumentOutOfRangeException me)
{
Console.WriteLine("The string was longer than 20 chars! {0}", me.Message);
}
}
private static string AddAsterisks(string input)
{
// This method appends asterisks at the end of the string.
var newString = new StringBuilder();
newString.Append(input);
for (var i = input.Length; i < 20; i++)
{
newString.Append('*');
}
return newString.ToString();
}
private static string GetInput()
{
// This only gets the input and throws an exception if it can't.
Console.Write("Please input a string (maximum 20 chars long: ");
var input = Console.ReadLine();
if (input.Length > 20)
{
throw new ArgumentOutOfRangeException();
}
return input;
}
}
}
|
b1c65a033da2fae6542f489cef25364288f5b2a5
|
C#
|
OleksiiPankov/FirstHomeTask
|
/ConsoleApplication1/Program.cs
| 3.4375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Задайте размер массива");
int n = Convert.ToInt32(Console.ReadLine());
int[] array = new int[n];
int len = n;
Random r = new Random();
for (int i = 0; i < len; i++)
{
array[i] = r.Next(-100, 101);
}
Console.WriteLine("Массив до сортировки");
for (int i = 0; i < len; i++)
{
Console.Write(array[i] + " ");
}
Console.WriteLine();
QuickSorting.QuickSort(array, 0, len - 1);
Console.WriteLine("Массив после сортировки");
for (int i = 0; i < len; i++)
{
Console.Write(array[i] + " ");
}
}
}
}
|
ddc3e7946ada9c1637ad5cc841232cefd3d5c14f
|
C#
|
jdidderen/TennisTableWPF
|
/TennisTableWPF/bin/Debug/A_Classements.cs
| 2.71875
| 3
|
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using TennisTable.Classes;
namespace TennisTable.Acces
{
/// <summary>
/// Couche d'accès aux données (Data Access Layer)
/// </summary>
public class AClassements : ABase
{
public AClassements(string sChaineConnexion)
: base(sChaineConnexion)
{ }
public int Ajouter(string classement)
{
CreerCommande("AjouterClassements");
Commande.Parameters.Add("ClassementId", SqlDbType.Int);
Direction("ClassementId", ParameterDirection.Output);
Commande.Parameters.AddWithValue("@Classement", classement);
Commande.Connection.Open();
Commande.ExecuteNonQuery();
var res = int.Parse(LireParametre("ClassementId"));
Commande.Connection.Close();
return res;
}
public int Modifier(int classementId, string classement)
{
CreerCommande("ModifierClassements");
int res = 0;
Commande.Parameters.AddWithValue("ClassementId", classementId);
Commande.Parameters.AddWithValue("@Classement", classement);
Commande.Connection.Open();
Commande.ExecuteNonQuery();
Commande.Connection.Close();
return res;
}
public List<CClassements> Lire(string index)
{
CreerCommande("SelectionnerClassements");
Commande.Parameters.AddWithValue("@Index", index);
Commande.Connection.Open();
SqlDataReader dr = Commande.ExecuteReader();
List<CClassements> res = new List<CClassements>();
while (dr.Read())
{
CClassements tmp = new CClassements
{
ClassementId = int.Parse(dr["ClassementId"].ToString()),
Classement = dr["Classement"].ToString()
};
res.Add(tmp);
}
dr.Close();
Commande.Connection.Close();
return res;
}
public CClassements Lire_ID(int classementId)
{
CreerCommande("SelectionnerClassements_ID");
Commande.Parameters.AddWithValue("@ClassementId", classementId);
Commande.Connection.Open();
SqlDataReader dr = Commande.ExecuteReader();
CClassements res = new CClassements();
while (dr.Read())
{
res.ClassementId = classementId;
res.Classement = dr["Classement"].ToString();
}
dr.Close();
Commande.Connection.Close();
return res;
}
public int Supprimer(int classementId)
{
CreerCommande("SupprimerClassements");
Commande.Parameters.AddWithValue("@ClassementId", classementId);
Commande.Connection.Open();
var res = Commande.ExecuteNonQuery();
Commande.Connection.Close();
return res;
}
public int ObtenirLigne(int classementId, string index)
{
CreerCommande("LigneClassements");
Commande.Parameters.Add("reponse", SqlDbType.Int);
Direction("reponse", ParameterDirection.Output);
Commande.Parameters.AddWithValue("@ClassementId", classementId);
Commande.Parameters.AddWithValue("@Index", index);
Commande.Connection.Open();
Commande.ExecuteNonQuery();
var res = int.Parse(LireParametre("reponse"));
Commande.Connection.Close();
return res;
}
}
}
|
238a94fba898ea0b60fb69b817000d60bc32bcb7
|
C#
|
jai-x/aoc2020
|
/Day4.cs
| 3.21875
| 3
|
using System;
using System.Linq;
using System.Globalization;
using System.Collections.Generic;
namespace aoc2020
{
public class Day4 : Day
{
private class Passport
{
private Dictionary<string, string> fields;
private Dictionary<string, Func<string, bool>> fieldValidations = new Dictionary<string, Func<string, bool>>
{
{ "byr", (f) => Int32.TryParse(f, out var year) && (year >= 1920) && (year <= 2002) },
{ "iyr", (f) => Int32.TryParse(f, out var year) && (year >= 2010) && (year <= 2020) },
{ "eyr", (f) => Int32.TryParse(f, out var year) && (year >= 2020) && (year <= 2030) },
{ "hgt", (f) => Int32.TryParse(f[..^2], out var hgt) && (((f[^2..^0] == "cm") && (hgt >= 150) && (hgt <= 193)) || ((f[^2..^0] == "in") && (hgt >= 59) && (hgt <= 76))) }, // one line expression >_<
{ "hcl", (f) => f[0] == '#' && Int32.TryParse(f[1..], NumberStyles.HexNumber, CultureInfo.InvariantCulture, out _)},
{ "ecl", (f) => new[] { "amb", "blu", "brn", "gry", "grn", "hzl", "oth" }.Any(f.Equals) },
{ "pid", (f) => f.Length == 9 && Int32.TryParse(f, out _) },
};
public Passport(string input)
{
fields = input
.Trim()
.Split(new[] { ' ', '\n' })
.Select(token => token.Split(':'))
.ToDictionary(pairArray => pairArray[0], pairArray => pairArray[1]);
}
public bool PresentFields() => fieldValidations.Keys.All(k => fields.ContainsKey(k));
public bool ValidFields() => PresentFields()
&& fieldValidations.Keys
.Select(k => (fields[k], fieldValidations[k]))
.All(pair => pair.Item2.Invoke(pair.Item1));
}
private List<Passport> passports;
public Day4(string input) : base(input)
{
passports = input
.Split("\n\n")
.Select(pInput => new Passport(pInput))
.ToList();
}
public override string Part1() => passports.Count(p => p.PresentFields()).ToString();
public override string Part2() => passports.Count(p => p.ValidFields()).ToString();
}
}
|
a6b1e6dd257d7b744fafd67101f139c29ac0728e
|
C#
|
mckeepa/SignalRChat
|
/ClientDesktop/Program.cs
| 2.671875
| 3
|
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Extensions.Configuration;
namespace ClientDesktop
{
class Program
{
static void Main(string[] args)
{
var sessionId = "715c5034-e97c-48b1-b461-2c411e398972";
if (args.Length > 0) sessionId = args[0];
// Create the connection.
HubConnection connection = SignalRConnection.ConnectToMessageHub("http://localhost:5000/" , "ChatHub");
try
{
connection.StartAsync().ContinueWith(task =>
{
if (task.IsFaulted)
{
Console.WriteLine("There was an error opening the connection:{0}", task.Exception.GetBaseException());
}
else
{
Console.WriteLine("Connected");
connection.InvokeAsync("Register","test1", sessionId, "TARGET").Wait();
}
}).Wait();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
connection.Reconnected += connectionId =>
{
Console.WriteLine("Reconnected. connectionId:" + connectionId);
connection.InvokeAsync("Register","test1", sessionId, "TARGET").Wait();
// Notify users the connection was reestablished.
// Start dequeuing messages queued while reconnecting if any.
return Task.CompletedTask;
};
connection.Reconnecting += error =>
{
Console.WriteLine("Re-connecting: " + connection.State + " " + HubConnectionState.Reconnecting);
// Notify users the connection was lost and the client is reconnecting.
// Start queuing or dropping messages.
return Task.CompletedTask;
};
connection.On<string,string>("Registered", ( clientType, connectionId) =>
{
Console.WriteLine("### Registered ###");
Console.WriteLine("Registered:" + clientType );
Console.WriteLine("Connect Id" + connectionId);
Console.WriteLine();
});
connection.On<string>("ReceiveTextMessage", param =>
{
Console.WriteLine("### ReceiveMessage ###");
Console.WriteLine("Received Text Message:" + param);
Console.WriteLine();
});
connection.On<string, string, string, string>("ReceiveMessage", (user, sessiontoken, message, fromConnectionID) =>
{
Console.WriteLine("### ReceiveMessage ###");
Console.WriteLine("Received From: " + fromConnectionID + "\\" + user );
Console.WriteLine("SessionToken:" + sessiontoken);
Console.WriteLine("Message: " + message);
Console.WriteLine();
});
var command = "";
Console.WriteLine("Enter message or type 'exit' to close console.");
// connection.InvokeAsync("Register","test1", sessionId, "TARGET").Wait();
while (true)
{
Console.WriteLine();
Console.WriteLine("Connection ID:" + connection.ConnectionId);
Console.WriteLine("Session ID:" + sessionId);
Console.WriteLine();
command = Console.ReadLine();
var commandArgs = command.Trim().ToUpper().Split(" ");
switch (commandArgs[0])
{
case "EXIT":
connection.StopAsync().Wait();
break;
case "SESSIONID:":
sessionId = commandArgs[1];
connection.InvokeAsync("Register","test1", sessionId, "TARGET").Wait();
Console.WriteLine("Connection ID:" + connection.ConnectionId);
Console.WriteLine("Session ID:" + sessionId);
break;
case "ALL:":
connection.InvokeAsync("SendTextMessage", command).Wait();
break;
default:
try
{
connection.InvokeAsync("SendMessage", "test1", sessionId, command).Wait();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
break;
}
}
}
}
}
|
1f508d6aa2d663459bf28b420d7fabe3f83250c9
|
C#
|
CraigChant/CD-Library
|
/Controllers/CDLibraryAPIController.cs
| 2.9375
| 3
|
using System;
using System.Collections.Generic;
using System.Web.Http;
using CD_Library.Models;
namespace CD_Library.Controllers
{
public class CDLibraryAPIController : ApiController
{
// CD Library repository
private ICDLibraryRepo _repository;
// Dependency Injection constructor
public CDLibraryAPIController(ICDLibraryRepo repository) { _repository = repository; }
// REST API
// GET : Get CD Library
[HttpGet]
public IEnumerable<CD> Get() {
return _repository.GetLibrary();
}
// DELETE : Remove a CD from the DB
[HttpDelete]
public IHttpActionResult Delete(string id) {
// try delete
Result result = result = _repository.DelCD(id);
if (result.ok)
{
return Ok(result.msg); // 200 OK
}
else
{
return BadRequest(result.msg); // 400 error
}
}
// POST : Add a CD to the DB
[HttpPost]
public IHttpActionResult Post([FromBody] CD cd)
{
// try insert
Result result = _repository.AddCD(cd);
if (result.ok)
{
return Ok(result.msg); // 200 OK
}
else
{
return BadRequest(result.msg); // 400 error
}
}
// PUT : Update a CD in the DB
[HttpPut]
public IHttpActionResult Put([FromBody] CD cd)
{
// try update
Result result = _repository.UpdCD(cd);
if (result.ok)
{
return Ok(result.msg); // 200 OK
}
else
{
return BadRequest(result.msg); // 400 error
}
}
}
}
|
0a472b8f617b7a392a4ca6549b7dbf6108e1b0ed
|
C#
|
iamal12/quiz
|
/quiz.core/ResultImpl.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using quiz.entities;
using quiz.api;
namespace quiz.core
{
/// <summary>
/// Class <see cref="ResultImpl "/> implements <see cref="IResult"/>
/// </summary>
public class ResultImpl:IResult
{
private QuizContext _context = new QuizContext();
private QuestionImpl _questionImpl = new QuestionImpl();
private AnswerImpl _answerImpl = new AnswerImpl();
private UserImpl userImpl = new UserImpl();
/// <summary>
/// Create new instance of <see cref="ResultImpl "/>
/// </summary>
public ResultImpl()
{
}
/// <summary>
/// Retrieve list of results
/// </summary>
/// <param name="userId">User identifier</param>
/// <param name="quizId">Quiz identifier</param>
/// <returns>List of results</returns>
public List<Result> GetResults(int userId, int quizId)
{
List<Question> list = _questionImpl.GetQuestionsByQuizId(quizId);
List<Result> results = new List<Result>();
foreach (Question question in list)
{
List<Answer> listAnswer = _answerImpl.GetListAnswerByQuestionId(question.QuestionId);
question.Answers = listAnswer;
Result result = new Result();
result.Description = question.Description;
List<Answer> userAnswers = new List<Answer>();
foreach (Answer answer in listAnswer)
{
Answer uAnswer = userImpl.GetUserAnswer(userId, answer.AnswerId);
var userAnswer = new Answer { AnswerId = answer.AnswerId, Description = answer.Description, IsCorrect = answer.IsCorrect };
if (answer.IsCorrect == true)
{
userAnswer.Message = "(Correct Answer)";
}
if (uAnswer != null)
{
userAnswer.IsUserCorrect = true;
if (answer.IsCorrect == true)
{
userAnswer.Message = "(Correct Answer)(Your Answer)";
}
else
{
userAnswer.Message = "(Your Answer)";
}
}
userAnswers.Add(userAnswer);
}
result.UserAnswers = userAnswers;
results.Add(result);
}
return (results);
}
}
}
|
7c95b1a02847caa54b780723d70af27fd2035bcc
|
C#
|
debsoft/RMS
|
/RMSAdminFinal/Database/InventoryKitchenStockReportDAO.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Common.ObjectModel;
using RMS.DataAccess;
namespace BistroAdmin.DAO
{
public class InventoryKitchenStockReportDAO:BaseDAO
{
public void InsertInventoryKitchenStock(List<InventoryStockReport> aInventoryStockReports)
{
try
{
this.OpenConnection();
foreach (InventoryStockReport report in aInventoryStockReports)
{
string sqlComm = String.Format(SqlQueries.GetQuery(Query.InsertInventoryKitchenStockReport),
report.CategoryId, report.CategoryName, report.ItemId,
report.ItemName, report.ReceivedQty, report.SendQty, report.DamageQty,
report.BalanceQty, report.Date = DateTime.Today.AddDays(-1));
this.ExecuteNonQuery(sqlComm);
}
}
catch (Exception ex)
{
throw new Exception("InsertInventoryKitchenStock", ex);
}
finally
{
this.CloseConnection();
}
}
public bool CheckInsertOrNotForKitchen()
{
int flag = 0;
try
{
this.OpenConnection();
string sqlComm = String.Format(SqlQueries.GetQuery(Query.CheckInsertOrNotForKitchen), DateTime.Today.AddDays(-1));
IDataReader aReader = this.ExecuteReader(sqlComm);
if (aReader != null)
{
while (aReader.Read())
{
flag++;
}
}
}
catch (Exception ex)
{
throw new Exception("CheckInsertOrNotForKitchen()", ex);
}
finally
{
this.CloseConnection();
}
if (flag > 0) return false;
return true;
}
public List<InventoryStockReport> GetInventoryStockReportBetweenDateForKitchen(DateTime fromdate, DateTime todate)
{
List<InventoryStockReport> aInventoryStockReports = new List<InventoryStockReport>();
try
{
this.OpenConnection();
string sqlComm = String.Format(SqlQueries.GetQuery(Query.GetInventoryStockReportBetweenDateForKitchen), fromdate,
todate);
IDataReader aReader = this.ExecuteReader(sqlComm);
if (aReader != null)
{
while (aReader.Read())
{
InventoryStockReport aReport = new InventoryStockReport();
aReport = ReaderToReadAllStock(aReader);
aInventoryStockReports.Add(aReport);
}
}
}
catch (Exception ex)
{
throw new Exception("GetInventoryStockReportBetweenDateForKitchen()", ex);
}
finally
{
this.CloseConnection();
}
return aInventoryStockReports;
}
private InventoryStockReport ReaderToReadAllStock(IDataReader aReader)
{
InventoryStockReport aStockReport = new InventoryStockReport();
try
{
aStockReport.CategoryId = Convert.ToInt32(aReader["category_id"]);
}
catch
{
}
try
{
aStockReport.CategoryName = (aReader["category_name"]).ToString();
}
catch
{
}
try
{
aStockReport.ItemId = Convert.ToInt32(aReader["item_id"]);
}
catch
{
}
try
{
aStockReport.ItemName = (aReader["item_name"]).ToString();
}
catch
{
}
try
{
aStockReport.BalanceQty = Convert.ToDouble(aReader["balance"]);
}
catch
{
}
try
{
aStockReport.SendQty = Convert.ToDouble(aReader["send"]);
}
catch
{
}
try
{
aStockReport.ReceivedQty = Convert.ToDouble(aReader["received"]);
}
catch
{
}
try
{
aStockReport.DamageQty = Convert.ToDouble(aReader["damage"]);
}
catch
{
}
try
{
aStockReport.Date = Convert.ToDateTime(aReader["date"]);
}
catch
{
}
return aStockReport;
}
public List<InventoryStockReport> GetInventoryKitchenStockReportBetweenDate(DateTime fromdate, DateTime todate)
{
List<InventoryStockReport> aInventoryStockReports = new List<InventoryStockReport>();
try
{
this.OpenConnection();
string sqlComm = String.Format(SqlQueries.GetQuery(Query.GetInventoryKitchenStockReportBetweenDate), fromdate,
todate);
IDataReader aReader = this.ExecuteReader(sqlComm);
if (aReader != null)
{
while (aReader.Read())
{
InventoryStockReport aReport = new InventoryStockReport();
aReport = ReaderToReadAllStock(aReader);
aInventoryStockReports.Add(aReport);
}
}
}
catch (Exception ex)
{
throw new Exception("GetInventoryStockReportBetweenDate()", ex);
}
finally
{
this.CloseConnection();
}
return aInventoryStockReports;
}
public List<InventoryStockReport> GetSaleReport(DateTime fromdate, DateTime todate)
{
List<InventoryStockReport> aInventoryStockReports = new List<InventoryStockReport>();
try
{
this.OpenConnection();
string sqlComm = String.Format(SqlQueries.GetQuery(Query.GetSaleReport), fromdate,
todate);
IDataReader aReader = this.ExecuteReader(sqlComm);
if (aReader != null)
{
while (aReader.Read())
{
InventoryStockReport aReport = new InventoryStockReport();
aReport = ReaderToReadSaleReport(aReader);
aInventoryStockReports.Add(aReport);
}
}
}
catch (Exception ex)
{
throw new Exception("GetSaleReport()", ex);
}
finally
{
this.CloseConnection();
}
return aInventoryStockReports;
}
private InventoryStockReport ReaderToReadSaleReport(IDataReader aReader)
{
InventoryStockReport aStockReport = new InventoryStockReport();
try
{
aStockReport.Date = Convert.ToDateTime(aReader["date"]);
}
catch
{
}
try
{
aStockReport.ItemId = Convert.ToInt32(aReader["item_id"]);
}
catch
{
}
try
{
aStockReport.SaleQty = Convert.ToDouble(aReader["item_qty"]);
}
catch
{
}
try
{
aStockReport.Price = Convert.ToDouble(aReader["sale_price"]);
}
catch
{
}
return aStockReport;
}
}
}
|
5eabe069643890aa899af133271ce9ca5e604b8a
|
C#
|
tandak/software-craftmanship
|
/Tests/Lib.UnitTests/UserProcesserShould.cs
| 2.578125
| 3
|
using FluentAssertions;
using software_craftsmanship.DesignPatterns.Behavioral_Design_Patterns.ChainOfResponsiblity;
using software_craftsmanship.Lib.ChainOfResponsibility.Validation;
using Xunit;
namespace software_craftsmanship.Lib.UnitTests
{
public class UserProcesserShould
{
private readonly UserProcessor _sut;
public UserProcesserShould()
{
_sut = new UserProcessor();
}
[Fact]
public void Return_True_When_User_Is_Valid()
{
var user = new User
{
Name = "Foo",
Age = 27,
Gender = "Non-Binary"
};
var result = _sut.Register(user);
result.Should().BeTrue();
}
[Fact]
public void Throw_Exception_If_Users_Age_Is_Less_Than_18()
{
var user = new User
{
Name = "Foo",
Age = 16,
Gender = "Non-Binary"
};
Assert.Throws<AgeValidationException>(() => _sut.Register(user));
}
[Fact]
public void Throw_Exception_If_Users_Name_Length_Is_Less_Than_1()
{
var user = new User
{
Name = "F",
Age = 18,
Gender = "Non-Binary"
};
Assert.Throws<NameValidationaException>(() => _sut.Register(user));
}
}
}
|
7e5a805e4c60cecaa911fc4b9b470ea9a6f3d9ed
|
C#
|
Newville23/RFIDapp
|
/lector1/Program.cs
| 2.890625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using com.caen.RFIDLibrary;
using MySql.Data.MySqlClient;
namespace ConsoleApplication1
{
class DBConnect
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
//Constructor
public DBConnect()
{
Initialize();
}
//Initialize values
private void Initialize()
{
server = "localhost";
database = "test";
uid = "root";
password = "";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
Console.WriteLine("No se logro conexión con el servidor");
break;
case 1045:
Console.WriteLine("Invalid username/password, please try again");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
//Insert statement
public void Insert(string id, string time, string source, string position)
{
string query = "INSERT INTO tags (id, time, position, source) VALUES ('"+id+"' , '"+time+"', '"+position+"', '"+source+"')";
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
//Execute command
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
//Select statement
public string Select(string id )
{
string tagreader = null;
string query = "SELECT id FROM tags WHERE id = '"+id+"'";
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
tagreader = reader.GetString(0);
//Console.WriteLine("Aqui");
}
reader.Close();
//close connection
this.CloseConnection();
}
return tagreader;
}
}
class Program: DBConnect
{
public static void Main(string[] args)
{
DBConnect DB = new DBConnect();
CAENRFIDReader davidreader = new CAENRFIDReader();
davidreader.CAENRFIDEvent += new CAENRFIDEventHandler(davidreader_EventHandler);
CAENRFIDLogicalSource LS0;
byte[] Mask = new byte[4];
//public event CAENRFIDEventHandler davidreader_EventHandler;
davidreader.Connect(CAENRFIDPort.CAENRFID_TCP, "192.168.10.1");
LS0 = davidreader.GetSource("Source_0"); // punto de lectura
LS0.SetReadCycle(0);
//LS0.InventoryTag(Mask, 0x0, 0x0, 0x06);
LS0.EventInventoryTag(Mask, 0x0, 0x0, 0x06); //ciclos de lectura continuos el metodo arroja un bool
Console.WriteLine("Inicia inventario");
DB.Insert("ABCD", "", "", "position");
System.IO.File.WriteAllText(@"C:\Users\David\Desktop\WriteLines.txt", "IDS");
Console.WriteLine("Presione una letra para finalizar");
Console.ReadKey();
davidreader.InventoryAbort();
davidreader.Disconnect();
}
static void davidreader_EventHandler(object Sender, CAENRFIDEventArgs Event)
{
CAENRFIDNotify[] Tags = Event.Data; // Class that return a struct like { byte ID[MAX_ID_LENGTH]; short Length; char LogicalSource[MAX_LOGICAL_SOURCE_NAME]; char ReadPoint[MAX_READPOINT_NAME]; CAENRFIDProtocol Type; short RSSI; byte TID[MAX_TID_SIZE]; short TIDLen; byte XPC[XPC_LENGTH]; byte PC[PC_LENGTH];}
DBConnect DB = new DBConnect();
if (Tags.Length > 0)
{
for (int i = 0; i < Tags.Length; i++)
{
String tag_id = BitConverter.ToString(Tags[i].getTagID());
DateTime tag_time = Tags[i].getDate();
string tag_source = Tags[i].getTagSource();
if (DB.Select(tag_id) != null)// si el tag esta en la tabla
{
Console.WriteLine("entre");
}
else {
//Escribiendo un tag nuevo en la tabla tags
DB.Insert(tag_id, tag_time.ToString(), tag_source, "position");
}
//hacer select para saber si el tag se encuentra guardado o no en la tabla
//Luego hacer un insert si el return da empty
Console.WriteLine(tag_id);
}
}
}
}
}
|
2e0d01f1b2b40247283c8822165e83605761b2af
|
C#
|
peekabooASH/Exception-Handling
|
/FileOperation/FileOperation/Program.cs
| 3.09375
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileOperation
{
class Program
{
static void Main(string[] args)
{
StreamReader sr= null;
try
{
sr = new StreamReader("d:/testing1.txt");
string line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
catch (FileNotFoundException exceptionObj)
{
Console.WriteLine(exceptionObj.Message);
}
finally
{
if (sr != null)
{
sr.Close();
}
}
Console.ReadKey();
}
}
}
|
6e3663de2d059d0c6d5b3d0e6a22543a9aae16df
|
C#
|
jy-repo/NewsABGN
|
/NewsABGN/NewsABGN.Console/Program.cs
| 2.8125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NewsABGN.Logic;
namespace NewsABGN.Console
{
class Program
{
static void Main(string[] args)
{
Test();
}
private static void Test()
{
var words = LogicRepository.Controller.WordCloud.MakeWordCloud("일동제약");
var wordListTmp = words.Trim().Substring(1, words.Length - 4).Replace("(", "").Replace("), ", "|").Replace(")", "").Split('|');
foreach (var word in wordListTmp.Reverse())
{
var NewWord = word.Replace(", ", "|").Split('|');
System.Console.WriteLine($"{NewWord[0],20}" + " ---- " + $"{NewWord[1],5}");
}
}
}
}
|
012a931e82bba723fec0c672769cf888a152bd9e
|
C#
|
Slion/SharpLibStreamDeck
|
/Project/Library/Exceptions.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SharpLib.StreamDeck
{
/// <summary>
/// Base class for all StreamDeckSharp Exceptions
/// </summary>
public abstract class BaseException : Exception
{
public BaseException(string Message) : base(Message) { }
}
public class NotFoundException : BaseException
{
public NotFoundException() : base("Stream Deck not found.") { }
}
}
|
18bf2ce3b05f57ebcb6cb87dfc4ad652d2bbf1e4
|
C#
|
Tsjunne/Physics
|
/src/PackageTest/WhenUsingPackage.cs
| 2.75
| 3
|
using Physics;
using Physics.Systems;
using System;
using System.Diagnostics;
using Xunit;
namespace PackageTest
{
public class WhenUsingPackage
{
[Fact]
public void CheckFullyDefinedSIPerformance()
{
var sytem = SI.System;
var W = sytem["W"];
var h = sytem["h"];
var m = sytem["m"];
var kWh = 1000 * W * h;
RunTest("FullSI", () =>
{
var m3 = m ^ 3;
var energy = new Quantity(100, kWh);
var volume = new Quantity(5, m3);
var result = energy / volume;
});
}
private void RunTest(string name, Action testCase)
{
var timeTaken = new Stopwatch();
timeTaken.Start();
for (var i = 0; i < 100000; i++)
{
testCase();
}
Console.WriteLine($"{name} took: {timeTaken.ElapsedMilliseconds}ms");
}
}
}
|
54060a41b52debd6ebccbefad3aacce6e8041292
|
C#
|
SeoDongWoo1216/SmartFactory-Edu
|
/20200909_004/Book.cs
| 2.859375
| 3
|
class Book
{
public string Name { get; set; }
public int Price { get; set; }
public Book(string _Name, int _Price)
{
Name = _Name;
Price = _Price;
}
}
|
57c4304f4e17144ab617e2f6279ab636eac56309
|
C#
|
remillner/HalloweenGame
|
/HalloweenGame/CharacterClasses/Vampire.cs
| 2.671875
| 3
|
using System;
namespace HalloweenGame
{
//>>Not Currently Used<<
class Vampire : Entity
{
public static int Vampires = 0;
string[] atkName = { "Drain Blood", "Swarm of Bats", "Glamour" };
//int[] attack = { 4, 12, 5 };
public Vampire(int lvl)
{
Vampires++;
name = String.Format("level{0} Vampire", (lvl + 1));
switch (lvl)
{
case 0:
life = (rand.Next(150, 250));
attackNum = 2;
dict[KEY_1] = rand.Next(3, 7);
dict[KEY_2] = rand.Next(2, 5);
attack = new int[] { 4, 12, 5 };
break;
case 1:
{
life = (rand.Next(160, 260));
attackNum = 3;
dict[KEY_1] = rand.Next(4, 8);
dict[KEY_2] = rand.Next(2, 5);
attack = new int[] { 4, 12, 5 };
break;
}
case 2:
{
life = (rand.Next(170, 270));
attackNum = 4;
dict[KEY_1] = rand.Next(5, 9);
dict[KEY_2] = rand.Next(2, 5);
attack = new int[] { 4, 12, 5 };
break;
}
case 3:
{
life = (rand.Next(180, 280));
attackNum = 5;
dict[KEY_1] = rand.Next(5, 9);
dict[KEY_2] = rand.Next(2, 5);
attack = new int[] { 4, 12, 5 };
break;
}
case 4:
{
life = (rand.Next(190, 290));
attackNum = 6;
dict[KEY_1] = rand.Next(5, 9);
dict[KEY_2] = rand.Next(2, 5);
attack = new int[] { 4, 12, 5 };
break;
}
default:
{
life = (rand.Next(200, 300));
attackNum = 7;
dict[KEY_1] = rand.Next(5, 9);
dict[KEY_2] = rand.Next(2, 5);
attack = new int[] { 4, 12, 5 };
break;
}
}
}
}
}
|
3afc46392882b4ddde1b307e449321a67f0948ed
|
C#
|
andersrosbaek/OOP2-ME
|
/WindowsFormsApplication1/WPF_GUI/Vehicles/RegisterVehicle.xaml.cs
| 2.8125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Domain;
namespace WPF_GUI
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class RegisterVehicle : Window
{
public RegisterVehicle()
{
InitializeComponent();
}
private void btnCarModel_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void btnCarColor_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void btnTruck_Checked(object sender, RoutedEventArgs e)
{
}
private void btnCar_Checked(object sender, RoutedEventArgs e)
{
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void btnRegister_Click(object sender, RoutedEventArgs e)
{
string type = (btnCar.IsChecked == true) ? "car" : "truck";
string model = btnVehicleModel.Text;
string color = btnVehicleColor.Text;
double price = Double.Parse(inputVehiclePrice.Text);
if (btnVehicleModel.SelectedIndex != 0 && btnVehicleColor.SelectedIndex != 0 && price > 0)
{
if(type == "car")
Cardealer.getInstance().registerCar(type, model, color, price);
else
Cardealer.getInstance().registerTruck(type, model, color, price);
lblStatus.Content = UppercaseFirst(type)+" registered!";
}
else
{
lblStatus.Content = "Check your values.";
}
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
GuiUtil.checkNumerical(inputVehiclePrice);
}
private string UppercaseFirst(string s)
{
// Check for empty string.
if (string.IsNullOrEmpty(s))
{
return string.Empty;
}
// Return char and concat substring.
return char.ToUpper(s[0]) + s.Substring(1);
}
}
}
|
de561dd07ab7ed65748d1ab4b617ffa0d4bad94c
|
C#
|
JerryXia/ML
|
/src/ML NET20/Xml/XmlHelper.cs
| 2.984375
| 3
|
using System;
using System.Xml;
namespace ML.Xml
{
public class XmlHelper : IDisposable
{
private XmlDocument xmlDoc;
#region 初始化XML文件
public XmlHelper()
{
xmlDoc = new XmlDocument();
}
public XmlHelper(string xmlFilePath)
{
xmlDoc = new XmlDocument();
CreateXml(xmlFilePath);
Load(xmlFilePath);
}
/// <summary>
/// 创建XML文件
/// </summary>
/// <param name="xmlFilePath">xml文件路径</param>
public void CreateXml(string xmlFilePath)
{
if (System.IO.File.Exists(xmlFilePath) == false)
{
InitFilePathDir(xmlFilePath);
InitXml(xmlFilePath);
}
}
/// <summary>
/// 加载路径上的xml文件
/// </summary>
/// <param name="xmlFilePath"></param>
public void Load(string xmlFilePath)
{
xmlDoc.Load(xmlFilePath);
}
#endregion
#region 内部私有方法
/// <summary>
/// 判断xml的上级目录是否存在,不存在则创建
/// </summary>
/// <param name="xmlFilePath">xml文件的目录</param>
private void InitFilePathDir(string xmlFilePath)
{
//string[] arrFilePath = xmlFilePath.Split('\\');
//int theLastIndex = xmlFilePath.LastIndexOf('\\');//arrFilePath.Length - 1;
//修改为跨平台用法
int theLastIndex = xmlFilePath.LastIndexOf(System.IO.Path.DirectorySeparatorChar);
string xmlFileDir = xmlFilePath.Remove(theLastIndex);
if (System.IO.Directory.Exists(xmlFileDir) == false)
{
System.IO.Directory.CreateDirectory(xmlFileDir);
}
}
/// <summary>
/// 内部初始化XML文件
/// </summary>
/// <param name="xmlFilePath"></param>
private void InitXml(string xmlFilePath)
{
//<?xml version="1.0" encoding="UTF-8" ?><root></root>
try
{
XmlNode declareNode = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
xmlDoc.AppendChild(declareNode);
XmlNode root = xmlDoc.CreateNode(XmlNodeType.Element, "root", "");
xmlDoc.AppendChild(root);
xmlDoc.Save(xmlFilePath);
}
catch (System.Exception ex)
{
throw (new Exception("创建默认XML文件失败" + ex.Message));
}
}
#endregion
#region XML文档操作
/// <summary>
/// 获取XML文档树的根
/// </summary>
/// <returns></returns>
public XmlElement RootNode
{
get { return xmlDoc.DocumentElement; }
}
/// <summary>
/// 文档创建结点
/// </summary>
/// <param name="name">结点名称</param>
/// <returns>创建的结点对象</returns>
public XmlNode CreateNode(string name)
{
return xmlDoc.CreateNode(XmlNodeType.Element, name, null);
}
/// <summary>
/// 父节点创建子结点
/// </summary>
/// <param name="parentNode">父节点</param>
/// <param name="name">结点名称</param>
/// <param name="value">结点值</param>
public void CreateNode(XmlNode parentNode, string name, string value)
{
XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null);
node.InnerText = value;
parentNode.AppendChild(node);
}
/// <summary>
/// XML文档保存
/// </summary>
/// <param name="xmlFilePath"></param>
public void Save(string xmlFilePath)
{
xmlDoc.Save(xmlFilePath);
}
#endregion
#region xml文档结点查询
public XmlNode SelNode(string path)
{
return xmlDoc.SelectSingleNode(path);
}
public XmlNodeList SelNodes(string path)
{
return xmlDoc.SelectNodes(path);
}
#endregion
#region IDisposable 成员
public virtual void Dispose()
{
if (xmlDoc != null)
{
xmlDoc.RemoveAll();
xmlDoc = null;
}
}
#endregion
}
}
|
41f2e2c9d4c4fdcdba3894eb9e63930336d0e5a5
|
C#
|
deflis/OpenSolar
|
/Solar/DateTimeConverter.cs
| 2.9375
| 3
|
using System;
using Ignition.Presentation;
namespace Solar
{
class DateTimeConverter : OneWayValueConverter<DateTime, string>
{
protected override string ConvertFromSource(DateTime value, object parameter)
{
if (value.DayOfYear == DateTime.Now.DayOfYear)
return value.ToString("HH:mm:ss");
else if (value.Year == DateTime.Now.Year)
return value.ToString("MM/dd HH:mm:ss");
else
return value.ToString("yy/MM/dd HH:mm:ss");
}
}
}
|
789b230ae3d3a334b401f05f91c805dfc64f3140
|
C#
|
StefaanAvonds/Encryptors
|
/Encryptors/Interfaces/IEncrypt.cs
| 2.625
| 3
|
namespace Encryptors.Interfaces
{
public interface IEncrypt
{
/// <summary>
/// Encrypt a text.
/// </summary>
/// <param name="text">The text to encrypt.</param>
/// <returns>The encrypted text.</returns>
string Encrypt(string text);
}
}
|
3f9dc9bbba565441462fdf54384f532cdb971828
|
C#
|
bt7s7k7/Space
|
/Assets/PlayerStatsDisplay.cs
| 2.609375
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerStatsDisplay : MonoBehaviour {
public Text display;
public bool multiline = true;
public bool showMoney = true;
public bool showLevel = true;
void Update() {
string show = "";
GameManager.PlayerStats stats = GameManager.GetPlayerStats();
if (showMoney) {
show += stats.money + "₪";
}
if (showLevel) {
if (multiline) show += "\n";
show += "Level " + stats.level;
}
display.text = show;
}
}
|
f5f025dfe97120220b565e862add2a94c55a258b
|
C#
|
trarck/DataBinding
|
/DataBinding/DataBinding/BindingProviders/PropertyProviders/SameTypeProvider.cs
| 2.53125
| 3
|
using System;
using System.Reflection;
namespace DataBinding.PropertyProviders
{
public class SameTypeProvider<T> : PropertyBindingProvider<T, T>
{
public override void SyncTarget()
{
m_TargetSetter(m_SourceGetter());
}
public override void SyncSource()
{
if (m_BindType == BindType.TwoWay)
{
m_SourceSetter(m_TargetGetter());
}
}
}
}
|
752ac4acbbb1f3fc850009820c23e999b20eb968
|
C#
|
xray/Chorizo
|
/tests/Logger/Output/Console/ConsoleOutTest.cs
| 2.5625
| 3
|
using System;
using Chorizo.Logger.Output.Console;
using Moq;
using Xunit;
namespace Chorizo.Tests.Logger.Output.Console
{
public class ConsoleOutTest
{
private const string TestText = "Test";
private DateTime _testTime = new DateTime(1997, 12, 02, 03, 32, 00, DateTimeKind.Utc);
private string _testTimeString;
public ConsoleOutTest()
{
_testTimeString = _testTime.ToString("t");
}
[Fact]
public void OutGivenAnErrorOutputsAMessageWithAErrorTag()
{
var mockConsole = new Mock<IConsole>();
var testConsoleOut = new ConsoleOut
{
WrappedConsole = mockConsole.Object
};
testConsoleOut.Out(TestText, 0, _testTime);
mockConsole.Verify(console => console.WriteLine($"{_testTimeString} -> [\x1b[31mERROR\x1b[0m] {TestText}"));
}
[Fact]
public void OutGivenAInfoOutputsAMessageWithAInfoTag()
{
var mockConsole = new Mock<IConsole>();
var testConsoleOut = new ConsoleOut
{
WrappedConsole = mockConsole.Object
};
testConsoleOut.Out(TestText, 1, _testTime);
mockConsole.Verify(console => console.WriteLine($"{_testTimeString} -> [\x1b[92mINFO\x1b[0m] {TestText}"));
}
[Fact]
public void OutGivenAWarningOutputsAMessageWithAWarningTag()
{
var mockConsole = new Mock<IConsole>();
var testConsoleOut = new ConsoleOut
{
WrappedConsole = mockConsole.Object
};
testConsoleOut.Out(TestText, 2, _testTime);
mockConsole.Verify(console => console.WriteLine($"{_testTimeString} -> [\x1b[93mWARNING\x1b[0m] {TestText}"));
}
}
}
|
5d0f29fdafddd550cba5aa6c4134c29d7626a18d
|
C#
|
GreatisNate/RavenNest
|
/src/RavenNest.BusinessLogic/Game/Managers/IServerManager.cs
| 2.609375
| 3
|
using Microsoft.EntityFrameworkCore;
using RavenNest.BusinessLogic.Data;
using RavenNest.BusinessLogic.Net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using RavenNest.DataModels;
namespace RavenNest.BusinessLogic.Game
{
public interface IServerManager
{
Task BroadcastMessageAsync(string message);
}
public class ServerManager : IServerManager
{
private readonly IGameData gameData;
public ServerManager(IGameData gameData)
{
this.gameData = gameData;
}
public Task BroadcastMessageAsync(string message)
{
// 1. get all active sessions
var sessions = gameData.GetActiveSessions();
//var sessions = await db.GameSession
// .Include(x => x.GameEvents)
// .Where(x => x.Stopped != null)
// .ToListAsync();
// 2. push a new event for each session
foreach (var session in sessions)
{
//var revision = session.GameEvents.Count > 0
// ? session.GameEvents.Max(x => x.Revision) + 1 : 1;
var gameEvent = gameData.CreateSessionEvent(GameEventType.ServerMessage, session, new ServerMessage()
{
Message = message,
});
gameData.Add(gameEvent);
//await db.GameEvent.AddAsync(new DataModels.GameEvent()
//{
// Id = Guid.NewGuid(),
// GameSessionId = session.Id,
// GameSession = session,
// Data = JSON.Stringify(new ServerMessage()
// {
// Message = message,
// }),
// Type = (int)GameEventType.ServerMessage,
// Revision = revision
//});
}
return Task.CompletedTask;
}
}
}
|
d3dcd429794572d2e5069114e4d8423cc889f447
|
C#
|
nov30th/LizhiRedBaoFiddlerPlugin
|
/LizhiRedBaoFiddlerPlugin/DesUtil.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace LizhiRedBaoFiddlerPlugin
{
public class DesUtil
{
private static readonly string encryptKey = "0fe3";
//字符串加密
public static string Encrypt(string str)
{
var descsp = new DESCryptoServiceProvider();
var key = Encoding.Unicode.GetBytes(encryptKey);
var data = Encoding.Unicode.GetBytes(str);
var MStream = new MemoryStream();
var CStream = new CryptoStream(MStream, descsp.CreateEncryptor(key, key), CryptoStreamMode.Write);
CStream.Write(data, 0, data.Length);
CStream.FlushFinalBlock();
return Convert.ToBase64String(MStream.ToArray());
}
//字符串解密
public static string Decrypt(string str)
{
var descsp = new DESCryptoServiceProvider();
var key = Encoding.Unicode.GetBytes(encryptKey);
var data = Convert.FromBase64String(str);
var MStream = new MemoryStream();
var CStram = new CryptoStream(MStream, descsp.CreateDecryptor(key, key), CryptoStreamMode.Write);
CStram.Write(data, 0, data.Length);
CStram.FlushFinalBlock();
return Encoding.Unicode.GetString(MStream.ToArray());
}
}
}
|
01239dd46424c6f0558073054e49c9ee95af1920
|
C#
|
Janbaz-khan/EServices
|
/EServices/CustomClasses/RandomValue.cs
| 2.84375
| 3
|
using EServices.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace EServices.CustomClasses
{
public class RandomValue
{
public int GeneratePassword()
{
Random rndm = new Random();
int min = 10000;
int max = 99999;
return rndm.Next(min, max);
}
}
public class CurrentSession
{
public string Session()
{
using (DB db=new DB())
{
var s = db.Sessions.OrderByDescending(a => a.SessionId).Take(1).FirstOrDefault();
if (s==null)
{
var currentyear = DateTime.Now.Year;
var nextyear = DateTime.Now.AddYears(1).Year;
Session session = new Session();
session.SessionId = 1;
session.SessionName = currentyear + "-" + nextyear;
db.Sessions.Add(session);
db.SaveChanges();
return session.SessionName;
}
else
{
string ses = s.SessionName;
return ses;
}
}
}
}
}
|
ccc8aead3dabc27164252b82f00fe45e70eb2725
|
C#
|
lotosbin/payment
|
/src/Essensoft.AspNetCore.Payment.Security/SHA1.cs
| 2.53125
| 3
|
using System;
using System.Text;
namespace Essensoft.AspNetCore.Payment.Security
{
public class SHA1
{
public static string Compute(string data)
{
if (string.IsNullOrEmpty(data))
{
throw new ArgumentNullException(nameof(data));
}
var sha1 = System.Security.Cryptography.SHA1.Create();
var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(data));
return BitConverter.ToString(hash).Replace("-", "").ToLower();
}
}
}
|
e5a77202de5fcbea9ee1cf20f5877060334aebe3
|
C#
|
OpenRIAServices/OpenRiaServices
|
/src/VisualStudio/Tools/Framework/DomainServiceWizard/CodeGenContext.cs
| 2.640625
| 3
|
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.CSharp;
using Microsoft.VisualBasic;
namespace OpenRiaServices.VisualStudio.DomainServices.Tools
{
/// <summary>
/// This class captures the CodeDom provider, root namespace, etc and provides some common code gen helper methods
/// </summary>
public sealed class CodeGenContext : IDisposable
{
private CodeDomProvider _provider;
private CodeCompileUnit _compileUnit = new CodeCompileUnit();
private CodeGeneratorOptions _options = new CodeGeneratorOptions();
private Dictionary<string, CodeNamespace> _namespaces = new Dictionary<string, CodeNamespace>();
private readonly List<string> _references = new List<string>();
private readonly string _rootNamespace;
/// <summary>
/// Creates a new instance
/// </summary>
/// <param name="language">Must be "C#" or "VB" currently</param>
/// <param name="rootNamespace">If non-null, please do not generate any namespace directives starting with it.</param>
public CodeGenContext(string language, string rootNamespace)
{
this._provider = language.Equals("C#") ? (CodeDomProvider)new CSharpCodeProvider() : (CodeDomProvider)new VBCodeProvider();
this._rootNamespace = rootNamespace;
this.Initialize();
}
/// <summary>
/// Sets up the generator options
/// </summary>
private void Initialize()
{
CodeGeneratorOptions cgo = new CodeGeneratorOptions(); // TODO: get from VS???
cgo.IndentString = " ";
// We require verbatim order for predictability for baselines
cgo.VerbatimOrder = true;
cgo.BlankLinesBetweenMembers = true;
cgo.BracingStyle = "C";
this._options = cgo;
}
/// <summary>
/// Gets the CodeCompileUnit for this context
/// </summary>
private CodeCompileUnit CompileUnit
{
get
{
return this._compileUnit;
}
}
/// <summary>
/// Gets the CodeGeneratorOptions for this context
/// </summary>
public CodeGeneratorOptions CodeGeneratorOptions
{
get
{
return this._options;
}
}
/// <summary>
/// Gets the CodeDomProvider for this context
/// </summary>
public CodeDomProvider Provider
{
get
{
return this._provider;
}
}
/// <summary>
/// Gets the value indicating whether the language is C#
/// </summary>
public bool IsCSharp
{
get
{
return this._provider is CSharpCodeProvider;
}
}
/// <summary>
/// Gets the set of assembly references generated code needs to compile
/// </summary>
/// <remarks>
/// This set represents only those additional references required for
/// the entity types and DAL types appearing in the generated code
/// </remarks>
public IEnumerable<string> References
{
get
{
return this._references;
}
}
/// <summary>
/// Gets the root namespace. For use with VB codegen only.
/// </summary>
public string RootNamespace
{
get
{
return this._rootNamespace;
}
}
/// <summary>
/// Adds the given assembly reference to the list of known assembly references
/// necessary to compile
/// </summary>
/// <param name="reference">The full name of the assembly reference.</param>
public void AddReference(string reference)
{
if (!this._references.Contains(reference, StringComparer.OrdinalIgnoreCase))
{
this._references.Add(reference);
}
}
/// <summary>
/// Returns <c>true</c> only if the given identifier is valid for the current language
/// </summary>
/// <param name="identifier">The string to check for validity. Null will cause a <c>false</c> to be returned.</param>
/// <returns><c>true</c> if the identifier is valid</returns>
public bool IsValidIdentifier(string identifier)
{
return !string.IsNullOrEmpty(identifier) && this._provider.IsValidIdentifier(identifier);
}
/// <summary>
/// Generates code for the current compile unit into a string. Also strips out auto-generated comments/
/// </summary>
/// <returns>The generated code and necessary references.</returns>
public GeneratedCode GenerateCode()
{
string generatedCode = string.Empty;
using (TextWriter t = new StringWriter(CultureInfo.InvariantCulture))
{
this.FixUpCompileUnit(this.CompileUnit);
this.Provider.GenerateCodeFromCompileUnit(this.CompileUnit, t, this._options);
generatedCode = this.FixupVBOptionStatements(t.ToString());
}
// Remove the auto-generated comment about "please don't modify this code"
string sourceCode = CodeGenUtilities.StripAutoGenPrefix(generatedCode, this.IsCSharp);
return new GeneratedCode(sourceCode, this.References);
}
/// <summary>
/// Fixes up a <see cref="CodeCompileUnit"/>.
/// </summary>
/// <param name="compileUnit">The <see cref="CodeCompileUnit"/> to fix up.</param>
private void FixUpCompileUnit(CodeCompileUnit compileUnit)
{
DomainServiceFixupCodeDomVisitor visitor = new DomainServiceFixupCodeDomVisitor(this);
visitor.Visit(compileUnit);
}
// WARNING:
// This code is copied verbatim from the OpenRiaServices.Tools.ClientProxyGenerator class
// changes in this code will likely be required to be ported to that class as well.
// See ClientProxyGenerator class for details.
private string FixupVBOptionStatements(string code)
{
if (!this.IsCSharp && code != null)
{
StringBuilder strBuilder = new StringBuilder(code);
// We need to change Option Strict from Off to On and add
// Option Infer and Compare. Option Explict is ok.
string optionStrictOff = "Option Strict Off";
string optionStrictOn = "Option Strict On";
string optionInferOn = "Option Infer On";
string optionCompareBinary = "Option Compare Binary";
int idx = code.IndexOf(optionStrictOff, StringComparison.Ordinal);
if (idx != -1)
{
strBuilder.Replace(optionStrictOff, optionStrictOn, idx, optionStrictOff.Length);
strBuilder.Insert(idx, optionInferOn + Environment.NewLine);
strBuilder.Insert(idx, optionCompareBinary + Environment.NewLine);
}
return strBuilder.ToString();
}
return code;
}
/// <summary>
/// Generates a new CodeNamespace or reuses an existing one of the given name
/// </summary>
/// <param name="namespaceName">The namespace in which to generate code.</param>
/// <returns>namespace with the given name</returns>
public CodeNamespace GetOrGenNamespace(string namespaceName)
{
CodeNamespace ns = null;
if (string.IsNullOrEmpty(namespaceName))
{
return null;
}
string adjustedNamespaceName = this.GetNamespaceName(namespaceName);
if (!this._namespaces.TryGetValue(adjustedNamespaceName, out ns))
{
ns = new CodeNamespace(adjustedNamespaceName);
this._namespaces[adjustedNamespaceName] = ns;
// Add all the fixed namespace imports
foreach (string fixedImport in BusinessLogicClassConstants.FixedImports)
{
CodeNamespaceImport import = new CodeNamespaceImport(fixedImport);
ns.Imports.Add(import);
}
this.CompileUnit.Namespaces.Add(ns);
}
return ns;
}
/// <summary>
/// If the project has a rootnamespace, it strips it out from the namespace passed in and returns the actual namespace to be generated in code.
/// </summary>
/// <param name="namespaceName">The full namespace (including the root namespace, if the project has one)</param>
/// <returns>The actual namespace to be generated in code.</returns>
private string GetNamespaceName(string namespaceName)
{
string adjustedNamespaceName = namespaceName;
if (!String.IsNullOrEmpty(this._rootNamespace) && namespaceName.Equals(this._rootNamespace, StringComparison.Ordinal))
{
adjustedNamespaceName = String.Empty;
}
else if (!String.IsNullOrEmpty(this._rootNamespace) && namespaceName.StartsWith(this._rootNamespace + ".", StringComparison.Ordinal))
{
adjustedNamespaceName = namespaceName.Substring(this._rootNamespace.Length + 1);
}
return adjustedNamespaceName;
}
/// <summary>
/// Gets the <see cref="CodeNamespace"/> for a <see cref="CodeTypeDeclaration"/>.
/// </summary>
/// <param name="typeDecl">A <see cref="CodeTypeDeclaration"/>.</param>
/// <returns>A <see cref="CodeNamespace"/> or null.</returns>
public CodeNamespace GetNamespace(CodeTypeDeclaration typeDecl)
{
string namespaceName = typeDecl.UserData["Namespace"] as string;
Debug.Assert(namespaceName != null, "Null namespace");
CodeNamespace ns = null;
this._namespaces.TryGetValue(namespaceName, out ns);
return ns;
}
#region IDisposable Members
/// <summary>
/// Override of IDisposable.Dispose to handle implementation details of dispose
/// </summary>
public void Dispose()
{
GC.SuppressFinalize(this);
CodeDomProvider provider = this._provider;
this._provider = null;
if (provider != null)
{
provider.Dispose();
}
this._compileUnit = null;
this._namespaces = null;
}
#endregion
}
}
|
dfd6d3c0b09ba9b723db93144d2e057b3ec1a30d
|
C#
|
andrewdoyle19/RfsForChromeService
|
/src/RfsForChrome.Service/OrderAndModelIncidents.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using RfsForChrome.Service.Extensions;
using RfsForChrome.Service.Models;
namespace RfsForChrome.Service
{
public interface IOrderAndModelIncidents
{
IEnumerable<Incident> CreateModel(XDocument document);
}
public class OrderAndModelIncidents : IOrderAndModelIncidents
{
public IEnumerable<Incident> CreateModel(XDocument document)
{
var items = document.Descendants("item");
var incidents = items.Select(s => new Incident()
{
Title = s.Element("title").Value,
Category = GetCategory(s.Element("category").Value),
LastUpdated = ParseLastUpdatedFromDescriptionString(s.Element("description").Value).MyToDateTime(),
CouncilArea = ParseItemFromDescriptionString(s.Element("description").Value, "COUNCIL AREA"),
Status = ParseItemFromDescriptionString(s.Element("description").Value, "STATUS"),
Location = ParseItemFromDescriptionString(s.Element("description").Value, "LOCATION"),
Size = ParseItemFromDescriptionString(s.Element("description").Value, "SIZE"),
Type = ParseItemFromDescriptionString(s.Element("description").Value, "TYPE"),
Link = s.Element("link").Value,
MajorFireUpdate = ParseItemFromDescriptionString(s.Element("description").Value, "MAJOR FIRE UPDATE"),
}).ToList();
//incidents.Add(new Incident()
// {
// Category = Category.EmergencyWarning,
// Title = "Some Dodgy Fire",
// Status = "out of control",
// LastUpdated = DateTime.Now,
// Location = "Somewhere",
// Size = "121 ha",
// CouncilArea = "Cessnock",
// Type = "Hazard Reduction"
// });
//incidents.Add(new Incident()
//{
// Category = Category.WatchAndAct,
// Title = "Another Dodgy Fire",
// Status = "out of control",
// LastUpdated = DateTime.Now,
// Location = "Somewhere",
// Size = "1 ha",
// CouncilArea = "Cessnock",
// Type = "Hazard Reduction"
//});
return incidents.OrderBy(incident => incident.Category).ThenByDescending(incident => incident.LastUpdated);
}
private string ParseItemFromDescriptionString(string value, string item)
{
if (value.IndexOf(item) == -1)
return string.Empty;
var trimmed = value.Trim().Replace("\n", " ");
string regex = string.Format("<br />{0}: (.*?)<br />",item);
return Regex.Split(trimmed, regex).ElementAt(1).Trim();
}
private string ParseLastUpdatedFromDescriptionString(string value)
{
var trimmed = value.Trim();
string regex = string.Format("<br />UPDATED: (.*?)");
return Regex.Split(trimmed, regex).ElementAt(2).Trim();
}
private Category GetCategory(string value)
{
switch (value)
{
case "Emergency Warning":
return Category.EmergencyWarning;
case "Watch and Act":
return Category.WatchAndAct;
case "Advice":
return Category.Advice;
default:
return Category.NotApplicable;
}
}
}
}
|
321443ef69bb7954a411800a448eff8a7275983d
|
C#
|
jhosehprendon/flyadealapp
|
/server/Newskies.WebApi/Extensions/SessionBagExtensions.cs
| 2.703125
| 3
|
using Newskies.WebApi.Services;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Newskies.WebApi.Extensions
{
public static class SessionBagExtensions
{
public async static Task<string> GetCustomSessionValue(this ISessionBagService sessionBagService, string sessionKey)
{
var customSessionValues = await sessionBagService.CustomSessionValues();
if (customSessionValues != null && customSessionValues.ContainsKey(sessionKey))
return customSessionValues[sessionKey];
return null;
}
public static async Task SetCustomSessionValue(this ISessionBagService sessionBagService, string sessionKey, string value)
{
var customSessionValues = await sessionBagService.CustomSessionValues();
if (customSessionValues == null)
{
customSessionValues = new Dictionary<string, string>();
}
if (customSessionValues.ContainsKey(sessionKey))
{
customSessionValues[sessionKey] = value;
}
else
{
customSessionValues.Add(sessionKey, value);
}
await sessionBagService.SetCustomSessionValues(customSessionValues);
}
}
}
|
2ca455851e5c5fb26c34f2e94c11391346f945c4
|
C#
|
jillaabhishek/OpenLMBookStoreWebApi
|
/OpenLMBookStore/Dtos/BookModel.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace OpenLMBookStore.Dtos
{
public class BookModel
{
public string BookId { get; set; }
[Required]
public string Name { get; set; }
[Required]
//[MinLength(1, ErrorMessage ="Book price should be greater than zero")]
//[MaxLength(1000, ErrorMessage ="Book price can't be greater than 1000")]
[Range(1, 1000, ErrorMessage ="Book price should range be 1 to 1000")]
public decimal Price { get; set; }
[Required]
public string Description { get; set; }
//[Required]
public byte[] BookCoverImage { get; set; }
[Required]
public BookCategory Category { get; set; }
[Required]
public Binding BookBinding { get; set; }
[Required]
//[MinLength(50, ErrorMessage = "No of pages in book should be greater than 50 pages")]
//[MaxLength(2000, ErrorMessage = "No of pages in book can't be greater than 2000 pages")]
[Range(1, 1000, ErrorMessage = "Book pages range should be 1 to 1000")]
public int NoOfPages { get; set; }
[Required]
public string Language { get; set; }
[Required]
//[MinLength(1, ErrorMessage = "Book quantity should be greater than zero")]
//[MaxLength(10000, ErrorMessage = "Book quantity can't be greater than 10000")]
[Range(1, 1000, ErrorMessage = "Book quantity range should be 1 to 10000")]
public int Quantity { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime PublishedDate { get; set; }
[Required]
public bool IsBookBestSeller { get; set; }
public AuthorModel Author { get; set; }
public PublisherModel Publisher { get; set; }
}
public enum Binding
{
Paperback,
Hardcover,
Online
}
public enum BookCategory
{
General,
Comics,
Cooking,
Horror,
Kids,
Fictional,
SciFiAndFantasy,
Biographies
}
}
|
1ca087107907d3d49bbedd0fe7c315494b78d361
|
C#
|
caioavidal/chip8-interpreter
|
/Chip8/Chip8/CPU/Stack.cs
| 2.90625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Chip8.CPU
{
public class MemoryStack
{
private Stack<ushort> Stack = new Stack<ushort>(16);
public ushort ReturnFromSubroutine() => Stack.Pop();
public ushort CallSubroutine(ushort address)
{
Stack.Push(address);
return address;
}
}
}
|
f1fab6d36dc29a934aab4222829a92afb6809000
|
C#
|
choi98772/pathtest
|
/CUnit.cs
| 2.8125
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace pathtest
{
//고양이와 쥐를 표현할 유닛
class CUnit
{
public int [] m_iPos = null; //현재 위치
private List<CNaviNode> m_vecPath; //A*알고리즘에 의해서 찾아진길의 노드
bool m_bMove; //현재 목표점으로 이동중인지를 나타내는 플래그
static Random m_RND = null; //임의의 위치를 생성하기 위한 난수 생성기
CUnit m_Target; //추적의 대상이 되는 유닛
bool m_bTracking; //추적이 활성화 되어 있는지 나타내는 플래그
bool m_bStartTracking = false; //추적이 시작되었는지 나타내는 플래그, 추적이 활성화 되어 있어도 시작되지 않았다면 추적하지 않느다.
public CUnit()
{
m_iPos = new int[2];
m_iPos[0] = m_iPos[1] = 0;
m_vecPath = null;
m_bMove = false;
if (m_RND == null)
{
m_RND = new Random();
}
m_Target = null;
m_bTracking = false;
}
//이동 경로 설정하기
public void SetPath(List<CNaviNode> vecPath)
{
m_vecPath = vecPath;
m_bMove = true;
}
//추적자인가?
public bool IsTracking() { return m_bTracking; }
//맵에서 임의의 위치를 선택해서 현재위치를 설정하기
public void RandomPos(CNavigationData ND)
{
//유효한 임의의 위치를 구할때까지 반복
while (true)
{
//임의의 위치를 구하고
int cx = m_RND.Next(ND.GetWidth());
int cy = m_RND.Next(ND.GetHeight());
//해당 위치가 이동가능한 위치면, 유닛 좌표를 해당위치로 설정한후 while 종료
if (ND.IsValidPos(cx, cy))
{
m_iPos[0] = cx;
m_iPos[1] = cy;
break;
}
}
}
public void SelectTarget(CUnit[] TargetList, int count)
{
if (m_Target == null)
{
m_Target = TargetList[m_RND.Next(count)];
}
else if (m_RND.Next(100) < 10)
{
m_Target = TargetList[m_RND.Next(count)];
}
}
//목표유닛 설정
public void SetTarget(CUnit target) { m_Target = target; }
public void EnableTracking(bool bEnable) { m_bTracking = bEnable; } //추적 모드를 활성화 한다.
public void StartTracking(bool bStart) { m_bStartTracking = bStart; } //추적을 시작한다
//유닛의 맵좌표 얻기
public int GetX() { return m_iPos[0]; }
public int GetY() { return m_iPos[1]; }
//매프레임 호출되어 유닛을 이동시킴
public void Update(CNavigationData ND, CAStarPathFinding FF)
{
//현재 이동중이지 않을 경우
if (!m_bMove)
{
//묙표유닛이 존재한다면
if (m_Target != null)
{//
//묙표유닛과 자신과의 거리를 구한다
int dx = m_iPos[0] - m_Target.GetX();
int dy = m_iPos[1] - m_Target.GetY();
if (m_bTracking)
{//타겟을 자동추적하는 모드라면
//추적중이라면
if (m_bStartTracking)
{
//목표와의 거리가 3셀이상이면
if (Math.Abs(dx) > 3 || Math.Abs(dy) > 3)
{
//나의 위치를 시작점, 목표위치를 끝점으로해서
CNaviNode pStart = CNaviNode.Create(m_iPos[0], m_iPos[1]);
CNaviNode pEnd = CNaviNode.Create(m_Target.GetX(), m_Target.GetY());
//경로를 구하고
m_vecPath = new List<CNaviNode>();
if (!FF.FindPath(pStart, pEnd, ref m_vecPath, ND))
{
}
else
{
//경로가 구해졌으면 유닛이동을 활성화
m_bMove = true;
}
}
}
}
else
{//타겟을 회피하는 모드다
//목표와의 거리가 4셀 이하이고, 현재 이동중이지 않으면
if (Math.Abs(dx) < 4 && Math.Abs(dy) < 4 && !m_bMove)
{
//무한반복
while (true)
{
//맵에서 임의의 위치를 하나 선택하고
int cx = m_RND.Next(ND.GetWidth());
int cy = m_RND.Next(ND.GetHeight());
//해당 위치가 이동가능한곳이면
if (ND.IsValidPos(cx, cy))
{
//유닛의 현재 위치를 시작점, 위에서 선택한 임의의 위치를 끝점으로 해서
CNaviNode pStart = CNaviNode.Create(m_iPos[0], m_iPos[1]);
CNaviNode pEnd = CNaviNode.Create(cx, cy);
//경로를 구하고
m_vecPath = new List<CNaviNode>();
if (!FF.FindPath(pStart, pEnd, ref m_vecPath, ND))
{
//경로가 구해지지 않았으면 while 루프를 다시 반복
continue;
}
else
{
//경로가 구해졌으면 유닛을 이동상태로 설정하고, while 루프를 종료
m_bMove = true;
break;
}
}
}
}
}
}
}
else //유닛이 현재 이동중인경우면
{
//경로가 존재하지 않으면, 이동모드를 중지
if (m_vecPath == null)
{
m_bMove = false;
}
else
{
int curindex = m_vecPath.Count - 1;
//경로의 목표점에 도달했으면
if (curindex < 0)
{
//이동모드를 중지하고, 경로는 클리어
m_bMove = false;
m_vecPath = null;
}
else
{
//경로의 현재 점을 유닛의 위치로 설정하고, 사용한 좌표는 경로 목록에서 제거하기
m_iPos[0] = m_vecPath[curindex].x;
m_iPos[1] = m_vecPath[curindex].y;
m_vecPath.RemoveAt(curindex);
}
}
}
}
}
}
|
00ef10033679801e5695c08f49f8b9a0836850ba
|
C#
|
cryply/explorer
|
/unity-client/Assets/Scripts/MainScripts/DCL/Controllers/HUD/QuestsHUD/QuestTaskUIEntry.cs
| 2.53125
| 3
|
using TMPro;
using UnityEngine;
namespace DCL.Huds
{
public class QuestTaskUIEntry : MonoBehaviour
{
[SerializeField] private TextMeshProUGUI description;
[SerializeField] private RectTransform stepsContainer;
[SerializeField] private QuestStepUIFactory factory;
public void Populate(QuestTask task)
{
CleanUpStepsList(); //TODO: Reuse already instantiated steps
description.text = task.description;
foreach (QuestStep step in task.steps)
{
CreateStep(step);
}
}
internal void CreateStep(QuestStep step)
{
GameObject prefab = factory.GetPrefab(step.type);
if (prefab == null)
{
Debug.LogError($"Type: {step.type} was not found in QuestStepFactory");
return;
}
var stepUIEntry = Instantiate(prefab, stepsContainer).GetComponent<IQuestStepUIEntry>();
stepUIEntry.Populate(step.payload);
}
internal void CleanUpStepsList()
{
while (stepsContainer.childCount > 0)
{
Destroy(stepsContainer.GetChild(0).gameObject);
}
}
}
}
|
9b6cdd6f3204b3662220e618d924cf7a0c1b119c
|
C#
|
CruzSanchez/CarLotSim
|
/CarLotSim/Car.cs
| 3.515625
| 4
|
using System;
using System.Collections.Generic;
using System.Text;
namespace CarLotSim
{
class Car : Vehicle
{
public string Honk { get; set; }
public static int NumOfCars { get; set; } = 0;
public Car(string _name, int _year, string _honk)
{
Name = _name;
Year = _year;
Honk = _honk;
NumOfCars++;
}
public override void Print()
{
Console.WriteLine("The model of the car is " + Name);
Console.WriteLine();
Console.WriteLine("The year of the car is " + Year);
Console.WriteLine();
Console.WriteLine("The horn makes the sound " + Honk);
Console.WriteLine();
}
}
}
|
f8ec5921024a2346af330bd16b7df3c7f3dfbd62
|
C#
|
dotnetfan/FluentSpotifyApi
|
/src/FluentSpotifyApi.Core/Utils/SpotifyTimeSpanConversionUtils.cs
| 3.234375
| 3
|
using System;
namespace FluentSpotifyApi.Core.Utils
{
/// <summary>
/// The set of TimeSpan conversion utilities intended for FluentSpotifyApi library usage.
/// </summary>
public static class SpotifyTimeSpanConversionUtils
{
/// <summary>
/// Converts specified value to whole milliseconds.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
public static int ToWholeMilliseconds(TimeSpan value) => checked((int)value.TotalMilliseconds);
/// <summary>
/// Converts specified value representing time interval in whole milliseconds to <see cref="TimeSpan"/>.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
public static TimeSpan FromWholeMilliseconds(int value) => TimeSpan.FromMilliseconds(value);
}
}
|
4cfbd352acf14bbd6f1efee89d8346b9a16a45d0
|
C#
|
hc-ro/LemmaGenerator-std
|
/Test/Program.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using LemmaSharp;
using Test.Classes;
namespace Test
{
class Program
{
static void Main(string[] args)
{
// Create readable file
var currentDirectory = Directory.GetCurrentDirectory();
var dataFilePath = $"{currentDirectory}/Data/Custom/full7z-mlteast-en-modified.lem";
using (var fstream = File.OpenRead(dataFilePath))
{
var lemmatizer = new Lemmatizer(fstream);
// add examples
var examples = new List<Tuple<string, string>>()
{
/*new Tuple<string,string>("acting","act"),
new Tuple<string,string>("balled","ball"),
new Tuple<string,string>("balled","ball"),
new Tuple<string,string>("ballsed","balls"),
new Tuple<string,string>("bogged","bog"),
new Tuple<string,string>("bottomed","bottom"),
new Tuple<string,string>("bounced","bounce"),
new Tuple<string,string>("boxed","box"),
new Tuple<string,string>("brought","bring"),
new Tuple<string,string>("cashed","cash"),
new Tuple<string,string>("clouded","cloud"),
new Tuple<string,string>("cozied","cozy"),
new Tuple<string,string>("divided","divide"),
new Tuple<string,string>("felt","feel"),
new Tuple<string,string>("fiddling","fiddle"),
new Tuple<string,string>("fishing","fish"),
new Tuple<string,string>("fleshed","flesh"),
new Tuple<string,string>("fobbed","fob"),
new Tuple<string,string>("following","follow"),
new Tuple<string,string>("homing","home"),
new Tuple<string,string>("hunkered","hunker"),
new Tuple<string,string>("leveled","level"),
new Tuple<string,string>("laid","lay"),
new Tuple<string,string>("limbered","limber"),
new Tuple<string,string>("livened","liven"),
new Tuple<string,string>("livened","liven"),
new Tuple<string,string>("loaded","load"),
new Tuple<string,string>("magicked","magic"),
new Tuple<string,string>("messing","mess"),
new Tuple<string,string>("meted","mete"),
new Tuple<string,string>("mouthing","mouth"),
new Tuple<string,string>("perked","perk"),
new Tuple<string,string>("pootling","pootle"),
new Tuple<string,string>("sacked","sack"),
new Tuple<string,string>("screwing","screw"),
new Tuple<string,string>("sexed","sex"),
new Tuple<string,string>("shacked","shack"),
new Tuple<string,string>("speeded","speed"),
new Tuple<string,string>("spirited","spirit"),
new Tuple<string,string>("started","start"),
new Tuple<string,string>("stove","stave"),
new Tuple<string,string>("swung","swing"),
new Tuple<string,string>("teed","tee"),
new Tuple<string,string>("tired","tire"),
new Tuple<string,string>("used","use"),
new Tuple<string,string>("vacuumed","vacuum"),
new Tuple<string,string>("whiled","while"),
new Tuple<string,string>("wigged","wig"),
new Tuple<string,string>("zoned","zone"),*/
new Tuple<string,string>("don't","do"),
new Tuple<string,string>("doesn't","do"),
new Tuple<string,string>("didn't","did"),
new Tuple<string,string>("won't","will"),
new Tuple<string,string>("shan't","shall"),
new Tuple<string,string>("can't","can"),
new Tuple<string,string>("couldn't","could"),
new Tuple<string,string>("wouldn't","would"),
new Tuple<string,string>("shouldn't","should"),
new Tuple<string,string>("mustn't","must"),
new Tuple<string,string>("mightn't","might"),
new Tuple<string,string>("oughtn't","ought"),
new Tuple<string,string>("needn't","need"),
new Tuple<string,string>("aren't","are"),
new Tuple<string,string>("isn't","be"),
new Tuple<string,string>("wasn't","be"),
new Tuple<string,string>("weren't","be"),
new Tuple<string,string>("haven't","have"),
new Tuple<string,string>("hasn't","have"),
new Tuple<string,string>("hadn't","have"),
new Tuple<string,string>("'s", "'s"),
new Tuple<string,string>("'ve", "have"),
new Tuple<string,string>("'m", "be"),
new Tuple<string,string>("'re", "be"),
new Tuple<string,string>("'ll", "will"),
};
foreach (var example in examples)
{
var lemma = lemmatizer.Lemmatize(example.Item1);
Console.WriteLine("{0} --> {1} {2}", example.Item1, lemma, lemma != example.Item2 ? ("!= " + example.Item2):"");
}
}
Console.WriteLine("==========");
Console.WriteLine("OK");
Console.ReadLine();
}
private static Lemmatizer CreatePreBuiltLemmatizer()
{
var lemmatizer = new LemmatizerPrebuiltFull(LanguagePrebuilt.English);
return lemmatizer;
}
private static Lemmatizer CreateLemmatizerFromFile()
{
var currentDirectory = Directory.GetCurrentDirectory();
var dataFilePath = string.Format("{0}/{1}/{2}", currentDirectory, "../../Data/Custom", "english.lem");
using (var stream = File.OpenRead(dataFilePath))
{
var lemmatizer = new Lemmatizer(stream);
return lemmatizer;
}
}
}
}
|
a47eb71ef032235371d5eef700ab45b060ac5658
|
C#
|
chavo12/EvaluacionDeDesempeno
|
/EvaluacionCelistics/LBSFramework/Helppers/Validaciones.cs
| 3.34375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace LBSFramework.Helppers
{
public class Validaciones
{
//----------------Metods Privados-----------------------
/// <summary>
/// retorna verdadero si se cumple la condicion para la cadena que ingresamos
/// </summary>
/// <param name="aValidar"></param>
/// <returns></returns>
private static Boolean validaBoolean(string aValidar, string condicion)
{
return (Regex.IsMatch(aValidar, condicion));
}
/// <summary>
/// evalua una cadena segun la condicion que deseamos y que su longitud sea igual a la que especificamos
/// </summary>
/// <param name="laCadena"></param>
/// <param name="cantidadCaracteres"></param>
/// <returns></returns>
private static Boolean validaBoolean(string laCadena, int cantidadCaracteres, string condicion)
{
//Valida por condicion y tamaño de palabra
return (Regex.IsMatch(laCadena, condicion) && (laCadena.Length == cantidadCaracteres));
}
//------------------------Publicos-----------------
/// <summary>
/// Valida que un texto sea unicamente letras y caracteres "." y ","
/// arroja False si posee caracteres especiales.
/// </summary>
/// <param name="elTestBox"></param>
/// <returns></returns>
public static Boolean validaTexto(string laCadena)
{
string condicion = @"\A[a-zA-Z0-9]*([ ]*[a-zA-Z0-9]*[/]*[,]*[.]*[a-zA-Z0-9]*)*\Z";
return (validaBoolean(laCadena, condicion));
}
/// <summary>
/// valida que el texto contenga unicamente numeros positivos
/// </summary>
/// <param name="elTextBox"></param>
public static Boolean validaNumero(string elNumero)
{
int res;
return int.TryParse(elNumero, out res);
//string condicion = @"\A[0-9]*\Z";
//return validaBoolean(elNumero, condicion);
}
public static Boolean validaFecha(string LaFecha)
{
if(LaFecha=="")
return true;
string condicion = @"^\d{1,2}\/\d{1,2}\/\d{2,4}$";
return validaBoolean(LaFecha, condicion);
}
/// <summary>
/// permite solo numeros positivos y un espacio
/// </summary>
/// <param name="elTextbox"></param>
public static Boolean validaNumeroyVacio(string elNumeroYVacio)
// Valida que solo pueda contener Numeros
{
string condicion = @"\A[0-9]+\Z";
return validaBoolean(elNumeroYVacio, condicion);
}
/// <summary>
/// acepta numeros positivos y negativos
/// </summary>
/// <param name="elNumZ"></param>
/// <returns></returns>
public static Boolean validaNumeroPositivoOnegativo(string elNumZ)
// Valida un TexBox que solo pueda contener Numeros y retorna true si es correcto o false cc
{
//string condicion = @"\A[-]*[0-9]+\Z";
string condicion = @"^[+-]?\d+(\.\d+)?$";
return (validaBoolean(elNumZ, condicion));
}
/// <summary>
/// Valida telefonos del tipo 0221-15-531-4484 con tantos guiones separando numeros como sea necesario
/// pero no permite dos guiones juntos ni al final del numero (45--45) (456-546-) "Error"
/// </summary>
/// <param name="elTel"></param>
public static Boolean validaTelefono(string elTel)
{
string condicion = @"\A[0-9]*([-]{1}[0-9]+)*\Z";
return validaBoolean(elTel, condicion);
}
/// <summary>
/// Valida un Textbox que solo contenga letras
/// </summary>
/// <param name="laPalabra"></param>
public static Boolean validaPalabra(string laPalabra)
{
string condicion = @"\A[a-zA-Z]*\Z";
return validaBoolean(laPalabra, condicion);
}
/// <summary>
/// Valida un Texto que solo contenga letras y este formado por una cantidad especifica de caracteres
/// </summary>
/// <param name="laPalabra"></param>
/// <param name="cantidadCaracteres"></param>
public static Boolean validaPalabrayLongitud(string laPalabra, int cantidadCaracteres)
{
string condicion = @"\A[a-zA-Z]*\Z";
return validaBoolean(laPalabra, cantidadCaracteres, condicion);
}
/// <summary>
///Valida un numero decimal teniendo en cuenta el separador de decimales el punto
///Lo tomo asi ya que resulta mas comodo el pinto para usar el pad nuemrico
/// </summary>
/// <param name="elDecimal"></param>
public static bool validaNumeroDecimal(string elDecimal)
{
decimal res;
return decimal.TryParse(elDecimal, out res);
//string condicion = @"\A[-]*[0-9]*[.]*[,]*[0-9]*\Z";
//return validaBoolean(elDecimal, condicion);
}
/// <summary>
/// Valido que la cadena ingresada sea un Email
/// </summary>
/// <param name="email"></param>
/// <returns></returns>
public static Boolean validaEmail(String email)
{
String expresion;
//un Email bien ingresado nunca podria tener las siguientes combinaciones de caracteres
expresion = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*[ ]*";
//si la cadena ingresada contiene alguna de las combinaciones anteriores
//devuelvo FALSE que indica que la expresion no es un Email
if (Regex.IsMatch(email, expresion))
{
if (Regex.Replace(email, expresion, String.Empty).Length == 0)
{
return true;//la cadena ingresada es un Email
}
else
{
return false;
}
}
else
{
return false;
}
}
/// <summary>
/// Valida que el numero recibido sea cuit (el número puedo o no contener los guiones.
/// </summary>
/// <param name="numero"></param>
/// <returns></returns>
public static Boolean esCuit(string numero)
{
numero = numero.Replace("-", string.Empty);
long res;
if (numero.Length == 11 && long.TryParse(numero, out res))
{
return int.Parse(numero.Substring(10)) == CalcularDigitoCuit(numero);
}
else return false;
}
public static int CalcularDigitoCuit(string cuit)
{
int[] mult = new[] { 5, 4, 3, 2, 7, 6, 5, 4, 3, 2 };
char[] nums = cuit.ToCharArray();
int total = 0;
for (int i = 0; i < mult.Length; i++)
{
total += int.Parse(nums[i].ToString()) * mult[i];
}
var resto = total % 11;
return resto == 0 ? 0 : resto == 1 ? 9 : 11 - resto;
}
}
}
|
515d2056f7ea78ce911a8dccd6fdf67d4d2bb086
|
C#
|
2She2/CSharpPartTwo
|
/06.TextFiles/03.InsertNumberOnEachLine/InsertNumberOnEachLine.cs
| 3.984375
| 4
|
// 03. Write a program that reads a text file and inserts line numbers in front of each of its lines.
// The result should be written to another text file.
using System;
using System.Text;
using System.IO;
namespace _03.InsertNumberOnEachLine
{
class InsertNumberOnEachLine
{
static void Main()
{
// Path to files to read and write to
string fileToRead = @"..\..\Text files\SomeText.txt";
string fileToWriteTo = @"..\..\Text files\NumberedText.txt";
// Insert line number in front of each line and write to "fileToWriteTo", using method "InsertLineNumbers(string fileToReadPath, string fileToWritePath)"
InsertLineNumbers(fileToRead, fileToWriteTo);
Console.WriteLine("Done.");
}
/// <summary>
/// Insert line number in front of each line and write to another file
/// </summary>
/// <param name="fileToReadPath">Path of file to read</param>
/// <param name="fileToWritePath">Path of file to write</param>
private static void InsertLineNumbers(string fileToReadPath, string fileToWritePath)
{
StreamReader reader = new StreamReader(fileToReadPath, Encoding.GetEncoding("windows-1251"));
using (reader)
{
int lineCounter = 1;
string lineText;
StreamWriter writer = new StreamWriter(fileToWritePath, false, Encoding.GetEncoding("windows-1251"));
using (writer)
{
// On each iteration check if file lines are over.
// Insert line number
// Every time increment the lines counter, to track the lines
while ((lineText = reader.ReadLine()) != null)
{
writer.WriteLine("{0}: {1}", lineCounter, lineText);
lineCounter++;
}
}
}
}
}
}
|
d4f7c680bcfe79f5cfc7d1386b4357bd710e0b0e
|
C#
|
DenisLevitin/ShootServ
|
/ShootServWeb/Models/Cup/ViewCupModelLogic.cs
| 2.546875
| 3
|
using System.Collections.Generic;
using System.Web.Mvc;
using BL;
using BO;
namespace ShootServ.Models.Cup
{
public class ViewCupModelLogic
{
private readonly EntryForCompetitionsLogic _entryLogic;
private readonly ShooterLogic _shooterLogic;
private readonly ShootingClubLogic _clubLogic;
private readonly CompetitionTypeLogic _competitionTypeLogic;
public ViewCupModelLogic()
{
_entryLogic = new EntryForCompetitionsLogic();
_clubLogic = new ShootingClubLogic();
_shooterLogic = new ShooterLogic();
_competitionTypeLogic = new CompetitionTypeLogic();
}
/// <summary>
/// Получить список упражнений на соревновании с информацией о состоянии заявки для стрелка
/// </summary>
/// <param name="idCup">ид. соревнования</param>
/// <param name="idUser">ид. юзера</param>
/// <returns></returns>
public List<ViewCupShooterCompetitionModel> GetCompetitionList(int idCup, int idUser = -1)
{
var res = new List<ViewCupShooterCompetitionModel>();
var query = _competitionTypeLogic.GetCupCompetitionListWithShooterEntryDetails(idCup, idUser);
foreach (var item in query)
{
res.Add(new ViewCupShooterCompetitionModel
{
IdCupCompetitionType = item.IdCupCompetitionType,
IdCompetitionType = item.IdCompetitionType,
IsShooterWasEntried = item.IsShooterWasEntried,
NameCompetition = item.NameCompetition,
TimeFirstShift = item.TimeFirstShift
});
}
return res;
}
/// <summary>
/// Добавить заявку
/// </summary>
/// <param name="idUser">ид. пользователя</param>
/// <param name="idCup">ид. соревнования</param>
/// <param name="idCompetitionType">ид. типа упражнения</param>
/// <returns></returns>
public ResultInfo CreateEntry(int idUser, int idCup, int idCompetitionType)
{
return _entryLogic.CreateEntry(idUser, idCup, idCompetitionType);
}
/// <summary>
/// Получить список заявленных стрелков
/// </summary>
/// <param name="idCup">ид. соревнования</param>
/// <param name="idClub">ид. команды</param>
public List<ShooterEntryDetailsParams> GetEntryShooters(int idCup, int idClub)
{
return idClub != -1 ? _shooterLogic.GetEntryShootersOnCupAndClub(idCup, idClub)
:
_shooterLogic.GetEntryShootersOnCup(idCup);
}
/// <summary>
/// Получить список команд на соревновании
/// </summary>
/// <param name="idCup"></param>
/// <returns></returns>
public List<SelectListItem> GetClubsByCup(int idCup)
{
var clubs = _clubLogic.GetByCup(idCup);
var res = new List<SelectListItem>();
res.Add(new SelectListItem { Value = "-1", Text = "Все" });
foreach (var club in clubs)
{
res.Add(new SelectListItem { Value = club.Id.ToString(), Text = club.Name });
}
return res;
}
}
}
|
6285f4233d2b11b9347b692689b1427245aac155
|
C#
|
Okuru1/xt_epam_KondidatovD
|
/xt_epam_Task02_KondidatovD/task2.2_Triangle/task2.2.cs
| 3.8125
| 4
|
using System;
using OtherClasses;
namespace task2_2
{
public class Program
{
public static void Main()
{
Console.WriteLine("Task 2.2 for XT_EPAM" + "\n\r--------------------");
double a, b, c;
Console.WriteLine("Enter A:");
a = InputFromConsole.IsDouble();
Console.WriteLine("Enter B:");
b = InputFromConsole.IsDouble();
Console.WriteLine("Enter C:");
c = InputFromConsole.IsDouble();
Triangle triangle = new Triangle(a, b, c);
triangle.GetInfo();
}
}
class Triangle
{
public readonly double A;
public readonly double B;
public readonly double C;
public Triangle (double a, double b, double c)
{
if ((a >= (b + c) || (b >= (a + c)) || (c >= (b + a))))
throw new ArgumentException("A non-existent triangle is specified. Each side must be less than the sum of the other two");
A = a;
B = b;
C = c;
}
public double GetPerimeter()
{
return A + B + C;
}
public double GetSquare()
{
double p;
p = halfPerimeter();
return Math.Sqrt(p*(p-A)*(p-B)*(p-C));
}
private double halfPerimeter()
{
return 1 % 2 * (A + B + C);
}
public void GetInfo()
{
Console.WriteLine($"A = {A:F2}");
Console.WriteLine($"B = {B:F2}");
Console.WriteLine($"C = {C:F2}");
Console.WriteLine($"Perimeter = {GetPerimeter():F4}");
Console.WriteLine($"Square of Triangle = {GetSquare():F4}");
}
}
}
|
7759cf29dc8ce37e233038618c78d1124922f9b5
|
C#
|
paulsmithkc/Shenanigans2017
|
/Assets/Scripts/Barbarian.cs
| 2.625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Barbarian : Hero
{
protected override float getPointsForProperty (string property)
{
float points;
switch (property) {
case "Beer":
case "Strength-Increasing" :
points = MAXIMUM_PURCHASE_POINTS;
break;
case "Axe":
case "Sword":
points = MAXIMUM_PURCHASE_POINTS * .85f;
break;
case "Chocolate":
case "Vanilla":
case "Caramel":
points = MAXIMUM_PURCHASE_POINTS * .5f;
break;
case "Stupidity":
points = MAXIMUM_PURCHASE_POINTS * .333f;
break;
case "Hummus":
case "Hemlock":
points = MAXIMUM_PURCHASE_POINTS * -.5f;
break;
case "Rusty":
case "Transparent":
case "Artificial":
points = MAXIMUM_PURCHASE_POINTS * -.333f;
break;
default :
points = base.getPointsForProperty (property);
break;
}
return points;
}
}
|
4de811748a3775e9f98a49b08467ba7878bf82ac
|
C#
|
mateuszokroj1/FileSizeEnumerator
|
/FileSizeEnumerator/UI/Views/MainView.xaml.cs
| 2.515625
| 3
|
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Data;
namespace FileSizeEnumerator.UI
{
/// <summary>
/// Represents main window of app
/// </summary>
public partial class MainView : Window
{
public MainView()
{
InitializeComponent();
var view = CollectionViewSource.GetDefaultView(List.ItemsSource);
view.SortDescriptions.Clear();
view.SortDescriptions.Add(new SortDescription
{
Direction = ListSortDirection.Descending,
PropertyName = "Length"
});
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
var model = DataContext as MainViewModel;
model?.Dispose();
}
}
}
|
30cc0f9d80c2e04cc7e53196ef1542f1bb507993
|
C#
|
alexeyprov/MCPD
|
/70-536/Instrumentation/CorrManagerTest/Backup/Program.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
namespace CorrManagerTest
{
class Program
{
static void Main(string[] args)
{
const string ID = "Primary Thread";
Trace.CorrelationManager.StartLogicalOperation(ID);
Trace.TraceInformation("(in main), stack = {0}", PrintLogicalStack());
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));
Thread.Sleep(1000);
Trace.CorrelationManager.StopLogicalOperation();
}
static void ThreadProc(object state)
{
const string ID = "Secondary Thread";
Trace.CorrelationManager.StartLogicalOperation(ID);
Trace.TraceInformation("(in thread proc), stack = {0}", PrintLogicalStack());
Trace.CorrelationManager.StopLogicalOperation();
}
static string PrintLogicalStack()
{
string[] frames = Array.ConvertAll(Trace.CorrelationManager.LogicalOperationStack.ToArray(),
new Converter<object, string>(Convert.ToString));
return String.Join(",", frames);
}
}
}
|
a76ab9149c3da5d12b8d0579ba4f8a8c01368207
|
C#
|
gormel/gormel
|
/TraceMe/TraceMe/Mesh.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace TraceMe
{
public class Mesh : BaseObject
{
public Matrix4 Transformation;
private Vector3[] vertices;
private int[] indices;
private Color[] colors;
private double[] reflections;
public Mesh(Vector3[] vertices, int[] indices, Color[] vertexColors, double[] reflections)
{
if (indices.Length % 3 != 0)
throw new ArgumentException("Indices do not describes triangles.");
if (indices.Any(i => i >= vertices.Length))
throw new ArgumentException("Indices do not describes triangles.");
this.vertices = new Vector3[vertices.Length];
this.indices = new int[indices.Length];
this.colors = new Color[vertexColors.Length];
this.reflections = new double[reflections.Length];
Array.Copy(reflections, this.reflections, reflections.Length);
Array.Copy(vertices, this.vertices, vertices.Length);
Array.Copy(indices, this.indices, indices.Length);
Array.Copy(vertexColors, colors, vertexColors.Length);
Transformation = Matrix4.Identity();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool SameSide(ref Vector3 p1, ref Vector3 p2, ref Vector3 a, ref Vector3 b)
{
Vector3 cp1 = new Vector3();
Vector3 cp2 = new Vector3();
Vector3 ba = b - a;
Vector3 p1a = p1 - a;
Vector3 p2a = p2 - a;
Vector3.Cross(ref ba, ref p1a, out cp1);
Vector3.Cross(ref ba, ref p2a, out cp2);
return cp1.Dot(cp2) >= 0;
}
public override Hit Intersections(Lay lay)
{
Hit result = null;
double mint = double.PositiveInfinity;
for (int v = 0; v < indices.Length; v += 3)
{
int aind = indices[v + 0];
int bind = indices[v + 1];
int cind = indices[v + 2];
Vector3 a = new Vector3();
Vector3 b = new Vector3();
Vector3 c = new Vector3();
Matrix4.Transform(ref Transformation, ref vertices[aind], out a);
Matrix4.Transform(ref Transformation, ref vertices[bind], out b);
Matrix4.Transform(ref Transformation, ref vertices[cind], out c);
Vector3 n = (b - a).Cross(c - a);
n.Normalize();
double d = -n.Dot(a);
double t = -(d + lay.Point.Dot(n)) / lay.Direction.Dot(n);
Vector3 i = lay.Point + lay.Direction * t;
if (!(SameSide(ref i, ref a, ref b, ref c) && SameSide(ref i,ref b, ref a, ref c) && SameSide(ref i, ref c, ref a, ref b)))
continue;
if (t > mint || t < 0)
continue;
mint = t;
double da = (i - b).Cross(i - c).Lenght();
double db = (i - a).Cross(i - c).Lenght();
double dc = (i - a).Cross(i - b).Lenght();
double s = da + db + dc;
da /= s;
db /= s;
dc /= s;
Color ca = colors[aind];
Color cb = colors[bind];
Color cc = colors[cind];
Color color = Color.FromArgb((byte)(ca.R * da + cb.R * db + cc.R * dc),
(byte)(ca.G * da + cb.G * db + cc.G * dc),
(byte)(ca.B * da + cb.B * db + cc.B * dc));
result = new Hit();
result.Color = color;
result.Distance = t;
result.Normal = n;
result.Reflection = reflections[aind] * da + reflections[bind] * db + reflections[cind] * dc;
}
return result;
}
}
}
|
761806c98c34b67bdf55db18a4960a5a5861ba1e
|
C#
|
MadalinaPlugariu/CegekaAcademy
|
/Course7/RentalCars/Program.cs
| 2.8125
| 3
|
using System;
namespace RentalCars
{
class Program
{
static void Main(string[] args)
{
RentalCars store = new RentalCars("Bucharest");
var customer1 = new Customer("Ion Popescu");
var customer2 = new Customer("Mihai Chirica");
var customer3 = new Customer("Gigi Becali");
store.AddRental(new Rental(customer1, new Car(PriceCode.Regular, "Ford Focus"), 2));
store.AddRental(new Rental(customer3, new Car(PriceCode.Regular, "Renault Clio"), 3));
store.AddRental(new Rental(customer1, new Car(PriceCode.Premium, "BMW 330i"), 1));
store.AddRental(new Rental(customer3, new Car(PriceCode.Premium, "Volvo XC90"), 3));
store.AddRental(new Rental(customer1, new Car(PriceCode.Mini, "Toyota Aygo"), 2));
store.AddRental(new Rental(customer1, new Car(PriceCode.Mini, "Hyundai i10"), 4));
store.AddRental(new Rental(customer3, new Car(PriceCode.Premium, "Volvo XC90"), 2));
store.AddRental(new Rental(customer3, new Car(PriceCode.Premium, "Mercedes E320"), 1));
store.AddRental(new Rental(customer2, new Car(PriceCode.Luxury, "Ford Fiesta"), 2));
Console.WriteLine(store.Statement());
}
}
}
|
9e4c4800824dcf99bc7ffaf33908a06b3ea62984
|
C#
|
nicklatkovich/ChipsBuilder
|
/Assets/Scripts/Utils.cs
| 2.8125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Text.RegularExpressions;
public static class Utils {
public static T[ ][ ] Init2DArray<T>(uint width, uint height, T defaultValue) {
T[ ][ ] result = new T[width][ ];
for (uint x = 0; x < width; x++) {
result[x] = new T[height];
for (uint y = 0; y < height; y++) {
result[x][y] = defaultValue;
}
}
return result;
}
public static List<T> Concat<T>(List<T> enum1, List<T> enum2) {
List<T> res = new List<T>(enum1);
res.AddRange(enum2);
return res;
}
public static Vector2 ToVector2XZ(this Vector3 v) {
return new Vector2(v.x, v.z);
}
public static Point Round(this Vector2 v) {
return new Point(
Mathf.RoundToInt(v.x),
Mathf.RoundToInt(v.y)
);
}
public static T Set<T>(this T[ ][ ] array, Point position, T value) {
return array[position.X][position.Y] = value;
}
public static T Set<T>(this T[ ][ ] array, Vector2 position, T value) {
return array.Set(position.Round( ), value);
}
public static Vector2 Add(this Vector2 v, float value) {
return new Vector2(v.x + value, v.y + value);
}
public static Vector3 Add(this Vector3 v, float value) {
return new Vector3(v.x + value, v.y + value, v.z + value);
}
public static float GetAtan2(this Vector2 v) {
return Mathf.Atan2(v.y, v.x);
}
public static Vector3 ToVector3XZ(this Vector2 v, float y = 0) {
return new Vector3(v.x, y, v.y);
}
public static float GetAtan2Deg(this Vector2 v) {
return v.GetAtan2( ) * Mathf.Rad2Deg;
}
public static void ChangeColor(this MonoBehaviour @object, string regex, Color color) {
Regex rgx = new Regex(regex);
foreach (var renderer in @object.GetComponentsInChildren<Renderer>( )) {
if (rgx.IsMatch(renderer.material.name)) {
renderer.material.color = color;
}
}
}
public static void ChangeColor(this MonoBehaviour @object, Color color) {
foreach (var renderer in @object.GetComponentsInChildren<Renderer>( )) {
renderer.material.color = color;
}
}
public static void ChangeAlpha(this MonoBehaviour @object, float newAlpha) {
foreach (var renderer in @object.GetComponentsInChildren<Renderer>( )) {
var rendererColor = renderer.material.color;
rendererColor.a = newAlpha;
renderer.material.color = rendererColor;
}
}
}
|
b2072441f323c57e8a2c8e62a93da42ce6dc311c
|
C#
|
ewin66/SAE
|
/CommonLibrary/SAE.CommonLibrary/src/SAE.CommonLibrary.Storage.MongoDB/MongoDBStorage.cs
| 2.578125
| 3
|
using SAE.CommonLibrary.Json;
using SAE.CommonLibrary.Log;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace SAE.CommonLibrary.Storage.MongoDB
{
/// <summary>
///
/// </summary>
public class MongoDBStorage : IStorage
{
#region Private Member
private readonly Type _stringType = typeof(string);
private readonly IJsonConvertor _jsonConvertor;
private readonly IDictionary<Type, Delegate> _idDelegateStorage=new Dictionary<Type, Delegate>();
private readonly MongoDBConfig _config;
private readonly ILog _log;
#endregion
#region Protected Member
/// <summary>
///
/// </summary>
protected MongoDatabase MongoDb
{
get;
private set;
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
protected MongoCollection<T> GetCollection<T>()
{
var colName = typeof(T).Name.ToLower();
return MongoDb.GetCollection<T>(colName);
}
#endregion
#region Ctor
/// <summary>
///
/// </summary>
/// <param name="jsonConvertor"></param>
/// <param name="config"></param>
/// <param name="log"></param>
public MongoDBStorage(IJsonConvertor jsonConvertor,
MongoDBConfig config,
ILog<MongoDBStorage> log)
{
_log = log;
_config = config;
_jsonConvertor = jsonConvertor;
var serverSetting = MongoServerSettings.FromUrl(new MongoUrl(this._config.Connection));
this._log.Debug($"Connection={this._config.Connection},DB={this._config.DB}");
this.MongoDb = new MongoServer(serverSetting).GetDatabase(this._config.DB);
}
#endregion
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="model"></param>
public void Add<T>(T model)
{
if (model == null) return;
this._log.Debug("Execute Add");
this.GetCollection<T>().Insert(model);
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="model"></param>
public void Update<T>(T model)
{
if (model == null) return;
this._log.Debug("Execute Update");
this.GetCollection<T>()
.Save(model);
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public IQueryable<T> AsQueryable<T>()
{
return this.GetCollection<T>().AsQueryable();
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="model"></param>
public void Remove<T>(T model)
{
if (model == null) return;
var id=IdentityDelegate(model);
var query = new QueryDocument("_id",BsonValue.Create(id));
var collection=this.GetCollection<T>();
collection.Remove(query);
this._log.Info($"Remove {collection.Name}:{id}");
}
/// <summary>
/// 标识表达式
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="model"></param>
/// <returns></returns>
private object IdentityDelegate<T>(T model)
{
var type = typeof(T);
Delegate @delegate;
if (!_idDelegateStorage.TryGetValue(type, out @delegate))
{
_log.Info("Identity Delegate:Get Id Property");
var property = type.GetTypeInfo()
.GetProperties()
.Where(s => s.Name.ToLower() == "_id" || s.Name.ToLower() == "id")
.FirstOrDefault();
if (property == null)
{
_log.Error("MongoDB Document Class You have to have a primary key");
throw new ArgumentNullException(nameof(model), $"{nameof(model)}中必须要有一个,唯一的键。默认为\"_id或\"\"id\"");
}
if (property.PropertyType.GetTypeInfo().IsValueType || property.PropertyType == _stringType)
{
var p = Expression.Parameter(typeof(T));
var body = Expression.Property(p, property.Name);
var expression = Expression.Lambda(body, p);
@delegate= expression.Compile();
_idDelegateStorage[type] = @delegate;
}
}
return @delegate.DynamicInvoke(model);
}
public T Find<T>(object id)
{
return this.GetCollection<T>()
.FindOneById(BsonValue.Create(id));
}
}
}
|
3473c260228eaf8ff6766fd0c0100a89d178cb68
|
C#
|
Hengle/framework
|
/ActionStreetMap.Maps/Formats/Xml/XmlApiReader.cs
| 2.53125
| 3
|
using System.Collections.Generic;
using System.Xml;
using ActionStreetMap.Core;
using ActionStreetMap.Maps.Data.Import;
using ActionStreetMap.Maps.Entities;
namespace ActionStreetMap.Maps.Formats.Xml
{
/// <summary> Provides API to parse response of Overpass API backend. </summary>
internal class XmlApiReader : IReader
{
private ReaderContext _context;
private IndexBuilder _builder;
private XmlReader _reader;
private Element _currentElement;
public void Read(ReaderContext context)
{
_context = context;
_builder = context.Builder;
using (_reader = XmlReader.Create(_context.SourceStream))
{
_reader.MoveToContent();
while (_reader.Read())
{
if (_reader.NodeType == XmlNodeType.Element)
{
if (_reader.Name == "node") ParseNode();
else if (_reader.Name == "tag") ParseTag();
else if (_reader.Name == "nd") ParseNd();
else if (_reader.Name == "way") ParseWay();
else if (_reader.Name == "relation") ParseRelation();
else if (_reader.Name == "member") ParseMember();
else if (_reader.Name == "bounds") ParseBounds();
}
}
ProcessCurrent();
}
}
private void ParseBounds()
{
var minLat = double.Parse(_reader.GetAttribute("minlat"));
var minLon = double.Parse(_reader.GetAttribute("minlon"));
var maxLat = double.Parse(_reader.GetAttribute("maxlat"));
var maxLon = double.Parse(_reader.GetAttribute("maxlon"));
_builder.ProcessBoundingBox(new BoundingBox(new GeoCoordinate(minLat, minLon),
new GeoCoordinate(maxLat, maxLon)));
}
private void ParseNode()
{
//id="21487162" lat="52.5271274" lon="13.3870120"
var id = long.Parse(_reader.GetAttribute("id"));
var lat = double.Parse(_reader.GetAttribute("lat"));
var lon = double.Parse(_reader.GetAttribute("lon"));
var node = new Node
{
Id = id,
Coordinate = new GeoCoordinate(lat, lon)
};
ProcessCurrent();
_currentElement = node;
}
private void ParseTag()
{
var key = _reader.GetAttribute("k");
var value = _reader.GetAttribute("v");
_currentElement.AddTag(key, value);
}
private void ParseWay()
{
var id = long.Parse(_reader.GetAttribute("id"));
ProcessCurrent();
// TODO use object pool
_currentElement = new Way
{
Id = id,
NodeIds = new List<long>()
};
}
private void ParseNd()
{
var refId = long.Parse(_reader.GetAttribute("ref"));
(_currentElement as Way).NodeIds.Add(refId);
}
private void ParseRelation()
{
var id = long.Parse(_reader.GetAttribute("id"));
ProcessCurrent();
_currentElement = new Relation
{
Id = id,
Members = new List<RelationMember>()
};
}
private void ParseMember()
{
var refId = long.Parse(_reader.GetAttribute("ref"));
var type = _reader.GetAttribute("type");
var role = _reader.GetAttribute("role");
(_currentElement as Relation).Members.Add(new RelationMember
{
TypeId = (type == "way" ? 1 : (type == "node" ? 0 : 2)),
MemberId = refId,
Role = role,
});
}
private void ProcessCurrent()
{
if (_currentElement == null) return;
var tagCount = _currentElement.Tags == null ? 0 : _currentElement.Tags.Count;
if (_currentElement is Node)
_builder.ProcessNode(_currentElement as Node, tagCount);
else if (_currentElement is Way)
_builder.ProcessWay(_currentElement as Way, tagCount);
else
_builder.ProcessRelation(_currentElement as Relation, tagCount);
}
}
}
|
dca646c63b00baa217dc29018db6a207acbfafc9
|
C#
|
alialinush99/Projects
|
/procp-city-traffic-simulation-master/procp-city-traffic-simulation-master/Traffic Application/TrafficDemo/Classes/TrafficLight.cs
| 3.265625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Timers;
using System.Drawing.Drawing2D;
namespace TrafficDemo.Classes
{
[Serializable]
public class TrafficLight
{
private int duration;
private bool isGreen;
private Color color; // not sure if we need it because we have the bool isGreen
private Point location;
// private Road road; // maybe we will need this later
// if you dont need the color property delete this constructor and use the isGreen in the mediator maybe
public TrafficLight(Color color , Point location)
{
this.color = color;
this.duration = 5;
this.isGreen = false;
this.location = location;
}
public TrafficLight(Point location)
{
this.duration = 5;
this.isGreen = false;
this.location = location;
}
public int Duration
{
get { return duration; }
set { duration = value; }
}
public bool IsGreen
{
get { return isGreen; }
set { isGreen = value; }
}
public Point Location
{
get { return location; }
set { location = value; }
}
public Color Color
{
get { return color; }
set { color = value; }
}
/// <summary>
/// Draws the traffic lights in the crossing
/// </summary>
/// <param name="gr">The graphics where the trafficlight will be drawn</param>
public void Draw(Graphics gr)
{
if (isGreen)
{
SolidBrush myBrush = new SolidBrush(Color.Green);
gr.FillEllipse(myBrush, location.X, location.Y, 7, 7);
}
else
{
SolidBrush myBrush = new SolidBrush(Color.Red);
gr.FillEllipse(myBrush, location.X, location.Y, 7, 7);
}
}
}
}
|
795f9a3257fe5b3238ae68a0253d502680e0f443
|
C#
|
furinji/Puzzle15
|
/Puzzle15/DrawManager.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
namespace Puzzle15
{
public class DrawManager
{
public DrawManager(Form1 form1)
{
_form1 = form1;
}
private Form1 _form1;
private DoubleBufferBitmap _dblBufBitmap;
private PanelImage _panelImage;
public void Init()
{
_dblBufBitmap = new DoubleBufferBitmap(_form1.Picbox.Size);
_panelImage = new PanelImage();
}
public void Redraw()
{
_form1.TextboxStep.Text =
String.Format("Step : {0}", _form1.GameManager.Step);
_dblBufBitmap.BufferGraphic.Clear(Color.Black);
foreach (var panel in _form1.PanelTable.GetPanels())
{
if (panel.Number < 1) { continue; }
LightState lightState =
_form1.PanelTable.LightStateInfos.GetLightState(panel);
_dblBufBitmap.BufferGraphic.DrawImage(
_panelImage.GetImage(lightState, panel.Number),
panel.X, panel.Y);
}
_form1.Picbox.Image = _dblBufBitmap.Flip();
}
public void Dispose()
{
_dblBufBitmap.Dispose();
_panelImage.Dispose();
}
}
}
|
4fc12039cbb87f47d0a2a075f9fd02026fc242a7
|
C#
|
EdwardSalter/ConsoleMenu
|
/src/ConsoleMenu/ConsoleMenuIOProvider.cs
| 3.078125
| 3
|
using System;
using System.Diagnostics.CodeAnalysis;
namespace ConsoleMenu
{
[ExcludeFromCodeCoverage]
internal class ConsoleMenuIOProvider : IMenuIOProvider
{
public void WriteMenuItem(char index, string choice)
{
Console.WriteLine("{0}. {1}", index, choice);
}
public void WriteInstructions(string instructions, int? lastUsed)
{
Console.Write("{0}{1}: ", instructions, lastUsed == null ? "" : " (" + lastUsed + ")");
}
public void Clear()
{
Console.Clear();
}
public char ReadCharacter()
{
return Console.ReadKey(true).KeyChar;
}
}
}
|
58bda1f7912b66e7c2b2574eb709aebddfc41701
|
C#
|
thehanu/gongura
|
/GeneralSamples/GeneralSamples/MyFunction.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
namespace GeneralSamples
{
class MyFunction
{
public static ICollection<RegionalNetworkConfigurationInfo> GetNetworkConfigurationInfoCollection(
Guid externalNic,
Dictionary<string, ICollection<RegionalNetworkConfigurationInfo>> customerAddressToRegionalConfigInfo)
{
ICollection<RegionalNetworkConfigurationInfo> configurationInfoCollection =
new Collection<RegionalNetworkConfigurationInfo>();
ICollection<RegionalNetworkConfigurationInfo> configurationInfoCollectionNicOnly =
new Collection<RegionalNetworkConfigurationInfo>();
// Add network resources (ACLs and Routes) associated to NIC
for (int i = 3; i < 7; i++)
{
configurationInfoCollection.Add(new RegionalNetworkConfigurationInfo { ConfigurationType = 0, Id = Guid.Parse(string.Format("{0}0808-CF60-429B-FEED-0C6452DDDD{1}{1}", "FEED", i)) } );
configurationInfoCollectionNicOnly.Add(new RegionalNetworkConfigurationInfo { ConfigurationType = 0, Id = Guid.Parse(string.Format("{0}0808-CF60-429B-FEED-0C6452DDDD{1}{1}", "FEED", i)) });
}
// For CAs being assigned from different Subnets, we provide CA mapped resource collection to apply network resources per subnet.
string[] subnets = { "CAFE", "CAFF", "CAFD" };
foreach (string subnet in subnets)
{
ICollection<RegionalNetworkConfigurationInfo> mappedConfigurationInfoCollection = new Collection<RegionalNetworkConfigurationInfo>();
for (int i = 3; i < 7; i++)
{
configurationInfoCollection.Add(new RegionalNetworkConfigurationInfo { ConfigurationType = 0, Id = Guid.Parse(string.Format("{0}0808-CF60-429B-FEED-0C6452DDDD{1}{1}", subnet, i)) });
mappedConfigurationInfoCollection.Add(new RegionalNetworkConfigurationInfo { ConfigurationType = 0, Id = Guid.Parse(string.Format("{0}0808-CF60-429B-FEED-0C6452DDDD{1}{1}", subnet, i)) });
}
// Add NIC resources to mapped configuration info collection.
foreach (RegionalNetworkConfigurationInfo configInfo in configurationInfoCollectionNicOnly)
{
mappedConfigurationInfoCollection.Add(new RegionalNetworkConfigurationInfo { ConfigurationType = configInfo.ConfigurationType, Id = configInfo.Id, });
}
// Add mapped configuration info collection to CA mapped dictionary customerAddressToRegionalConfigInfo
customerAddressToRegionalConfigInfo.Add(subnet, mappedConfigurationInfoCollection);
}
return configurationInfoCollection;
}
/*public static void TestRef()
{
Dictionary<string, ICollection<RegionalNetworkConfigurationInfo>> customerAddressToRegionalConfigInfo =
new Dictionary<string, ICollection<RegionalNetworkConfigurationInfo>>();
GetNetworkConfigurationInfoCollection(Guid.NewGuid(), ref customerAddressToRegionalConfigInfo);
Console.WriteLine("IntCollection: {0}", customerAddressToRegionalConfigInfo);
}*/
public static void TestNonRef()
{
Dictionary<string, ICollection<RegionalNetworkConfigurationInfo>> customerAddressToRegionalConfigInfo =
new Dictionary<string, ICollection<RegionalNetworkConfigurationInfo>>();
GetNetworkConfigurationInfoCollection(Guid.NewGuid(), customerAddressToRegionalConfigInfo);
Console.WriteLine("IntCollection: {0}", customerAddressToRegionalConfigInfo);
}
}
class FuncArgument
{
public delegate string MyFunction(string name, Uri value);
public static void TestFunctionArgument()
{
FuncArgument funcArgument = new FuncArgument();
string returnValue = funcArgument.ExecuteWithRetry(funcArgument.GetValue, "Hanu");
returnValue = funcArgument.ExecuteWithRetry(funcArgument.GetNewValue, "Hanu");
returnValue = PerformWithRetry(funcArgument.GetValue, "Hanu");
Uri myUri = PerformWithRetry(funcArgument.GetUriValue, "Hanu");
}
string ExecuteWithRetry(MyFunction myFunction, string name)
{
Uri uri = new Uri("http://thehanu.com");
try
{
return myFunction(name, uri);
}
catch
{
return myFunction(name, null);
}
}
string GetValue(string name, Uri uri)
{
return $"{name}:{uri?.ToString()}";
}
string GetNewValue(string name , Uri uri)
{
return $"New {name}:{uri?.ToString()}";
}
Uri GetUriValue(string name, Uri uri)
{
return new Uri($"{uri?.ToString()}/{name})");
}
public static TResult PerformWithRetry<TResult>(Func<string, Uri, TResult> func, string name)
{
Uri uri = new Uri("http://thehanu.com");
try
{
return func(name, uri);
}
catch
{
return func(name, null);
}
}
}
}
|
542e1d54e91057049a80fea68cc9b6481f9fde9e
|
C#
|
JohnNarvaez/TeamDS
|
/VeterinariaGato.App.Persistencia/AppRepositorios/RepositorioGatosMemoria.cs
| 3
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using VeterinariaGato.App.Dominio;
namespace VeterinariaGato.App.Persistencia.AppRepositorios
{
public class RepositorioGatosMemoria : IRepositorioGatos
{
List<Gato> gatos;
public RepositorioGatosMemoria()
{
gatos = new List<Gato>()
{
new Gato{Codigo=1, Nombre="Rufus", Raza="Himalayo", Color="Marrón", Edad="2"},
new Gato{Codigo=2, Nombre="Pacho", Raza="Van turco", Color="Blanco", Edad="3"}
};
}
public Gato Add(Gato nuevoGato)
{
nuevoGato.Codigo=gatos.Max(r => r.Codigo) +1;
gatos.Add(nuevoGato);
return nuevoGato;
}
public IEnumerable<Gato> GetAll()
{
return gatos;
}
public Gato GetGatoPorCodigo(int GatoCodigo)
{
return gatos.SingleOrDefault(s => s.Codigo==GatoCodigo);
}
public IEnumerable<Gato> GetGatosPorFiltro(string filtro=null) // el parámetro es opcional
{
var gatos = GetAll(); // Obtiene todos los gatos
if (gatos != null) //Si se tienen gatos
{
if (!String.IsNullOrEmpty(filtro)) // Si el filtro tiene algun valor
{
gatos = gatos.Where(s => s.Nombre.Contains(filtro));
/// <summary>
/// Filtra los mensajes que contienen el filtro
/// </summary>
}
}
return gatos;
}
public Gato Update(Gato gatoActualizado)
{
var gato= gatos.SingleOrDefault(r => r.Codigo==gatoActualizado.Codigo);
if (gato!=null)
{
gato.Codigo = gatoActualizado.Codigo;
gato.Nombre=gatoActualizado.Nombre;
gato.Raza=gatoActualizado.Raza;
gato.Color=gatoActualizado.Color;
gato.Edad=gatoActualizado.Edad;
gato.Veterinario=gatoActualizado.Veterinario;
gato.SignoVital=gatoActualizado.SignoVital;
gato.Propietario=gatoActualizado.Propietario;
gato.Enfermera=gatoActualizado.Enfermera;
gato.Historia=gatoActualizado.Historia;
}
return gato;
}
}
}
|
26e3392e6b28064841ee46854f9223ac3a00aa59
|
C#
|
kdkarki/CS5974
|
/DotnetCore_Mac/TrustMgmtSimulation/TrustMgmtSimulation/Entities/ServiceUnit.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace TrustMgmtSimulation.Entities
{
public class ServiceUnit
{
/// <summary>
/// The time the server will be available to server a new customer
/// </summary>
/// <returns></returns>
public double NextAvailableTime { get; set; }
/// <summary>
/// The customer currently being served and the time the service of the customer ends
/// </summary>
/// <returns></returns>
public KeyValuePair<Customer, double> CurrentCustomerEndTime { get; set; }
/// <summary>
/// All the customers queued to receive service from service unit
/// This does not include the customer currently in service
/// </summary>
/// <returns></returns>
public Dictionary<Entities.Customer, double> QueuedCustomerServiceTime { get; set; }
public ServiceUnit()
{
NextAvailableTime = 0.0;
QueuedCustomerServiceTime = new Dictionary<Customer, double>();
}
public bool AddCustomerToQueue(Customer customer, double customerServiceTime)
{
bool isSuccessfullAdded = false;
if(customer != null)
{
QueuedCustomerServiceTime.Add(customer, customerServiceTime);
isSuccessfullAdded = true;
}
return isSuccessfullAdded;
}
public bool StartServiceForCustomer(Customer customer, double currentTime)
{
bool isServiceSuccessfullyStarted = false;
if(QueuedCustomerServiceTime != null && QueuedCustomerServiceTime.Count > 0
&& QueuedCustomerServiceTime.ContainsKey(customer))
{
CurrentCustomerEndTime = KeyValuePair.Create(customer, (currentTime + QueuedCustomerServiceTime[customer]));
QueuedCustomerServiceTime.Remove(customer);
//TODO: Verify the calculation of next available time is correct
// because queued customer service time should be in hours (it is) and when summed with 'currentTime'
// it should be give correct next available time
NextAvailableTime = currentTime + QueuedCustomerServiceTime.Sum(c => c.Value);
isServiceSuccessfullyStarted = true;
}
return isServiceSuccessfullyStarted;
}
}
}
|
76f8a1f9f58eb801c48b82b8925e4887e42863cd
|
C#
|
pttb369/GameDevRepo
|
/Scripts/GameManager/MusicManager.cs
| 2.6875
| 3
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace CyberBullet.Events {
public class MusicManager : MonoBehaviour
{
public AudioSource source1; // assign via inspector
public AudioSource source2; // assign via inspector
public float fadeTime = 4.0f;
private Queue clips = new Queue();
private Queue volumes = new Queue();
private bool running = false;
public void CrossFade(AudioClip clip, float maxVolume)
{
clips.Enqueue(clip);
volumes.Enqueue(maxVolume);
if (running == false)
{
StartCoroutine(CrossFadeClips());
}
}
public void CrossFade(AudioClip clip)
{
clips.Enqueue(clip);
volumes.Enqueue(0.5f);
if (running == false)
{
StartCoroutine(CrossFadeClips());
}
}
IEnumerator CrossFadeClips ()
{
AudioClip targetClip = (AudioClip)clips.Dequeue();
float targetVolume = (float)volumes.Dequeue();
AudioSource oldSource = (source1.isPlaying) ? source1 : source2;
AudioSource newSource = (source1.isPlaying) ? source2 : source1;
float startTime = Time.unscaledTime;
float elapsed;
float orgVol = oldSource.volume;
newSource.clip = targetClip;
newSource.Play();
while ((Time.unscaledTime - startTime) < fadeTime)
{
elapsed = (Time.unscaledTime - startTime) / fadeTime;
oldSource.volume = Mathf.Lerp(orgVol, 0f, elapsed);
newSource.volume = Mathf.Lerp(0f, targetVolume, elapsed);
yield return null;
}
oldSource.Stop();
if (clips.Count > 0)
{
StartCoroutine(CrossFadeClips());
}
else
{
running = false;
}
yield return null;
}
}
}
|
366e21c73d7c54279abf9ade52f8a618e634dd0a
|
C#
|
nuvemtecnologia/fieldclimate-pessl
|
/src/Fieldclimate.Pessl.Domain/Services/ServiceBase.cs
| 2.65625
| 3
|
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Fieldclimate.Pessl.Domain.ExtensionsMethods;
using Fieldclimate.Pessl.Domain.Factories;
using Newtonsoft.Json;
namespace Fieldclimate.Pessl.Domain.Services
{
/// <summary>
///
/// </summary>
public abstract class ServiceBase
{
private readonly IPesslHttpClientFactory _pesslHttpClientFactory;
protected ServiceBase(IPesslHttpClientFactory pesslHttpClientFactory)
{
_pesslHttpClientFactory = pesslHttpClientFactory;
}
/// <summary>
///
/// </summary>
/// <param name="requestUri"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
protected async Task<T> GetAsync<T>(string requestUri)
{
var client = _pesslHttpClientFactory.Create();
var response = await client.GetAsync(requestUri);
return await response.DeserializeResponseContentString<T>();
}
/// <summary>
///
/// </summary>
/// <param name="requestUri"></param>
/// <param name="body"></param>
/// <typeparam name="TReturn"></typeparam>
/// <returns></returns>
protected async Task<TReturn> PostAsync<TReturn>(string requestUri, object body)
{
var jsonContent = JsonConvert.SerializeObject(body);
var contentString = new StringContent(jsonContent, Encoding.UTF8, "application/json");
var client = _pesslHttpClientFactory.Create();
var response = await client.PostAsync(requestUri, contentString);
return await response.DeserializeResponseContentString<TReturn>();
}
}
}
|
bec8deb157e89418633ed868cc75f8ebd2de0e7f
|
C#
|
johannroth/model-mapper-demo
|
/ModelMapperDemo/src/GraphQL/Types/EntityGraphQLType.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using GraphQL.Resolvers;
using GraphQL.Types;
using Humanizer;
using ModelMapperDemo.GraphQL.Mappers;
using ModelMapperDemo.Model.Framework;
using ModelMapperDemo.Utility;
namespace ModelMapperDemo.GraphQL.Types
{
/// <summary>
/// The GraphQL representation of an entity type.
/// </summary>
public class EntityGraphQLType : ObjectGraphType
{
private readonly IGraphQLMapper _mapper;
private readonly IEnumerable<IProperty> _properties;
public EntityGraphQLType(
IEntityDescriptor descriptor,
IGraphQLMapper mapper)
{
_mapper = mapper;
_properties = descriptor.Properties;
Name = descriptor.Name;
Description = XmlDoc.ReadSummary(descriptor.EntityType);
AddField(new FieldType
{
Name = "id",
Description = $"The ID of the {descriptor.Name.Humanize(LetterCasing.LowerCase)}.",
ResolvedType = new NonNullGraphType(new IdGraphType()),
Resolver = new FuncFieldResolver<IEntity, Guid>(resolveContext => resolveContext.Source.Id),
});
}
/// <summary>
/// Add the fields for the entity's properties to this GraphQL type.
/// </summary>
/// <notes>
/// This cannot be done in the constructor, because the GraphQL types may cyclically
/// depend on each other.
/// </notes>
public void AddAllPropertyFields()
{
foreach (var property in _properties)
{
var context = GraphQLMapperContext.FromProperty(property);
foreach (var field in _mapper.CreateFields(context))
{
AddField(new FieldType
{
Name = field.Name,
Description = field.Description,
ResolvedType = field.Type,
Resolver = new FuncFieldResolver<object>(field.Resolver),
});
}
}
}
}
}
|
7b3d6dd4f363644ee3261a11efb1bbc17c17de93
|
C#
|
colgreen/sharpneat
|
/src/SharpNeat/Neat/Genome/IO/NeatPopulationLoader.cs
| 2.78125
| 3
|
// This file is part of SharpNEAT; Copyright Colin D. Green.
// See LICENSE.txt for details.
using System.IO.Compression;
namespace SharpNeat.Neat.Genome.IO;
/// <summary>
/// For loading/deserializing a population of <see cref="NeatGenome{T}"/> instances from the local filesystem.
/// </summary>
/// <typeparam name="T">Connection weight data type.</typeparam>
public sealed class NeatPopulationLoader<T>
where T : struct
{
readonly MetaNeatGenome<T> _metaNeatGenome;
int _genomeId;
/// <summary>
/// Construct with the provided <see cref="MetaNeatGenome{T}"/>.
/// </summary>
/// <param name="metaNeatGenome">Neat genome metadata object.</param>
public NeatPopulationLoader(
MetaNeatGenome<T> metaNeatGenome)
{
_metaNeatGenome = metaNeatGenome ?? throw new ArgumentNullException(nameof(metaNeatGenome));
}
/// <summary>
/// Load a population from a folder containing one or more genome files (with a .net file extension).
/// </summary>
/// <param name="path">Path to the folder to load genomes from.</param>
/// <returns>A list of the loaded genomes.</returns>
public List<NeatGenome<T>> LoadFromFolder(string path)
{
if(!Directory.Exists(path))
throw new IOException($"Directory does not exist [{path}]");
// Determine the set of genome files to load.
DirectoryInfo dirInfo = new(path);
FileInfo[] fileInfoArr = dirInfo.GetFiles("*.net");
// Alloc genome list with an appropriate capacity.
List<NeatGenome<T>> genomeList = new(fileInfoArr.Length);
// Loop the genome files, loading each in turn.
foreach(FileInfo fileInfo in fileInfoArr)
{
NeatGenome<T> genome = NeatGenomeLoader.Load(
fileInfo.FullName, _metaNeatGenome, _genomeId++);
genomeList.Add(genome);
}
return genomeList;
}
/// <summary>
/// Load a population from a zip archive file containing one or more genome file entries (with a .net file extension).
/// </summary>
/// <param name="path">Path to the zip file to load.</param>
/// <returns>A list of the loaded genomes.</returns>
public List<NeatGenome<T>> LoadFromZipArchive(string path)
{
if(!File.Exists(path))
throw new IOException($"File does not exist [{path}]");
using ZipArchive zipArchive = ZipFile.OpenRead(path);
// Alloc genome list with an appropriate capacity.
List<NeatGenome<T>> genomeList = new(zipArchive.Entries.Count);
// Loop the genome file entries, loading each in turn.
foreach(ZipArchiveEntry zipEntry in zipArchive.Entries)
{
// Skip non-net files.
if(Path.GetExtension(zipEntry.Name) != ".net")
continue;
using(Stream zipEntryStream = zipEntry.Open())
{
NeatGenome<T> genome = NeatGenomeLoader.Load(
zipEntryStream, _metaNeatGenome, _genomeId++);
genomeList.Add(genome);
}
}
return genomeList;
}
}
|
e0166d4b9614f36602a9fc9be48323908b9bfb88
|
C#
|
alastairwyse/StandardAbstraction
|
/StandardAbstraction/NetworkStream.cs
| 2.640625
| 3
|
/*
* Copyright 2021 Alastair Wyse (https://github.com/alastairwyse/StandardAbstraction)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace StandardAbstraction
{
/// <summary>
/// Provides an abstraction of the System.Net.Sockets.NetworkStream class, to facilitate mocking and unit testing.
/// </summary>
/// <remarks>Although instances of this class compose a System.Net.Sockets.NetworkStream object which implements IDisposable, this class does not implement IDisposable due to the fact that its use-case is to return a mockable NetworkStream from a call to TcpClient.GetStream(). The underlying NetworkStream is created by the TcpClient class, and hence the TcpClient should also dispose/finalize it.</remarks>
public class NetworkStream : INetworkStream
{
private System.Net.Sockets.NetworkStream networkStream;
/// <summary>
/// Initialises a new instance of the StandardAbstraction.NetworkStream class.
/// </summary>
/// <param name="underlyingStream">The System.Net.Sockets.NetworkStream underlying the instance of the class.</param>
public NetworkStream(System.Net.Sockets.NetworkStream underlyingStream)
{
networkStream = underlyingStream;
}
/// <include file='InterfaceDocumentationComments.xml' path='doc/members/member[@name="P:StandardAbstraction.INetworkStream.CanRead"]/*'/>
public bool CanRead
{
get
{
return networkStream.CanRead;
}
}
/// <include file='InterfaceDocumentationComments.xml' path='doc/members/member[@name="M:StandardAbstraction.INetworkStream.Read(System.Byte[]@,System.Int32,System.Int32)"]/*'/>
public int Read(ref byte[] buffer, int offset, int size)
{
return networkStream.Read(buffer, offset, size);
}
/// <include file='InterfaceDocumentationComments.xml' path='doc/members/member[@name="M:StandardAbstraction.INetworkStream.ReadByte"]/*'/>
public int ReadByte()
{
return networkStream.ReadByte();
}
/// <include file='InterfaceDocumentationComments.xml' path='doc/members/member[@name="M:StandardAbstraction.INetworkStream.Write(System.Byte[],System.Int32,System.Int32)"]/*'/>
public void Write(byte[] buffer, int offset, int size)
{
networkStream.Write(buffer, offset, size);
}
/// <include file='InterfaceDocumentationComments.xml' path='doc/members/member[@name="M:StandardAbstraction.INetworkStream.WriteByte(System.Byte)"]/*'/>
public void WriteByte(byte value)
{
networkStream.WriteByte(value);
}
}
}
|
c6fe3dc8802396e4c5f78c7b3bbda261493b8abf
|
C#
|
Open-FL/PluginSystem
|
/src/PluginSystem/Events/Args/LogMessageEventArgs.cs
| 2.5625
| 3
|
namespace PluginSystem.Events.Args
{
public class LogMessageEventArgs
{
public LogMessageEventArgs(string message)
{
Message = message;
}
public string Message { get; }
public static implicit operator string(LogMessageEventArgs args)
{
return args.Message;
}
public static implicit operator LogMessageEventArgs(string message)
{
return new LogMessageEventArgs(message);
}
}
}
|
bd8d7f40d6f3df39689807baf189dea4e15ef4aa
|
C#
|
ppedvAG/dotnet_berlin_05112019
|
/Calc/Calc.Tests/CalcTests.cs
| 2.625
| 3
|
using System;
using FluentAssertions;
using Microsoft.QualityTools.Testing.Fakes;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Calc.Tests
{
[TestClass]
public class CalcTests
{
[TestMethod]
public void Calc_Sum_3_and_4_result_7()
{
var calc = new Calc();
var result = calc.Sum(3, 4);
Assert.AreEqual(7, result);
result.Should().Be(7);
result.Should().BeInRange(3, 4);
}
[TestMethod]
public void Calc_Sum_MAX_and_1_result____()
{
var calc = new Calc();
Assert.ThrowsException<OverflowException>(() => calc.Sum(Int32.MaxValue, 1));
}
[TestMethod]
public void Calc_IsWeekend()
{
var calc = new Calc();
using (ShimsContext.Create())
{
System.Fakes.ShimDateTime.NowGet = () => new DateTime(2019, 11, 5);
Assert.IsFalse(calc.IsWeekend());
//So
System.Fakes.ShimDateTime.NowGet = () => new DateTime(2019, 11, 10);
Assert.IsTrue(calc.IsWeekend());
}
}
}
}
|
d61d797562a47c15ee2b409b3abe0981235a5a0c
|
C#
|
kaloyanTry/ProgrammingFundamentals2020
|
/DataTypes/Concat2Names.cs
| 3.03125
| 3
|
using System;
namespace ConcatNames
{
class Concat2Names
{
static void Main(string[] args)
{
string nameFirst = Console.ReadLine();
string nameSecond = Console.ReadLine();
string nameDelimiter = Console.ReadLine();
Console.Write($"{nameFirst}{nameDelimiter}{nameSecond}");
}
}
}
|
c650f8513f9b7ae8c3012ebe8bdf2c0f754ce48b
|
C#
|
Abhash99/Prepackaging
|
/Abhash_SeniorProject/Source Files/Sport.cs
| 3.390625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrePackaging
{
/**/
/*
* CLASS DESCRIPTION:
* Represents a sport read from the sports information file.
* PURPOSE:
* Holds the sport (name) and the practice times as intervals.
*
* AUTHOR:
* Abhash Panta
*/
/**/
class Sport
{
// Member variables
// Represents the name of the sport (Ex. Men's Soccer)
private string m_name;
// Represents the list of practice times (as an interval object) for the sport
private List<Interval> m_intervals;
/**/
/*
* NAME: Sport()
*
* SYNOPSIS:
* Sport()
*
* DESCRIPTION:
* Default constructor of the sport class.
* Sets name to empty string and intervals to null.
*
* RETURNS:
* Nothing
*
* AUTHOR:
* Abhash Panta
*/
/**/
public Sport()
{
Name = "";
Intervals = null;
}
/**/
/*
* NAME: Sport()
*
* SYNOPSIS:
* Sport(string a_name, List<Interval> a_intervalList)
* a_name --> name of the sport
* a_intervalList --> list of intervals (each of which represent a practive time slot for the sport.
*
* DESCRIPTION:
* Parametrized constructor for Sport class. It obtains attribute values as parameters and sets each attribute
* respectively.
*
* RETURNS:
* Nothing
*
* AUTHOR:
* Abhash Panta
*/
/**/
public Sport(string a_name, List<Interval> a_intervalList)
{
Name = a_name;
Intervals = a_intervalList;
}
// Properties for member variables
public string Name { get => m_name; set => m_name = value; }
public List<Interval> Intervals { get => m_intervals; set => m_intervals = value; }
/**/
/*
* NAME: IsNull()
*
* SYNOPSIS:
* bool IsNull()
*
* DESCRIPTION:
* Determines if the Sport is a null sport (no value).
* If the name is empty string and intervals is null, it is a null sport.
*
* RETURNS:
* True, if the sport is null.
* False, otherwise.
*
* AUTHOR:
* Abhash Panta
*/
/**/
public bool IsNull()
{
if (Name == "" && Intervals == null)
{
return true;
}
return false;
}
}
}
|
d6edce801554785dc1558807188b8e521350a550
|
C#
|
iamprovidence/University_Apps
|
/Image_Processing/Task2/Task2/DomainModels/Filters/Abstract/OperatorFilterBase.cs
| 3.125
| 3
|
using System;
using System.Drawing;
using Task2.DomainModels.Interfaces;
namespace Task2.DomainModels.Filters.Abstract
{
abstract class OperatorFilterBase : IFilter
{
public abstract string Name { get; }
protected abstract int[,] GetHorizontalFilterMatrix();
protected abstract int[,] GetVerticalFilterMatrix();
public Bitmap Filter(Bitmap image)
{
Bitmap result = new Bitmap(image.Width, image.Height);
int[,] xFilterMatrix = GetHorizontalFilterMatrix();
int[,] yFiltermatrix = GetVerticalFilterMatrix();
int operatorMatrixSize = GetMatrixSize(xFilterMatrix, yFiltermatrix) - 1;
Color[,] pixels = GetCachedPixels(image);
for (int i = 1; i < image.Width - 1; ++i)
{
for (int j = 1; j < image.Height - 1; ++j)
{
int Rx = 0, Ry = 0;
int Gx = 0, Gy = 0;
int Bx = 0, By = 0;
for (int x = -1; x < operatorMatrixSize; ++x)
{
for (int y = -1; y < operatorMatrixSize; ++y)
{
Color pixel = pixels[i + y, j + x];
int xFilterValue = xFilterMatrix[x + 1, y + 1];
int yFilterValue = yFiltermatrix[x + 1, y + 1];
// accumulate
Rx += xFilterValue * pixel.R;
Ry += yFilterValue * pixel.R;
Gx += xFilterValue * pixel.G;
Gy += yFilterValue * pixel.G;
Bx += xFilterValue * pixel.B;
By += yFilterValue * pixel.B;
}
}
result.SetPixel(i, j, Color.FromArgb(ColorCast(Rx, Ry), ColorCast(Gx, Gy), ColorCast(Bx, By)));
}
}
return result;
}
private int GetMatrixSize(int[,] horizontal, int[,] vertical)
{
if (horizontal.GetLength(0) != horizontal.GetLength(1)) throw new ArgumentException("Horizontal matrix should be square");
if (vertical.GetLength(0) != vertical.GetLength(1)) throw new ArgumentException("Vertical matrix should be square");
if (horizontal.GetLength(0) != vertical.GetLength(0)) throw new ArgumentException("Matrices should have same sizes");
return horizontal.GetLength(0);
}
private Color[,] GetCachedPixels(Bitmap image)
{
Color[,] pixels = new Color[image.Width, image.Height];
for (int i = 0; i < image.Width; ++i)
{
for (int j = 0; j < image.Height; ++j)
{
pixels[i, j] = image.GetPixel(i, j);
}
}
return pixels;
}
protected virtual int ColorCast(double cx, double cy)
{
double number = Math.Sqrt(cx * cx + cy * cy);
return (int)Math.Min(number, 255);
}
}
}
|
f72bbdf0c19507122fedc7985320afb34074ae3d
|
C#
|
SerheyDemchuk/TestProject
|
/TestProject/Program.cs
| 3.203125
| 3
|
using System;
using System.IO;
using System.IO.Compression;
namespace TestProject
{
public static class ZipArchiveExtensionMethods
{
public static void B(this ZipArchiveEntry zipArchiveEntry)
{
//Some code here
}
}
class Program
{
void A()
{
//Path to zip
string zipPath = @"..\..\testZip.zip";
//Path to temporary folder
string folderPath = @"..\..\temporary";
//Create test zip archive
ZipFile.CreateFromDirectory(@"..\..\zip", zipPath);
//Create temporary folder
System.IO.Directory.CreateDirectory(folderPath);
//using code block for ensuring disposing of opened streams
using (ZipArchive archive = ZipFile.OpenRead(zipPath))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
if (entry.FullName.EndsWith(".csv", StringComparison.OrdinalIgnoreCase))
{
//Get destination path
string destinationPath = Path.GetFullPath(Path.Combine(folderPath, entry.FullName));
//Extract csv files to destination path
entry.ExtractToFile(destinationPath);
//Calling method B for every csv file in zip
entry.B();
}
}
}
//Delete temporary folder and all files inside it
System.IO.Directory.Delete(folderPath, true);
}
static void Main(string[] args)
{
Program test = new Program();
test.A();
}
}
}
|
4ac3e129d8fab7d6eae233087b72af0689a9b18a
|
C#
|
ralmeida1070793/cocus_flights_manager
|
/CocusFlightAPI/Business/Services/AeroplaneService.cs
| 2.609375
| 3
|
using Entities;
using Entities.Models;
using Business.Mappings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using Microsoft.Extensions.DependencyInjection;
namespace Business.Services
{
public class AeroplaneService : AbstractService, IBusinessServices<Aeroplane>
{
public AeroplaneService(
IServiceScopeFactory scopeFactory
) : base(scopeFactory)
{ }
public async Task<Aeroplane> CreateAsync(Aeroplane entity, CancellationToken ct)
{
var aeroplane = await this._databaseContext.Aeroplanes.AddAsync(entity.ToDatabase(), ct);
this._databaseContext.SaveChanges();
return aeroplane.Entity.ToModel();
}
public async Task<Dictionary<MessageType, string>> DeleteAsync(Aeroplane entity, CancellationToken ct)
{
return await Task.Run(() =>
{
Dictionary<MessageType, string> result = new Dictionary<MessageType, string>();
try
{
var aeroplane = this._databaseContext.Aeroplanes.Find(entity.Id);
this._databaseContext.Aeroplanes.Remove(aeroplane);
this._databaseContext.SaveChanges();
}
catch (Exception e)
{
result.Add(MessageType.ERROR, "An error occured while trying to delete the aeroplane. Exception: " + e.Message);
}
finally
{
result.Add(MessageType.SUCCESS, "The aeroplane was successfully deleted.");
}
return result;
}, ct);
}
public async Task<EntityCollection<Aeroplane>> GetResourceAsync(CancellationToken ct)
{
return await Task.Run(() =>
{
return new EntityCollection<Aeroplane>()
{
Total = this._databaseContext.Aeroplanes.Count(),
Entities = this._databaseContext.Aeroplanes.Select(e => e.ToModel()).ToList()
};
}, ct);
}
public async Task<EntityCollection<Aeroplane>> GetResourceAsync(int itemsPerPage, int page, CancellationToken ct)
{
return await Task.Run(() =>
{
return new EntityCollection<Aeroplane>()
{
Total = this._databaseContext.Aeroplanes.Count(),
Entities = this._databaseContext.Aeroplanes.Skip(page * itemsPerPage).Take(itemsPerPage).Select(e => e.ToModel()).ToList()
};
}, ct);
}
public async Task<Aeroplane> UpdateAsync(Aeroplane entity, CancellationToken ct)
{
return await Task.Run(() =>
{
var aeroplane = this._databaseContext.Aeroplanes.Find(entity.Id);
aeroplane.Capacity = entity.Capacity;
aeroplane.FuelConsumptionPerSeat = entity.FuelConsumptionPerSeat;
aeroplane.MilesToCruisingAltitude = entity.MilesToCruisingAltitude;
aeroplane.Name = entity.Name;
aeroplane.TakeoffEffortPerOccupiedSeat = entity.TakeoffEffortPerOccupiedSeat;
this._databaseContext.Update(aeroplane);
this._databaseContext.SaveChanges();
return aeroplane.ToModel();
}, ct);
}
public async Task<Aeroplane> GetById(long id, CancellationToken ct)
{
var result = await this._databaseContext.Aeroplanes.FindAsync(new object[] { id }, ct);
return result.ToModel();
}
}
}
|
e653e621676ff595af1b7969937d45311f43a6a5
|
C#
|
AvOehsen/Investigator-Academy
|
/Rules/Actions/IRuleAction.cs
| 2.8125
| 3
|
using Rules.Actionsets;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Rules.Actions
{
public interface IRuleAction
{
bool IsDone { get; set; }
IEnumerable<IOption> Options { get; }
string Name { get; }
}
public abstract class AbstractRuleAction : IRuleAction
{
abstract public string Name { get; }
protected AbstractActionset Actionset { get; private set; }
private bool _isDone;
public bool IsDone
{
get { return _isDone; }
set
{
_isDone = value;
if (_isDone)
Actionset.SetDone(this);
}
}
private List<IOption> _options = new List<IOption>();
public IEnumerable<IOption> Options
{
get { return _options; }
}
public AbstractRuleAction(AbstractActionset actionset)
{
Actionset = actionset;
}
protected void AddOption(IOption option)
{
_options.Add(option);
}
}
}
|
4d560b20ebdca7851b6748fc173cf9e7747347fd
|
C#
|
jiajionline/LeetcodeSolutionWithMultipleLanguages
|
/0002_Add Two Numbers/AddTwoNumbers.cs
| 3.484375
| 3
|
namespace LeetcodePracticeCsharpVersion
{
public class AddTwoNumbersQuestion
{
public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
{
if (l1 == null && l2 == null) return null;
ListNode preHead = new ListNode(-1);
ListNode current = preHead;
ListNode p1 = l1;
ListNode p2 = l2;
int carry = 0;
while(p1 != null || p2 != null || carry > 0)
{
int value = 0;
if (p1 != null)
{
value += p1.val;
p1 = p1.next;
}
if(p2 != null){
value += p2.val;
p2 = p2.next;
}
value += carry;
carry = value / 10;
value = value % 10;
ListNode temp = new ListNode(value);
current.next = temp;
current = temp;
}
return preHead.next;
}
}
}
|
cc8fb10d906cc831378516b622a4495bd0784775
|
C#
|
santiaago/pattern-lib
|
/cs/Composite/Composite.Pattern/Tree.cs
| 3.078125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Composite.Pattern
{
public class Tree : Forest
{
public string Name { get; set; }
public int Leafs { get; set; }
public void Stats() {
Console.WriteLine("{0} has {1} leafs.", Name, Leafs);
}
}
}
|
22e089f684281696653ec5db4cb1384b10d07949
|
C#
|
marcelomesmo/Caieta
|
/Caieta/Caieta/Entities/Sprites/TextBox.cs
| 2.71875
| 3
|
using System;
using Caieta.Components.Renderables.Text;
using Caieta.Entities;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Caieta.Entities.Sprites
{
public class TextBox : Entity
{
public Text Text;
public BoxCollider Collider;
public bool FitToBox;
public TextBox(string entityname, string content, SpriteFont font, bool initial_visibility = true) : base(entityname, initial_visibility)
{
Text = new Text(content, font);
Vector2 _textSize = Text.Font.MeasureString(Text.Content);
Collider = new BoxCollider(_textSize.X, _textSize.Y);
}
public override void Create()
{
base.Create();
Add(Text);
Add(Collider);
Get<Text>().Align(Collider);
//Get<Text>().FitText(Collider);
if (FitToBox)
Text.Content = Text.FitText(Collider);
}
public override void Update()
{
base.Update();
}
}
}
|
fc33a388a4644e0fd2ec57b29f98c26e578e05e9
|
C#
|
etijera/RecordRatings
|
/RecordRating 1.0/Fuentes/Escritorio/RecordRatings/GLUserControls/BasicForm.cs
| 2.578125
| 3
|
/***
* Formulario : BasicForm
* Proposito : Es la clase base a partir de la cual se hereda para crear los nuevos
* formularios, de tal manera que se especifica el Icono de la ventana y demas
* Características básicas
*
* Fecha : Febrero, 2012
* Fecha Act. :
* Autor :
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
namespace GLUserControls
{
public partial class BasicForm : DevExpress.XtraEditors.XtraForm
{
#region Propiedades
#endregion
#region Variables
Point formPosition;
Boolean mouseAction;
#endregion
#region Metodos
/// <summary>
/// Constructor de la clase BasicForm
/// </summary>
public BasicForm()
{
InitializeComponent();
}
#endregion
#region Eventos
private void BasicForm_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (Char)Keys.Escape)
{
Close();
}
}
private void BasicForm_MouseDown(object sender, MouseEventArgs e)
{
formPosition = new Point(Cursor.Position.X - Location.X, Cursor.Position.Y - Location.Y);
mouseAction = true;
}
private void BasicForm_MouseMove(object sender, MouseEventArgs e)
{
if (mouseAction == true)
{
Location = new Point(Cursor.Position.X - formPosition.X, Cursor.Position.Y - formPosition.Y);
}
}
private void BasicForm_MouseUp(object sender, MouseEventArgs e)
{
mouseAction = false;
}
#endregion
}
}
|
c5e2791078b8976348f7d4f96c5cf287c5dfd7c2
|
C#
|
Garderoben/MudBlazor
|
/src/MudBlazor/Components/DatePicker/MudDatePicker.cs
| 2.59375
| 3
|
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using MudBlazor.Extensions;
using MudBlazor.Utilities;
namespace MudBlazor
{
public class MudDatePicker : MudBaseDatePicker
{
private DateTime? _selectedDate;
/// <summary>
/// Fired when the DateFormat changes.
/// </summary>
[Parameter] public EventCallback<DateTime?> DateChanged { get; set; }
/// <summary>
/// The currently selected date (two-way bindable). If null, then nothing was selected.
/// </summary>
[Parameter]
[Category(CategoryTypes.FormComponent.Data)]
public DateTime? Date
{
get => _value;
set => SetDateAsync(value, true).AndForget();
}
protected async Task SetDateAsync(DateTime? date, bool updateValue)
{
if (_value != date)
{
Touched = true;
if (date is not null && IsDateDisabledFunc(date.Value.Date))
{
await SetTextAsync(null, false);
return;
}
_value = date;
if (updateValue)
{
Converter.GetError = false;
await SetTextAsync(Converter.Set(_value), false);
}
await DateChanged.InvokeAsync(_value);
await BeginValidateAsync();
FieldChanged(_value);
}
}
protected override Task DateFormatChanged(string newFormat)
{
Touched = true;
return SetTextAsync(Converter.Set(_value), false);
}
protected override Task StringValueChanged(string value)
{
Touched = true;
// Update the date property (without updating back the Value property)
return SetDateAsync(Converter.Get(value), false);
}
protected override string GetDayClasses(int month, DateTime day)
{
var b = new CssBuilder("mud-day");
b.AddClass(AdditionalDateClassesFunc?.Invoke(day) ?? string.Empty);
if (day < GetMonthStart(month) || day > GetMonthEnd(month))
return b.AddClass("mud-hidden").Build();
if ((Date?.Date == day && _selectedDate == null) || _selectedDate?.Date == day)
return b.AddClass("mud-selected").AddClass($"mud-theme-{Color.ToDescriptionString()}").Build();
if (day == DateTime.Today)
return b.AddClass("mud-current mud-button-outlined").AddClass($"mud-button-outlined-{Color.ToDescriptionString()} mud-{Color.ToDescriptionString()}-text").Build();
return b.Build();
}
protected override async void OnDayClicked(DateTime dateTime)
{
_selectedDate = dateTime;
if (PickerActions == null || AutoClose || PickerVariant == PickerVariant.Static)
{
Submit();
if (PickerVariant != PickerVariant.Static)
{
await Task.Delay(ClosingDelay);
Close(false);
}
}
}
/// <summary>
/// user clicked on a month
/// </summary>
/// <param name="month"></param>
protected override void OnMonthSelected(DateTime month)
{
PickerMonth = month;
var nextView = GetNextView();
if (nextView == null)
{
_selectedDate = _selectedDate.HasValue ?
//everything has to be set because a value could already defined -> fix values can be ignored as they are set in submit anyway
new DateTime(month.Year, month.Month, _selectedDate.Value.Day, _selectedDate.Value.Hour, _selectedDate.Value.Minute, _selectedDate.Value.Second, _selectedDate.Value.Millisecond, _selectedDate.Value.Kind)
//We can assume day here, as it was not set yet. If a fix value is set, it will be overriden in Submit
: new DateTime(month.Year, month.Month, 1);
SubmitAndClose();
}
else
{
CurrentView = (OpenTo)nextView;
}
}
/// <summary>
/// user clicked on a year
/// </summary>
/// <param name="year"></param>
protected override void OnYearClicked(int year)
{
var current = GetMonthStart(0);
PickerMonth = new DateTime(year, current.Month, 1);
var nextView = GetNextView();
if (nextView == null)
{
_selectedDate = _selectedDate.HasValue ?
//everything has to be set because a value could already defined -> fix values can be ignored as they are set in submit anyway
new DateTime(_selectedDate.Value.Year, _selectedDate.Value.Month, _selectedDate.Value.Day, _selectedDate.Value.Hour, _selectedDate.Value.Minute, _selectedDate.Value.Second, _selectedDate.Value.Millisecond, _selectedDate.Value.Kind)
//We can assume month and day here, as they were not set yet
: new DateTime(year, 1, 1);
SubmitAndClose();
}
else
{
CurrentView = (OpenTo)nextView;
}
}
protected override void OnOpened()
{
_selectedDate = null;
base.OnOpened();
}
protected internal override async void Submit()
{
if (GetReadOnlyState())
return;
if (_selectedDate == null)
return;
if (FixYear.HasValue || FixMonth.HasValue || FixDay.HasValue)
_selectedDate = new DateTime(FixYear ?? _selectedDate.Value.Year,
FixMonth ?? _selectedDate.Value.Month,
FixDay ?? _selectedDate.Value.Day,
_selectedDate.Value.Hour,
_selectedDate.Value.Minute,
_selectedDate.Value.Second,
_selectedDate.Value.Millisecond);
await SetDateAsync(_selectedDate, true);
_selectedDate = null;
}
public override async void Clear(bool close = true)
{
_selectedDate = null;
await SetDateAsync(null, true);
if (AutoClose == true)
{
Close(false);
}
}
protected override string GetTitleDateString()
{
return FormatTitleDate(_selectedDate ?? Date);
}
protected override DateTime GetCalendarStartOfMonth()
{
var date = StartMonth ?? Date ?? DateTime.Today;
return date.StartOfMonth(Culture);
}
protected override int GetCalendarYear(int year)
{
var date = Date ?? DateTime.Today;
var diff = date.Year - year;
var calenderYear = Culture.Calendar.GetYear(date);
return calenderYear - diff;
}
//To be completed on next PR
protected internal override void HandleKeyDown(KeyboardEventArgs obj)
{
if (GetDisabledState() || GetReadOnlyState())
return;
base.HandleKeyDown(obj);
switch (obj.Key)
{
case "ArrowRight":
if (IsOpen)
{
}
break;
case "ArrowLeft":
if (IsOpen)
{
}
break;
case "ArrowUp":
if (IsOpen == false && Editable == false)
{
IsOpen = true;
}
else if (obj.AltKey == true)
{
IsOpen = false;
}
else if (obj.ShiftKey == true)
{
}
else
{
}
break;
case "ArrowDown":
if (IsOpen == false && Editable == false)
{
IsOpen = true;
}
else if (obj.ShiftKey == true)
{
}
else
{
}
break;
case "Escape":
ReturnDateBackUp();
break;
case "Enter":
case "NumpadEnter":
if (!IsOpen)
{
Open();
}
else
{
Submit();
Close();
_inputReference?.SetText(Text);
}
break;
case " ":
if (!Editable)
{
if (!IsOpen)
{
Open();
}
else
{
Submit();
Close();
_inputReference?.SetText(Text);
}
}
break;
}
StateHasChanged();
}
private void ReturnDateBackUp()
{
Close();
}
/// <summary>
/// Scrolls to the date.
/// </summary>
public void GoToDate()
{
if (Date.HasValue)
{
PickerMonth = new DateTime(Date.Value.Year, Date.Value.Month, 1);
ScrollToYear();
}
}
/// <summary>
/// Scrolls to the defined date.
/// </summary>
public async Task GoToDate(DateTime date, bool submitDate = true)
{
PickerMonth = new DateTime(date.Year, date.Month, 1);
if (submitDate)
{
await SetDateAsync(date, true);
ScrollToYear();
}
}
}
}
|
46862c1b09ca920e10fa136ba880031fcf921a6b
|
C#
|
marcelooliveira/marcelo-refactorings
|
/Refactorings/ComposingMethods/SplitTemporaryVariable/Solution.cs
| 3.53125
| 4
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Refactorings.SplitTemporaryVariable
{
//Use different variables for different values. Each variable should be responsible for only one particular thing
class Solution
{
private int height;
private int width;
public Solution()
{
double perimeter = 2 * (height + width);
Console.WriteLine(perimeter);
double area = height * width;
Console.WriteLine(area);
}
}
}
|
653828d7cf83dbf613f931b0da03b24280c4bfd2
|
C#
|
dorenz-svg/-s-grammar
|
/Service/Infrastructure.cs
| 3.296875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Service
{
public class Infrastructure
{
public static List<Rule> FillList(string[] arr)
{
List<Rule> res = new List<Rule>();
for (int i = 0; i < arr.Length; i++)
{
res.Add(new Rule { Name = arr[i].Split(' ').First(), Rules = AddRules(arr[i].Split(' ')) });
}
return res;
}
private static List<string> AddRules(string[] str)
{
List<string> res = new List<string>();
for (int i = 1; i < str.Length; i++)
{
res.Add(str[i]);
}
return res;
}
public static List<string> Search(List<Rule> rules, in int N)
{
List<string> result = new List<string>() { rules[0].Name };
List<string> words = new List<string>();
for (int i = 0; i < N; i++)
{
List<string> temp = new List<string>();
for (int j = 0; j < result.Count; j++)
{
for (int k = 0; k < result[j].Length; k++)
{
if (Char.IsUpper(result[j][k]))
AddChilder(rules, result[j],k,temp);
}
}
result = temp;
foreach (var item in result)
{
if (item.IsLower())
words.Add(item);
}
}
var temp1 = words.Distinct().Where(x => x.IsNotEpsilon()).Select(x => x= "ε").ToList();
var temp2 = words.Distinct().Select(x => x.Replace("ε", "")).ToList();
return temp1.Union(temp2).ToList();
}
private static void AddChilder(List<Rule> rules, string word,int index,List<string> res)
{
char letter = word[index];
word = word.Remove(index, 1);
var temp = rules.First(x => x.Name == letter.ToString());
for (int i = 0; i < temp.Rules.Count; i++)
{
res.Add(word.Insert(index, temp.Rules[i]));
}
}
}
}
|
b6c545d64debec726caadf5cb512b9a994450a10
|
C#
|
unclefil/Common
|
/CoreTechs.Common.Std.Tests/DelegateEqualityComparerTests.cs
| 3.109375
| 3
|
using NUnit.Framework;
namespace CoreTechs.Common.Std.Tests
{
public class DelegateEqualityComparerTests
{
[Test]
public void CanMakeEqualityTest()
{
var first = new ExampleClass {Number = 1, Word = "Hat"};
var second = new ExampleClass {Number = 1, Word = "Sock"};
var comparer = new DelegateEqualityComparer<ExampleClass>((c1, c2) => c1.Number == c2.Number);
var defaultEquals = first == second;
var result = comparer.Equals(first, second);
Assume.That(defaultEquals, Is.False);
Assert.That(result, Is.True);
}
[Test]
public void CanAlsoRecognizeInequality()
{
var first = new ExampleClass { Number = 1, Word = "Hat" };
var second = new ExampleClass { Number = 2, Word = "Hat" };
var comparer = new DelegateEqualityComparer<ExampleClass>((c1, c2) => c1.Number == c2.Number);
var defaultEquals = first == second;
var result = comparer.Equals(first, second);
Assume.That(defaultEquals, Is.False);
Assert.That(result, Is.False);
}
[Test]
public void CanComputeHashOfClass()
{
var first = new ExampleClass();
var comparer = new DelegateEqualityComparer<ExampleClass>((c1, c2) => false, c => 1);
var result = comparer.GetHashCode(first);
Assert.That(result, Is.EqualTo(1));
}
[Test]
public void NullWithNonNullIsAlwaysUnequal()
{
var otherClass = new ExampleClass();
var trueComparer = new DelegateEqualityComparer<ExampleClass>((c1, c2) => true);
var result = trueComparer.Equals(null, otherClass);
Assert.That(result, Is.False);
}
[Test]
public void NullsAreEqual()
{
var falseComparer = new DelegateEqualityComparer<ExampleClass>((c1, c2) => false);
var result = falseComparer.Equals(null, null);
Assert.That(result, Is.True);
}
[Test]
public void SelfIsAlwaysEqualWithSelf()
{
var self = new ExampleClass();
var falseComparer = new DelegateEqualityComparer<ExampleClass>((c1, c2) => false);
var result = falseComparer.Equals(self, self);
Assert.That(result, Is.True);
}
[Test]
public void NullsHaveHashOfZero()
{
var comparer = new DelegateEqualityComparer<ExampleClass>((c1, c2) => false, c => 1);
var result = comparer.GetHashCode(null);
Assert.That(result, Is.EqualTo(0));
}
private class ExampleClass
{
public int Number { get; set; }
public string Word { get; set; }
}
}
}
|
0ee4800c227f1c4780fcf7faf004329ab5e99f0b
|
C#
|
alandrieu/CSHARP_ISITECH
|
/Projects/CaveProject/CaveLib/Controller/MainController.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// Hibernate Lib
using NHibernate.Collection;
using NHibernate.Cfg;
//
using CaveLib.Utils;
namespace CaveLib.Controller
{
/// <summary>
/// Le MainController créer toutes les connexions avec la Base de données et initialise Hibernate.
/// Il peuple aussi la BDD en Vendeur, Commande, Bouteille, Client.
/// </summary>
public class MainController
{
public NHibernate.ISessionFactory sessionsController;
public NHibernate.ISession session;
public static MainController CurrentDao{get; set;}
Configuration cfg;
public MainController()
{
// Init Cave
// Initialize NHibernate
cfg = new Configuration();
cfg.Configure();
cfg.AddAssembly(typeof(Bean.Product).Assembly);
//new SchemaExport(cfg).Execute(true, true, false);
// Get ourselves an NHibernate Session
//var sessions = cfg.BuildSessionFactory();
sessionsController = cfg.BuildSessionFactory();
session = sessionsController.OpenSession();
for (int i = 0; i < 10; i++)
createVendeurs(i);
for (int i = 0; i < 10; i++)
createBouteilles(i);
for (int i = 0; i < 10; i++)
createCustomers(i);
CurrentDao = this;
// Créer un utilisateur par défaut
createADefaultVendeur();
}
/// <summary>
/// Méthode qui créer un utilisateur par défaut pour la démonstration
/// </summary>
private void createADefaultVendeur()
{
Random rand = new Random();
// Créer un Vendeur
var vendeur = new Bean.Vendeur
{
Name = "Isitech Account",
Login = "ISITECH",
Password = Hashing.SHA512("ISITECH")
};
// And save it to the database
session.Save(vendeur);
session.Flush();
}
private void createVendeurs(int cpt)
{
Random rand = new Random();
// Créer un Vendeur
var vendeur = new Bean.Vendeur
{
Name = "Alandrieu",
Login = "USER#" + cpt.ToString(),
Password = Hashing.SHA512(rand.Next().ToString())
};
// And save it to the database
session.Save(vendeur);
session.Flush();
}
private void createBouteilles(int cpt)
{
// Créer une Bouteille
var bouteille = new Bean.Bouteille
{
Name = "Château Haut Vigneau Pessac-Léognan#" + cpt.ToString(),
PrixU = 56,
Category = "Vin Rouge"
};
// And save it to the database
session.Save(bouteille);
session.Flush();
}
private void createCustomers(int cpt)
{
// Créer une Client
var client = new Bean.Client
{
FirstName = "Jean#" + cpt.ToString(),
LastName = "Du Lac"
};
// And save it to the database
session.Save(client);
session.Flush();
}
}
}
|
70a9d9b9be6884549b052601c1f4ee17b0a2e47d
|
C#
|
brSaif/PFE2019
|
/Code Source/vegaplatform/VEGAACABLE/DAL/Repositories/UserRepository.cs
| 2.578125
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VEGAACABLE.BL.Domain;
using VEGAACABLE.BL.Repositories;
namespace VEGAACABLE.DAL.Repositories
{
public class UserRepository : Repository<User>, IUserRepository
{
public UserRepository(VegaContext context) : base(context)
{
}
public IEnumerable<User> AllUsers()
{
var s = VegaContext.Users
.OrderBy(c => c.Id)
.ThenBy(c => c.FullName)
.ToList();
return s;
}
public User Find(int id)
{
return VegaContext.Users.Find(id);
}
public void InsertOrUpdate(User user)
{
if (user.Id == default(int))
{
VegaContext.Users.Add(user);
}
else
{
VegaContext.Entry(user).State = EntityState.Modified;
}
}
public void Delete(int id)
{
var user = VegaContext.Users.Find(id);
VegaContext.Users.Remove(user);
}
public VegaContext VegaContext
{
get { return Context as VegaContext; }
}
}
}
|
8b8063cdd5df83bec90e3d34b182b7a61a449f65
|
C#
|
sunpander/VSDT
|
/source/Core/Common/Utility/UtilityFile.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Data;
namespace VSDT.Common.Utility
{
public static class UtilityFile
{
public static string ChooseOneDirectory()
{
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
folderDialog.ShowDialog();
return folderDialog.SelectedPath;
}
public static string ChooseOneFile()
{
OpenFileDialog openfile = new OpenFileDialog();
openfile.ShowDialog();
return openfile.FileName;
}
public static string ChooseOneFile(string filter)
{
OpenFileDialog openfile = new OpenFileDialog();
openfile.Filter = filter;
openfile.ShowDialog();
return openfile.FileName;
}
public static string[] ChooseMultiFiles(string filter,bool multiSel)
{
OpenFileDialog openfile = new OpenFileDialog();
openfile.Filter = filter;
openfile.Multiselect = multiSel;
openfile.ShowDialog();
return openfile.FileNames;
}
public static string ChooseOneFileToSave()
{
SaveFileDialog saveFile = new SaveFileDialog();
saveFile.ShowDialog();
return saveFile.FileName;
}
public static bool SaveOneFile(string fileContent)
{
try
{
string strFileName = ChooseOneFileToSave();
System.IO.StreamWriter sw = new System.IO.StreamWriter(strFileName, false, System.Text.Encoding.Default);
sw.WriteLine(fileContent);
sw.Close();
return true;
}
catch (Exception ex)
{
Log.ShowErrorBox(ex);
return false;
}
}
/***************
#region 创建文件
/// <summary>
/// 创建文件
/// </summary>
/// <param name="savePath"></param>
/// <param name="fileName"></param>
/// <param name="GetHoleCode"></param>
/// <returns></returns>
public string CreateFile(string savePath, string fileName, string GetHoleCode)
{
string filePathName;
filePathName = savePath + fileName;
FileStream newCodeFS = File.Create(filePathName);
StreamWriter newCodeSW = new StreamWriter(newCodeFS, Encoding.Default);
newCodeSW.Write(GetHoleCode);
newCodeSW.Close();
return filePathName;
}
#endregion
#region 保存文件(重载)
/// <summary>
/// 保存文件(重载)
/// </summary>
/// <param name="saveFileName"></param>
/// <param name="GetHoleCode"></param>
public void CreateFile(string saveFileName, string GetHoleCode)
{
FileStream newCodeFS = File.Create(saveFileName);
StreamWriter newCodeSW = new StreamWriter(newCodeFS, Encoding.Default);
newCodeSW.Write(GetHoleCode);
newCodeSW.Close();
}
#endregion
#region 获取文件内容
/// <summary>
/// 获取文件内容
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public string GetAllFileContent(string filePath)
{
string oldCodeText = "";
StreamReader CodeReader = new StreamReader(filePath, Encoding.Default);
oldCodeText = CodeReader.ReadToEnd();
CodeReader.Close();
return oldCodeText;
}
#endregion
#region 取得路径下所有文件
private ArrayList AllDirFilePath = new ArrayList();
/// <summary>
/// 取得路径下所有文件
/// </summary>
/// <param name="directory">目录</param>
/// <param name="fileModel">类似*.txt</param>
/// <returns></returns>
public ArrayList GetAllDirFileList(DirectoryInfo directory, string fileModel)
{
System.IO.FileInfo[] fileInfos = fileModel.Equals("") ? directory.GetFiles() : directory.GetFiles(fileModel);
foreach (System.IO.FileInfo file in fileInfos)
{
AllDirFilePath.Add(file.FullName);
}
DirectoryInfo[] SUBDirectories = directory.GetDirectories();
foreach (DirectoryInfo subdirectory in SUBDirectories)
{
GetAllDirFileList(subdirectory, fileModel);
}
return AllDirFilePath;
}
/// <summary>
/// 取得路径下所有文件
/// </summary>
/// <param name="directory">目录</param>
/// <param name="fileModel">类似*.txt</param>
/// <returns></returns>
public ArrayList GetFileList(DirectoryInfo directory, string fileModel)
{
ArrayList AllFilePath = new ArrayList();
System.IO.FileInfo[] fileInfos = fileModel.Equals("") ? directory.GetFiles() : directory.GetFiles(fileModel);
foreach (System.IO.FileInfo file in fileInfos)
{
AllFilePath.Add(file.FullName);
}
return AllFilePath;
}
#endregion
#region 获取子目录
/// <summary>
/// 获取子目录
/// </summary>
/// <param name="directory"></param>
/// <returns></returns>
public ArrayList GetChildPath(DirectoryInfo directory)
{
ArrayList DIRPath = new ArrayList();
DirectoryInfo[] files = directory.GetDirectories();
foreach (DirectoryInfo file in files)
{
DIRPath.Add(file.FullName);
}
return DIRPath;
}
#endregion
#region 获取所有子目录
/// <summary>
/// 获取所有子目录
/// </summary>
private ArrayList AllDIRPath = new ArrayList();
public ArrayList GetAllChildPath(DirectoryInfo directory)
{
AllDIRPath.Clear();
DirectoryInfo[] files = directory.GetDirectories();
foreach (DirectoryInfo file in files)
{
AllDIRPath.Add(file.FullName);
}
DirectoryInfo[] directoies = directory.GetDirectories();
foreach (DirectoryInfo subDirectory in directoies)
{
GetAllChildPath(subDirectory);
}
return AllDIRPath;
}
#endregion
#region 选择保存文件
/// <summary>
/// 选择保存文件
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public string SaveXmlFile(string model)
{
string resultfile = "";
try
{
SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = "..\\DIXml";
save.Filter = model;
save.FilterIndex = 2;
save.RestoreDirectory = true;
if (save.ShowDialog() == DialogResult.OK)
resultfile = save.FileName;
}
catch
{ }
return resultfile;
}
#endregion
#region 选择打开文件
/// <summary>
/// 选择打开文件
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public string OpenXmlFile(string model)
{
string resultfile = "";
try
{
OpenFileDialog open = new OpenFileDialog();
open.InitialDirectory = "..\\DIXml";
open.Filter = model;
open.FilterIndex = 2;
open.RestoreDirectory = true;
if (open.ShowDialog() == DialogResult.OK)
resultfile = open.FileName;
}
catch
{ }
return resultfile;
}
#endregion
#region 创建文件夹
/// <summary>
/// 创建文件夹
/// </summary>
/// <param name="path">创建目录</param>
public void CreateDirectory(string path)
{
Directory.CreateDirectory(path);
}
#endregion
#region 复制现有文件静态方法可以覆盖同名文件
/// <summary>
/// 复制现有文件静态方法可以覆盖同名文件
/// </summary>
/// <param name="sourceFilePath">源路径</param>
/// <param name="aimFilePath">目标路径</param>
/// <param name="isOver">是否覆盖</param>
public void CopyFile(string sourceFilePath, string aimFilePath, bool isOver)
{
File.Copy(sourceFilePath, aimFilePath, isOver);
}
#endregion
#region 判断文件夹是否存在
/// <summary>
/// 判断文件夹是否存在
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public bool isDirectoryExist(string path)
{
bool isExist = false;
isExist = Directory.Exists(path);
return isExist;
}
#endregion
#region 取得当前工作目录
/// <summary>
/// 取得当前工作目录
/// </summary>
/// <returns></returns>
public string GetCurrentDirectory()
{
string currentDirectory = "";
currentDirectory = Directory.GetCurrentDirectory();
return currentDirectory;
}
#endregion
public void MoveToDirectory(string oldDirectory, string newDirectory)
{
DirectoryInfo myInfo = new DirectoryInfo(oldDirectory);
myInfo.MoveTo(newDirectory);
}
* ***/
#region
////导出Excel的方法
//private static void ExportExcel()
//{
// DataSet ds = new DataSet();
// System.Data.DataTable dt = new System.Data.DataTable();
// dt.Columns.Add("NAME");
// dt.Columns.Add("Version");
// dt.Columns.Add("SymbolicName");
// dt.Columns.Add("State");
// dt.Columns.Add("Operate");
// for (int i = 0; i < 10; i++)
// {
// dt.Rows.Add("NAME:" + i, "Version" + i, "sName" + i, i);
// }
// ds.Tables.Add(dt);
// DataTable dt2 = dt.Copy();
// dt2.TableName = "ddf";
// ds.Tables.Add( dt2 );
// bool fileSaved = false;
// //获取路径
// string saveFileName = "";
// SaveFileDialog saveDialog = new SaveFileDialog();
// saveDialog.DefaultExt = "xls";
// saveDialog.Filter = "Excel文件|*.xlsx|Excel文件|*.xls";
// saveDialog.FileName = "Sheet1";
// saveDialog.ShowDialog();
// saveFileName = saveDialog.FileName;
// if (saveFileName.IndexOf(":") < 0) return; //被点了取消
// //声明一Excel Application 对象
// Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
// if (xlApp == null)
// {
// MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
// return;
// }
// //声明一Excel Workbook 对象
// Microsoft.Office.Interop.Excel.Workbooks workBooks = xlApp.Workbooks;
// //增加一工作薄 Workbook
// Microsoft.Office.Interop.Excel.Workbook workBook = workBooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
// //新建工作薄后默认有一个工作表,取得第一个工作表
// Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Worksheets[1];//取得sheet1
// int count = ds.Tables.Count;
// for (int j = 0; j < count; j++)
// {
// addExcelValue(worksheet, ds.Tables[j]);
// Microsoft.Office.Interop.Excel.Sheets xlSheets = workBook.Sheets as Microsoft.Office.Interop.Excel.Sheets;
// // 添加 Sheet
// worksheet = (Microsoft.Office.Interop.Excel.Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
// }
// worksheet.Columns.EntireColumn.AutoFit();//列宽自适应。
// if (saveFileName != "")
// {
// try
// {
// workBook.Saved = true;
// workBook.SaveCopyAs(saveFileName);
// fileSaved = true;
// }
// catch (Exception ex)
// {
// fileSaved = false;
// MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
// }
// }
// else
// {
// fileSaved = false;
// }
// xlApp.Quit();
// GC.Collect();
// // GC.Collect();//强行销毁
// //if (fileSaved && System.IO.File.Exists(saveFileName))
// // System.Diagnostics.Process.Start(saveFileName); //打开EXCEL
//}
///// <summary>
///// 根据gridview给excel添加列和值
///// </summary>
///// <param name="worksheet"></param>
///// <param name="gridViewExcel"></param>
//private static void addExcelValue(Microsoft.Office.Interop.Excel.Worksheet worksheet, DataTable gridViewExcel)
//{
// List<string> listFieldName = new List<string>();
// string colName = "";
// string colValue = "";
// worksheet.Name = gridViewExcel.TableName;
// //写入字段
// for (int i = gridViewExcel.Columns.Count; i > 0; i--)
// {
// worksheet.Cells[1, i] = gridViewExcel.Columns[i - 1].Caption;
// listFieldName.Add(gridViewExcel.Columns[i - 1].ColumnName);
// }
// //写入数值
// for (int r = 0; r < gridViewExcel.Rows.Count; r++)
// {
// for (int i = gridViewExcel.Columns.Count; i > 0; i--)
// {
// colName = listFieldName[i - 1].ToString().Trim();
// colValue = gridViewExcel.Rows[r][colName].ToString().Trim();
// worksheet.Cells[r + 2, gridViewExcel.Columns.Count + 1 - i] = "'"+colValue;
// }
// System.Windows.Forms.Application.DoEvents();
// }
//}
#endregion
}
}
|
00fba58a58590c508490cec49fdde3089cbea3d2
|
C#
|
shendongnian/download4
|
/first_version_download2/427968-37678585-119865783-1.cs
| 2.5625
| 3
|
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
SqlCommand cmd = new SqlCommand("select ID from CustomerDetails ", conn);
SqlDataAdapter da = new SqlDataAdapter("", conn);
DataTable dt = new DataTable();
da.fill(dt);
int count=dt.Rows.Count;
if (Count > 0)
{
for (int i = 0; i < Count; i++)
{
Label2.Text =dt1.Rows[i]["ID"].ToString();
}
}
}
|
dba3637142ae66d234f727ec35c51c7d19500928
|
C#
|
daniellepelley/Infrastructure
|
/Newton.Factory/Newton.Factory/Model/Constraints/Speed/SlowRunningComposite.cs
| 2.859375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newton.Factory;
namespace Newton.Factory
{
public class SlowRunningComposite : ISlowRunning
{
private string title;
/// <summary>
/// The title of the downtime
/// </summary>
public string Title
{
get { return title; }
set { title = value; }
}
private TimeSpan timeSpan;
/// <summary>
/// The timespan for the downtime to be measured over
/// </summary>
public TimeSpan TimeSpan
{
get { return timeSpan; }
set { timeSpan = value; }
}
private List<ISlowRunning> speeds = new List<ISlowRunning>();
public List<ISlowRunning> Speeds
{
get { return speeds; }
set { speeds = value; }
}
/// <summary>
/// The rate of down time over a given timespan
/// </summary>
public Rate Rate
{
get { return speeds[0].Rate; }
}
/// <summary>
/// The rate in units
/// </summary>
public Rate UnitRate(Rate conversionRate)
{
return
new Rate()
{
Quantity = Rate.GetQuantityForTimeSpan(conversionRate.TimeSpan),
TimeSpan = conversionRate.TimeSpan
};
}
/// <summary>
/// The timespan rate
/// </summary>
public TimeSpanRate TimeSpanRate(Rate conversionRate)
{
return
new TimeSpanRate()
{
Quantity = Rate.ToTimeSpanRate(conversionRate).GetQuantityForTimeSpan(conversionRate.TimeSpan),
TimeSpan = conversionRate.TimeSpan
};
}
/// <summary>
/// The efficiency of the dimension
/// </summary>
public double Efficiency(Rate conversionRate)
{
return TimeSpanRate(conversionRate).Efficiency;
}
}
}
|
e4df8fa03b3b72a5f3af3af2c1d077610e08d35c
|
C#
|
kingshady77/CSharpCourse_1
|
/MathematicalOperations/MathematicalOperations/Program.cs
| 3.796875
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MathematicalOperations
{
class Program
{
static void Main(string[] args)
{
// + - / *
int myvar1 = 15;
int myvar2 = 10;
int temp = myvar1 + myvar2;
int temp2 = myvar2 - myvar1;
int temp3 = myvar1 % myvar2;
int temp4 = myvar1 / myvar2;
// + -
int myNegativeVar = -10;
int temp5 = +myvar1;
int temp6 = -myvar1;
int temp7 = +myNegativeVar;
string myStr = "This is wonderful.";
string myStr2 = "How is it ?";
string AddString = myStr2 + myStr;
//Console.WriteLine("The result is {0} The result2 is {1} The result3 is {2} The result4 is {3}", temp, temp2, temp3, temp4);
Console.WriteLine("{0}\n\n{1}\n\n{2}", temp5, temp6, temp7);
Console.Write("{0}", AddString);
Console.ReadKey();
}
}
}
|
473afdabc6d2e39e82ce989b3db6bb9893b7a6a6
|
C#
|
MEMOGAMES2019/memogames
|
/Assets/Scripts/FindTheWay/CameraMove.cs
| 2.953125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
///<summary>
///It ensures that the cameras change directions following the rhythm of the car
///Se encarga de que las camaras cambien de direcciones siguiendo el ritmo del coche
///</summary>
public class CameraMove : MonoBehaviour {
public GameObject car;
public GameObject city;
private bool _chaseCar = true;
///<summary>
// Use this for initialization
///</summary>
void Start () {
}
///<summary>
// Update is called once per frame , following the position of the car
///<summary>
void Update () {
if(_chaseCar) {
Vector3 v=car.GetComponent<Transform> ().position;
this.gameObject.GetComponent<Transform> ().position= new Vector3(v.x, v.y, -30);
}
else
{
Vector3 v = city.GetComponent<Transform>().position;
this.gameObject.GetComponent<Transform>().position = new Vector3(v.x, v.y, -45);
this.gameObject.GetComponent<Transform>().position = new Vector3(v.x, v.y, -30);
}
}
///<summary>
///Set and get of chase
///<param bool = value >
///Identify when the car changes its way
///Identifica cuando el coche cambie de vía
///</param>
///</summary>
public bool chase
{
get { return this._chaseCar; }
set { this._chaseCar = value; }
}
}
|
7480234d5b19f91b8d824857d5f8f3b0de5ec751
|
C#
|
1412183/final_project_design_patterns
|
/SimpleValidationFramework/SimpleValidationLibrary/Validators/CustomValidator.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace SimpleValidationLibrary.Validators
{
public class CustomValidator : Validator
{
ICustomValidationRule custValidationRule;
protected override Type[] ValidPropertyTypes { get { return null; } }
public CustomValidator(string errorMessage, PropertyInfo propertyInfo, ICustomValidationRule customValidationRule)
: base(errorMessage, propertyInfo)
{
this.custValidationRule = customValidationRule;
}
protected override bool DoIsValid(object instance, object value)
{
return this.custValidationRule.DoIsValid(value);
}
public static CustomValidator CreateValidator<T>(string errorMessage, string propertyName, ICustomValidationRule customValidationRule)
{
return CreateValidator(typeof(T), errorMessage, propertyName, customValidationRule);
}
public static CustomValidator CreateValidator(Type type, string errorMessage, string propertyName, ICustomValidationRule customValidationRule)
{
return new CustomValidator(errorMessage, Validator.GetPropertyInfo(type, propertyName), customValidationRule);
}
}
}
|
d23986a6b7ebb191dd6e00688e34ad3027937fe6
|
C#
|
Scraniel/chronos
|
/tests/Core/Unit/TimerFactoryUnitTests.cs
| 2.578125
| 3
|
using Chronos.Timer.Core;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Chronos.Timer.Tests.Core
{
[TestClass]
public class TimerFactoryUnitTests
{
private TimerFactory _target;
private BasicTimerAction _timerTask;
public TimerFactoryUnitTests()
{
}
[TestInitialize]
public void Initialize()
{
_target = new TimerFactory();
_timerTask = new BasicTimerAction(() => { }, TimeSpan.FromSeconds(1), 1);
}
[TestMethod]
public void CreateTimer_CreateTwoTimer_CreatesDifferentTimers()
{
ITimer timer1 = _target.CreateTimer<TestTimer>(_timerTask);
ITimer timer2 = _target.CreateTimer<TestTimer>(_timerTask);
Assert.AreNotEqual(timer1, timer2);
}
[TestMethod]
public void CreateTimer_WithSystemTimeTracking_CreatesValidNewTimer()
{
TestTimer timer = _target.CreateTimer<TestTimer>(_timerTask, new SystemTimeTrackingStrategy());
AssertValidCreation(timer);
Assert.IsInstanceOfType(timer.TimeTrackingStrategy, typeof(SystemTimeTrackingStrategy));
}
[TestMethod]
public void CreateTimer_NullTimerTask_ThrowsArgumentNullException()
{
Assert.ThrowsException<ArgumentNullException>(() =>
{
_target.CreateTimer<TestTimer>(
task: null,
timeTracker: null);
});
}
[TestMethod]
public void CreateTimer_SingleTimerTask_CreatesValidNewTimer()
{
TestTimer timer = _target.CreateTimer<TestTimer>(
new BasicTimerAction(() => { }, TimeSpan.FromSeconds(1), 1),
new SystemTimeTrackingStrategy());
AssertValidCreation(timer);
Assert.AreEqual(1, timer.Tasks.Count);
}
[TestMethod]
public void CreateTimer_MultipleTimerTask_CreatesValidNewTimer()
{
List<ITimerAction> tasks = new List<ITimerAction>
{
new BasicTimerAction(() => { }, TimeSpan.FromSeconds(1), 1),
new BasicTimerAction(() => { }, TimeSpan.FromSeconds(1), 1)
};
TestTimer timer = _target.CreateTimer<TestTimer>(
tasks,
new SystemTimeTrackingStrategy());
AssertValidCreation(timer);
Assert.AreEqual(2, timer.Tasks.Count);
}
private void AssertValidCreation(TestTimer timer)
{
Assert.IsNotNull(timer);
Assert.IsTrue(timer.Initialized);
}
// TODO Replace with mock implementation
private class TestTimer : ITimer
{
public TimeSpan TotalElapsedTime => throw new NotImplementedException();
public TimeSpan TimeLeft => throw new NotImplementedException();
public bool Initialized { get; set; } = false;
public ITimeTrackingStrategy TimeTrackingStrategy { get; set; }
public List<ITimerAction> Tasks { get; set; }
Guid ITimer.Id => Guid.NewGuid();
public void Clear()
{
throw new NotImplementedException();
}
public bool IsPaused()
{
throw new NotImplementedException();
}
public void Pause()
{
throw new NotImplementedException();
}
public void Unpause()
{
throw new NotImplementedException();
}
public void Initialize(IEnumerable<ITimerAction> timerTasks, ITimeTrackingStrategy timeTrackingStrategy)
{
Initialized = true;
TimeTrackingStrategy = timeTrackingStrategy;
Tasks = timerTasks.ToList();
}
Task ITimer.UpdateAsync()
{
throw new NotImplementedException();
}
}
}
}
|
de2c326499b1e56a616172d3343184bf86372a9a
|
C#
|
terrorizer1980/GameMechanics
|
/GameMechanics/GameMechanics.Tests/BoardTests.cs
| 3.015625
| 3
|
using System;
using Moq;
using NUnit.Framework;
namespace GameMechanics.Tests
{
[TestFixture]
public class BoardTests
{
private const int Width = 10;
private const int Height = 10;
[Test]
public void BoardTest()
{
var board = new Board(Width, Height);
Assert.That(board.Width, Is.EqualTo(Width));
Assert.That(board.Height, Is.EqualTo(Height));
board.ForEachCell((Cell c) => Assert.That(c, Is.Not.Null));
}
[Test]
public void FillTest()
{
var board = new Board(Width, Height);
Func<IItem> factory1 = () => new Item1();
Func<IItem> factory2 = () => new Item2();
board.FillInstantly(factory1, factory2);
board.ForEachCell(c => Assert.That(c.Item, Is.TypeOf<Item1>().Or.TypeOf<Item2>()));
}
[Test]
public void FillNoFactoriesTest()
{
var board = new Board(Width, Height);
Assert.Throws<ArgumentException>(() => board.Fill());
}
private class Item1: CommonItem { }
private class Item2 : CommonItem { }
}
}
|
098bb3957a7f687a7115012901b94c62c3006273
|
C#
|
arslan77/FYP
|
/Attendance System/Attributes/AuthorizeRequestAttribute.cs
| 2.59375
| 3
|
using Attendance_System.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Controllers;
namespace Attendance_System.Attributes
{
public class AuthorizeRequestAttribute : System.Web.Http.AuthorizeAttribute
{
public override bool AllowMultiple
{
get { return false; }
}
public override void OnAuthorization(HttpActionContext actionContext)
{
//Perform your logic here
base.OnAuthorization(actionContext);
}
protected override bool IsAuthorized(HttpActionContext actionContext)
{
String token="";
try {
token = actionContext.Request.Headers.Authorization.Parameter;
}
catch(NullReferenceException)
{
token = "-1";
}
finally
{
if(token==""||token==null)
{
token = "-1";
}
}
if (AccountManager.validateToken(token))
{
if(Roles == AccountManager.getRoleFromToken(token) || Roles == "")
return true;
}
return false;
}
}
}
|
79d6162139ebe377873cbebeef50b20dead15647
|
C#
|
iovation/launchkey-dotnet
|
/src/iovation.LaunchKey.Sdk/Domain/PublicKey.cs
| 3.125
| 3
|
using System;
using System.Collections.Generic;
namespace iovation.LaunchKey.Sdk.Domain
{
/// <summary>
/// Represents a public key on a service or directory
/// </summary>
public class PublicKey
{
/// <summary>
/// The unique ID for this public key. Use this when updating/removing the key via API calls.
/// </summary>
public string Id { get; }
/// <summary>
/// Whether or not the key is currently active
/// </summary>
public bool Active { get; }
/// <summary>
/// The date and time this key was created
/// </summary>
public DateTime Created { get; }
/// <summary>
/// The date and time this key will expire
/// </summary>
public DateTime? Expires { get; }
/// <summary>
/// The type of key that represents what it will be used for. IE: encryption, signature, or both.
/// </summary>
public KeyType KeyType { get; }
public PublicKey(string id, bool active, DateTime created, DateTime? expires, KeyType keyType = KeyType.BOTH)
{
Id = id;
Active = active;
Created = created;
Expires = expires;
KeyType = keyType;
}
public override bool Equals(object obj)
{
return obj is PublicKey key &&
Id == key.Id &&
Active == key.Active &&
Created == key.Created &&
Expires == key.Expires &&
KeyType == key.KeyType;
}
public override int GetHashCode()
{
int hashCode = -683061471;
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Id);
hashCode = hashCode * -1521134295 + Active.GetHashCode();
hashCode = hashCode * -1521134295 + Created.GetHashCode();
hashCode = hashCode * -1521134295 + Expires.GetHashCode();
hashCode = hashCode * -1521134295 + KeyType.GetHashCode();
return hashCode;
}
}
/// <summary>
/// The type of key that is being utilized
/// </summary>
public enum KeyType
{
/// <summary>
/// Other exists only to allow for forward compatibility to future key types
/// </summary>
OTHER = -1,
/// <summary>
/// This key can be used to both decrypt responses as well as sign requests
/// </summary>
BOTH = 0,
/// <summary>
/// This key can only be used to decrypt requests
/// </summary>
ENCRYPTION = 1,
/// <summary>
/// This key can only be used to sign requests
/// </summary>
SIGNATURE = 2
}
}
|
e6c5090715114a92e02a0e1dd50598c3b3764893
|
C#
|
pederfo/Bombe
|
/Bombe/Explosion.cs
| 3.015625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace Bombe
{
class Explosion
{
public int Xposition { get; set; }
public int Yposition { get; set; }
public Explosion(int xposition, int yposition)
{
Xposition = xposition;
Yposition = yposition;
}
// \ /
// \ @ /
// ---( @@@ )---
// / @ \
// / \
// HIT EXPLOSION
#region Hit Explosion
public void Explode()
{
Console.SetCursorPosition(Xposition, Yposition - 1);
Console.WriteLine("@");
Console.SetCursorPosition(Xposition + 1, Yposition - 1);
Console.WriteLine("@");
Console.SetCursorPosition(Xposition + 2, Yposition - 1);
Console.WriteLine("@");
Console.SetCursorPosition(Xposition + 1, Yposition);
Console.WriteLine("@");
Console.SetCursorPosition(Xposition + 1, Yposition - 2);
Console.WriteLine("@");
Console.SetCursorPosition(Xposition - 2, Yposition - 1);
Console.WriteLine("(");
Console.SetCursorPosition(Xposition + 4, Yposition - 1);
Console.WriteLine(")");
Thread.Sleep(100);
Console.SetCursorPosition(Xposition - 1, Yposition - 2);
Console.WriteLine(@"\");
Console.SetCursorPosition(Xposition + 3, Yposition - 2);
Console.WriteLine("/");
Console.SetCursorPosition(Xposition - 1, Yposition);
Console.WriteLine("/");
Console.SetCursorPosition(Xposition + 3, Yposition);
Console.WriteLine(@"\");
Console.SetCursorPosition(Xposition - 3, Yposition - 1);
Console.WriteLine("-");
Console.SetCursorPosition(Xposition + 5, Yposition - 1);
Console.WriteLine("-");
Thread.Sleep(100);
Console.SetCursorPosition(Xposition - 2, Yposition - 3);
Console.WriteLine(@"\");
Console.SetCursorPosition(Xposition + 4, Yposition - 3);
Console.WriteLine("/");
Console.SetCursorPosition(Xposition - 2, Yposition + 1);
Console.WriteLine("/");
Console.SetCursorPosition(Xposition + 4, Yposition + 1);
Console.WriteLine(@"\");
Console.SetCursorPosition(Xposition - 4, Yposition - 1);
Console.WriteLine("-");
Console.SetCursorPosition(Xposition - 5, Yposition - 1);
Console.WriteLine("-");
Thread.Sleep(300);
Console.SetCursorPosition(Xposition + 6, Yposition - 1);
Console.WriteLine("-");
Console.SetCursorPosition(Xposition + 7, Yposition - 1);
Console.WriteLine("-");
Thread.Sleep(200);
Console.SetCursorPosition(Xposition, Yposition - 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition + 1, Yposition - 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition + 2, Yposition - 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition + 1, Yposition);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition + 1, Yposition - 2);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition, Yposition);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition + 1, Yposition);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition + 2, Yposition);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition, Yposition + 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition + 1, Yposition + 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition + 2, Yposition + 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition, Yposition - 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition + 1, Yposition - 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition + 2, Yposition - 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition + 3, Yposition - 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition + 4, Yposition - 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition + 5, Yposition - 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition + 6, Yposition - 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition + 7, Yposition - 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition - 2, Yposition - 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition + 4, Yposition - 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition - 1, Yposition - 2);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition + 3, Yposition - 2);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition - 1, Yposition);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition + 3, Yposition);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition - 3, Yposition - 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition + 5, Yposition - 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition - 2, Yposition - 3);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition + 4, Yposition - 3);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition - 2, Yposition + 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition + 4, Yposition + 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition - 4, Yposition - 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition - 5, Yposition - 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition + 6, Yposition - 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition + 7, Yposition - 1);
Console.WriteLine(" ");
}
#endregion
// \ /
// -- @ --
// / \
#region Small Explosion
public void ExplosionSmall()
{
Console.SetCursorPosition(Xposition, Yposition - 1);
Console.WriteLine("@");
Thread.Sleep(50);
Console.SetCursorPosition(Xposition - 2, Yposition - 1);
Console.WriteLine("-");
Console.SetCursorPosition(Xposition - 3, Yposition - 1);
Console.WriteLine("-");
Console.SetCursorPosition(Xposition + 2, Yposition - 1);
Console.WriteLine("-");
Console.SetCursorPosition(Xposition + 3, Yposition - 1);
Console.WriteLine("-");
Console.SetCursorPosition(Xposition - 1, Yposition - 2);
Console.WriteLine(@"\");
Console.SetCursorPosition(Xposition + 1, Yposition - 2);
Console.WriteLine("/");
Console.SetCursorPosition(Xposition - 1, Yposition);
Console.WriteLine("/");
Console.SetCursorPosition(Xposition + 1, Yposition);
Console.WriteLine(@"\");
Thread.Sleep(200);
Console.SetCursorPosition(Xposition, Yposition - 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition - 2, Yposition - 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition - 3, Yposition - 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition + 2, Yposition - 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition + 3, Yposition - 1);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition - 1, Yposition - 2);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition + 1, Yposition - 2);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition - 1, Yposition);
Console.WriteLine(" ");
Console.SetCursorPosition(Xposition + 1, Yposition);
Console.WriteLine(" ");
}
#endregion
//
// (@@@@@)
// |@|
// |@|
// (( @@@ ))
//
//
}
}
|
43af3dfed76876ac24ab1edeee4c6b430b3d50be
|
C#
|
EricVoll/PARRHI
|
/04_PARRHI_Library/PARRHI/Objects/DataImport.cs
| 2.609375
| 3
|
using PARRHI.HelperClasses;
using PARRHI.HelperClasses.XML;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace PARRHI.Objects
{
public class DataImport
{
public DataImport()
{
BaseElement.Element.RegisterId = RegisterId;
}
private string XSDFilePath = @"C:\Users\ericv\Documents\TUM\BA\PARRHI\10_XSD\PARS_XSD_Test\PARS_XSD_Test\parsScheme.xsd";
public XMLValidationResult XMLValidationResult { get; set; }
/// <summary>
/// Imports the PARRHI data with both files specified
/// </summary>
/// <param name="xmlFilePath"></param>
/// <param name="xsdFilePath"></param>
/// <returns></returns>
public Container Import(string xmlFilePath, string xsdFilePath)
{
XSDFilePath = xsdFilePath;
return Import(xmlFilePath, false);
}
/// <summary>
/// Imports the xml file with the default xsd file
/// </summary>
/// <param name="xmlFilePath"></param>
/// <returns></returns>
public Container Import(string xmlFilePath, bool skipValidation = true)
{
HelperClasses.XML.XMLSerializerClass xmlSerializer = new HelperClasses.XML.XMLSerializerClass();
if (!skipValidation)
{
Output.Instance.Log("Validating XML document");
XMLValidationResult = xmlSerializer.ValidateXML(xmlFilePath, XSDFilePath);
}
else
{
XMLValidationResult = new XMLValidationResult() { DidThrowExceptionWhileValidating = false };
}
if (!XMLValidationResult.DidThrowExceptionWhileValidating)
{
Output.Instance.Log("Deserialising XML document");
var pProgram = xmlSerializer.Deserialize<Objects.PProgram>(xmlFilePath);
var container = new PProgramToContainer(pProgram, XMLValidationResult).ConvertToContainer();
return container;
}
return null;
}
public Container Import(string xmlContent)
{
Output.Instance.Log("Skipped XML Validation");
HelperClasses.XML.XMLSerializerClass xmlSerializer = new HelperClasses.XML.XMLSerializerClass();
XMLValidationResult = new XMLValidationResult() { DidThrowExceptionWhileValidating = false };
if (!XMLValidationResult.DidThrowExceptionWhileValidating)
{
var pProgram = xmlSerializer.DeserializeFromContent<Objects.PProgram>(xmlContent);
var container = new PProgramToContainer(pProgram, XMLValidationResult).ConvertToContainer();
return container;
}
return null;
}
private List<string> Ids = new List<string>();
/// <summary>
/// Adds the Id to the specified element and checks for duplicates
/// </summary>
/// <param name="id"></param>
public void RegisterId(string id)
{
if (Ids.Any(x => x == id))
{
XMLValidationResult.AddConversionError(new XMLValidationError($"Duplicate ID: {id}, nrOfElements:{Ids.Count}", System.Xml.Schema.XmlSeverityType.Error, null));
}
Ids.Add(id);
}
}
}
|
9c6481e7db8557b3f9cc43eea4d8822f9123d043
|
C#
|
StacyGay/Stacy.Core
|
/Stacy.Core/Data/Validator.cs
| 2.59375
| 3
|
using Stacy.Core.Exceptions;
namespace Stacy.Core.Data
{
public abstract class Validator
{
public List<string> Messages { get; set; } = new List<string>();
public string ErrorMessage => "There has been a validation error";
public CoreUserAggregateException GetAggregateException()
{
if (!Messages.Any())
return null;
var exceptions = Messages.Select(m => new CoreUserException(m));
return new CoreUserAggregateException(ErrorMessage, exceptions);
}
public List<CoreUserException> GetExceptionList()
{
return Messages.Select(m => new CoreUserException(m)).ToList();
}
}
}
|
10d2d4e45f752db1a72e22426458f1b8b8467c17
|
C#
|
Pengxiaoxi/HouseRent
|
/DAL/HouseDao.cs
| 2.609375
| 3
|
using System;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using Maticsoft.DBUtility;//Please add references
namespace myhouse.DAL
{
/// <summary>
/// 数据访问类:HouseDao
/// </summary>
public partial class HouseDao
{
public HouseDao()
{}
#region BasicMethod
/// <summary>
/// 得到最大ID
/// </summary>
public int GetMaxId()
{
return DbHelperSQL.GetMaxID("cid", "t_house");
}
/// <summary>
/// 是否存在该记录
/// </summary>
public bool Exists(int cid,int uid,int sid,int hid)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("select count(1) from t_house");
strSql.Append(" where cid=@cid and uid=@uid and sid=@sid and hid=@hid ");
SqlParameter[] parameters = {
new SqlParameter("@cid", SqlDbType.Int,4),
new SqlParameter("@uid", SqlDbType.Int,4),
new SqlParameter("@sid", SqlDbType.Int,4),
new SqlParameter("@hid", SqlDbType.Int,4) };
parameters[0].Value = cid;
parameters[1].Value = uid;
parameters[2].Value = sid;
parameters[3].Value = hid;
return DbHelperSQL.Exists(strSql.ToString(),parameters);
}
/// <summary>
/// 增加一条数据
/// </summary>
public int Add(myhouse.Model.House model)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("insert into t_house(");
strSql.Append("cid,uid,sid,hname,hdescription,hmoney,htype,hphotoone,hphototwo,hphotothree,hphotofour,hfloor,hsize,harea,hcommunity,hadress,htime,hmode,hstatus)");
strSql.Append(" values (");
strSql.Append("@cid,@uid,@sid,@hname,@hdescription,@hmoney,@htype,@hphotoone,@hphototwo,@hphotothree,@hphotofour,@hfloor,@hsize,@harea,@hcommunity,@hadress,@htime,@hmode,@hstatus)");
strSql.Append(";select @@IDENTITY");
SqlParameter[] parameters = {
new SqlParameter("@cid", SqlDbType.Int,4),
new SqlParameter("@uid", SqlDbType.Int,4),
new SqlParameter("@sid", SqlDbType.Int,4),
new SqlParameter("@hname", SqlDbType.VarChar,30),
new SqlParameter("@hdescription", SqlDbType.VarChar,200),
new SqlParameter("@hmoney", SqlDbType.VarChar,10),
new SqlParameter("@htype", SqlDbType.Int,4),
new SqlParameter("@hphotoone", SqlDbType.VarChar,200),
new SqlParameter("@hphototwo", SqlDbType.VarChar,200),
new SqlParameter("@hphotothree", SqlDbType.VarChar,200),
new SqlParameter("@hphotofour", SqlDbType.VarChar,200),
new SqlParameter("@hfloor", SqlDbType.Char,4),
new SqlParameter("@hsize", SqlDbType.Char,4),
new SqlParameter("@harea", SqlDbType.Int,4),
new SqlParameter("@hcommunity", SqlDbType.VarChar,100),
new SqlParameter("@hadress", SqlDbType.VarChar,200),
new SqlParameter("@htime", SqlDbType.DateTime),
new SqlParameter("@hmode", SqlDbType.Int,4),
new SqlParameter("@hstatus", SqlDbType.Int,4)};
parameters[0].Value = model.cid;
parameters[1].Value = model.uid;
parameters[2].Value = model.sid;
parameters[3].Value = model.hname;
parameters[4].Value = model.hdescription;
parameters[5].Value = model.hmoney;
parameters[6].Value = model.htype;
parameters[7].Value = model.hphotoone;
parameters[8].Value = model.hphototwo;
parameters[9].Value = model.hphotothree;
parameters[10].Value = model.hphotofour;
parameters[11].Value = model.hfloor;
parameters[12].Value = model.hsize;
parameters[13].Value = model.harea;
parameters[14].Value = model.hcommunity;
parameters[15].Value = model.hadress;
parameters[16].Value = model.htime;
parameters[17].Value = model.hmode;
parameters[18].Value = model.hstatus;
object obj = DbHelperSQL.GetSingle(strSql.ToString(),parameters);
if (obj == null)
{
return 0;
}
else
{
return Convert.ToInt32(obj);
}
}
/// <summary>
/// 更新一条数据
/// </summary>
public bool Update(myhouse.Model.House model)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("update t_house set ");
strSql.Append("hname=@hname,");
strSql.Append("hdescription=@hdescription,");
strSql.Append("hmoney=@hmoney,");
strSql.Append("htype=@htype,");
strSql.Append("hphotoone=@hphotoone,");
strSql.Append("hphototwo=@hphototwo,");
strSql.Append("hphotothree=@hphotothree,");
strSql.Append("hphotofour=@hphotofour,");
strSql.Append("hfloor=@hfloor,");
strSql.Append("hsize=@hsize,");
strSql.Append("harea=@harea,");
strSql.Append("hcommunity=@hcommunity,");
strSql.Append("hadress=@hadress,");
strSql.Append("htime=@htime,");
strSql.Append("hmode=@hmode,");
strSql.Append("hstatus=@hstatus");
strSql.Append(" where hid=@hid");
SqlParameter[] parameters = {
new SqlParameter("@hname", SqlDbType.VarChar,30),
new SqlParameter("@hdescription", SqlDbType.VarChar,200),
new SqlParameter("@hmoney", SqlDbType.VarChar,10),
new SqlParameter("@htype", SqlDbType.Int,4),
new SqlParameter("@hphotoone", SqlDbType.VarChar,200),
new SqlParameter("@hphototwo", SqlDbType.VarChar,200),
new SqlParameter("@hphotothree", SqlDbType.VarChar,200),
new SqlParameter("@hphotofour", SqlDbType.VarChar,200),
new SqlParameter("@hfloor", SqlDbType.Char,4),
new SqlParameter("@hsize", SqlDbType.Char,4),
new SqlParameter("@harea", SqlDbType.Int,4),
new SqlParameter("@hcommunity", SqlDbType.VarChar,100),
new SqlParameter("@hadress", SqlDbType.VarChar,200),
new SqlParameter("@htime", SqlDbType.DateTime),
new SqlParameter("@hmode", SqlDbType.Int,4),
new SqlParameter("@hstatus", SqlDbType.Int,4),
new SqlParameter("@hid", SqlDbType.Int,4),
new SqlParameter("@cid", SqlDbType.Int,4),
new SqlParameter("@uid", SqlDbType.Int,4),
new SqlParameter("@sid", SqlDbType.Int,4)};
parameters[0].Value = model.hname;
parameters[1].Value = model.hdescription;
parameters[2].Value = model.hmoney;
parameters[3].Value = model.htype;
parameters[4].Value = model.hphotoone;
parameters[5].Value = model.hphototwo;
parameters[6].Value = model.hphotothree;
parameters[7].Value = model.hphotofour;
parameters[8].Value = model.hfloor;
parameters[9].Value = model.hsize;
parameters[10].Value = model.harea;
parameters[11].Value = model.hcommunity;
parameters[12].Value = model.hadress;
parameters[13].Value = model.htime;
parameters[14].Value = model.hmode;
parameters[15].Value = model.hstatus;
parameters[16].Value = model.hid;
parameters[17].Value = model.cid;
parameters[18].Value = model.uid;
parameters[19].Value = model.sid;
int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
//UpdateAll 包含外键更新
public bool UpdateAll(myhouse.Model.House model)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("update t_house set ");
strSql.Append("hname=@hname,");
strSql.Append("hdescription=@hdescription,");
strSql.Append("hmoney=@hmoney,");
strSql.Append("htype=@htype,");
strSql.Append("hphotoone=@hphotoone,");
strSql.Append("hphototwo=@hphototwo,");
strSql.Append("hphotothree=@hphotothree,");
strSql.Append("hphotofour=@hphotofour,");
strSql.Append("hfloor=@hfloor,");
strSql.Append("hsize=@hsize,");
strSql.Append("harea=@harea,");
strSql.Append("hcommunity=@hcommunity,");
strSql.Append("hadress=@hadress,");
strSql.Append("htime=@htime,");
strSql.Append("hmode=@hmode,");
strSql.Append("hstatus=@hstatus,");
strSql.Append("sid=@sid"); /*外键sid更新*/
strSql.Append(" where hid=@hid");
SqlParameter[] parameters = {
new SqlParameter("@hname", SqlDbType.VarChar,30),
new SqlParameter("@hdescription", SqlDbType.VarChar,200),
new SqlParameter("@hmoney", SqlDbType.VarChar,10),
new SqlParameter("@htype", SqlDbType.Int,4),
new SqlParameter("@hphotoone", SqlDbType.VarChar,200),
new SqlParameter("@hphototwo", SqlDbType.VarChar,200),
new SqlParameter("@hphotothree", SqlDbType.VarChar,200),
new SqlParameter("@hphotofour", SqlDbType.VarChar,200),
new SqlParameter("@hfloor", SqlDbType.Char,4),
new SqlParameter("@hsize", SqlDbType.Char,4),
new SqlParameter("@harea", SqlDbType.Int,4),
new SqlParameter("@hcommunity", SqlDbType.VarChar,100),
new SqlParameter("@hadress", SqlDbType.VarChar,200),
new SqlParameter("@htime", SqlDbType.DateTime),
new SqlParameter("@hmode", SqlDbType.Int,4),
new SqlParameter("@hstatus", SqlDbType.Int,4),
new SqlParameter("@hid", SqlDbType.Int,4),
new SqlParameter("@cid", SqlDbType.Int,4),
new SqlParameter("@uid", SqlDbType.Int,4),
new SqlParameter("@sid", SqlDbType.Int,4)};
parameters[0].Value = model.hname;
parameters[1].Value = model.hdescription;
parameters[2].Value = model.hmoney;
parameters[3].Value = model.htype;
parameters[4].Value = model.hphotoone;
parameters[5].Value = model.hphototwo;
parameters[6].Value = model.hphotothree;
parameters[7].Value = model.hphotofour;
parameters[8].Value = model.hfloor;
parameters[9].Value = model.hsize;
parameters[10].Value = model.harea;
parameters[11].Value = model.hcommunity;
parameters[12].Value = model.hadress;
parameters[13].Value = model.htime;
parameters[14].Value = model.hmode;
parameters[15].Value = model.hstatus;
parameters[16].Value = model.hid;
parameters[17].Value = model.cid;
parameters[18].Value = model.uid;
parameters[19].Value = model.sid;
int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 删除一条数据
/// </summary>
public bool Delete(int hid)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("delete from t_house ");
strSql.Append(" where hid=@hid");
SqlParameter[] parameters = {
new SqlParameter("@hid", SqlDbType.Int,4)
};
parameters[0].Value = hid;
int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
// 通过外键sid删除数据
public bool DeleteBySid(int sid)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("delete from t_house ");
strSql.Append(" where sid=@sid");
SqlParameter[] parameters = {
new SqlParameter("@sid", SqlDbType.Int,4)
};
parameters[0].Value = sid;
int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
// 通过外键uid删除数据(删除该用户发布的所有房屋信息)
public bool DeleteByUid(int uid)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("delete from t_house ");
strSql.Append(" where uid=@uid");
SqlParameter[] parameters = {
new SqlParameter("@uid", SqlDbType.Int,4)
};
parameters[0].Value = uid;
int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 删除一条数据
/// </summary>
public bool Delete(int cid,int uid,int sid,int hid)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("delete from t_house ");
strSql.Append(" where cid=@cid and uid=@uid and sid=@sid and hid=@hid ");
SqlParameter[] parameters = {
new SqlParameter("@cid", SqlDbType.Int,4),
new SqlParameter("@uid", SqlDbType.Int,4),
new SqlParameter("@sid", SqlDbType.Int,4),
new SqlParameter("@hid", SqlDbType.Int,4) };
parameters[0].Value = cid;
parameters[1].Value = uid;
parameters[2].Value = sid;
parameters[3].Value = hid;
int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 批量删除数据
/// </summary>
public bool DeleteList(string hidlist )
{
StringBuilder strSql=new StringBuilder();
strSql.Append("delete from t_house ");
strSql.Append(" where hid in ("+hidlist + ") ");
int rows=DbHelperSQL.ExecuteSql(strSql.ToString());
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 得到一个对象实体
/// </summary>
public myhouse.Model.House GetModel(int hid)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("select top 1 hid,cid,uid,sid,hname,hdescription,hmoney,htype,hphotoone,hphototwo,hphotothree,hphotofour,hfloor,hsize,harea,hcommunity,hadress,htime,hmode,hstatus from t_house ");
strSql.Append(" where hid=@hid");
SqlParameter[] parameters = {
new SqlParameter("@hid", SqlDbType.Int,4)
};
parameters[0].Value = hid;
myhouse.Model.House model=new myhouse.Model.House();
DataSet ds=DbHelperSQL.Query(strSql.ToString(),parameters);
if(ds.Tables[0].Rows.Count>0)
{
return DataRowToModel(ds.Tables[0].Rows[0]);
}
else
{
return null;
}
}
/// <summary>
/// 得到一个对象实体
/// </summary>
public myhouse.Model.House DataRowToModel(DataRow row)
{
myhouse.Model.House model=new myhouse.Model.House();
if (row != null)
{
if(row["hid"]!=null && row["hid"].ToString()!="")
{
model.hid=int.Parse(row["hid"].ToString());
}
if(row["cid"]!=null && row["cid"].ToString()!="")
{
model.cid=int.Parse(row["cid"].ToString());
}
if(row["uid"]!=null && row["uid"].ToString()!="")
{
model.uid=int.Parse(row["uid"].ToString());
}
if(row["sid"]!=null && row["sid"].ToString()!="")
{
model.sid=int.Parse(row["sid"].ToString());
}
if(row["hname"]!=null)
{
model.hname=row["hname"].ToString();
}
if(row["hdescription"]!=null)
{
model.hdescription=row["hdescription"].ToString();
}
if(row["hmoney"]!=null)
{
model.hmoney=row["hmoney"].ToString();
}
if(row["htype"]!=null && row["htype"].ToString()!="")
{
model.htype=int.Parse(row["htype"].ToString());
}
if(row["hphotoone"]!=null)
{
model.hphotoone=row["hphotoone"].ToString();
}
if(row["hphototwo"]!=null)
{
model.hphototwo=row["hphototwo"].ToString();
}
if(row["hphotothree"]!=null)
{
model.hphotothree=row["hphotothree"].ToString();
}
if(row["hphotofour"]!=null)
{
model.hphotofour=row["hphotofour"].ToString();
}
if(row["hfloor"]!=null)
{
model.hfloor=row["hfloor"].ToString();
}
if(row["hsize"]!=null)
{
model.hsize=row["hsize"].ToString();
}
if(row["harea"]!=null && row["harea"].ToString()!="")
{
model.harea=int.Parse(row["harea"].ToString());
}
if(row["hcommunity"]!=null)
{
model.hcommunity=row["hcommunity"].ToString();
}
if(row["hadress"]!=null)
{
model.hadress=row["hadress"].ToString();
}
if(row["htime"]!=null && row["htime"].ToString()!="")
{
model.htime=DateTime.Parse(row["htime"].ToString());
}
if(row["hmode"]!=null && row["hmode"].ToString()!="")
{
model.hmode=int.Parse(row["hmode"].ToString());
}
if(row["hstatus"]!=null && row["hstatus"].ToString()!="")
{
model.hstatus=int.Parse(row["hstatus"].ToString());
}
}
return model;
}
/// <summary>
/// 获得数据列表
/// </summary>
public DataSet GetList(string strWhere)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("select hid,cid,uid,sid,hname,hdescription,hmoney,htype,hphotoone,hphototwo,hphotothree,hphotofour,hfloor,hsize,harea,hcommunity,hadress,htime,hmode,hstatus ");
strSql.Append(" FROM t_house ");
if(strWhere.Trim()!="")
{
strSql.Append(" where "+strWhere);
}
return DbHelperSQL.Query(strSql.ToString());
}
/// <summary>
/// 获得前几行数据
/// </summary>
public DataSet GetList(int Top,string strWhere,string filedOrder)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("select ");
if(Top>0)
{
strSql.Append(" top "+Top.ToString());
}
strSql.Append(" hid,cid,uid,sid,hname,hdescription,hmoney,htype,hphotoone,hphototwo,hphotothree,hphotofour,hfloor,hsize,harea,hcommunity,hadress,htime,hmode,hstatus ");
strSql.Append(" FROM t_house ");
if(strWhere.Trim()!="")
{
strSql.Append(" where "+strWhere);
}
strSql.Append(" order by " + filedOrder);
return DbHelperSQL.Query(strSql.ToString());
}
/// <summary>
/// 获取记录总数
/// </summary>
public int GetRecordCount(string strWhere)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("select count(1) FROM t_house ");
if(strWhere.Trim()!="")
{
strSql.Append(" where "+strWhere);
}
object obj = DbHelperSQL.GetSingle(strSql.ToString());
if (obj == null)
{
return 0;
}
else
{
return Convert.ToInt32(obj);
}
}
/// <summary>
/// 分页获取数据列表
/// </summary>
public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("SELECT * FROM ( ");
strSql.Append(" SELECT ROW_NUMBER() OVER (");
if (!string.IsNullOrEmpty(orderby.Trim()))
{
strSql.Append("order by T." + orderby );
}
else
{
strSql.Append("order by T.hid desc");
}
strSql.Append(")AS Row, T.* from t_house T ");
if (!string.IsNullOrEmpty(strWhere.Trim()))
{
strSql.Append(" WHERE " + strWhere);
//strSql.Append(strWhere);
}
strSql.Append(" ) TT");
strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
return DbHelperSQL.Query(strSql.ToString());
}
/*
/// <summary>
/// 分页获取数据列表
/// </summary>
public DataSet GetList(int PageSize,int PageIndex,string strWhere)
{
SqlParameter[] parameters = {
new SqlParameter("@tblName", SqlDbType.VarChar, 255),
new SqlParameter("@fldName", SqlDbType.VarChar, 255),
new SqlParameter("@PageSize", SqlDbType.Int),
new SqlParameter("@PageIndex", SqlDbType.Int),
new SqlParameter("@IsReCount", SqlDbType.Bit),
new SqlParameter("@OrderType", SqlDbType.Bit),
new SqlParameter("@strWhere", SqlDbType.VarChar,1000),
};
parameters[0].Value = "t_house";
parameters[1].Value = "hid";
parameters[2].Value = PageSize;
parameters[3].Value = PageIndex;
parameters[4].Value = 0;
parameters[5].Value = 0;
parameters[6].Value = strWhere;
return DbHelperSQL.RunProcedure("UP_GetRecordByPage",parameters,"ds");
}*/
#endregion BasicMethod
#region ExtensionMethod
#endregion ExtensionMethod
}
}
|
33d92f549bfde550c2b4c6c704f1f7b30ce5f9bc
|
C#
|
rex1234/ships_online
|
/Ships/Player.cs
| 3
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ships
{
class Player
{
//board codes
public const int EmptyField = 0;
public const int ShipField = 1;
//network codes
public const int Miss = 0;
public const int Hit = 1;
public const int HitWholeShip = 2;
public string Name { get; set; }
public bool Ready { get; set; }
public int Height { get; set; }
public int Width { get; set; }
public bool IsError { get; private set; } //wrongly places ship
//Ships we destroyed to the enemy
public IDictionary<int, int> FoundShipCounts { get; private set; }
public int RemainingShips
{
get
{
return Form1.ShipCounts.Select(s => s.Value).Sum() -
destroyedShips.Select(s => s.Value).Sum();
}
}
public bool FoundAll
{
get
{
return FoundShipCounts.Select(s => s.Value).Sum() ==
Form1.ShipCounts.Select(s => s.Value).Sum();
}
}
//which fields enemy tried to guess
public bool[,] Guessed { get; private set; }
private int[,] board;
//no. of placed ships when creating the game
IDictionary<int, int> ships;
//no. of ships the enemy destroyed
IDictionary<int, int> destroyedShips;
public int this[int i, int j]
{
get { return board[i, j]; }
set
{
board[i, j] = value;
FindShips();
}
}
public Player(int width, int height)
{
Width = width;
Height = height;
board = new int[width, height];
Guessed = new bool[width, height];
Name = System.Environment.MachineName;
ships = new Dictionary<int, int>();
destroyedShips = new Dictionary<int, int>();
FoundShipCounts = new Dictionary<int, int>();
for (int i = 0; i <= Width; i++)
{
ships[i] = 0;
destroyedShips[i] = 0;
FoundShipCounts[i] = 0;
}
}
public int GetShipCount(int shipLength)
{
return ships[shipLength];
}
public int Guess(int x, int y)
{
Guessed[x, y] = true;
if (board[x, y] == Player.ShipField)
{
int shipLength;
if (IsWholeShipGuessed(x, y, out shipLength))
{
destroyedShips[shipLength]++;
return HitWholeShip;
}
else
{
return Hit;
}
}
else
{
return Miss;
}
}
public bool IsWholeShipGuessed(int x, int y, out int shipLength)
{
bool whole = true;
//najde prvu hornu / lavu kocku lode
while (x > 0 && board[x - 1, y] == ShipField) --x;
while (y > 0 && board[x, y - 1] == ShipField) --y;
int startX = x;
int startY = y;
shipLength = 0;
while (whole && y < Height && board[x, y] == ShipField)
{
whole = whole && Guessed[x, y];
++y;
++shipLength;
}
x = startX;
y = startY;
while (whole && x < Width && board[x, y] == ShipField)
{
whole = whole && Guessed[x, y];
++x;
++shipLength;
}
--shipLength;
return whole;
}
private void FindShips()
{
bool error = false;
for (int i = 0; i < 12; i++)
{
ships[i] = 0;
}
for (int i = 0; i < Height; i++)
{
for (int j = 0; j < Width; j++)
{
if (board[i, j] != ShipField)
{
continue;
}
int shipLength = 0;
bool found = true;
//finds horizontal ships
if (j == 0 || board[i, j - 1] != ShipField)
{
while (j + shipLength < Width && board[i, j + shipLength] == ShipField)
{
//check if there is only water around the ship
found = (i == Height - 1 || board[i + 1, j + shipLength] != ShipField) &&
(i == 0 || board[i - 1, j + shipLength] != ShipField);
++shipLength;
}
//corners
found = found &&
(i == 0 || j == 0 || board[i - 1, j - 1] != ShipField) &&
(i == Height - 1 || j == 0 || board[i + 1, j - 1] != ShipField) &&
(i == 0 || j + shipLength == Width || board[i - 1, j + shipLength] != ShipField) &&
(i == Height - 1 || j + shipLength == Width || board[i + 1, j + shipLength] != ShipField);
//finds vertical ships
if (!found)
{
found = true;
shipLength = 0;
if (i == 0 || board[i - 1, j] != ShipField)
{
while (found && i + shipLength < 12 && board[i + shipLength, j] == ShipField)
{
//check if there is only water around the ship
found = (j == Width - 1 || board[i + shipLength, j + 1] != ShipField) &&
(j == 0 || board[i + shipLength, j - 1] != ShipField);
++shipLength;
}
//corners
found = found &&
(j == 0 || i == 0 || board[i - 1, j - 1] != ShipField) &&
(j == Width - 1 || i == 0 || board[i - 1, j + 1] != ShipField) &&
(j == 0 || i + shipLength == Height || board[i + shipLength, j - 1] != ShipField) &&
(j == Width - 1 || i + shipLength == Height || board[i + shipLength, j + 1] != ShipField);
}
}
if (found)
{
++ships[shipLength];
}
else
{
error = true;
}
}
}
}
IsError = error;
}
public int GetDestroyedShipCount(int shipLength)
{
return destroyedShips[shipLength];
}
}
}
|
c16ebb4bafca48b9e5b39df847b76ab2277a6aae
|
C#
|
rajvarma/Sage.unitTest
|
/Sage-CloudPlatform-Core-/Projects/Sage.Core.Framework/Logging/ILogger.cs
| 2.9375
| 3
|
namespace Sage.Core.Framework.Logging
{
using System;
public interface ILogger
{
#region Critical method overloads
/// <summary>
/// Logs the given messageContent, tenant id, user id and exception with a Severity of Critical.
/// The entire messageContent and stack trace of the entire exception chain will be logged. (Each inner exception is logged).
/// The given messageContent will have a ": " appended to the end. For readability
/// of your log messages, do not end the messageContent with any punctuation characters.
/// </summary>
/// <param name="message">Message to log</param>
/// <param name="tenantId">Tenant ID under whose context the application is running</param>
/// <param name="userId">User ID under whose context the application is running</param>
/// <param name="e">The exception to log</param>
void Critical(string message, Guid tenantId, Guid userId, Exception e = null);
/// <summary>
/// Logs the given messageContent and Exception with a severity of Critical. This method is to be used when the TenantId
/// and UserId is not known.
/// </summary>
/// <param name="message">Message to log</param>
/// <param name="e">The exception to log</param>
void Critical(string message, Exception e = null);
#endregion
#region Error method overloads
/// <summary>
/// Logs the given messageContent, tenant id, user id and exception with a Severity of Error.
/// The entire messageContent and stack trace of the entire exception chain will be logged. (Each inner exception is logged).
/// The given messageContent will have a ": " appended to the end. For readability
/// of your log messages, do not end the messageContent with any punctuation characters.
/// </summary>
/// <param name="message">Message to log</param>
/// <param name="tenantId">Tenant ID under whose context the application is running</param>
/// <param name="userId">User ID under whose context the application is running</param>
/// <param name="e">The exception to log</param>
void Error(string message, Guid tenantId, Guid userId, Exception e = null);
/// <summary>
/// Logs the given messageContent and Exception with a severity of Error. This method is to be used when the TenantId
/// and UserId is not known.
/// </summary>
/// <param name="message">Message to log</param>
/// <param name="e">The exception to log</param>
void Error(string message, Exception e = null);
#endregion
#region Warning method overloads
/// <summary>
/// Logs the given messageContent, tenant id, user id and exception with a Severity of Warning.
/// The entire messageContent and stack trace of the entire exception chain will be logged. (Each inner exception is logged).
/// The given messageContent will have a ": " appended to the end. For readability
/// of your log messages, do not end the messageContent with any punctuation characters.
/// </summary>
/// <param name="message">Message to log</param>
/// <param name="tenantId">Tenant ID under whose context the application is running</param>
/// <param name="userId">User ID under whose context the application is running</param>
/// <param name="e">The exception to log</param>
void Warning(string message, Guid tenantId, Guid userId, Exception e = null);
/// <summary>
/// Logs the given messageContent and Exception with a severity of Warning. This method is to be used when the TenantId
/// and UserId is not known.
/// </summary>
/// <param name="message">Message to log</param>
/// <param name="e">The exception to log</param>
void Warning(string message, Exception e = null);
#endregion
#region Info method overloads
/// <summary>
/// Logs the given messageContent, tenant id, user id and exception with a Severity of Info.
/// The entire messageContent and stack trace of the entire exception chain will be logged. (Each inner exception is logged).
/// The given messageContent will have a ": " appended to the end. For readability
/// of your log messages, do not end the messageContent with any punctuation characters.
/// </summary>
/// <param name="message">Message to log</param>
/// <param name="tenantId">Tenant ID under whose context the application is running</param>
/// <param name="userId">User ID under whose context the application is running</param>
/// <param name="e">The exception to log</param>
void Info(string message, Guid tenantId, Guid userId, Exception e = null);
/// <summary>
/// Logs the given messageContent and Exception with a severity of Info. This method is to be used when the TenantId
/// and UserId is not known.
/// </summary>
/// <param name="message">Message to log</param>
/// <param name="e">The exception to log</param>
void Info(string message, Exception e = null);
#endregion
#region Verbose method overloads
/// <summary>
/// Logs the given messageContent, tenant id, user id and exception with a Severity of Verbose.
/// The entire messageContent and stack trace of the entire exception chain will be logged. (Each inner exception is logged).
/// The given messageContent will have a ": " appended to the end. For readability
/// of your log messages, do not end the messageContent with any punctuation characters.
/// </summary>
/// <param name="message">Message to log</param>
/// <param name="tenantId">Tenant ID under whose context the application is running</param>
/// <param name="userId">User ID under whose context the application is running</param>
/// <param name="e">The exception to log</param>
void Verbose(string message, Guid tenantId, Guid userId, Exception e = null);
/// <summary>
/// Logs the given messageContent and Exception with a severity of Verbose. This method is to be used when the TenantId
/// and UserId is not known.
/// </summary>
/// <param name="message">Message to log</param>
/// <param name="e">The exception to log</param>
void Verbose(string message, Exception e = null);
#endregion
/// <summary>
/// Can be used by the client to determine if the message should be logged. Use in cases when the client wants to
/// avoid doing a work to construct a message that won't ever be logged
/// </summary>
/// <param name="level"></param>
/// <returns></returns>
bool ShouldLog(LogLevel level);
}
}
|
75ebc2a1d0c88a38ac618f414ec1509b82b38cfd
|
C#
|
GalRabin/csharp-course
|
/Ex5/GameLogic/Cell.cs
| 3.421875
| 3
|
using System;
namespace GameLogic
{
public class Cell
{
private readonly string r_CellValue;
private bool m_RevealCellState;
private Player m_PlayerRevealed = null;
private bool m_IsInCheck = false;
private static readonly Random sr_Rnd = new Random();
public Cell()
{
r_CellValue = getRandomCharacter();
}
public Cell(string i_Character)
{
r_CellValue = i_Character;
}
public bool IsReveal
{
get
{
return m_RevealCellState;
}
}
public Player PlayerRevealed
{
get
{
return m_PlayerRevealed;//IsReveal ? m_PlayerRevealed : null;
}
}
public bool Incheck
{
get
{
return m_IsInCheck;
}
set
{
m_IsInCheck = value;
}
}
private string getRandomCharacter()
{
// Random character
char randomChar = (char)sr_Rnd.Next('a', 'z');
// Random lowercase or uppercase
if (sr_Rnd.Next(1, 3) == 1)
{
randomChar = char.ToUpper(randomChar);
}
return randomChar.ToString();
}
public void RevealState(bool i_RevealState, Player i_PlayerReveal = null)
{
m_RevealCellState = i_RevealState;
m_PlayerRevealed = i_PlayerReveal;
/*if(i_PlayerReveal == null)
{
m_IsInCheck = i_RevealState;
}*/
}
public string GetStringIfRevealed(bool i_Force = false)
{
string returnValue = null;
if (m_RevealCellState || i_Force)
{
returnValue = r_CellValue;
}
return returnValue;
}
}
}
|
c5c41a923d6be80798897d4d71faef98720b87a5
|
C#
|
otto-krause/guias-de-ejercicios-BrahianSozaki
|
/Guia 7/E4/Ejercicio/Terence.cs
| 2.53125
| 3
|
namespace Ejercicio
{
public class Terence : Pajaros
{
private int cantidadDeEnojos;
public Terence( int ira) : base(ira)
{
}
public override void seEnoja() => cantidadDeEnojos++;
public override int fuerza(){
return ira * cantidadDeEnojos * 10;
}
}
}
|
be29fb519d9f69372f405dd26bb7783e3d5e996d
|
C#
|
rgicheva/SoftwareUniversity_Homeworks
|
/00.C# BASICS/06.Loops/03.MinMaxSumAndAverageOfNNumbers.cs
| 4.28125
| 4
|
/* Problem 03. Min, Max, Sum and Average of N Numbers
Write a program that reads from the console a sequence of n integer numbers and returns the minimal,
the maximal number, the sum and the average of all numbers (displayed with 2 digits after the decimal point).
The input starts by the number n (alone in a line) followed by n lines, each holding an integer number.
The output is like in the examples below. Examples:
*/
using System;
class MinMaxSumAndAverageOfNNumbers
{
static void Main()
{
Console.Write("Please enter a positive integer number for count of sequence, n = ");
int nNumber;
int min = int.MaxValue;
int max = int.MinValue;
double sum = 0;
double avg = 0;
while (!int.TryParse(Console.ReadLine(), out nNumber)|| nNumber < 0)
{
Console.Write("Invalid number!!! Please enter a valid positive integer: ");
}
for (int i = 0; i < nNumber; i++)
{
int numbers = int.Parse(Console.ReadLine());
min = Math.Min(min, numbers);
max = Math.Max(max, numbers);
sum += numbers;
avg = sum / nNumber;
}
Console.WriteLine("Min = " + min);
Console.WriteLine("Max = " + max);
Console.WriteLine("Sum = " + sum);
Console.WriteLine("Avg = {0:F2}", avg);
}
}
|
7688dd1ae91bedb7f71aaa01523abf25411c1b2c
|
C#
|
lei130102/GuidelinesVS
|
/WPF_Command/CustomCommand.xaml.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
//自定义命令
//本例定义了自定义命令requery,类型为RoutedUICommand,注意是静态字段,XAML中使用的是对应的静态属性
//注意,当使用自定义命令时,可能需要调用静态的CommandManager.InvalidateRequerySuggested()方法,通知WPF重新评估命令的状态,
//然后WPF会触发CanExecute事件,并更新使用该命令的任意命令源
namespace WPF_Command
{
public class DataCommands
{
private static RoutedUICommand requery;
static DataCommands()
{
InputGestureCollection inputs = new InputGestureCollection();
inputs.Add(new KeyGesture(Key.R, ModifierKeys.Control, "Ctrl+R"));
requery = new RoutedUICommand("Requery", "Requery", typeof(DataCommands), inputs);
//也可修改已有命令的RoutedCommand.InputGestures集合——例如,删除已有的键绑定或添加新的键绑定。甚至可添加鼠标绑定,
//从而当同时按下鼠标键和键盘上的修饰键时触发命令(尽管对于这种情况,可能希望只将命令绑定放置到鼠标处理起作用的元素上)
}
public static RoutedUICommand Requery
{
get
{
return requery;
}
}
}
/// <summary>
/// CustomCommand.xaml 的交互逻辑
/// </summary>
public partial class CustomCommand : Window
{
public CustomCommand()
{
InitializeComponent();
}
private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("Requery");
}
}
}
|