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
|
|---|---|---|---|---|---|---|
949531396d36e9c03119893d4c0b90ea7ba7a436
|
C#
|
ChristinaGislason/Lab05-OOPPrinciples
|
/Lab05-OOPPrinciples/Lab05-OOPPrinciples/Classes/Jaguar.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Lab05_OOPPrinciples.Classes
{
// Inheriting Feline class
public class Jaguar : Feline
{
public bool SpotsOnCoat { get; set; }
public string JungleHabitat { get; set; }
public override string Bites()
{
return "Jaguars bite!";
}
public override string Cry()
{
return "Jaguars roar to cry.";
}
}
}
|
738b97fabb888586b526bcf0bececf7e8fa76380
|
C#
|
mantvydasBra/OOP_homework
|
/skirtaUzduotis/loginScreen.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace skirtaUzduotis
{
public partial class loginScreen : Form
{
public loginScreen()
{
InitializeComponent();
}
//String to connect to LocalDB
string connectionStr = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\manta\source\repos\skirtaUzduotis\skirtaUzduotis\loginInformacija.mdf;Integrated Security=True";
//btn_Login Click event
private void btn_Login_Click_1(object sender, EventArgs e)
{
//checking if information is entered
if (txt_Username.Text == "" || txt_Password.Text == "")
{
MessageBox.Show("Įrašykite informaciją!");
return;
}
try
{
//Creating sql connection
SqlConnection con = new SqlConnection(connectionStr);
SqlCommand cmd = new SqlCommand("Select * from tbl_LoginInfo where UserName=@username and Password=@password", con);
//Adding reference
cmd.Parameters.AddWithValue("@username", txt_Username.Text);
cmd.Parameters.AddWithValue("@password", txt_Password.Text);
//Opening connection
con.Open();
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapt.Fill(ds);
con.Close();
int count = ds.Tables[0].Rows.Count;
//If count is equal to 1, then show Main form
if (count == 1)
{
MessageBox.Show("Sėkmingai prisijungta!");
this.Hide();
if (txt_Username.Text == "Admin")
{
frmAdmin fmA = new frmAdmin();
fmA.Show();
}
else
{
string surname = Convert.ToString(ds.Tables[0].Rows[0]["Surname"]);
int id = Convert.ToInt32(ds.Tables[0].Rows[0]["Id"]);
string personalID = Convert.ToString(ds.Tables[0].Rows[0]["PersonalID"]);
string fullName = txt_Username.Text + " " + surname;
FrmMain fm = new FrmMain(fullName, personalID);
fm.Text = fullName;
fm.DisplayExams(id);
fm.Show();
}
}
else
{
MessageBox.Show("Prisijungimas nesėkmingas. Patikrinkite įvestą informaciją.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void loginScreen_Closing(object sender, FormClosingEventArgs e)
{
Environment.Exit(0);
}
}
}
|
425e2df09a6c89e55aacd72cc7f17631a7269a7e
|
C#
|
shendongnian/download4
|
/code4/740559-17988332-44650886-6.cs
| 3.28125
| 3
|
public static class Program
{
static void Main(string[] args)
{
List<int> numList=new List<int>(){1,2,2,2,4,5,3,2};
numList = numList.RemoveSequentialRepeats();
}
public static List<T> RemoveSequentialRepeats<T>(this List<T> p_input) p_input)
{
var result = new List<T> { p_input.First() };
result.AddRange(p_input.Where(p_element => !result.Last().Equals(p_element)));
return result;
}
|
bd5b86e7f347db5614af747252214d6cf969a6f1
|
C#
|
Igorium/Leetcode
|
/hard/465. Optimal Account Balancing.txt.cs
| 3.21875
| 3
|
public class Solution {
public int MinTransfers(int[][] transactions) {
var balance = new Dictionary<int, int>();
foreach(var t in transactions){
if(!balance.ContainsKey(t[0]))
balance[t[0]] = 0;
if(!balance.ContainsKey(t[1]))
balance[t[1]] = 0;
balance[t[0]] += t[2];
balance[t[1]] -= t[2];
}
var d = balance.Values.Where(v => v != 0).ToArray();
var n = d.Length;
if(n == 0)
return 0;
int rebalance(int p){
while(p < n && d[p] == 0)
p++;
if(p == n)
return 0;
var count = int.MaxValue;
for(var i = p+1; i < n; i++){
if((d[p] > 0 && d[i] < 0) || (d[p] < 0 && d[i] > 0)){
d[i] += d[p];
count = Math.Min(count, rebalance(p+1)+1);
d[i] -= d[p];
}
}
return count;
}
return rebalance(0);
}
}
|
6cf043a66967a95db5af39802addf232593112b5
|
C#
|
vosonhiep/QuanLyQuanCF
|
/QuanLyQuanCafe/DAO/TableDAO.cs
| 2.828125
| 3
|
using QuanLyQuanCafe.DTO;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QuanLyQuanCafe.DAO
{
public class TableDAO
{
private static TableDAO instance;
public static TableDAO Instance
{
get { if (instance == null) instance = new TableDAO(); return TableDAO.instance; }
private set { TableDAO.instance = value; }
}
public static int TableWidth = 90;
public static int TableHeight = 90;
private TableDAO() { }
public void SwitchTable(int id1, int id2)
{
DataProvider.Instance.ExecuteQuery("USP_SwitchTable @idTable1 , @idTabel2", new object[] { id1, id2 });
}
public List<Table> LoadTableList()
{
List<Table> tableList = new List<Table>();
DataTable data = DataProvider.Instance.ExecuteQuery("Select * from TableFood where isUsed = 'true'");
foreach (DataRow item in data.Rows)
{
Table table = new Table(item);
tableList.Add(table);
}
return tableList;
}
public int GetMaxIdTable()
{
return (int)DataProvider.Instance.ExecuteScalar("select MAX(id) from TableFood ");
}
public bool InsertTable(string name, string status, bool isUsed)
{
string query = string.Format("INSERT dbo.TableFood( name, status, isUsed ) VALUES ( N'{0}', N'{1}', '{2}')", name, status, isUsed);
int result = DataProvider.Instance.ExecuteNonQuery(query);
return result > 0;
}
public bool UpdateTable(int idTable, string name, string status)
{
string query = string.Format("UPDATE dbo.TableFood SET name = N'{0}', status = N'{1}' WHERE id = {2}", name, status, idTable);
int result = DataProvider.Instance.ExecuteNonQuery(query);
return result > 0;
}
public Table GetTableById(int idTable)
{
string query = "select * from TableFood where id = " + idTable;
DataTable data = DataProvider.Instance.ExecuteQuery(query);
foreach (DataRow item in data.Rows)
{
return new Table(item);
}
return null;
}
public bool TableIsEmpty(int idTable)
{
Table item = GetTableById(idTable);
return item.Status.Equals("Trống") == true ? true : false;
}
public bool DeleteTable(int idTable)
{
if(TableIsEmpty(idTable))
{
string query = string.Format("UPDATE dbo.TableFood SET IsUsed = 'false' WHERE id = " + idTable);
int result = DataProvider.Instance.ExecuteNonQuery(query);
return result > 0;
}
return false;
}
public int DeleteTableEmpty(int idTable)
{
string query = string.Format("Delete dbo.TableFood WHERE id = " + idTable);
return (int)DataProvider.Instance.ExecuteNonQuery(query);
}
}
}
|
dafb84eee95a429de1ddc22b3bbc2953e0d720ab
|
C#
|
safaintegrated/asm
|
/DataAccess/Models/PuDeliveryAddressModel.cs
| 2.65625
| 3
|
using DataAccess.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess.Models
{
public class PuDeliveryAddressModel : BaseModel<PuDeliveryAddressModel>
{
public static IEnumerable<PuDeliveryAddress> FindAll()
{
return _db.PuDeliveryAddresses.AsEnumerable();
}
public static void Add(PuDeliveryAddress o)
{
_db.PuDeliveryAddresses.Add(o);
_db.SaveChanges();
}
//Update record
public static void Update(PuDeliveryAddress o)
{
var result = from r in _db.PuDeliveryAddresses where r.Id == o.Id select r;
_db.SaveChanges();
}
//Delete record
public static void Delete(PuDeliveryAddress o)
{
var result = from r in _db.PuDeliveryAddresses where r.Id == o.Id select r;
_db.PuDeliveryAddresses.Remove(result.FirstOrDefault());
_db.SaveChanges();
}
public static PuDeliveryAddress FindById(string id)
{
var result = from r in _db.PuDeliveryAddresses where r.Id == id select r;
return result.FirstOrDefault();
}
}
}
|
ee62e0a109c894d346f6927f76ab896274842587
|
C#
|
hakimoss/Rocket_Elevators_REST_API
|
/Controllers/UsersController.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using FactInterventionApi.Models;
namespace FactIntervention.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
private readonly FactInterventionContext _context;
public UsersController(FactInterventionContext context)
{
_context = context;
}
// GET: api/Users
[HttpGet]
public async Task<ActionResult<IEnumerable<Users>>> GetUsers()
{
return await _context.users.ToListAsync();
}
// [HttpGet("email/{email}")]
// public async Task<ActionResult<string>> GetUserEmail(string email)
// {
// IEnumerable<Users> usersAll = await _context.users.ToListAsync();
// foreach (Users user in usersAll)
// {
// if (user.email == email)
// {
// return user.email;
// }
// }
// return NotFound();
// }
[HttpGet("find/{email}")]
public ActionResult<Users> GetEmployeeEmail(string email)
{
var decodedEmail = System.Web.HttpUtility.UrlDecode(email);
Console.WriteLine(decodedEmail);
var employeeEmail = _context.users
.Where(u => u.email == decodedEmail);
//.FirstOrDefaultAsync();
if (employeeEmail == null)
{
return NotFound();
}
return Ok(employeeEmail);
}
// GET: api/Users/email
// [HttpGet("email/{email}")]
// public async Task<ActionResult<Users>> Getuser(string email)
// {
// var user = await _context.users.FindAsync(email);
// if (user == null)
// {
// return NotFound();
// }
// return user;
// }
// POST: api/Users
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
// [HttpPost]
// public async Task<ActionResult<Employee>> PostEmployee(Employee employee)
// {
// _context.employees.Add(employee);
// await _context.SaveChangesAsync();
// return CreatedAtAction("GetUsers", new { id = employee.Id }, employee);
// }
// private bool UsersExists(long id)
// {
// return _context.users.Any(e => e.Id == id);
// }
}
}
|
1a332457635687c78fffe7c1cd62bcb4d09d95e1
|
C#
|
Aegz/Turing
|
/SQLValidator/Parser/DataObjects/SQLQuery.cs
| 3
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SQLValidator.Lexer.DataObjects
{
public class SQLQuery
{
protected List<SQLStatement> aoStatements;
public List<SQLStatement> Statements
{
get
{
if (aoStatements == null)
{
aoStatements = new List<SQLStatement>();
}
return aoStatements;
}
set { aoStatements = value; }
}
public SQLQuery()
{
// Always start with one
Statements.Add(new SQLStatement());
}
public void AddStatement(SQLStatement xoChild)
{
//
Statements.Add(xoChild);
}
public override String ToString()
{
// Recursive call on children to get their string values
return (aoStatements != null ? String.Join("", Statements.Select((oVar) => oVar.ToString())) : "");
}
}
}
|
961cf76306340603d2375c7114ec6d7062acc061
|
C#
|
guojianbin/SugiBpm
|
/SugiBpm.Delegation/SugiBpm.Delegation.Interface/Evaluation.cs
| 3.015625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SugiBpm.Delegation.Interface
{
public sealed class Evaluation
{
public static readonly Evaluation APPROVE = new Evaluation("approve");
public static readonly Evaluation DISAPPROVE = new Evaluation("disapprove");
private string _name = null;
public static bool TryParseEvaluation(string text, out Evaluation evaluation)
{
try
{
evaluation = Evaluation.ParseEvaluation(text);
return true;
}
catch (FormatException)
{
evaluation = null;
return false;
}
}
public static Evaluation ParseEvaluation(string text)
{
if (text == null)
return null;
if (text.ToUpper().Equals(APPROVE.ToString().ToUpper()))
{
return APPROVE;
}
else
{
if (text.ToUpper().Equals(DISAPPROVE.ToString().ToUpper()))
{
return DISAPPROVE;
}
else
{
throw new FormatException("Couldn't parse " + text + " to a valid EvaluationResult");
}
}
}
private Evaluation(string name)
{
this._name = name;
}
public override string ToString()
{
return _name;
}
}
}
|
f051eaadcaec2843bd77838e0cb55e475652dfe6
|
C#
|
S-Oktay-Bicici/C-SHARP-PROGRAMMING
|
/2-Veri-Tipleri-ve-Değişkenler/tür-dönüşümü.cs
| 3.40625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace tür_dönüşümü
{
class Program
{
static void Main(string[] args)
{
//bilinçli ve bilinçsiz tür dönüşümleri vardır.
//Inplicit ve Explicit denir.
//kapalı bilinçsiz tür dönüşümü
double d = 12.3;
Console.WriteLine(d);
int i = 5;
d = i;
Console.WriteLine(d);
//bilinçli tür dönüşümü
double a = 12.3;
Console.WriteLine(a);
int b = 5;
b = Convert.ToInt32(a);
Console.WriteLine(d);
float f = 100.15f;
int x1 = (int)f;
int x2 = Convert.ToInt32(f);
//parse ile tür dönüşümü
string strNumber1 = "10";
string strNumber2 = "10C";
string strNUmber3 = "10,2";
int y1 = int.Parse(strNumber1);
int y2 = int.Parse(strNumber2); //hata vericek
int y3 = int.Parse(strNUmber3); //hata vericek
Console.WriteLine(y1);
Console.WriteLine(y2);
Console.WriteLine(y3);
//tryparse ile tür dönüşümü
int result;
string strNumber = "10K";
int.TryParse(strNumber, out result);
Console.WriteLine(result); //hata vermez yapamadığı için 0 verir result a
Console.ReadLine();
}
}
}
|
8c58c08480d43a1b0e51a9fbe67644ee9df389d1
|
C#
|
vgdagpin/Multi-Tenant-Sample
|
/MultiTenantSample.Application/Personnels/Commands/CreatePersonnelCommand.cs
| 2.546875
| 3
|
using System;
using System.Threading;
using System.Threading.Tasks;
using FluentValidation;
using MediatR;
using MultiTenantSample.Application.Personnels.Queries.Models;
using MultiTenantSample.Domain.Entities;
namespace MultiTenantSample.Application.Personnels.Commands
{
public class CreatePersonnelCommand : IRequest<TenantPersonnel>
{
#region Public members
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public DateTime Birthdate { get; set; }
public string Gender { get; set; }
#endregion
#region Handler
public class CreatePersonnelCommandHandler : IRequestHandler<CreatePersonnelCommand, TenantPersonnel>
{
private readonly IMediator mediator;
private readonly IMultiTenantSampleDbContext dbContext;
public CreatePersonnelCommandHandler(IMediator mediator, IMultiTenantSampleDbContext dbContext)
{
this.mediator = mediator;
this.dbContext = dbContext;
}
public async Task<TenantPersonnel> Handle(CreatePersonnelCommand request, CancellationToken cancellationToken)
{
var _retVal = new TenantPersonnel
{
FirstName = request.FirstName,
MiddleName = request.MiddleName,
LastName = request.LastName,
DOB = request.Birthdate,
Active = true,
PrefixId = 1,
GenderFk = new Gender
{
Name = request.Gender
}
};
dbContext.TenantPersonnels.Add(_retVal);
return _retVal;
}
}
#endregion
#region Validator
public class CreatePersonnelCommandValidator : AbstractValidator<CreatePersonnelCommand>
{
public CreatePersonnelCommandValidator()
{
RuleFor(a => a.FirstName)
.NotNull().WithMessage("Firstname is required")
.MaximumLength(50).WithMessage("Maximum character for FirstName is 50");
RuleFor(a => a.MiddleName)
.MaximumLength(50).WithMessage("Maximum character for MiddleName is 50");
RuleFor(a => a.LastName)
.NotNull().WithMessage("LastName is required")
.MaximumLength(50).WithMessage("Maximum character for LastName is 50");
RuleFor(a => a.Gender)
.NotNull().WithMessage("Gender is required")
.MaximumLength(25).WithMessage("Maximum character for Gender is 25");
}
}
#endregion
}
}
|
0dd21b9d1e090fead7b1c0902de0fc6bfd0c33c3
|
C#
|
pjanotti/signalfx-dotnet-tracing
|
/tracer/test/test-applications/integrations/Samples.NUnitTests/TestSuite.cs
| 2.8125
| 3
|
using System;
using System.Collections;
using System.Diagnostics;
using NUnit.Framework;
namespace Samples.NUnitTests
{
public class TestSuite
{
[OneTimeSetUp]
public void Setup()
{
var writer = TestContext.Progress;
writer.WriteLine($"Pid: {Process.GetCurrentProcess().Id}");
writer.WriteLine("Environment Variables:");
foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables())
{
writer.WriteLine($" {entry.Key} = {entry.Value}");
}
writer.WriteLine(string.Empty);
}
[Test]
public void SimplePassTest()
{
}
[Test]
[Ignore("Simple skip reason")]
public void SimpleSkipFromAttributeTest()
{
}
[Test]
public void SimpleErrorTest()
{
int i = 0;
int z = 0 / i;
}
// **********************************************************************************
[Test]
[Category("Category01")]
[Property("Compatibility", "Windows")]
[Property("Compatibility", "Linux")]
public void TraitPassTest()
{
}
[Test]
[Ignore("Simple skip reason")]
[Category("Category01")]
[Property("Compatibility", "Windows")]
[Property("Compatibility", "Linux")]
public void TraitSkipFromAttributeTest()
{
}
[Test]
[Category("Category01")]
[Property("Compatibility", "Windows")]
[Property("Compatibility", "Linux")]
public void TraitErrorTest()
{
int i = 0;
int z = 0 / i;
}
// **********************************************************************************
[Theory]
[TestCase(1, 1, 2)]
[TestCase(2, 2, 4)]
[TestCase(3, 3, 6)]
public void SimpleParameterizedTest(int xValue, int yValue, int expectedResult)
{
Assert.AreEqual(expectedResult, xValue + yValue);
}
[Theory]
[Ignore("Simple skip reason")]
[TestCase(1, 1, 2)]
[TestCase(2, 2, 4)]
[TestCase(3, 3, 6)]
public void SimpleSkipParameterizedTest(int xValue, int yValue, int expectedResult)
{
Assert.AreEqual(expectedResult, xValue + yValue);
}
[Theory]
[TestCase(1, 0, 2)]
[TestCase(2, 0, 4)]
[TestCase(3, 0, 6)]
public void SimpleErrorParameterizedTest(int xValue, int yValue, int expectedResult)
{
Assert.AreEqual(expectedResult, xValue / yValue);
}
// **********************************************************************************
[Test]
public void SimpleAssertPassTest()
{
Assert.Pass("The test passed.");
}
[Test]
public void SimpleAssertInconclusive()
{
Assert.Inconclusive("The test is inconclusive.");
}
}
[TestFixture("Test01")]
[TestFixture("Test02")]
public class TestFixtureTest
{
private string _name;
public TestFixtureTest(string name)
{
_name = name;
}
[Test]
public void Test()
{
Assert.Pass("Test is ok");
}
}
public class TestBase<T>
{
[Test]
public void IsNull()
{
Assert.IsNull(default(T));
}
}
public class TestString : TestBase<string>
{ }
}
|
df72374cf49be03ef533914a721d3cde7dcdd293
|
C#
|
patnir/TimeCardCloudServer
|
/ServerSide/clsQueryResults.cs
| 3.109375
| 3
|
using System;
using System.Data.SqlClient;
// This class works with clsDatabase to encapsulate the ADO.NET OleDb provider
// to create a layer of abstraction between our application code and ADO.NET. This
// allows us to change ADO.NET providers without affecting our application code.
public class clsQueryResults : IDisposable
{
private bool mEOF;
private SqlDataReader mDataReader = null;
public void Dispose()
{
if (mDataReader != null)
{
mDataReader.Close();
}
}
// Returns true when there are no more records/rows in the query results.
public bool EOF
{
get
{
return mEOF;
}
}
// Performs a query and sets the current record/row pointer to the first one.
public void Open(clsDatabase db, string sqlQuery)
{
mDataReader = db.ExecuteQuery(sqlQuery);
MoveNext();
}
// Moves to the next record/row and sets the EOF property.
public void MoveNext()
{
if (mDataReader.Read() == true)
{
mEOF = false;
}
else
{
mEOF = true;
}
}
// Closes the query results.
public void Close()
{
mDataReader.Close();
}
// Returns a reference to the value of the column name passed. If
// the value is null, a reasonable non-null value is returned instead.
public object GetColValue(string columnName)
{
int columnNumber = mDataReader.GetOrdinal(columnName);
if (mDataReader.IsDBNull(columnNumber) == false)
{
return mDataReader.GetValue(columnNumber);
}
else
{
switch (mDataReader.GetDataTypeName(columnNumber))
{
case "DBTYPE_I4": return 0; // int
case "DBTYPE_DATE": return DateTime.MaxValue;
case "DBTYPE_R4": return 0.00f;
case "DBTYPE_WLONGVARCHAR": return "";
case "DBTYPE_WVARCHAR": return "";
default:
throw new Exception ("Unexpected database type "
+ columnName + " = " + mDataReader.GetDataTypeName(columnNumber));
}
}
}
}
|
8b8c385b1f3ef41420e430277059f907ef4f7c02
|
C#
|
Ivan-Proskurin/Cashed
|
/DataAccess.Db/NamedModelQueryRepository.cs
| 2.75
| 3
|
using Cashed.DataAccess.Contract;
using System;
using System.Data.Entity;
using System.Threading.Tasks;
using Cashed.DataAccess.Contract.Base;
namespace Cashed.DataAccess.Db
{
public class NamedModelQueryRepository<T> : QueryRepository<T>, INamedModelQueryRepository<T>
where T : class, IHasId, IHasName
{
public NamedModelQueryRepository(DbSet<T> dbSet) : base(dbSet)
{
}
public async Task<T> GetByName(string name)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException(nameof(name));
var model = await Query.FirstOrDefaultAsync(x => x.Name.ToLower() == name.ToLower());
return model;
}
}
}
|
7e589d84f847d1920635c6de6a25ad591ec4a1b4
|
C#
|
darianbenito/doppler-currency
|
/Doppler.Currency/Services/TrmHandler.cs
| 2.59375
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using CrossCutting;
using CrossCutting.SlackHooksService;
using Doppler.Currency.Dtos;
using Doppler.Currency.Enums;
using Doppler.Currency.Settings;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
namespace Doppler.Currency.Services
{
public class TrmHandler : CurrencyHandler
{
public TrmHandler(
IHttpClientFactory httpClientFactory,
HttpClientPoliciesSettings httpClientPoliciesSettings,
IOptionsMonitor<CurrencySettings> serviceSettings,
ISlackHooksService slackHooksService,
ILogger<CurrencyHandler> logger) : base(httpClientFactory, httpClientPoliciesSettings, serviceSettings.Get("TrmService"), slackHooksService, logger) { }
public override async Task<EntityOperationResult<CurrencyDto>> Handle(DateTime date)
{
// Construct URL
Logger.LogInformation("building url to get html data.");
var dateUrl = System.Web.HttpUtility.UrlEncode($"{date:yyyy-MM-dd}");
var uri = new Uri($"{ServiceSettings.Url}{dateUrl}");
Logger.LogInformation("Building http request with url {uri}", uri);
var httpRequest = new HttpRequestMessage
{
RequestUri = uri,
Method = new HttpMethod("GET")
};
Logger.LogInformation("Sending request to Trm server.");
var client = HttpClientFactory.CreateClient();
var httpResponse = await client.SendAsync(httpRequest).ConfigureAwait(false);
Logger.LogInformation("Getting Html content of the Trm.");
var jsonContent = await httpResponse.Content.ReadAsStringAsync();
return await GetDataFromHtmlAsync(jsonContent, date);
}
private Task<EntityOperationResult<CurrencyDto>> GetDataFromHtmlAsync(string jsonContent, DateTime date)
{
var result = new EntityOperationResult<CurrencyDto>();
var data = JsonConvert.DeserializeObject<IList<TrmResponse>>(jsonContent);
if (data.Count() > 0)
{
result.Entity = new CurrencyDto
{
Date = $"{date.ToUniversalTime():yyyy-MM-dd}",
SaleValue = data.FirstOrDefault().Valor,
CurrencyName = ServiceSettings.CurrencyName,
CurrencyCode = ServiceSettings.CurrencyCode.ToUpper()
};
}
else
{
result.Entity = CreateCurrency(date, "0", ServiceSettings.CurrencyCode);
}
return Task.FromResult(result);
}
}
}
|
b5818948571b816a8cb173bdac7cd74f496616cd
|
C#
|
artgl42/Algorithms
|
/SortingLibrary/SortingLibrary/SortingMethod/MergeSort.cs
| 3.546875
| 4
|
using System;
using System.Linq;
namespace SortingLibrary
{
public class MergeSort : ISortingMethod
{
public ulong Sort<T>(T[] arrayForSort) where T : IComparable<T>
{
MergeSorting(arrayForSort).CopyTo(arrayForSort, 0);
return 0;
}
private T[] MergeSorting<T>(T[] arrayForSort) where T : IComparable<T>
{
if (arrayForSort.Length == 1) return arrayForSort;
var _middle = arrayForSort.Length >> 1;
var _leftArray = MergeSorting(arrayForSort.Take(_middle).ToArray());
var _rightArray = MergeSorting(arrayForSort.Skip(_middle).ToArray());
return Merge(_leftArray, _rightArray);
}
private T[] Merge<T>(T[] leftArray, T[] rightArray) where T : IComparable<T>
{
var _indexLeftArray = 0;
var _indexRightArray = 0;
T[] _mergedArray = new T[leftArray.Length + rightArray.Length];
for (int i = 0; i < _mergedArray.Length; i++)
{
if (_indexLeftArray < leftArray.Length && _indexRightArray < rightArray.Length)
{
_mergedArray[i] = leftArray[_indexLeftArray].CompareTo(rightArray[_indexRightArray]) > 0 ? rightArray[_indexRightArray++] : leftArray[_indexLeftArray++];
}
else
{
_mergedArray[i] = _indexRightArray < rightArray.Length ? rightArray[_indexRightArray++] : leftArray[_indexLeftArray++];
}
}
return _mergedArray;
}
}
}
|
ff457b971cfd080713887f9b5f2455ee4fd2688a
|
C#
|
taglia90/Swimmy
|
/DB/Annuncio.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySql.Data.MySqlClient;
namespace Swimmy.DB
{
public class Annuncio
{
private int idAnnuncio;
private int idUtente;
private string titolo;
private string descrizione;
private string regione;
private string provincia;
private string citta;
private string indirizzo;
private string telefono;
private string urlFotoPrincipale;
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
MySql.Data.MySqlClient.MySqlDataReader reader;
String queryStr;
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["MySqlConnection"].ToString();
public Annuncio()
{
}
public int InserisciAnnuncio(int idUtente, string titolo, string descrizione, string regione, string provincia, string citta, string indirizzo, string telefono)
{
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "INSERT INTO swimmy.annuncio (idUtente, titolo, descrizione, regione, provincia, citta, indirizzo, telefono) VALUES(?idu, ?titolo,?descr, ?reg, ?pro, ?citta, ?indirizzo, ?telefono);" +
"SELECT LAST_INSERT_ID();";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("?idu", idUtente);
cmd.Parameters.AddWithValue("?titolo", titolo);
cmd.Parameters.AddWithValue("?descr", descrizione);
cmd.Parameters.AddWithValue("?reg", regione);
cmd.Parameters.AddWithValue("?pro", provincia);
cmd.Parameters.AddWithValue("?citta", citta);
cmd.Parameters.AddWithValue("?indirizzo", indirizzo);
cmd.Parameters.AddWithValue("?telefono", telefono);
reader = cmd.ExecuteReader();
int idAnnuncio = -1;
if (reader.HasRows)
{
while (reader.Read())
{
idAnnuncio = reader.GetInt32(0);
}
}
reader.Close();
conn.Close();
return idAnnuncio;
}
public Annuncio GetAnnuncio(int idAnnuncio)
{
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "SELECT * FROM swimmy.annuncio WHERE idAnnuncio=?idA;";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("?idA", idAnnuncio);
reader = cmd.ExecuteReader();
Annuncio a = new Annuncio();
if (reader.HasRows)
{
while (reader.Read())
{
a.IdAnnuncio = idAnnuncio;
a.IdUtente = Convert.ToInt32(reader["idUtente"]);
a.Titolo = reader["titolo"].ToString();
a.Descrizione = reader["descrizione"].ToString();
a.Regione = reader["regione"].ToString();
a.Provincia = reader["provincia"].ToString();
a.Citta = reader["citta"].ToString();
a.Indirizzo = reader["indirizzo"].ToString();
a.Telefono = reader["telefono"].ToString();
}
}
reader.Close();
conn.Close();
return a;
}
public int InserisciFoto(int idUtente, int idAnnuncio, string urlFoto)
{
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "INSERT INTO swimmy.foto (idUtente, idAnnuncio, urlFoto) VALUES(?idu, ?ida,?url);" +
"SELECT LAST_INSERT_ID();";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("?idu", idUtente);
cmd.Parameters.AddWithValue("?ida", idAnnuncio);
cmd.Parameters.AddWithValue("?url", urlFoto);
reader = cmd.ExecuteReader();
int idFoto = -1;
if (reader.HasRows)
{
while (reader.Read())
{
idFoto = reader.GetInt32(0);
}
}
reader.Close();
conn.Close();
return idFoto;
}
public List<string> getListaFotoDiAnnuncio(int idAnnuncio)
{
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "SELECT urlFoto FROM swimmy.foto WHERE idAnnuncio=?ida;";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("?ida", idAnnuncio);
reader = cmd.ExecuteReader();
List<string> listaFoto = new List<string>();
if (reader.HasRows)
{
while (reader.Read())
{
listaFoto.Add(reader["urlFoto"].ToString());
}
}
reader.Close();
conn.Close();
return listaFoto;
}
public List<string> GetProvinceDaRegione(string regione)
{
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "SELECT provincia FROM swimmy.regione_province WHERE regione=?reg;";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("?reg", regione);
reader = cmd.ExecuteReader();
List<string> province = new List<string>();
if (reader.HasRows)
{
while (reader.Read())
{
province.Add(reader.GetString(0));
}
}
reader.Close();
conn.Close();
return province;
}
public List<Annuncio> getListaAnnunci(string regione, string provincia, string citta)
{
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
//queryStr = "SELECT * FROM swimmy.annuncio WHERE regione=?reg AND provincia LIKE ?pro AND citta LIKE ?cit;";
queryStr = "SELECT a.*, f.urlFoto FROM swimmy.annuncio a LEFT JOIN swimmy.foto f" +
" ON a.idAnnuncio = f.idAnnuncio" +
" WHERE regione=?reg AND provincia LIKE ?pro AND citta LIKE ?cit" +
" GROUP BY a.idAnnuncio;";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("?reg", regione);
cmd.Parameters.AddWithValue("?pro", "%" + provincia + "%");
cmd.Parameters.AddWithValue("?cit", "%" + citta + "%");
reader = cmd.ExecuteReader();
List<Annuncio> listaAnnunci = new List<Annuncio>();
if (reader.HasRows)
{
while (reader.Read())
{
var annuncio = new Annuncio();
annuncio.IdAnnuncio = Convert.ToInt32(reader["idAnnuncio"]);
annuncio.IdUtente = Convert.ToInt32(reader["idUtente"]);
annuncio.Titolo = reader["titolo"].ToString();
annuncio.Descrizione = reader["descrizione"].ToString();
annuncio.Regione = reader["regione"].ToString();
annuncio.Provincia = reader["provincia"].ToString();
annuncio.Citta = reader["citta"].ToString();
annuncio.Indirizzo = reader["indirizzo"].ToString();
annuncio.Telefono = reader["telefono"].ToString();
annuncio.UrlFotoPrincipale = reader["urlFoto"].ToString();
listaAnnunci.Add(annuncio);
}
}
reader.Close();
conn.Close();
return listaAnnunci;
}
public List<Annuncio> getListaAnnunciDiUtente(int idUtente)
{
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "SELECT a.*, f.urlFoto FROM swimmy.annuncio a LEFT JOIN swimmy.foto f" +
" ON a.idAnnuncio = f.idAnnuncio" +
" WHERE a.idUtente=?idu" +
" GROUP BY a.idAnnuncio;";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("?idu", idUtente);
reader = cmd.ExecuteReader();
List<Annuncio> listaAnnunci = new List<Annuncio>();
if (reader.HasRows)
{
while (reader.Read())
{
var annuncio = new Annuncio();
annuncio.IdAnnuncio = Convert.ToInt32(reader["idAnnuncio"]);
annuncio.IdUtente = Convert.ToInt32(reader["idUtente"]);
annuncio.Titolo = reader["titolo"].ToString();
annuncio.Descrizione = reader["descrizione"].ToString();
annuncio.Regione = reader["regione"].ToString();
annuncio.Provincia = reader["provincia"].ToString();
annuncio.Citta = reader["citta"].ToString();
annuncio.Indirizzo = reader["indirizzo"].ToString();
annuncio.Telefono = reader["telefono"].ToString();
annuncio.UrlFotoPrincipale = reader["urlFoto"].ToString();
listaAnnunci.Add(annuncio);
}
}
reader.Close();
conn.Close();
return listaAnnunci;
}
#region getters & setters
public int IdAnnuncio
{
get { return idAnnuncio; }
set { idAnnuncio = value; }
}
public int IdUtente
{
get { return idUtente; }
set { idUtente = value; }
}
public string Titolo
{
get { return titolo; }
set { titolo = value; }
}
public string Descrizione
{
get { return descrizione; }
set { descrizione = value; }
}
public string Regione
{
get { return regione; }
set { regione = value; }
}
public string Provincia
{
get { return provincia; }
set { provincia = value; }
}
public string Citta
{
get { return citta; }
set { citta = value; }
}
public string Indirizzo
{
get { return indirizzo; }
set { indirizzo = value; }
}
public string Telefono
{
get { return telefono; }
set { telefono = value; }
}
public string UrlFotoPrincipale
{
get { return urlFotoPrincipale; }
set { urlFotoPrincipale = value; }
}
#endregion
}
}
|
0430684e7b78b43dbad66ce96452d82fe9a17b3b
|
C#
|
szefo09/YgoProPatcher
|
/YgoProPatcher/LocalData.cs
| 2.640625
| 3
|
using Octokit;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YgoProPatcher
{
public class LocalData
{
private readonly static string saveLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "YgoProPatcher");
static private void CreateDirIfMissing()
{
if (!Directory.Exists(saveLocation))
{
Directory.CreateDirectory(saveLocation);
}
}
static public List<string> LoadFileToList(string fileName)
{
string saveFile = Path.Combine(saveLocation, fileName);
if (Directory.Exists(saveLocation) && File.Exists(saveFile))
{
return File.ReadAllLines(saveFile).ToList<string>();
}
else
{
//returns null to use array?[]
return null;
}
}
static public void SaveFile(List<string> List,string fileName)
{
CreateDirIfMissing();
File.WriteAllLines(Path.Combine(saveLocation, fileName), List);
}
static public void SaveSHA(List<GitHubCommit> commits)
{
List<string> commitSHA = new List<string>();
foreach(var commit in commits)
{
commitSHA.Add(commit.Sha);
}
SaveFile(commitSHA, "SHAs");
}
}
}
|
3b825f1d00d8d0185d51c24da18fbb25795a7193
|
C#
|
VKeCRM/V2
|
/Framework/VKeCRM.Common/NamedPipe/ClientNamedPipe.cs
| 2.578125
| 3
|
using System;
using System.Threading;
using System.IO.Pipes;
using VKeCRM.Common.Logging;
namespace VKeCRM.Common.NamedPipe
{
public class ClientNamedPipe : NamedPipeBase<NamedPipeClientStream>, IDisposable
{
#region Fields
private const int OneSecond = 1000;
private const int connectionTimeout = 60 * OneSecond; // 1 minute
private const int sleepingTime = OneSecond;
#endregion
#region Constructor
public ClientNamedPipe(string pipeName)
: base(pipeName)
{
}
public ClientNamedPipe(string pipeName, Logger logger)
: base(pipeName, logger)
{
}
#endregion
#region Properties
protected override bool AutoFlushPipeWriter
{
get { return true; }
}
#endregion
#region Methods
protected override NamedPipeClientStream CreatePipe()
{
NamedPipeClientStream stream = new NamedPipeClientStream(".",
PipeName,
PipeDirection.InOut,
PipeOptions.Asynchronous);
stream.Connect(connectionTimeout);
stream.ReadMode = PipeTransmissionMode.Message;
return stream;
}
/// <summary>
/// Method that runs on the ThreadPool for reading messages from the pipe.
/// </summary>
/// <param name="state"></param>
protected override void ReadFromPipe()
{
int timeElapsed = 0;
System.Threading.Thread messageReader = new System.Threading.Thread(new System.Threading.ThreadStart(ReadMessage));
messageReader.Name = "MessageReader";
try
{
while (Pipe != null && IsListening == true)
{
if (Pipe.IsConnected == true)
{
// reset time elapsed
timeElapsed = 0;
// sleep for 100 milliseconds to wait for message to be read from the pipe
System.Threading.Thread.Sleep(100);
if (messageReader.ThreadState == System.Threading.ThreadState.WaitSleepJoin && !string.IsNullOrEmpty(Message))
{
InvokeOnReceivedMessage(Message);
ClearMessage();
}
else if (messageReader.ThreadState == System.Threading.ThreadState.Unstarted)
{
messageReader.Start();
}
else if (messageReader.ThreadState == System.Threading.ThreadState.Stopped ||
messageReader.ThreadState == System.Threading.ThreadState.Aborted)
{
messageReader = new System.Threading.Thread(new System.Threading.ThreadStart(ReadMessage));
}
}
else
{
Thread.Sleep(sleepingTime);
timeElapsed += sleepingTime;
if (timeElapsed >= connectionTimeout)
{
TimeoutException timeoutException = new TimeoutException("Client Name Pipe Connection Timeout.");
IsListening = false;
_pipeReadExceptions.Add(timeoutException);
LogError(timeoutException.ToString());
break;
}
}
}
}
catch (Exception ex)
{
IsListening = false;
_pipeReadExceptions.Add(ex);
LogError(ex.ToString());
}
}
/// <summary>
/// Writes message to pipe
/// </summary>
/// <param name="message">The message to be written to the pipe.</param>
public override void WriteToPipe(string message)
{
try
{
// wait for connection if client is not yet connected
if (!Pipe.IsConnected)
{
LogMessage("The client named pipe is not connected and is trying to reconnect for one minute.");
Pipe.Connect(connectionTimeout);
}
// wait for pipe to be read
Pipe.WaitForPipeDrain();
// write message to the pipe
WriteMessage(message);
// wait for pipe to be read
Pipe.WaitForPipeDrain();
}
catch (Exception ex)
{
IsListening = false;
LogError(ex.ToString());
throw ex;
}
}
/// <summary>
/// Dispose underlying resources
/// </summary>
public void Dispose()
{
Pipe.Close();
Pipe.Dispose();
}
#endregion
}
}
|
3ae4c1602171db78a947bfef8152d03837a4018f
|
C#
|
Derian37/SistemaOpticaSantaMarta
|
/CapaLogica/LogicaNegocio/Producto.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CapaLogica.LogicaNegocio
{
/// <summary>
/// Description of Producto.
/// </summary>
public class Producto
{
#region ATRIBUTOS
private int Monto;
private string Codig;
private string Codigo;
private string Detalle;
private string Nombre;
private int Cantidad;
private string Marca;
private string Tipo;
private string Iva;
private string Estado;
#endregion ATRIBUTOS
#region CONSTRUCTOR
public Producto()
{
}
//constructor para el procedimiento almacenado de insertar
public Producto(string Pcodigo, string Pnombre, string Pdetalle, int Pmonto, int Pcantidad, string Pmarca, string Ptipo, string Piva, string Pestado)
{
codigo = Pcodigo;
nombre = Pnombre;
detalle = Pdetalle;
monto = Pmonto;
cantidad = Pcantidad;
marca = Pmarca;
tipo = Ptipo;
iva = Piva;
estado = Pestado;
}
//constructor para el procedimiento almacenado de modificar
public Producto(string Pcodig, string Pcodigo, string Pnombre, string Pdetalle, int Pmonto, int Pcantidad, string Pmarca, string Ptipo, string Piva, string Pestado)
{
codig = Pcodig;
codigo = Pcodigo;
nombre = Pnombre;
detalle = Pdetalle;
monto = Pmonto;
cantidad = Pcantidad;
marca = Pmarca;
tipo = Ptipo;
iva = Piva;
estado = Pestado;
}
//Constructor para el procedimiento almacenado de Inactivar, eliminar y consultar
public Producto(string Pcodigo)
{
codigo = Pcodigo;
}
#endregion CONSTRUCTOR
#region get y set
public string codig
{
get
{
return Codig;
}
set
{
Codig = value;
}
}
public string codigo
{
get
{
return Codigo;
}
set
{
Codigo = value;
}
}
public int monto
{
get
{
return Monto;
}
set
{
Monto = value;
}
}
public string detalle
{
get
{
return Detalle;
}
set
{
Detalle = value;
}
}
public string nombre
{
get
{
return Nombre;
}
set
{
Nombre = value;
}
}
public int cantidad
{
get
{
return Cantidad;
}
set
{
Cantidad = value;
}
}
public string marca
{
get
{
return Marca;
}
set
{
Marca = value;
}
}
public string tipo
{
get
{
return Tipo;
}
set
{
Tipo = value;
}
}
public string iva
{
get
{
return Iva;
}
set
{
Iva = value;
}
}
public string estado
{
get
{
return Estado;
}
set
{
Estado = value;
}
}
#endregion get y set
}
}
|
b7bc5d52c08bac4afd86170dc9f0e58e7cb207bb
|
C#
|
todo-it/philadelphia
|
/Philadelphia.Web/Mvp/LocalValueFieldBuilder.cs
| 2.671875
| 3
|
using System;
using System.Text.RegularExpressions;
using Bridge;
using Philadelphia.Common;
namespace Philadelphia.Web {
public static class LocalValueFieldBuilder {
public static LocalValue<T> Build<WidgetT,T>(
IReadWriteValueView<WidgetT,T> view, params Validate<T>[] validators) {
var result = new LocalValue<T>(default(T), default(T));
view.BindReadWriteAndInitialize(result);
validators.ForEach(y => result.AddValidatorAndRevalidate(y));
return result;
}
public static LocalValue<T> Build<WidgetT,T>(T defaultValue,
IReadWriteValueView<WidgetT,T> view, params Validate<T>[] validators) {
var result = new LocalValue<T>(defaultValue, default(T));
view.BindReadWriteAndInitialize(result);
validators.ForEach(y => result.AddValidatorAndRevalidate(y));
return result;
}
public static LocalValue<DateTime?> BuildDateTimePicker(
DateTimePickerView view, DateTime? defaultValue = null,
params Validate<DateTime?>[] validators) {
var result = new LocalValue<DateTime?>(defaultValue);
view.BindReadWriteAndInitialize(result);
validators.ForEach(y => result.AddValidatorAndRevalidate(y));
return result;
}
/// <param name="domainToView">doesn't need to handle nulls/empty values</param>
/// <param name="viewToDomain">doesn't need to handle nulls/empty values</param>
public static LocalValue<DataT> BuildNullableDropdown<WidgetT,DataT>(
Func<DataT,string> domainToView,
Func<string,DataT> viewToDomain,
// REVIEW: make view be of some new class or make it ValueTuple with element names
IReadWriteValueView<WidgetT,Tuple<string,string>> view, params Validate<DataT>[] validators)
where DataT:class {
return Build(null, view,
x => Tuple.Create(x == null ? "" : domainToView(x), ""), //2nd param is irrelevant
x => string.IsNullOrEmpty(x.Item1) ? null : viewToDomain(x.Item1),
validators);
}
public static LocalValue<DataT> BuildChoice<WidgetT,DataT>(
DataT defaultVal,
Func<string,DataT> viewToDomain,
// REVIEW: make view be of some new class or make it ValueTuple with element names
IReadWriteValueView<WidgetT,Tuple<string,string>> view, params Validate<DataT>[] validators) {
return Build(defaultVal, view,
x => Tuple.Create(x.ToString(), ""), //2nd param is irrelevant
x => {
if (string.IsNullOrEmpty(x.Item1)) {
throw new Exception("cannot have null value in non nullable enum dropdown");
}
return viewToDomain(x.Item1);
},
validators);
}
//T should be enum but impossible to give such constraint. Using:
//http://stackoverflow.com/questions/79126/create-generic-method-constraining-t-to-an-enum
//but thrown out IConvertible doesn't seem to work in bridge.net
public static LocalValue<EnumT> BuildEnumBasedChoice<WidgetT,EnumT>(
EnumT defaultVal,
// REVIEW: make view be of some new class or make it ValueTuple with element names
IReadWriteValueView<WidgetT,Tuple<string,string>> view, params Validate<EnumT>[] validators)
where EnumT:struct {
return Build(defaultVal, view,
x => Tuple.Create(x.ToString(), ""), //2nd param is irrelevant
x => {
if (string.IsNullOrEmpty(x.Item1)) {
throw new Exception("cannot have null value in non nullable enum dropdown");
}
return (EnumT)(object)Convert.ToInt32(x.Item1);
},
validators);
}
public static LocalValue<T> BuildGeneralChoice<WidgetT,T>(
T defaultVal,
Func<int,T> intToItem,
Func<T,int> itemToInt,
// REVIEW: make view be of some new class or make it ValueTuple with element names
IReadWriteValueView<WidgetT,Tuple<string,string>> view, params Validate<T>[] validators) {
return Build(defaultVal, view,
x => Tuple.Create(itemToInt(x) + "", ""), //2nd param is irrelevant
x => {
if (string.IsNullOrEmpty(x.Item1)) {
throw new Exception("cannot have null value in non nullable enum dropdown");
}
return intToItem(Convert.ToInt32(x.Item1));
},
validators);
}
//T should be enum but impossible to give such constraint. Using:
//http://stackoverflow.com/questions/79126/create-generic-method-constraining-t-to-an-enum
//but thrown out IConvertible doesn't seem to work in bridge.net
public static LocalValue<EnumT?> BuildNullableEnumBasedDropdown<WidgetT,EnumT>(
// REVIEW: make view be of some new class or make it ValueTuple with element names
IReadWriteValueView<WidgetT,Tuple<string,string>> view, params Validate<EnumT?>[] validators)
where EnumT:struct {
return Build(null, view,
x => Tuple.Create(x.ToString(), ""), //2nd param is irrelevant
x => string.IsNullOrEmpty(x.Item1) ? (EnumT?)null : (EnumT)(object)Convert.ToInt32(x.Item1),
validators);
}
//T should be enum but impossible to give such constraint. Using:
//http://stackoverflow.com/questions/79126/create-generic-method-constraining-t-to-an-enum
//but thrown out IConvertible doesn't seem to work in bridge.net
public static LocalValue<EnumT?> BuildNullableEnumBasedDropdown<WidgetT,EnumT>(
EnumT defaultVal,
// REVIEW: make view be of some new class or make it ValueTuple with element names
IReadWriteValueView<WidgetT,Tuple<string,string>> view, params Validate<EnumT?>[] validators)
where EnumT:struct {
return Build(defaultVal, view,
x => Tuple.Create(x.ToString(), ""), //2nd param is irrelevant
x => string.IsNullOrEmpty(x.Item1) ? (EnumT?)null : (EnumT)(object)Convert.ToInt32(x.Item1),
validators);
}
public static LocalValue<int> BuildIntBasedDropdown<WidgetT>(
int defaultValue,
// REVIEW: make view be of some new class or make it ValueTuple with element names
IReadWriteValueView<WidgetT,Tuple<string,string>> view,
params Validate<int>[] validators) {
return Build(defaultValue, view,
x => Tuple.Create(x.ToString(), ""), //2nd param is irrelevant
x => x.Item1 == "" ? -1 : Convert.ToInt32(x.Item1),
validators);
}
public static LocalValue<string> BuildStringBasedDropdown<WidgetT>(
// REVIEW: make view be of some new class or make it ValueTuple with element names
IReadWriteValueView<WidgetT,Tuple<string,string>> view, params Validate<string>[] validators) {
return Build(null, view,
x => Tuple.Create(x != null ? x : "", ""), //2nd param is irrelevant
x => string.IsNullOrEmpty(x?.Item1) ? null : x.Item1,
validators);
}
public static LocalValue<int?> BuildNullableIntBasedDropdown<WidgetT>(
// REVIEW: make view be of some new class or make it ValueTuple with element names
IReadWriteValueView<WidgetT,Tuple<string,string>> view, params Validate<int?>[] validators) {
return Build(null, view,
x => Tuple.Create(x.HasValue ? x.Value.ToString() : "", ""), //2nd param is irrelevant
x => string.IsNullOrEmpty(x?.Item1) ? (int?)null : Convert.ToInt32(x.Item1),
validators);
}
public static LocalValue<ModelT> Build<WidgetT,ModelT,ViewT>(
ModelT defaultValue, IReadWriteValueView<WidgetT,ViewT> view,
Func<ModelT,ViewT> convertFromDomain, Func<ViewT,ModelT> convertToDomain,
params Validate<ModelT>[] validators) {
var result = new LocalValue<ModelT>(defaultValue);
view.BindReadWriteAndInitialize(result, convertFromDomain, convertToDomain);
validators.ForEach(y => result.AddValidatorAndRevalidate(y));
return result;
}
public static LocalValue<ModelT> Build<WidgetT,ModelT,ViewT>(
ModelT defaultValue, IReadOnlyValueView<WidgetT,ViewT> view,
Func<ModelT,ViewT> convertFromDomain,
params Validate<ModelT>[] validators) {
var result = new LocalValue<ModelT>(defaultValue);
view.BindReadOnlyAndInitialize(result, convertFromDomain);
validators.ForEach(y => result.AddValidatorAndRevalidate(y));
return result;
}
public static LocalValue<ModelT> Build<WidgetT,ModelT,ViewT>(
IReadOnlyValueView<WidgetT,ViewT> view, Func<ModelT,ViewT> convertFromDomain,
params Validate<ModelT>[] validators) {
var result = new LocalValue<ModelT>(default(ModelT));
view.BindReadOnlyAndInitialize(result, convertFromDomain);
validators.ForEach(y => result.AddValidatorAndRevalidate(y));
return result;
}
public static LocalValue<DataT> Build<WidgetT,DataT>(
DataT defaultValue, IReadOnlyValueView<WidgetT,DataT> view,
params Validate<DataT>[] validators) {
var result = new LocalValue<DataT>(defaultValue);
view.BindReadOnlyAndInitialize(result, x => x);
validators.ForEach(y => result.AddValidatorAndRevalidate(y));
return result;
}
public static LocalValue<DataT> Build<WidgetT,DataT>(
IReadOnlyValueView<WidgetT,DataT> view, params Validate<DataT>[] validators) {
var result = new LocalValue<DataT>(default(DataT));
view.BindReadOnlyAndInitialize(result, x => x);
validators.ForEach(y => result.AddValidatorAndRevalidate(y));
return result;
}
public static LocalValue<decimal> BuildDecimal<WidgetT>(
IReadOnlyValueView<WidgetT,string> view, DecimalFormat format, params Validate<decimal>[] validators) {
var result = new LocalValue<decimal>(0);
view.BindReadOnlyAndInitialize(result,
x => I18n.Localize(x, format));
validators.ForEach(y => result.AddValidatorAndRevalidate(y));
return result;
}
public static LocalValue<decimal> BuildDecimal(
InputView view, DecimalFormat format, params Validate<decimal>[] validators) {
view.RaisesChangedOnKeyPressed = false;
var result = new LocalValue<decimal>(0);
view.BindReadWriteAndInitialize(result,
x => I18n.Localize(x, format),
x => I18n.ParseDecimal(x));
validators.ForEach(y => result.AddValidatorAndRevalidate(y));
return result;
}
public static LocalValue<decimal?> BuildNullableDecimal(
InputView view, DecimalFormat format, params Validate<decimal?>[] validators) {
view.RaisesChangedOnKeyPressed = false;
var result = new LocalValue<decimal?>(null);
view.BindReadWriteAndInitialize(result,
x => !x.HasValue ? "" : I18n.Localize(x.Value, format),
x => string.IsNullOrEmpty(x) ? (decimal?)null : I18n.ParseDecimal(x));
validators.ForEach(y => result.AddValidatorAndRevalidate(y));
return result;
}
public static LocalValue<decimal> BuildDecimalWithPrecision<WidgetT>(
IReadOnlyValueView<WidgetT,string> view, decimal defaultValue, Func<int> getPrecision,
params Validate<decimal>[] validators) {
var result = new LocalValue<decimal>(defaultValue);
view.BindReadOnlyAndInitialize(result,
x => I18n.Localize(x, DecimalFormatExtensions.GetWithPrecision(getPrecision())));
validators.ForEach(y => result.AddValidatorAndRevalidate(y));
return result;
}
public static LocalValue<decimal> BuildDecimalWithPrecision(
InputView view, decimal defaultValue, Func<int> getPrecision,
params Validate<decimal>[] validators) {
var result = new LocalValue<decimal>(defaultValue);
view.RaisesChangedOnKeyPressed = false;
view.BindReadWriteAndInitialize(result,
x => I18n.Localize(x, DecimalFormatExtensions.GetWithPrecision(getPrecision())),
x => I18n.ParseDecimalWithoutLoss(x, getPrecision()));
validators.ForEach(y => result.AddValidatorAndRevalidate(y));
return result;
}
public static LocalValue<decimal?> BuildNullableDecimalWithPrecision(
InputView view, Func<int> getPrecision, params Validate<decimal?>[] validators) {
view.RaisesChangedOnKeyPressed = false;
var result = new LocalValue<decimal?>(null);
view.BindReadWriteAndInitialize(result,
x => !x.HasValue ?
""
:
I18n.Localize(x.Value, DecimalFormatExtensions.GetWithPrecision(getPrecision())),
x => string.IsNullOrEmpty(x) ?
(decimal?)null
:
I18n.ParseDecimalWithoutLoss(x, getPrecision()));
validators.ForEach(y => result.AddValidatorAndRevalidate(y));
return result;
}
public static LocalValue<int?> BuildNullableInt<WidgetT>(
int? defaultValue, IReadWriteValueView<WidgetT,string> view,
params Validate<int?>[] validators) {
var result = new LocalValue<int?>(defaultValue);
view.BindReadWriteAndInitialize(result,
x => !x.HasValue ? "" : I18n.Localize(x.Value),
x => string.IsNullOrEmpty(x) ? (int?)null : I18n.ParseInt(x));
validators.ForEach(y => result.AddValidatorAndRevalidate(y));
return result;
}
public static LocalValue<int?> BuildNullableInt<WidgetT>(
IReadWriteValueView<WidgetT,string> view,
params Validate<int?>[] validators) {
return BuildNullableInt(null, view, validators);
}
public static LocalValue<int> BuildInt<WidgetT>(
IReadOnlyValueView<WidgetT,string> view, params Validate<int>[] validators) {
var result = new LocalValue<int>(0);
view.BindReadOnlyAndInitialize(result, x => I18n.Localize(x));
validators.ForEach(y => result.AddValidatorAndRevalidate(y));
return result;
}
public static LocalValue<int> BuildInt<WidgetT>(
IReadWriteValueView<WidgetT,string> view, params Validate<int>[] validators) {
return BuildInt(0, view, validators);
}
public static LocalValue<int> BuildInt<WidgetT>(
int defaultvalue, IReadWriteValueView<WidgetT,string> view, params Validate<int>[] validators) {
var result = new LocalValue<int>(defaultvalue);
view.BindReadWriteAndInitialize(result, x => I18n.Localize(x), x => {
try {
var val = I18n.ParseInt(x);
return val;
} catch (Exception ex) {
Logger.Error(typeof(LocalValueFieldBuilder), "BuildInt converter got exception {0}", ex);
throw new Exception(
I18n.Translate("Wrong integer format entered. Remove letters or special characters"));
}
});
validators.ForEach(y => result.AddValidatorAndRevalidate(y));
return result;
}
}
}
|
204a476b29ffff16e4ff4f8b3cbd490ebaebd98d
|
C#
|
sh1ch/Samples
|
/DisposableTest/DisposableTest/Program.cs
| 3.25
| 3
|
using System;
namespace DisposableTest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var program = new Program();
program.Run();
}
public DisposableEventHandler<int> Sample = new DisposableEventHandler<int>();
public void Run()
{
Console.WriteLine("---");
Test1();
Sample.Dispose();
Console.WriteLine("---");
Test2();
}
public void Test1()
{
Sample.SubScribe((sender, args) =>
{
Console.WriteLine($"{sender}.{args}");
});
Sample.Raise(this, 1);
Sample.Raise(this, 2);
}
public void Test2()
{
using (var sample = new DisposableEventHandler<string>())
{
sample.SubScribe((sender, args) =>
{
Console.WriteLine($"{sender}={args}");
});
sample.SubScribe((sender, args) =>
{
Console.WriteLine($"{sender}+{args}");
});
sample.Raise(this, "ランス");
sample.Raise(this, "シィル");
}
}
}
}
|
c0953a37d26e63b546cc0408eff741e2c7b17fd3
|
C#
|
pipecaniza/OneCore.Demo
|
/OneCore.Demo/Models/ManageViewModels/IndexViewModel.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace OneCore.Demo.Models.ManageViewModels
{
public class IndexViewModel
{
public string Id { get; set; }
[Required(ErrorMessage = "El campo Usuario es requerido")]
[MinLength(7, ErrorMessage = "El campo Usuario debe contener al menos 7 caracteres.")]
[Display(Name = "Usuario")]
public string User { get; set; }
[Required(ErrorMessage = "El campo Email es requerido")]
[EmailAddress(ErrorMessage = "El campo Email no es un correo electrónico válido.")]
public string Email { get; set; }
[Required(ErrorMessage = "El campo Sexo es requerido")]
[Display(Name = "Sexo")]
public string Gender { get; set; }
[StringLength(100, ErrorMessage = "La {0} debe contener al menos {2} y máximo {1} caractéres de longitud.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Nueva contraseña")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirmar nueva contraseña")]
[Compare("NewPassword", ErrorMessage = "La contraseña no coincide.")]
public string ConfirmPassword { get; set; }
public string StatusMessage { get; set; }
}
}
|
ad04c0aaa8742f453b64ff5610aa99e060f9ab90
|
C#
|
StyleSilviu/TimeCounter
|
/TimeCounter/TimeCount/Methods/MySqlDataBase.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//thread library
using System.Threading;
//mysql
using MySql.Data.MySqlClient;
//for the thread
using TimeCount.Pages;
using System.Reflection;
//reg key namespace
using Microsoft.Win32;
using TimeCount.ViewModels;
//cryptography dynamic link library
using Crypto8;
namespace TimeCount.Methods
{
public class MySqlDataBase
{
//internal string Link;
static MySqlCommand _MySqlCommand;
AccountViewModel _AccountViewModel = new AccountViewModel();
#region private
static MySqlConnection Connection = new MySqlConnection(Crypto8.Cryptography.Decrypt("OH1UyOm6jJLaz6Wd2fLhTe8ONXWxVYNMPBhp4dJ+EoGYQTuqxQSRIAyD8pjSziFjOqWDS4feLbM2hkqp/yiv0/pRUm7oL+sOs1afR9UPR/zIcH78RImKJg==", true));
#endregion
// MessageBox.Show(Crypto8.Cryptography.Encrypt("lol", true) );
// MessageBox.Show(Crypto8.Cryptography.Decrypt(Crypto8.Cryptography.Encrypt("lol", true), true));
internal void SignIn()
{
try
{
if (Connection.State != System.Data.ConnectionState.Open)
Connection.Open();
}
catch (MySqlException)
{
MainPage.main1.ReturnedMySqlConnectionState = false;
MainWindow.main.IfSignedIn = false;
return;
}
catch (TimeoutException)
{
MainWindow.main.IfSignedIn = false;
return;
}
//if (!Connected) CreateConnection();
//Search for a date : mysql> SELECT * FROM employee WHERE dept = 'TECHNOLOGY' AND salary >= 6000;
//mysql> SELECT * FROM TimeCounterUsers WHERE UserName = '" + TextUserName.Text + "' AND Password='" + TextPassword.Text + "';"
using (_MySqlCommand = new MySqlCommand("SELECT * FROM TimeCounterUsers WHERE UserName = '" + _AccountViewModel.UserName + "' AND Password='" + Crypto8.Cryptography.Encrypt(_AccountViewModel.Password, true) + "';", Connection))
{
try
{
MySqlDataReader _MySqlDataReader = _MySqlCommand.ExecuteReader();
if (_MySqlDataReader.Read())
{
//save if it is correct to the application settings
TimeCount.Properties.Settings.Default.UserName = _AccountViewModel.UserName;
TimeCount.Properties.Settings.Default.UserPassword = _AccountViewModel.Password;
TimeCount.Properties.Settings.Default.SignedIn = true;
TimeCount.Properties.Settings.Default.Save();
MainWindow.main.IfSignedIn = true;
//if (!TimeCount.Properties.Settings.Default.SignedIn)
//{
//get the first and last user name from the db by split the source string at `:`
//set value of the MainPage SignInBtn
//var window2 = System.Windows.Application.Current.Windows.Cast<System.Windows.UIElement>().FirstOrDefault(window => window is UserPage) as UserPage;
//window2.UserNameLbl.Content = _MySqlDataReader["UserInformations"].ToString();
}
else MainWindow.main.IfSignedIn = false;
_MySqlDataReader.Dispose();
}
catch (MySqlException)
{
MainWindow.main.IfSignedIn = false;
}
//disp.
_MySqlCommand.Dispose();
}
}
public void CreateNewUser()
{
try
{
if (Connection.State != System.Data.ConnectionState.Open)
Connection.Open();
int i;
}
catch (MySqlException)
{
return;
}
catch (TimeoutException)
{
return;
}
//initialize the class for the new user informations
AccountCreationViewModel _AccountCreationViewModel = new AccountCreationViewModel();
//create the user table
//string new_table = string.Concat("CREATE TABLE `" + _AccountCreationViewModel.UserName + "` (" +
// "`UserName` VARCHAR(255)," +
// "`Password` VARCHAR(255));");
//"`Password` VARCHAR(255));");
//"`Password` VARCHAR(255));");
//"`Password` VARCHAR(255));");
//ERROR MEANS THAT THIS USER EXIST
//using (_MySqlCommand = new MySqlCommand(new_table, Connection)) _MySqlCommand.ExecuteNonQuery();
string UserInformation = string.Concat("First name: " + _AccountCreationViewModel.FirstName +
":Last name: " + _AccountCreationViewModel.LastName +
":Birth day: " + _AccountCreationViewModel.BirthDay );
//writte the user informations in the TimeCounterUsers table
//if no error appear, we writte the user informations to the database
using (_MySqlCommand = new MySqlCommand("INSERT INTO TimeCounterUsers (UserName, Password, UserInformations) VALUES('" + _AccountCreationViewModel.UserName + "', '" + Crypto8.Cryptography.Encrypt(_AccountCreationViewModel.Password, true) + "', '" + UserInformation + "')", Connection))
{
_MySqlCommand.ExecuteNonQuery();
}
_MySqlCommand.Dispose();
//create a table to store data
string new_table = string.Concat("CREATE TABLE `" + _AccountViewModel.UserName + "` (" +
"`Date` VARCHAR(255)," +
"`Progress` VARCHAR(255));");
using (_MySqlCommand = new MySqlCommand(new_table, Connection))
{
_MySqlCommand.ExecuteNonQuery();
_MySqlCommand.Dispose();
}
//sign in directly
//save if it is correct to the application settings
TimeCount.Properties.Settings.Default.UserName = _AccountViewModel.UserName;
TimeCount.Properties.Settings.Default.UserPassword = _AccountViewModel.Password;
TimeCount.Properties.Settings.Default.SignedIn = true;
TimeCount.Properties.Settings.Default.Save();
// sign in to the new user
MainWindow.main.IfSignedIn = true;
}
private bool IsDataFound { get; set; }
public void GetMySqlData()
{
try
{
if (Connection.State != System.Data.ConnectionState.Open)
Connection.Open();
}
catch (MySqlException)
{
return;
}
catch (TimeoutException)
{
return;
}
//Search for a date
using (_MySqlCommand = new MySqlCommand("SELECT * FROM " + _AccountViewModel.UserName + " WHERE Date='" + _AccountViewModel.Date + "'", Connection))
{
//MySqlDataReader rdr = null;
MySqlDataReader _MySqlDataReader;
try
{
IsDataFound = false;
_MySqlDataReader = _MySqlCommand.ExecuteReader();
while (_MySqlDataReader.Read())
{
MainPage.main1.ReturnedMySqlData = _MySqlDataReader["Progress"].ToString();
IsDataFound = true;
}
if(!IsDataFound) MainPage.main1.ReturnedMySqlData = "no data found";
_MySqlDataReader.Dispose();
}
catch (MySqlException)
{
MainPage.main1.ReturnedMySqlData = "no data found";
}
_MySqlCommand.Dispose();
}
}
public void WritteData(string RegLocation, string sourceDate)
{
try
{
if (Connection.State != System.Data.ConnectionState.Open)
Connection.Open();
}
catch (MySqlException)
{
// //on error, we writte it to the application setting, and in an another time if no error appear we writte it
// //TimeCount.Properties.Settings.Default.InBearbeitung.Add(RegLocation);
// //exit statement
return;
}
catch (TimeoutException)
{
//on error, we writte it to the application setting, and in an another time if no error appear we writte it
//TimeCount.Properties.Settings.Default.InBearbeitung.Add(RegLocation);
//exit statement
return;
}
//if (Properties.Settings.Default.SignedIn == true)
//{
// //if there are loged in, then get all the wanted data
//}
string DataToMysql = string.Empty;
//string SerchedDate = DateTime.Now.ToString("d");
foreach (string aplicatie in Registry.CurrentUser.OpenSubKey(RegLocation, true).GetValueNames())
{
DataToMysql += aplicatie.ToString() + "|" + Convert.ToInt32(Registry.CurrentUser.OpenSubKey(RegLocation, true).GetValue(aplicatie)) + Environment.NewLine;
}
using ( _MySqlCommand = new MySqlCommand("INSERT INTO " + _AccountViewModel.UserName + " (Date, Progress) VALUES('" + sourceDate + "', '" + DataToMysql + "')", Connection))
{
_MySqlCommand.ExecuteNonQuery();
_MySqlCommand.Dispose();
}
TimeCount.Properties.Settings.Default.LastWrittedDate = RegLocation;
TimeCount.Properties.Settings.Default.Save();
return;
}
}
}
//public void CreateMyretSqlConn()
// {
// if (Properties.Settings.Default.SignedIn == true)
// {
// //if there are loged in, then get all the wanted data
// }
// //create a table if it does not exist
// string new_table = string.Concat("CREATE TABLE IF NOT EXISTS `StyleSSilviu` (" +
// "`Date` VARCHAR(255)," +
// "`Progress` VARCHAR(255));");
// using (_MySqlCommand = new MySqlCommand(new_table, Connection)) { _MySqlCommand.ExecuteNonQuery(); _MySqlCommand.Dispose(); }
// //save all data to the database
// string RegLocation = "SOFTWARE\\TimeCount\\" + DateTime.Now.Month + "\\" + DateTime.Now.ToString("d");
// string DataToMysql = string.Empty;
// //string SerchedDate = DateTime.Now.ToString("d");
// string SerchedDate = "lol";
// foreach (string aplicatie in Registry.CurrentUser.OpenSubKey(RegLocation, true).GetValueNames())
// {
// DataToMysql += aplicatie.ToString() + "|" + Convert.ToInt32(Registry.CurrentUser.OpenSubKey(RegLocation, true).GetValue(aplicatie)) + Environment.NewLine;
// }
// using (_MySqlCommand = new MySqlCommand("INSERT INTO " + _AccountViewModel.UserName + " (Date, Progress) VALUES('" + DateTime.Now.ToString("d") + "', '" + DataToMysql + "')", Connection))
// {
// _MySqlCommand.ExecuteNonQuery();
// _MySqlCommand.Dispose();
// }
// //Search for a date
// using (_MySqlCommand = new MySqlCommand("select * from " + _AccountViewModel.UserName + " where Date='" + SerchedDate + "';", Connection))
// {
// //MySqlDataReader rdr = null;
// MySqlDataReader _MySqlDataReader = _MySqlCommand.ExecuteReader();
// while (_MySqlDataReader.Read())
// {
// //MessageBox.Show(_MySqlDataReader["Progress"].ToString());
// }
// }
// }
//using (_MySqlCommand = new MySqlCommand("select * from TimeCounterUsers where Date='" + SerchedDate + "';", Connection))
//{
// //MySqlDataReader rdr = null;
// MySqlDataReader _MySqlDataReader = _MySqlCommand.ExecuteReader();
// while (_MySqlDataReader.Read())
// {
// //MessageBox.Show(_MySqlDataReader["Progress"].ToString());
// }
//}
/// <summary>
/// Get the date from database by the date
/// </summary>
//private string SignedIn
//{
// get { return signedin; }
// set { signedin = value; }
//}
//public bool Connected { get; set; }
//chech if the connection state is changed
//void Connection_StateChange(object sender, System.Data.StateChangeEventArgs e)
//{
// if (Connection.State == System.Data.ConnectionState.Closed) Connected = false;
//}
//private bool ConnectionState()
//{
// if (Connection.State == System.Data.ConnectionState.Closed)
// {
// try
// {
// Connection.Open();
// return true;
// // Connection.StateChange += Connection_StateChange;
// }
// catch (MySqlException)
// {
// return false;
// }
// }
// return false;
//}
|
c1a513185f839ceb0fdaceaefd5d89a9e13eebed
|
C#
|
rikes/Guia-De-Estudos-Certificacao
|
/Exam-70-783/3.1 Data Annotation/Program.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace _3._1_Data_Annotation
{
class Program
{
static void Main(string[] args)
{
Cliente cliente = new Cliente();
Address endereco = new Address();
endereco.Avenida = "Avenida Brasil";
endereco.Bairro = "Cobi de Baixo";
endereco.Cidade = "VV";
endereco.Numero = 420;
endereco.ZipCode = "29.115-795";
cliente.EnderecoDeEnvio = endereco;
cliente.Idade = 20;
cliente.Nome = "Henrique";
cliente.UltimoNome = "Santos";
cliente.email = "henricke@gmail.com";
var validation = new ValidationContext(cliente,null,null);
var validation2 = new ValidationContext(endereco, null, null);
List<ValidationResult> results = new List<ValidationResult>();
bool valido = Validator.TryValidateObject(cliente, validation, results, true);
valido = Validator.TryValidateObject(endereco, validation2, results, true);
if (!valido)
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Employee class Validation");
Console.WriteLine("---------------------------\n");
foreach (var validacaoResult in results)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write("Atributo: {0}", validacaoResult.MemberNames.First());
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(" :: {0}", validacaoResult.ErrorMessage);
}
}
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("\nPress any key to exit");
Console.ReadKey();
}
}
}
|
ded8ca14ee06944fc4425b00c17ff408df31b027
|
C#
|
MIlky92way/_rupor
|
/Rupor/Rupor.Rss/Core/Readers/FeedReader.cs
| 2.515625
| 3
|
using System;
using Rupor.Feed.Core.Parsers;
using Rupor.Feed.Core.Parsers.Versions;
using Rupor.Feed.Core.Types;
using Rupor.Feed.Feeds;
using Rupor.Feed.Feeds.Versions;
using Rupor.Feed.Feeds.Versions.RSS2;
using Rupor.Feed.Utility;
namespace Rupor.Feed.Core.Readers
{
public class FeedReader:IFeedReader<RSS2Feed>
{
public RSS2Feed ReadFeed(string url)
{
var xmlContent = UrlUtility.HttpGetString(url);
var docInitializer = new DocInitializer();
var xDoc = docInitializer.Initial(xmlContent);
var parser = GetParser(docInitializer.FeedType);
return parser.Parse(xDoc);
}
private XmlParser<RSS2Feed> GetParser(FeedType feedType)
{
RSS2Parser parser = null;
switch (feedType)
{
case FeedType.Atom:
//TODO instance Atom Parser
throw new NotImplementedException("Atom parser not implement");
case FeedType.Default:
default:
parser = new RSS2Parser();
break;
}
return parser;
}
}
}
|
bee22d223ccd5c66a7c0f830ea73150896d4ef7a
|
C#
|
marsscotia/ArtCat
|
/ArtCat/ViewModels/MasterDetailViewModel.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using ArtCat.Helpers;
using ArtCat.Models;
using ArtCat.Services;
using Microsoft.Toolkit.Uwp.UI.Controls;
namespace ArtCat.ViewModels
{
public class MasterDetailViewModel : Observable
{
private PieceViewModel _selected;
private RelayCommand<object> _deletePieceCommand;
private string _searchTerm;
public PieceViewModel Selected
{
get { return _selected; }
set
{
PersistPiece();
Set(ref _selected, value);
}
}
public ObservableCollection<PieceViewModel> Pieces { get; private set; } = new ObservableCollection<PieceViewModel>();
public RelayCommand<object> DeletePieceCommand
=> _deletePieceCommand ?? (_deletePieceCommand = new RelayCommand<object>(DeletePiece));
public ObservableCollection<string> SearchSuggestions { get; private set; } = new ObservableCollection<string>();
public string SearchTerm
{
get
{
return _searchTerm;
}
set
{
Set(ref _searchTerm, value);
if (string.IsNullOrEmpty(SearchTerm))
{
ClearFilter();
}
}
}
public MasterDetailViewModel()
{
}
public void LoadData(MasterDetailsViewState viewState)
{
ClearFilter();
if (viewState == MasterDetailsViewState.Both)
{
if (Pieces.Count > 0)
{
Selected = Pieces.First();
}
else
{
Selected = null;
}
}
}
public void AddPiece()
{
Piece newPiece = new Piece();
PieceViewModel newPieceViewModel = new PieceViewModel(newPiece);
Pieces.Add(newPieceViewModel);
Selected = newPieceViewModel;
}
public void PersistPiece()
{
if (Selected != null)
{
DataService.PersistPiece(Selected.ComponentPiece);
}
}
public void UpdateSearchSuggestions()
{
SearchSuggestions.Clear();
if (!string.IsNullOrWhiteSpace(SearchTerm))
{
var suggestions = from piece in DataService.GetNames()
where piece.Contains(SearchTerm, StringComparison.InvariantCultureIgnoreCase)
orderby piece
select piece;
foreach (var name in suggestions)
{
SearchSuggestions.Add(name);
}
}
}
private void DeletePiece(object aPiece)
{
if (aPiece != null)
{
PieceViewModel selectedPieceViewModel = aPiece as PieceViewModel;
Piece selectedPiece = selectedPieceViewModel.ComponentPiece;
selectedPieceViewModel.DeleteImages();
Pieces.Remove(selectedPieceViewModel);
DataService.DestroyPiece(selectedPiece);
}
}
public void FilterPieces()
{
Pieces.Clear();
var pieces = DataService.FindPieces(SearchTerm);
foreach (var piece in pieces)
{
Pieces.Add(new PieceViewModel(piece));
}
}
public void ClearFilter()
{
Pieces.Clear();
var data = DataService.GetPieces();
foreach (var piece in data)
{
Pieces.Add(new PieceViewModel(piece));
}
}
}
}
|
82d71994faeb002c027010a05b77592eb1dc397e
|
C#
|
dhlopez/XamarinMVCapi
|
/ArtHistoryWebAPI - MVC/Test3_ArtHistoryWebAPI - MVC/Test3_ArtHistoryWebAPI/Models/Artist.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test3_ArtHistory.Models
{
public class Artist
{
public int ID { get; set; }
[Required(ErrorMessage = "You cannot leave the name for the Artist blank.")]
[StringLength(50)]
[Display(Name = "Artist")]
[Index("IX_Unique_Artist", IsUnique = true)]
public string Name { get; set; }
[Required(ErrorMessage = "You must enter the full name of the artist.")]
[StringLength(255)]
[Display(Name = "Artist's Full Name")]
public string WholeName { get; set; }
[Required(ErrorMessage = "You must enter the year of birth for the artist.")]
[RegularExpression("^\\d{4}$", ErrorMessage = "The year of birth for the artist must be exactly 4 numeric digits.")]
[StringLength(4)]
[Display(Name = "Year of Birth")]
public string YearOfBirth { get; set; }
[Required(ErrorMessage = "You must enter the artist's country.")]
[StringLength(50)]
public string Country { get; set; }
//public virtual ICollection<Painting> Paintings { get; set; }
}
}
|
e1508247278659e9b1f65a0bcda69a9be6ca2b6b
|
C#
|
rainer13/TrofeulNational
|
/TrofeulNational/Concurent/Jucator.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using MySql.Data.MySqlClient;
using System.Data.Common;
using TrofeulNational.DAL;
namespace TrofeulNational.Concurent
{
//[Serializable]
public class Jucator
{
private string nume;
private string prenume;
private Int32 iid;
private int total_mp;
public Jucator(int i, int m, string n, string p)
{
prenume = p;
nume = n;
total_mp = m;
iid = i;
}
public Jucator(int i, string n, string p)
{
prenume = p;
nume = n;
iid = i;
}
public Jucator(string n, string p)
{
nume = n;
prenume = p;
}
public Int32 getIID()
{
return iid;
}
public string getNume()
{
return nume;
}
public string getPrenume()
{
return prenume;
}
public string getNumeComplet()
{
return nume + " ," + prenume;
}
public override string ToString()
{
return this.getNumeComplet() + " " + iid;
}
//aici trebuie modificat
public static Jucator jucatorFromDBRow(MySqlDataReader reader)
{
return new Jucator(reader.GetInt32(0), reader.GetString(1), reader.GetString(2));
}
public int getMP()
{
return total_mp;
}
public static Jucator jucatorWithMPFromDBRow(DbDataReader reader)
{
return new Jucator(reader.GetInt32(0), reader.GetInt32(3), reader.GetString(1), reader.GetString(2));
}
//adauga baza de date
public static void createInDB(int id, String n, String p)
{
Jucator j = new Jucator(id, n, p);
//db.add(j)
}
public static Jucator ConcurentByName()
{
return new Jucator(1, "a", "b");
}
public static Jucator ConcurentByInitials()
{
return new Jucator(1, "a", "b");
}
public static List<Jucator> ConcurentiByName()
{
List<Jucator> a = new List<Jucator>();
a.Add(new Jucator(1, "a", "b"));
return a;
}
public static List<Jucator> ConcurentiByInitials()
{
List<Jucator> a = new List<Jucator>();
a.Add(new Jucator(1, "a", "b"));
return a;
}
public static Jucator getFromTextBox(String textBoxString, DBConection con)
{
if (textBoxString == "" || textBoxString.StartsWith("Jucator"))
return null;
int n;
bool b = int.TryParse(textBoxString, out n);
bool b1 = textBoxString.All(char.IsDigit);
if (b1)
{
return con.getConcurentWithMPByID(textBoxString);
}
else
{
//prenume, nume
int i = textBoxString.IndexOf(',');
return con.getJucatorByFullName(textBoxString.Substring(i + 2), textBoxString.Substring(0, i));
}
}
}
}
|
f983d9d56d461efdfc30df187ed73cc7d161ed57
|
C#
|
danielefongo/Playground
|
/Master v.1.1/GestoreGiocatori.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
namespace Utility
{
public class GestoreGiocatori
{
private Dictionary<String, Giocatore> _giocatori;
public GestoreGiocatori()
{
_giocatori = new Dictionary<String, Giocatore>();
}
public void AddGiocatore(String ip)
{
if (!_giocatori.ContainsKey(ip)) _giocatori.Add(ip, new Giocatore(ip));
else _giocatori[ip] = new Giocatore(ip);
}
public void AddGiocatore(String ip, IEnumerable<Scheda> schede)
{
AddGiocatore(ip);
_giocatori[ip].AddSchede(schede.ToArray());
}
public void RemoveGiocatore(String ip)
{
if (_giocatori.ContainsKey(ip)) _giocatori.Remove(ip);
}
public IEnumerable<String> GetGiocatori()
{
return _giocatori.Keys;
}
public String GetNomeGiocatore(String ip)
{
if (_giocatori.ContainsKey(ip))
{
if (String.IsNullOrEmpty(_giocatori[ip].Nome)) return "Giocatore " + (_giocatori.Keys.ToList<String>().IndexOf(ip)+1);
else return _giocatori[ip].Nome;
}
return null;
}
public void SetNomeGiocatore(String ip, String nome)
{
if (_giocatori.ContainsKey(ip)) _giocatori[ip].Nome = nome;
}
#region Connections
public void SetConnected(String ip)
{
if (_giocatori.ContainsKey(ip)) _giocatori[ip].Connected = true;
}
public void SetDisconnected(String ip)
{
if (_giocatori.ContainsKey(ip)) _giocatori[ip].Connected = false;
}
public void ToggleConnected(String ip)
{
if (_giocatori.ContainsKey(ip)) _giocatori[ip].Connected = !_giocatori[ip].Connected;
}
public Boolean IsConnected(String ip)
{
if (_giocatori.ContainsKey(ip)) return _giocatori[ip].Connected;
else return false;
}
#endregion
public void AddSchede(String ip, params Scheda[] schede)
{
if (_giocatori.ContainsKey(ip)) _giocatori[ip].AddSchede(schede);
}
public void RemoveSchede(String ip, params Scheda[] schede)
{
if (_giocatori.ContainsKey(ip)) _giocatori[ip].RemoveSchede(schede);
}
public IEnumerable<Scheda> GetSchede(String ip)
{
if (_giocatori.ContainsKey(ip)) return _giocatori[ip].GetSchede();
return new List<Scheda>();
}
public String getIpGiocatoreFromScheda(String idScheda)
{
foreach(Giocatore giocatore in _giocatori.Values)
foreach(Scheda scheda in giocatore.GetSchede())
if(scheda.IdScheda==idScheda)return giocatore.Ip;
return null;
}
#region CLASSE-GIOCATORE
public class Giocatore
{
private readonly String _ip;
private String _nome;
private List<Scheda> _schede;
private Boolean _connected;
#region Properties
public Boolean Connected
{
get { return _connected; }
set { _connected = value; }
}
public String Ip
{
get { return _ip; }
}
public String Nome
{
get { return _nome; }
set { _nome = value; }
}
#endregion
public Giocatore(String ip)
{
_schede = new List<Scheda>();
_ip = ip;
}
public void AddSchede(params Scheda[] schede)
{
_schede.AddRange(from s in schede where !_schede.Contains(s) select s);
}
public void RemoveSchede(params Scheda[] schede)
{
foreach (Scheda s in schede) if (_schede.Contains(s)) _schede.Remove(s);
}
public IEnumerable<Scheda> GetSchede()
{
return _schede;
}
}
#endregion
}
}
namespace Utility.Messages
{
[Serializable]
public class GiocatoreKickedMessageEventArgs : MessageEventArgs
{
public GiocatoreKickedMessageEventArgs(String argomento) : base(argomento) { }
public GiocatoreKickedMessageEventArgs(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
[Serializable]
public class GestoreGiocatoriMessageEventArgs : MessageEventArgs
{
private readonly MessageEventArgs _messaggio;
public MessageEventArgs Messaggio { get { return _messaggio; } }
public override String ToString()
{
String temp = this.Argomento + ":" + _messaggio.ToString() + ":";
return temp;
}
public GestoreGiocatoriMessageEventArgs(String argomento, MessageEventArgs messaggio) : base(argomento) { _messaggio = messaggio; }
public GestoreGiocatoriMessageEventArgs(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
|
ed428138a39e782180b527d727dec0c9a0d90ee4
|
C#
|
Rockleeking/PRJ_ResearcherViewSystem
|
/Wpf_assignment_kit206/Wpf_assignment_kit206/Entity/Researher.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//KIT506_Hbt_F1500_7
namespace Wpf_assignment_kit206.Entity
{
public enum EmploymentLevel {student,A, B, C, D, E, Any };
public enum type { Staff, Student };
class Researher
{
//get basic details
public int id { get; set; }
public string GivenName { get; set; }
public string Name { get { return "" + GivenName + " " + FamilyName +""; } set { } }
public string FamilyName { get; set; }
public string Title { get; set; }
public string Unit { get; set; }
public String Campus { get; set; }
public EmploymentLevel employmentLevel { get; set; }
public List <Publication> publish { get; set; }
public List<Position> position { get; set; }
public List<Student> sup_student { get; set; }
public string threeYearAverage { get; set; }
public string performance { get; set; }
public String previousStart { get; set; }
public String previousEnd{ get; set; }
public String previousJob { get; set; }
public string Email { get; set; }
public type types { get; set; }
public string degree { get; set; }
public DateTime utas_start { get; set; }
public DateTime current_start { get; set; }
public int supervisor_id { get; set; }
public string Photo { get; set; }
//get current job position detail
public Position GetCurrentJob() {
Position p = new Position();
p.start_date = current_start;
p.level = employmentLevel;
return p;
}
//get string of current position
public String CurrentJobTitle
{
get
{
String t = "";
foreach (Position p in position)
{
if (p.level == employmentLevel)
{
t = p.ToTitle(employmentLevel);
}
}
return t;
}
set { }
}
//calculate previous job detail
public void previousJobDetail() {
if (employmentLevel == EmploymentLevel.E && (position.Count > 1))
{
foreach (Position p in position)
{
if (p.level == EmploymentLevel.D)
{
previousEnd = p.end_date.Date.ToString("MM/dd/yyyy");
previousStart = p.start_date.Date.ToString("MM/dd/yyyy");
previousJob = p.Title;
break;
}
}
}
else if (employmentLevel == EmploymentLevel.D && (position.Count > 1))
{
foreach (Position p in position)
{
if (p.level == EmploymentLevel.C)
{
previousEnd = p.end_date.Date.ToString("MM/dd/yyyy");
previousStart = p.start_date.Date.ToString("MM/dd/yyyy");
previousJob = p.Title;
break;
}
}
}
else if (employmentLevel == EmploymentLevel.C && (position.Count > 1))
{
foreach (Position p in position)
{
if (p.level == EmploymentLevel.B)
{
previousEnd = p.end_date.Date.ToString("MM/dd/yyyy");
previousStart = p.start_date.Date.ToString("MM/dd/yyyy");
previousJob = p.Title;
break;
}
}
}
else if (employmentLevel == EmploymentLevel.B && (position.Count > 1))
{
foreach (Position p in position)
{
if (p.level == EmploymentLevel.A)
{
previousEnd = p.end_date.Date.ToString("MM/dd/yyyy");
previousStart = p.start_date.Date.ToString("MM/dd/yyyy");
previousJob = p.Title;
break;
}
}
}
else if (employmentLevel == EmploymentLevel.A && (position.Count > 1))
{
previousStart = current_start.Date.ToString("MM/dd/yyyy");
previousEnd = "\t\t";
previousJob = CurrentJobTitle;
}
else if (employmentLevel == EmploymentLevel.student)
{
previousStart = "\t\t";
previousEnd = "\t\t";
previousJob = CurrentJobTitle;
}
else
{
previousStart = current_start.Date.ToString("MM/dd/yyyy");
previousEnd = "\t\t";
previousJob = CurrentJobTitle;
}
}
//calculate staff to get three year average
public void calculateStaff(List<Publication> lp) {
Staff s = new Staff(lp);
threeYearAverage = s.threeYearAverage;
performance = s.Performance;
}
//calculate tenure of current position
public string Tenure
{
get
{
return String.Format("{0:0.00}", ((double)DateTime.Now.Year + (((double)DateTime.Now.Month) / 12)) - ((double)current_start.Year + (((double)current_start.Month) / 12)));
}
set { }
}
//calculate publication count and return
public int PublicationCount {
get
{
return publish.Count();
}
set { }
}
//get supersion count
public int supervisionNumer {
get
{
if (types == type.Staff)
{
return sup_student.Count();
}
else {
return 0;
}
}
set { }
}
//tostring
public override string ToString()
{
return String.Format("{0}\t{1}, {2}", id, Title,Name) ;
}
}
}
|
0994c5c8ac3f0ff68e393dd781dcdbf834ccfce7
|
C#
|
superactive/RuleOfFirewall
|
/RuleOfFirewall/Extensions.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace RuleOfFirewall
{
public static class Extensions
{
#region DataTable
public static void AddColumn<T>(this DataTable dt, string ColumnName)
{
dt.Columns.Add(ColumnName, typeof(T));
}
public static T Cell<T>(this DataTable dt, int RowIndex, string ColumnName)
{
if (dt == null)
throw new ArgumentNullException("Cell<T>: DataTable is null.", "dt");
if (RowIndex < 0)
throw new ArgumentOutOfRangeException("Cell<T>: RowIndex {0} is less than 0.", "RowIndex");
if (dt.Rows.Count <= RowIndex)
throw new ArgumentOutOfRangeException(string.Format("Cell<T>: RowIndex {0} is greater than DataTable's row count {1}.", RowIndex, dt.Rows.Count), "RowIndex");
if (string.IsNullOrWhiteSpace(ColumnName))
throw new ArgumentException("Cell<T>: ColumnName cannot be null or empty.", "ColumnName");
int ColumnIndex = dt.Columns.IndexOf(ColumnName);
if (ColumnIndex < 0)
throw new ArgumentException(string.Format("Cell<T>: ColumnName {0} not in DataTable.", ColumnName), "ColumnName");
return (T)dt.Rows[RowIndex][ColumnName];
}
public static T Cell<T>(this DataTable dt, int RowIndex, int ColumnIndex)
{
if (dt == null)
throw new ArgumentNullException("Cell<T>: DataTable is null.", "dt");
if (RowIndex < 0)
throw new ArgumentOutOfRangeException("Cell<T>: RowIndex {0} is less than 0.", "RowIndex");
if (dt.Rows.Count <= RowIndex)
throw new ArgumentOutOfRangeException(string.Format("Cell<T>: RowIndex {0} is greater than DataTable's row count {1}", RowIndex, dt.Rows.Count), "RowIndex");
if (ColumnIndex < 0 || ColumnIndex >= dt.Columns.Count)
throw new ArgumentOutOfRangeException(string.Format("Cell<T>: ColumnIndex {0} is out of range.", ColumnIndex), "ColumnIndex");
return (T)dt.Rows[RowIndex][ColumnIndex];
}
#endregion
#region DataRow
public static T Value<T>(this DataRow dr, string ColumnName)
{
if (dr == null)
throw new ArgumentNullException("Cell<T>: DataRow is null.", "dr");
if (string.IsNullOrWhiteSpace(ColumnName))
throw new ArgumentException("Cell<T>: ColumnName cannot be null or empty.", "ColumnName");
//if (dr.Table == null)
// throw new ArgumentNullException("Cell<T>: DataRow.Table is null. Can't lookup the ColumnName.", "dr.Table");
//int ColumnIndex = dr.Table.Columns.IndexOf(ColumnName);
//if (ColumnIndex < 0)
// throw new ArgumentException(string.Format("Cell<T>: ColumnName {0} not in DataTable.", ColumnName), "ColumnName");
//return (T)dr[ColumnIndex];
return (T)dr[ColumnName];
}
public static T Value<T>(this DataRow dr, int ColumnIndex)
{
if (dr == null)
throw new ArgumentNullException("Cell<T>: DataRow is null.", "dr");
if (ColumnIndex < 0 || ColumnIndex >= dr.ItemArray.Length)
throw new ArgumentOutOfRangeException(string.Format("Cell<T>: ColumnIndex {0} is out of range.", ColumnIndex), "ColumnIndex");
return (T)dr[ColumnIndex];
}
#endregion
#region Enums
public static T ParseEnum<T>(this string EnumString) where T : struct, IConvertible, IFormattable
{
return (T)EnumString.ParseEnum(typeof(T));
}
public static object ParseEnum(this string EnumString, Type tEnumType)
{
if (!tEnumType.IsEnum)
throw new ArgumentException("ParseEnum<T> requires that T be an Enum type.");
return Enum.Parse(tEnumType, EnumString, true);
}
#region Conversion
internal static NetFwTypeLib.NET_FW_RULE_DIRECTION_ GetCOMEnum(this Enums.TrafficDirectionTypeEnum eVal)
{
switch (eVal)
{
case Enums.TrafficDirectionTypeEnum.Incoming:
return NetFwTypeLib.NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
case Enums.TrafficDirectionTypeEnum.Outgoing:
return NetFwTypeLib.NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;
case Enums.TrafficDirectionTypeEnum.Max:
return NetFwTypeLib.NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_MAX;
default:
throw new ArgumentException(string.Format("Unknown TrafficDirectionTypeEnum value", eVal.ToString()));
}
}
internal static Enums.TrafficDirectionTypeEnum GetPublicEnum(this NetFwTypeLib.NET_FW_RULE_DIRECTION_ eVal)
{
switch (eVal)
{
case NetFwTypeLib.NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN:
return Enums.TrafficDirectionTypeEnum.Incoming;
case NetFwTypeLib.NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT:
return Enums.TrafficDirectionTypeEnum.Outgoing;
case NetFwTypeLib.NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_MAX:
return Enums.TrafficDirectionTypeEnum.Max;
default:
throw new ArgumentException(string.Format("Unknown NET_FW_RULE_DIRECTION_ value", eVal.ToString()));
}
}
internal static NetFwTypeLib.NET_FW_ACTION_ GetCOMEnum(this Enums.FirewallActionTypeEnum eVal)
{
switch (eVal)
{
case Enums.FirewallActionTypeEnum.Allow:
return NetFwTypeLib.NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
case Enums.FirewallActionTypeEnum.Block:
return NetFwTypeLib.NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
case Enums.FirewallActionTypeEnum.Max:
return NetFwTypeLib.NET_FW_ACTION_.NET_FW_ACTION_MAX;
default :
throw new ArgumentException(string.Format("Unknown FirewallActionTypeEnum value", eVal.ToString()));
}
}
internal static Enums.FirewallActionTypeEnum GetPublicEnum(this NetFwTypeLib.NET_FW_ACTION_ eVal)
{
switch (eVal)
{
case NetFwTypeLib.NET_FW_ACTION_.NET_FW_ACTION_ALLOW:
return Enums.FirewallActionTypeEnum.Allow;
case NetFwTypeLib.NET_FW_ACTION_.NET_FW_ACTION_BLOCK:
return Enums.FirewallActionTypeEnum.Block;
case NetFwTypeLib.NET_FW_ACTION_.NET_FW_ACTION_MAX:
return Enums.FirewallActionTypeEnum.Max;
default:
throw new ArgumentException(string.Format("Unknown NET_FW_ACTION_ value", eVal.ToString()));
}
}
internal static NetFwTypeLib.NET_FW_PROFILE_TYPE2_ GetCOMEnum(this Enums.ProfileTypeEnum eVal)
{
switch (eVal)
{
case Enums.ProfileTypeEnum.Domain:
return NetFwTypeLib.NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_DOMAIN;
case Enums.ProfileTypeEnum.Private:
return NetFwTypeLib.NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE;
case Enums.ProfileTypeEnum.Public:
return NetFwTypeLib.NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC;
case Enums.ProfileTypeEnum.All:
return NetFwTypeLib.NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_ALL;
default:
throw new ArgumentException(string.Format("Unknown ProfileTypeEnum value", eVal.ToString()));
}
}
internal static Enums.ProfileTypeEnum GetPublicEnum(this NetFwTypeLib.NET_FW_PROFILE_TYPE2_ eVal)
{
switch (eVal)
{
case NetFwTypeLib.NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_DOMAIN:
return Enums.ProfileTypeEnum.Domain;
case NetFwTypeLib.NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE:
return Enums.ProfileTypeEnum.Private;
case NetFwTypeLib.NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC:
return Enums.ProfileTypeEnum.Public;
case NetFwTypeLib.NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_ALL:
return Enums.ProfileTypeEnum.All;
default:
throw new ArgumentException(string.Format("Unknown NET_FW_PROFILE_TYPE2_ value", eVal.ToString()));
}
}
internal static NetFwTypeLib.NET_FW_IP_PROTOCOL_ GetCOMEnum(this Enums.ProtocolTypeEnum eVal)
{
switch (eVal)
{
case Enums.ProtocolTypeEnum.TCP:
return NetFwTypeLib.NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
case Enums.ProtocolTypeEnum.UDP:
return NetFwTypeLib.NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP;
case Enums.ProtocolTypeEnum.Any:
return NetFwTypeLib.NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_ANY;
default:
throw new ArgumentException(string.Format("Unknown ProtocolTypeEnum value", eVal.ToString()));
}
}
internal static Enums.ProtocolTypeEnum GetPublicEnum(this NetFwTypeLib.NET_FW_IP_PROTOCOL_ eVal)
{
switch (eVal)
{
case NetFwTypeLib.NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP:
return Enums.ProtocolTypeEnum.TCP;
case NetFwTypeLib.NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP:
return Enums.ProtocolTypeEnum.UDP;
case NetFwTypeLib.NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_ANY:
return Enums.ProtocolTypeEnum.Any;
default:
throw new ArgumentException(string.Format("Unknown NET_FW_IP_PROTOCOL_ value", eVal.ToString()));
}
}
#endregion
#endregion
internal static dynamic InstantiateTypeFromGUID(string sGUID)
{
Type tRef = Type.GetTypeFromCLSID(new Guid(sGUID));
return Activator.CreateInstance(tRef);
}
internal static dynamic InstantiateTypeFromProgID(string sProgID)
{
Type tRef = Type.GetTypeFromProgID(sProgID);
return Activator.CreateInstance(tRef);
}
public static bool Matches(this string ValueToTest, string ComparisonValue, bool AnyCase = true)
{
if (AnyCase)
return ValueToTest.ToLower().Equals(ComparisonValue.ToLower());
else
return ValueToTest.Equals(ComparisonValue);
}
public static bool Same(this NetFwTypeLib.INetFwRule rule1, NetFwTypeLib.INetFwRule rule2)
{
if (rule1.Name != null && rule2.Name != null)
{
if (!rule1.Name.Equals(rule2.Name))
return false;
}
if (!rule1.Profiles.Equals(rule2.Profiles))
return false;
if (!rule1.Action.Equals(rule2.Action))
return false;
if (rule1.ApplicationName != null && rule2.ApplicationName != null)
{
if (!rule1.ApplicationName.Equals(rule2.ApplicationName))
return false;
}
if (rule1.Description != null && rule2.Description != null)
{
if (!rule1.Description.Equals(rule2.Description))
return false;
}
if (!rule1.Direction.Equals(rule2.Direction))
return false;
if (!rule1.EdgeTraversal.Equals(rule2.EdgeTraversal))
return false;
if (rule1.Grouping != null && rule2.Grouping != null)
{
if (!rule1.Grouping.Equals(rule2.Grouping))
return false;
}
if (rule1.IcmpTypesAndCodes != null && rule2.IcmpTypesAndCodes != null)
{
if (!rule1.IcmpTypesAndCodes.Equals(rule2.IcmpTypesAndCodes))
return false;
}
//TODO: compare Interfaces? References of Interfaces usage: //http://msdn.microsoft.com/en-us/library/windows/desktop/dd339603(v=vs.85).aspx
if (rule1.InterfaceTypes != null && rule2.InterfaceTypes != null)
{
if (!rule1.InterfaceTypes.Equals(rule2.InterfaceTypes))
return false;
}
if (rule1.LocalAddresses != null && rule2.LocalAddresses != null)
{
if (!rule1.LocalAddresses.Equals(rule2.LocalAddresses))
return false;
}
if (rule1.LocalPorts != null && rule2.LocalPorts != null)
{
if (!rule1.LocalPorts.Equals(rule2.LocalPorts))
return false;
}
if (!rule1.Protocol.Equals(rule2.Protocol))
return false;
if (rule1.RemoteAddresses != null && rule2.RemoteAddresses != null)
{
if (!rule1.RemoteAddresses.Equals(rule2.RemoteAddresses))
return false;
}
if (rule1.RemotePorts != null && rule2.RemotePorts != null)
{
if (!rule1.RemotePorts.Equals(rule2.RemotePorts))
return false;
}
if (rule1.serviceName != null && rule2.serviceName != null)
{
if (!rule1.serviceName.Equals(rule2.serviceName))
return false;
}
if (!rule1.Enabled.Equals(rule2.Enabled))
return false;
return true;
}
}
}
|
6a4b070702bda384b532b831bdf400ae7b58ecac
|
C#
|
Kyronomix/idleclicker
|
/GameManager.cs
| 2.625
| 3
|
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
// Text
public Text cashText;
public Text cashPerSecText;
public Text clickCashText;
public Text clickUpgrade1Text;
public Text clickUpgrade1MaxText;
public Text clickUpgrade2Text;
public Text productionUpgrade1Text;
public Text productionUpgrade2Text;
public Text rareRockText;
public Text rareRockBoostText;
public Text rareRockToGetText;
// UI
public double cash;
public double rareRock;
public double rareRockBoost;
public double rareRockToGet;
public double prestige;
public double cashPerSecond;
public double cashClickValue;
public Image clickUpgrade1Bar;
public Image clickUpgrade2Bar;
public Image productionUpgrade1Bar;
public Image productionUpgrade2Bar;
// Click Upgrade 1
public double clickUpgrade1Cost;
public int clickUpgrade1Level;
// Production Upgrade 1
public double productionUpgrade1Cost;
public int productionUpgrade1Level;
// Click Upgrade 2
public double clickUpgrade2Cost;
public int clickUpgrade2Level;
// Production Upgrade 2
public double productionUpgrade2Cost;
public double productionUpgrade2Power;
public int productionUpgrade2Level;
public void Start()
{
Load();
}
public void Load()
{
// UI Defaults
cash = double.Parse(PlayerPrefs.GetString("cash", "0"));
cashClickValue = double.Parse(PlayerPrefs.GetString("cashClickValue", "1"));
rareRock = double.Parse(PlayerPrefs.GetString("rareRock", "0"));
rareRockBoost = double.Parse(PlayerPrefs.GetString("rareRockBoost", "0"));
// Click Upgrades
clickUpgrade1Cost = double.Parse(PlayerPrefs.GetString("clickUpgrade1Cost", "10"));
clickUpgrade2Cost = double.Parse(PlayerPrefs.GetString("clickUpgrade2Cost", "25"));
// Production Upgrades
productionUpgrade1Cost = double.Parse(PlayerPrefs.GetString("productionUpgrade1Cost", "25"));
productionUpgrade2Power = double.Parse(PlayerPrefs.GetString("productionUpgrade2Power", "5"));
productionUpgrade2Cost = double.Parse(PlayerPrefs.GetString("productionUpgrade2Cost", "100"));
// Upgrade Levels
clickUpgrade1Level = (PlayerPrefs.GetInt("clickUpgrade1Level", 0));
clickUpgrade2Level = (PlayerPrefs.GetInt("clickUpgrade2Level", 0));
productionUpgrade1Level = (PlayerPrefs.GetInt("productionUpgrade1Level", 0));
productionUpgrade2Level = (PlayerPrefs.GetInt("productionUpgrade2Level", 0));
}
public void Save()
{
// UI Defaults
PlayerPrefs.SetString("cash", cash.ToString());
PlayerPrefs.SetString("cashClickValue", cashClickValue.ToString());
PlayerPrefs.SetString("rareRock", rareRock.ToString());
PlayerPrefs.SetString("rareRockBoost", rareRockBoost.ToString());
// Click Upgrades
PlayerPrefs.SetString("clickUpgrade1Cost", clickUpgrade1Cost.ToString());
PlayerPrefs.SetString("clickUpgrade2Cost", clickUpgrade2Cost.ToString());
// Production Upgrades
PlayerPrefs.SetString("productionUpgrade1Cost", productionUpgrade1Cost.ToString());
PlayerPrefs.SetString("productionUpgrade2Power", productionUpgrade2Power.ToString());
PlayerPrefs.SetString("productionUpgrade2Cost", productionUpgrade2Cost.ToString());
// Upgrade Levels
PlayerPrefs.SetInt("clickUpgrade1Level", clickUpgrade1Level);
PlayerPrefs.SetInt("clickUpgrade2Level", clickUpgrade2Level);
PlayerPrefs.SetInt("productionUpgrade1Level", productionUpgrade1Level);
PlayerPrefs.SetInt("productionUpgrade2Level", productionUpgrade2Level);
}
public void Update()
{
cashPerSecond = (productionUpgrade1Level + (productionUpgrade2Power * productionUpgrade2Level)) * rareRockBoost;
cash += cashPerSecond * Time.deltaTime;
// Click Value Exponent System
if (cashClickValue > 1000)
{
var exponent = (System.Math.Floor(System.Math.Log10(System.Math.Abs(cashClickValue))));
var mantissa = (cashClickValue / System.Math.Pow(10, exponent));
clickCashText.text = "Click: \n" + mantissa.ToString("F2") + "e" + exponent + " Cash";
}
else
clickCashText.text = "Click: \n" + cashClickValue.ToString("F0") + " Cash";
// Cash Value Exponent System
if (cash > 1000)
{
var exponent = (System.Math.Floor(System.Math.Log10(System.Math.Abs(cash))));
var mantissa = (cash / System.Math.Pow(10, exponent));
cashText.text = "Cash: " + mantissa.ToString("F2") + "e" + exponent;
}
else
cashText.text = "Cash: " + cash.ToString("F0");
// Click Upgrade 1 Cost Exponent System
string clickUpgrade1CostString;
var clickUpgrade1Cost = 10 * System.Math.Pow(1.1, clickUpgrade1Level);
if (clickUpgrade1Cost > 1000)
{
var exponent = (System.Math.Floor(System.Math.Log10(System.Math.Abs(clickUpgrade1Cost))));
var mantissa = (clickUpgrade1Cost / System.Math.Pow(10, exponent));
clickUpgrade1CostString = mantissa.ToString("F2") + "e" + exponent;
}
else
clickUpgrade1CostString = clickUpgrade1Cost.ToString("F0");
// Click Upgrade 2 Cost Exponent System
string clickUpgrade2CostString;
if (clickUpgrade2Cost > 1000)
{
var exponent = (System.Math.Floor(System.Math.Log10(System.Math.Abs(clickUpgrade2Cost))));
var mantissa = (clickUpgrade2Cost / System.Math.Pow(10, exponent));
clickUpgrade2CostString = mantissa.ToString("F2") + "e" + exponent;
}
else
clickUpgrade2CostString = clickUpgrade2Cost.ToString("F0");
// Production Upgrade 1 Cost Exponent System
string productionUpgrade1CostString;
if (productionUpgrade1Cost > 1000)
{
var exponent = (System.Math.Floor(System.Math.Log10(System.Math.Abs(productionUpgrade1Cost))));
var mantissa = (productionUpgrade1Cost / System.Math.Pow(10, exponent));
productionUpgrade1CostString = mantissa.ToString("F2") + "e" + exponent;
}
else
productionUpgrade1CostString = productionUpgrade1Cost.ToString("F0");
// Production Upgrade 2 Cost Exponent System
string productionUpgrade2CostString;
if (productionUpgrade2Cost > 1000)
{
var exponent = (System.Math.Floor(System.Math.Log10(System.Math.Abs(productionUpgrade2Cost))));
var mantissa = (productionUpgrade2Cost / System.Math.Pow(10, exponent));
productionUpgrade2CostString = mantissa.ToString("F2") + "e" + exponent;
}
else
productionUpgrade2CostString = productionUpgrade2Cost.ToString("F0");
// UI
cashPerSecText.text = cashPerSecond.ToString("F2") + " cash/s";
// Click Upgrade 1
clickUpgrade1Text.text = "Click Upgrade 1\nCost: " + clickUpgrade1CostString + " cash\n+1 Cash per Click";
clickUpgrade1MaxText.text = "Buy Max (" + BuyClickUpgrade1MaxCount() +")";
// Click Upgrade 2
clickUpgrade2Text.text = "Click Upgrade 2\nCost: " + clickUpgrade2CostString + " cash\n+5 Cash per Click";
// Production Upgrade 1
productionUpgrade1Text.text = "Production Upgrade 1\n Cost: " + productionUpgrade1CostString + " cash\n+" + rareRockBoost.ToString("F2") + " cash/s";
// Production Upgrade 2
productionUpgrade2Text.text = "Production Upgrade 2\n Cost: " + productionUpgrade2CostString + " cash\n+" + (productionUpgrade2Power * rareRockBoost).ToString("F2") + " cash/s";
// Cash per Click
clickCashText.text = "Click\n+" + cashClickValue.ToString("F0") + " Cash";
// Rare Rock Currency
rareRockToGet = (150 * System.Math.Sqrt(cash / 1e7));
rareRockToGetText.text = "Prestige:\n+" + System.Math.Floor(rareRockToGet).ToString("F0") + " Rare Rock";
rareRockText.text = "Rare Rock: " + System.Math.Floor(rareRock).ToString("F0");
rareRockBoostText.text = rareRockBoost.ToString("F2") + "x Boost";
// Gem Boost
rareRockBoost = (rareRock * 0.05) + 1;
// Progress Bars
// Click Upgrade 1 Bar
if (cash / clickUpgrade1Cost < 0.01)
clickUpgrade1Bar.fillAmount = 0;
else if (cash / clickUpgrade1Cost > 10)
clickUpgrade1Bar.fillAmount = 1;
else
clickUpgrade1Bar.fillAmount = (float)(cash / clickUpgrade1Cost);
// Click Upgrade 2 Bar
if (cash / clickUpgrade2Cost < 0.01)
clickUpgrade2Bar.fillAmount = 0;
else if (cash / clickUpgrade2Cost > 10)
clickUpgrade2Bar.fillAmount = 1;
else
clickUpgrade2Bar.fillAmount = (float)(cash / clickUpgrade2Cost);
// Save
Save();
}
// Buttons
public void Click()
{
cash += cashClickValue;
}
// Prestige
public void Prestige()
{
if (cash > 1000)
{
// UI Defaults
cash = 0;
cashClickValue = 1;
// Click Upgrades
clickUpgrade1Cost = 10;
clickUpgrade2Cost = 25;
// Production Upgrades
productionUpgrade1Cost = 25;
productionUpgrade2Power = 5;
productionUpgrade2Cost = 100;
// Upgrade Levels
clickUpgrade1Level = 0;
clickUpgrade2Level = 0;
productionUpgrade1Level = 0;
productionUpgrade2Level = 0;
rareRock += rareRockToGet;
}
}
// Click Upgrade 1
public void BuyClickUprade1()
{
if (cash >= clickUpgrade1Cost)
{
clickUpgrade1Level++;
cash -= clickUpgrade1Cost;
clickUpgrade1Cost *= 1.1;
cashClickValue++;
}
}
// Click Upgrade 1 Max
public void BuyClickUpgrade1Max()
{
var b = 10;
var c = cash;
var r = 1.1;
var k = clickUpgrade1Level;
var n = System.Math.Floor(System.Math.Log((c * (r - 1)) / (b * System.Math.Pow(r, k)) + 1, r));
var cost = b * (System.Math.Pow(r, k) * (System.Math.Pow(r, n) - 1) / (r - 1));
if (cash >= clickUpgrade1Cost)
{
clickUpgrade1Level += (int)n;
cash -= cost;
cashClickValue += n;
}
}
// Click Upgrade 1 Max Count
public double BuyClickUpgrade1MaxCount()
{
var b = 10;
var c = cash;
var r = 1.1;
var k = clickUpgrade1Level;
var n = System.Math.Floor(System.Math.Log((c * (r - 1)) / (b * System.Math.Pow(r, k)) + 1, r));
return n;
}
// Click Upgrade 2
public void BuyClickUpgrade2()
{
if (cash >= clickUpgrade2Cost)
{
clickUpgrade2Level++;
cash -= clickUpgrade2Cost;
clickUpgrade2Cost *= 2;
cashClickValue += 5;
}
}
// Production Upgrade 1
public void BuyProductionUprade1()
{
if (cash >= productionUpgrade1Cost)
{
productionUpgrade1Level++;
cash -= productionUpgrade1Cost;
productionUpgrade1Cost *= 1.1;
}
}
// Production Upgrade 2
public void BuyProductionUprade2()
{
if (cash >= productionUpgrade2Cost)
{
productionUpgrade2Level++;
cash -= productionUpgrade2Cost;
productionUpgrade2Cost *= 2;
}
}
}
|
0e331adac4dfb0c48593d58a6ba3ea812c1ab58c
|
C#
|
Lastonedown/RockPaperScissor
|
/RockPaperScissor.cs
| 3.46875
| 3
|
using System;
namespace PracticeCode
{
class Program
{
static void Main(string[] args)
{
string[] rps = new string[] { "rock", "paper", "scissor" };
Random rand = new Random();
string randomRps;
int randNum;
randNum = rand.Next(0, 3);
randomRps = rps[randNum];
do
{
Console.WriteLine("Please select Rock,Paper,Scissor or Press any key to quit");
string userInput = Console.ReadLine().ToLower();
if (userInput.Equals("rock") || userInput.Equals("paper") || userInput.Equals("scissor"))
{
rpsConditions(userInput, randomRps);
continue;
}
if (userInput.Equals(""))
{
Console.WriteLine("Thanks for playing");
break;
}
} while (true);
void rpsConditions(String userInput, String randomRps)
{
if (userInput.Equals(randomRps))
{
Console.WriteLine("Tie");
}
else if (userInput.Equals("rock") && randomRps.Equals("paper") || (userInput.Equals("scissor") && randomRps.Equals("rock")) || (userInput.Equals("paper") && randomRps.Equals("scissor")))
{
cpuWin(randomRps, userInput);
}
else if (userInput.Equals("paper") && randomRps.Equals("rock") || (userInput.Equals("rock") && randomRps.Equals("scissor")) || (userInput.Equals("scissors") && randomRps.Equals("rock")))
{
humanWin(userInput, randomRps);
}
}
void cpuWin(String randomRps, String userInput)
{
Console.WriteLine("You picked {0}", char.ToUpper(userInput[0]) + userInput.Substring(1));
Console.WriteLine("The computer picked {0}", char.ToUpper(randomRps[0]) + randomRps.Substring(1) + " the computer wins");
}
void humanWin(String userInput, String randomRps)
{
Console.WriteLine("The computer picked {0} ", char.ToUpper(randomRps[0]) + randomRps.Substring(1));
Console.WriteLine("You picked {0}", char.ToUpper(userInput[0]) + userInput.Substring(1) + " you win");
}
}
}
}
|
f72ca2460d587df62bba1483ccef531b31eb55b8
|
C#
|
arifahmed411/70-483
|
/ThreadLocalVariable/Program.cs
| 3.609375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
class Test
{
static void Main()
{
int[] nums = Enumerable.Range(0, 5).ToArray();
long total = 0;
// Use type parameter to make subtotal a long, not an int
Parallel.For<long>(0, nums.Length, () => { return 10; },
(j, loop, subtotal) =>
{
subtotal += nums[j];
return subtotal;
},
(x) => Interlocked.Add(ref total, x)
);
Console.WriteLine("The total is {0:N0}", total);
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}
|
0f073b8dbf197c803eef7c819c6c84481a61fcff
|
C#
|
tuandnvn/ecat
|
/Annotator/depth/IDepthReader.cs
| 2.90625
| 3
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Annotator
{
public interface IDepthReader : IDisposable
{
/// <summary>
///
/// </summary>
/// <param name="milisecondFromStart"></param>
/// <returns></returns>
ushort[] readFrameAtTime(int milisecondFromStart);
/// <summary>
/// Turn the depth frame into a bitmap to show on the screen
///
/// </summary>
/// <param name="milisecondFromStart"> A time from start of recording session</param>
/// <param name="depthBitmap"> Output bitmap </param>
/// <param name="depthValuesToByte"> buffer of size depthFrameDescription.Width * depthFrameDescription.Height * 4, allow reusing of buffer </param>
/// <param name="scale"> scale from depth range to [0-255], e.g. 8000 / 256 </param>
void readFrameAtTimeToBitmap(int milisecondFromStart, Bitmap depthBitmap, byte[] depthValuesToByte, float scale);
/// <summary>
///
/// </summary>
/// <param name="frame"></param>
/// <returns></returns>
ushort[] readFrame(int frame);
int getFrameCount();
int getWidth();
int getHeight();
}
}
|
806f68c45d3cdabef3d9e08dcf71d3fb2db0b0ff
|
C#
|
Dana-Ferguson/WeakAuraAutomationTool
|
/WeakAuraAutomationTool/Automation/AuraScale.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using WeakAuraAutomationTool.WeakAuras;
using WeakAuraAutomationTool.WeakAuras.Data;
namespace WeakAuraAutomationTool.Automation
{
internal static class AuraScale
{
public static Aura SetSize(this Aura aura, int width, int height)
{
aura.Width = width;
aura.Height = height;
return aura;
}
public static List<Aura> SetSize(this List<Aura> auras, int width, int height)
{
foreach (var aura in auras)
{
aura.Width = width;
aura.Height = height;
}
return auras;
}
}
}
|
11e00e7907a5f86f604fbcd3a9eed1fb868bfd28
|
C#
|
SaarPeleg/DataCrea
|
/Unity - only scripts and scenes/TacticsMove.cs
| 2.515625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
//general character definition and actions
public class TacticsMove : MonoBehaviour
{
public bool turn = false;//is it the unit's turn
List<Tile> selectableTiles = new List<Tile>();//list of slectable tiles
GameObject[] tiles;//list of all tiles
Stack<Tile> path = new Stack<Tile>();//path to a tile;
public Tile currentTile;//tile you are on
public Sprite up, down, left, right;//sprite states, to change direction
public string name;
public int move = 3;//move distance
public float movespeed = 2f;//move speed
public bool moving = false;//is the unit currently moving
Vector3 velocity = new Vector3();//velocity of unit
Vector3 heading = new Vector3();//direction vector
//for A*
public Tile actualTargetTile;
//attack phase
public bool attackphase = false;
public int attackrange = 1;
//stats
public int attack = 1;
public int hp = 10;
public int mhp = 10;
GameObject hpbar;
//initializetion
protected void Init()
{
tiles = GameObject.FindGameObjectsWithTag("Tile");
hpbar = GameObject.Find(gameObject.name + "HpBar");
TurnManager.AddUnit(this);
}
//assign current tile to be the tile the player is on
public void GetCurrentTile()
{
currentTile = GetTargetTile(gameObject);
currentTile.current = true;
}
//return the target tile
public Tile GetTargetTile(GameObject target)
{
RaycastHit hit;
Tile tile=null;
if (Physics.Raycast(target.transform.position, new Vector3(0, 0, 1), out hit, 1))
{
tile = hit.collider.GetComponent<Tile>();
}
return tile;
}
//compute adjacent tiles
public void ComputeAdjacencyLists(Tile target)
{
foreach (GameObject tile in tiles)
{
Tile t = tile.GetComponent<Tile>();
t.FindNeighbors(target,attackphase,this.tag);
}
}
//find selectable tiles around user using bfs search
public void FindSelectableTiles(int range)
{
ComputeAdjacencyLists(null);
GetCurrentTile();
Queue<Tile> process = new Queue<Tile>();
process.Enqueue(currentTile);
currentTile.visited = true;
while (process.Count > 0)
{
Tile t = process.Dequeue();
selectableTiles.Add(t);
t.selectable = true;
if (t.distance < range)
{
foreach (Tile ti in t.adjacentcyList)
{
if (!ti.visited)
{
ti.parent = t;
ti.visited = true;
ti.distance = t.distance + 1;
process.Enqueue(ti);
}
}
}
}
}
//calculate path to tile
public void MoveToTile(Tile tile)
{
path.Clear();
tile.target = true;
moving = true;
Tile next = tile;
while (next.parent != null)
{
path.Push(next);
next = next.parent;
}
}
//movement implementation
public void Move()
{
if (path.Count > 0)
{
currentTile.occupied = false;
currentTile.occupier = null;
Tile t = path.Peek();
if (path.Count == 1)
{
t.occupied = true;
t.occupier = this;
}
Vector3 target = t.transform.position;
//Debug.Log(transform.position.x + "," + transform.position.y + "," + transform.position.z + ":" + target.x + "," + target.y + "," + target.z);
if (Vector3.Distance(new Vector3(transform.position.x,transform.position.y,1), target) >= 0.2f)
{
CalculateHeading(target);
SetHorizontalVelocity();
//transform.up = heading;
transform.position += velocity * Time.deltaTime;
}
else
{
//tile center reached
transform.position = new Vector3(target.x, target.y, 0);
path.Pop();
if (Math.Abs(heading.x) > Math.Abs(heading.y))
{
if (heading.x >= 0)
{
this.GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>(name+"/right/1");
}
else
{
this.GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>(name +"/left/1");
}
}
else
{
if (heading.y >= 0)
{
this.GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>(name+"/up/1");
}
else
{
this.GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>(name+"/down/1");
}
}
transform.position = new Vector3(transform.position.x, transform.position.y, 0);
}
}
else
{
GetCurrentTile();
currentTile.occupier = this;
currentTile.occupied = true;
RemoveSelectableTiles();
moving = false;
attackphase = true;
if (this.tag == "Player")
{
StartCoroutine(Touchwait());
}
//until npc attack is implemented
if(this.tag=="NPC"){
FindSelectableTiles(attack);
foreach(Tile t in selectableTiles){
if (t.occupied)
{
if (t.occupier.tag != this.tag)
{
Attack(t);
break;
}
}
}
TurnManager.EndTurn();
attackphase = false;
}
}
}
//calculate velocity
void SetHorizontalVelocity()
{
velocity = heading * movespeed;
}
//move direction calculation and sprite assignment
void CalculateHeading(Vector3 target)
{
heading = target - transform.position;
heading = new Vector3(heading.x, heading.y, 0);//remove any rouge z movement to minimize
heading.Normalize();
if (Math.Abs(heading.x) > Math.Abs(heading.y))
{
if (heading.x >= 0)
{
this.GetComponent<SpriteRenderer>().sprite = right;
}
else
{
this.GetComponent<SpriteRenderer>().sprite = left;
}
}
else
{
if (heading.y >= 0)
{
this.GetComponent<SpriteRenderer>().sprite = up;
}
else
{
this.GetComponent<SpriteRenderer>().sprite = down;
}
}
}
//remove all selectable tiles from list for recalculation
protected void RemoveSelectableTiles()
{
if (currentTile != null)
{
currentTile.current = false;
currentTile = null;
}
foreach (Tile t in selectableTiles)
{
t.Reset();
}
selectableTiles.Clear();
}
//NPC Move related, A* algorithm
protected Tile FindEndTile(Tile t)
{
Stack<Tile> tempPath = new Stack<Tile>();
Tile next = t.parent;
while (next != null)
{
tempPath.Push(next);
next = next.parent;
}
if (tempPath.Count <= move)
{
return t.parent;
}
Tile endTile = null;
for (int i = 0; i <= move; i++)
{
endTile = tempPath.Pop();
}
return endTile;
}
protected void FindPath(Tile target)
{
ComputeAdjacencyLists(target);
GetCurrentTile();
List<Tile> openList = new List<Tile>();//every tile that was not processed
List<Tile> closedList = new List<Tile>();//every tile that was processed
openList.Add(currentTile);
currentTile.h = Vector3.Distance(currentTile.transform.position, target.transform.position);
currentTile.f = currentTile.h;
while (openList.Count > 0)
{
Tile t = FindLowestF(openList);
closedList.Add(t);
if (t == target)
{
actualTargetTile = FindEndTile(t);
MoveToTile(actualTargetTile);
return;
}
foreach (Tile tile in t.adjacentcyList)
{
if (closedList.Contains(tile))
{
Debug.Log("Path not found1");
//in closed list, do nothing
}
else if (openList.Contains(tile))
{//found second way to this tile
float tempG = t.g + Vector3.Distance(tile.transform.position, t.transform.position);
if (tempG < tile.g)
{
tile.parent = t;
tile.g = tempG;
tile.f = tile.g + tile.h;
}
}
else//on none of the lists
{
tile.parent = t;
tile.g = t.g + Vector3.Distance(tile.transform.position, t.transform.position);
tile.h = Vector3.Distance(tile.transform.position, target.transform.position);
tile.f = tile.h + tile.g;
openList.Add(tile);
}
}
}
//todo: if no path
//Debug.Log("Path not found");
}
protected Tile FindLowestF(List<Tile> list)
{
Tile lowest = list[0];
foreach (Tile t in list)
{
if (t.f < lowest.f)
{
lowest = t;
}
}
list.Remove(lowest);
return lowest;
}
//end of A* methods
//start unit turn
public void BeginTurn()
{
GetCurrentTile();
currentTile.occupier = this;
currentTile.occupied = true;
turn = true;
}
//end unit turn
public void EndTurn()
{
turn = false;
}
//wait between touches to prevent early end turn
IEnumerator Touchwait()
{
TurnManager.cantouch = false;
yield return new WaitForSeconds(0.5f);
TurnManager.cantouch = true;
}
protected void Attack(Tile t)
{
if (t != null&&t.occupied)
{
t.occupier.hp = t.occupier.hp - this.attack;
float reduced = (float)this.attack / (float)t.occupier.mhp;
Vector3 scaleChange = new Vector3(-reduced, 0, 0);
t.occupier.hpbar.transform.localScale += scaleChange;
Debug.Log(this.name);
if (t.occupier.hp <= 0)
{
TurnManager.RemoveUnit(t.occupier);
}
if (this.tag == "Player")
{
StartCoroutine(Touchwait());
}
}
}
}
|
38385d06421282c601910a81bafe760716cbd2b7
|
C#
|
acmercyj/Framework
|
/Assets/Scripts/Base/Utils/FileUtil.cs
| 3.015625
| 3
|
/**
* 文件工具类
*/
using System;
using System.IO;
namespace Base.Utils
{
using Debug;
public class FileUtil
{
/// <summary>
/// 读取文件
/// </summary>
public static byte[] ReadFile(string fullpath)
{
byte[] buffer = null;
if (File.Exists(fullpath))
{
FileStream fs = null;
try
{
fs = File.OpenRead(fullpath);
buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
}
catch (Exception e)
{
Debugger.LogError("ReadFile() Path:{0}, Error:{1}", fullpath, e.Message);
}
finally
{
if (fs != null)
fs.Close();
}
}
else
{
Debugger.LogError("ReadFile() File is Not Exist:{0}", fullpath);
}
return buffer;
}
/// <summary>
/// 保存数据到文件
/// </summary>
public static int SaveFile(string fullpath, byte[] content)
{
if (content == null)
content = new byte[0];
string dir = PathUtil.GetParentDir(fullpath);
if (!Directory.Exists(dir))
{
try
{
Directory.CreateDirectory(dir);
}
catch (Exception e)
{
Debugger.LogError("SaveFile() CreateDirectory Error! Dir:{0}, Error:{1}", dir, e.Message);
return -1;
}
}
FileStream fs = null;
try
{
fs = new FileStream(fullpath, FileMode.Create, FileAccess.Write);
fs.Write(content, 0, content.Length);
}
catch (Exception e)
{
Debugger.LogError("SaveFild() Path:{0}, Error{1}", fullpath, e.Message);
fs.Close();
return -1;
}
fs.Close();
return content.Length;
}
/// <summary>
/// 判断是否存在
/// </summary>
public static bool Exists(string fullpath)
{
return File.Exists(fullpath);
}
}
}
|
48c53f7157b2f68d6f1c25e46a44b89c1d2c71f5
|
C#
|
ahmedshuhel/NUnitEX
|
/NUnitEx/ExtensionsImpl/AssertionInfo.cs
| 2.8125
| 3
|
using System;
namespace NUnit.Framework.ExtensionsImpl
{
public interface INegable
{
void Nagate();
}
public class AssertionInfo<T> : IAssertionInfo<T>, INegable
{
private readonly Func<string> messageBuilder;
public AssertionInfo(T actual)
{
Actual = actual;
}
public AssertionInfo(T actual, Func<string> messageBuilder)
{
this.messageBuilder = messageBuilder;
Actual = actual;
}
#region Implementation of IAssertionInfo<T>
public T Actual { get; private set; }
public bool IsNegated { get; private set; }
public string FailureMessage
{
get { return messageBuilder != null ? messageBuilder() : null; }
}
#endregion
#region INegable Members
void INegable.Nagate()
{
IsNegated = !IsNegated;
}
#endregion
}
}
|
9cc1cffe1e744c2adfec52e0998872706d35c314
|
C#
|
Valryia/calc
|
/SuperCalculator/Presenter/CalculatorPresenter.cs
| 2.671875
| 3
|
using System.Collections.Generic;
using System.Numerics;
using SuperCalculator.Model;
using SuperCalculator.Service;
namespace SuperCalculator.Presenter
{
public class CalculatorPresenter
{
private readonly CalculatorView calculatorView;
private readonly CalculatorService calculatorService;
public CalculatorPresenter(CalculatorView calculatorView, CalculatorService calculatorService)
{
this.calculatorView = calculatorView;
this.calculatorService = calculatorService;
calculatorView.SetData += SetNumbers;
calculatorView.OperationExecuteEvent += ExecuteOperationExecute;
calculatorView.OperationRedoEvent += Redo;
calculatorView.OperationUndoEvent += Undo;
calculatorView.AggregateOperationExecuteEvent += ExecuteAggregateOperationExecute;
}
private void ExecuteAggregateOperationExecute(Operation operation)
{
List<BigInteger> numbers = calculatorService.Execute(operation);
calculatorView.UpdateTemporaryOutput(numbers);
calculatorView.updateAllOperations(calculatorService.GetAllOperationsCount());
calculatorView.updateCurrentOperation(calculatorService.GetCurrentOperation());
}
private void Undo()
{
List<BigInteger> numbers = calculatorService.Undo();
calculatorView.UpdateNumbers(numbers);
calculatorView.updateAllOperations(calculatorService.GetAllOperationsCount());
calculatorView.updateCurrentOperation(calculatorService.GetCurrentOperation());
}
private void Redo()
{
List<BigInteger> numbers = calculatorService.Redo();
calculatorView.UpdateNumbers(numbers);
calculatorView.updateAllOperations(calculatorService.GetAllOperationsCount());
calculatorView.updateCurrentOperation(calculatorService.GetCurrentOperation());
}
private void SetNumbers(List<BigInteger> numbers)
{
calculatorService.SetData(numbers);
calculatorView.UpdateNumbers(numbers);
}
private void ExecuteOperationExecute(Operation operation)
{
List<BigInteger> numbers = calculatorService.Execute(operation);
calculatorView.UpdateNumbers(numbers);
calculatorView.updateAllOperations(calculatorService.GetAllOperationsCount());
calculatorView.updateCurrentOperation(calculatorService.GetCurrentOperation());
}
}
}
|
046fc155dcca35913752fc406e9ba63f972f4a90
|
C#
|
visweswarpenti/ArticlesDemo
|
/ArticlesProject/Controllers/CommentController.cs
| 2.5625
| 3
|
using ArticlesProject.DatabaseEntities;
using ArticlesProject.Repository;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace ArticlesProject.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CommentController : ControllerBase
{
IUnitOfWork _uow;
public CommentController(IUnitOfWork uow)
{
_uow = uow;
}
// GET: api/<CommentController>
[HttpGet]
public ActionResult<IEnumerable<Comment>> Get()
{
return Ok(_uow.CommentRepo.GetAll());
}
// GET api/<CommentController>/5
[HttpGet("{id}")]
public ActionResult<Comment> Get(int id)
{
return _uow.CommentRepo.Find(id);
}
// POST api/<CommentController>
[HttpPost]
public IActionResult Post(Comment comment)
{
_uow.CommentRepo.Add(comment);
_uow.SaveChanges();
return Ok();
}
// PUT api/<CommentController>/5
[HttpPut("{id}")]
public ActionResult<Comment> Put(int id, [FromBody] Comment value)
{
Comment article = _uow.CommentRepo.Find(id);
if (article != null)
{
_uow.CommentRepo.Update(value);
_uow.SaveChanges();
}
return Ok(value);
}
// DELETE api/<CommentController>/5
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
Comment article = _uow.CommentRepo.Find(id);
if (article != null)
{
_uow.CommentRepo.DeleteById(id);
_uow.SaveChanges();
}
return Ok();
}
}
}
|
3b05c4e06983ff878bb3848cb4d84df256b99893
|
C#
|
AlexCernov/cms-new
|
/CMS/CMS/Repositories/Entities/ConferenceRepository.cs
| 2.875
| 3
|
using CMS.Exceptions;
using CMS.Models;
using System;
using System.Collections.Generic;
using System.Linq;
namespace CMS.Repositories.Entities
{
public class ConferenceRepository : IEntityRepository<Conference>
{
public Conference Add(Conference entity)
{
try
{
using (DatabaseContext context = new DatabaseContext())
{
context.Conferences.Add(entity);
context.SaveChanges();
}
}
catch (System.Exception)
{
throw new DatabaseException("Cannot connect to Database!\n");
}
return entity;
}
public Conference Delete(Conference entity)
{
try
{
using (DatabaseContext context = new DatabaseContext())
{
context.Conferences.Remove(entity);
context.SaveChanges();
}
}
catch (System.Exception)
{
throw new DatabaseException("Cannot connect to Database!\n");
}
return entity;
}
public IList<Conference> FindAll()
{
IList<Conference> conferences = new List<Conference>();
try
{
using (DatabaseContext context = new DatabaseContext())
{
conferences = context.Conferences.ToList();
}
}
catch (System.Exception)
{
throw new DatabaseException("Cannot connect to Database!\n");
}
return conferences;
}
public Conference Update(Conference entity)
{
try
{
using (DatabaseContext context = new DatabaseContext())
{
context.Conferences.Remove(entity);
context.SaveChanges();
}
}
catch (System.Exception)
{
throw new DatabaseException("Cannot connect to Database!\n");
}
return entity;
}
}
}
|
f29891fb52be4ef6c08c35324a2b9df1f3250a4b
|
C#
|
mansiadoshi/CodingClass1
|
/CodingClass_7_3_2019/CodingClassContext.cs
| 2.53125
| 3
|
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
namespace CodingClass_7_3_2019
{
public class CodingClassContext : DbContext
{
public DbSet<StudentAccount> StudentAccounts { get; set; }
public DbSet<StudentCourseHistory> StudentHistory { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=CodingClass_1stProject;Integrated Security=True;Connect Timeout=30;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<StudentAccount>(e =>
{
e.HasKey(a => a.StudentAccountNumber).HasName("PK_AccountNumber");
e.ToTable("StudentAccounts");
e.Property(a => a.StudentAccountNumber).ValueGeneratedOnAdd();
e.Property(a => a.StudentEmailAddress).IsRequired().HasMaxLength(100);
e.Property(a => a.StudentDifficultyLevel).IsRequired();
e.Property(a => a.StudentClassType).IsRequired();
}
);
modelBuilder.Entity<StudentCourseHistory>(e =>
{
e.ToTable("StudentHistory");
e.HasKey(h => h.CourseHistoryID).HasName("PK_CourseHistoryID");
e.Property(h => h.ClassesEnrolledFor).IsRequired();
e.HasOne(h => h.account).WithMany().HasForeignKey(h => h.AccountNumber);
}
);
}
}
}
|
ddcbd7e9dbeb03509a9d3d9841fd0696f23f44d3
|
C#
|
piksel/ConLib
|
/src/ConLib/PrettyConsole.Public.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using ConLib.Console;
namespace ConLib
{
public static partial class PrettyConsole
{
public static List<IConsoleFormatter> PrettyFormatters => Fmts;
public static void Write(FormattableString fs, params ConCol?[] conCols)
{
foreach (var fmt in Fmts) fmt.Write(fs, conCols);
}
public static void WriteLine(FormattableString fs, params ConCol?[] conCols)
{
foreach (var fmt in Fmts) fmt.WriteLine(fs, conCols);
}
public static void WriteLine()
{
foreach (var fmt in Fmts) fmt.WriteLine();
}
public static void WriteColor(string text, ConCol color)
{
foreach (var fmt in Fmts) fmt.WriteColor(text, color);
}
public static void Write(Exception x, string? context = null)
{
foreach (var fmt in Fmts) fmt.Write(x, context);
}
public static void Write(TimeSpan elapsed)
{
foreach (var fmt in Fmts) fmt.Write(elapsed);
}
public static void PushGroup(string? type = null)
{
foreach (var fmt in Fmts) fmt.PushGroup(type);
}
public static void PopGroup(bool wasWrittenTo = true)
{
foreach (var fmt in Fmts) fmt.PopGroup(wasWrittenTo);
}
public static void WriteVersion<T>() => WriteVersion(typeof(T).Assembly.GetName().Version);
public static void WriteVersion(Version? version = null)
{
version ??= typeof(PrettyConsole).Assembly.GetName().Version;
Write($"v{version.Major}.{version.Minor}.{version.Build}");
}
}
}
|
fc4fc7f84282b0face36130a4d23861b43d9c709
|
C#
|
bezourokq/RobotFashion
|
/Assets/Scripts/Controllers/PlayerControl.cs
| 2.515625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerControl : MonoBehaviour
{
float inputX;
float inputY;
string lastKey;//last key pressed, w or s
float vel = 1f;
public GameObject upperG, downG;
public Sprite upperSide1, upperSide2, downSide1, downSide2;
public GameObject inventory;
bool showInventory;
int money = 100;//start money
public Text text;//money text
void Start()
{
showInventory = false;
inventory.SetActive(false);
lastKey = "w";
}
void Update()
{
if (Input.GetKeyDown("space") && !Input.GetMouseButton(0))
{
showInventory = !showInventory;
inventory.SetActive(showInventory);
}
else if (Input.GetKeyDown("s"))
lastKey = "w";
else if (Input.GetKeyDown("w"))
lastKey = "s";
else if (Input.GetKeyDown("r"))
{
upperG.GetComponent<SpriteRenderer>().sprite = null;
downG.GetComponent<SpriteRenderer>().sprite = null;
upperSide1 = null;
upperSide2 = null;
downSide1 = null;
downSide2 = null;
}
inputY = Input.GetAxis("Vertical");
inputX = Input.GetAxis("Horizontal");
Vector3 movement = new Vector3(inputX, inputY, 0);
movement *= Time.deltaTime / vel;
transform.Translate(movement);
updateCloth();
gameObject.GetComponent<Animator>().SetFloat("Direction", inputY);
}
//Updates the clothes using the direction the player is facing, do not works on directional keys
void updateCloth()
{
if(lastKey == "w")
{
upperG.GetComponent<SpriteRenderer>().sprite = upperSide1;
downG.GetComponent<SpriteRenderer>().sprite = downSide1;
}
else
{
upperG.GetComponent<SpriteRenderer>().sprite = upperSide2;
downG.GetComponent<SpriteRenderer>().sprite = downSide2;
}
}
//detect the clothes on top of the player on the drop and drag mechanic, if the item has the name bought the player can wear
private void OnCollisionEnter2D(Collision2D Collider)
{
GameObject temp = Collider.gameObject;
if (temp.name.Contains("bought"))
{
temp.GetComponent<ItemControl>().resetPosition();
temp.GetComponent<BoxCollider2D>().isTrigger = true;
Item item = temp.GetComponent<ItemControl>().getItem();
if (item.getCloth().getModel() == 1 || item.getCloth().getModel() == 2)
{
//upperG.GetComponent<SpriteRenderer>().sprite = item.GetCloth().getFront();
upperSide1 = item.getCloth().getFront();
upperSide2 = item.getCloth().getBack();
}
else
{
//downG.GetComponent<SpriteRenderer>().sprite = item.GetCloth().getFront();
downSide1 = item.getCloth().getFront();
downSide2 = item.getCloth().getBack();
}
updateCloth();
}
}
//control the money that the player has
public void setMoney(int transaction)
{
money = money + transaction;
text.text = money.ToString();
}
}
|
d4b4d0773cf1f899d3686235fa90c2ed337ec95a
|
C#
|
MansurKurtov/NumberSystems
|
/DecimalNumberSystem/DecimalNumber.cs
| 3.546875
| 4
|
using CoreNumberSystem;
using System;
namespace DecimalNumberSystem
{
public class DecimalNumber : INumberSystem
{
public string Add(string a, string b)
{
int number_one = Convert.ToInt32(a, 10);
int number_two = Convert.ToInt32(b, 10);
return Convert.ToString(number_one + number_two, 10);
}
public string Multiply(string a, string b)
{
int number_one = Convert.ToInt32(a, 10);
int number_two = Convert.ToInt32(b, 10);
return Convert.ToString(number_one * number_two, 10);
}
public string Subtract(string a, string b)
{
int number_one = Convert.ToInt32(a, 10);
int number_two = Convert.ToInt32(b, 10);
return Convert.ToString(number_one - number_two, 10);
}
}
}
|
238b785f52ea146afdcfad887ebeaaddb71f052e
|
C#
|
TeamOrg/WorkPackRestructured
|
/WorkpackCore/BusinessLibrary/BLDesignationRepository.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DataAccessLibrary;
using DomainModelLibrary;
namespace BusinessLibrary
{
public class BLDesignationRepository : IBLDesignationRepository
{
private readonly WorkpackDBContext _context;
private readonly IGenericDataRepository<Designation> _designationRepository;
public BLDesignationRepository(WorkpackDBContext context, IGenericDataRepository<Designation> designationRepository)
{
_context = context;
_designationRepository = designationRepository;
}
public IList<Designation> GetAllDesignations()
{
List<Designation> lst = (from q in _context.Designation select q).ToList<Designation>();
return lst;
}
public List<object> GetAllDesgn()
{
List<object> lst = null;
//using (var context = new Cubicle_EntityEntities())
//{
// lst = (from q in context.Designations select new { q.DesignationID, q.DesignationName, q.DesignationCode, q.DisplayOrder, q.DistributationReq }).ToList<object>();
//}
return lst;
}
public Designation GetDesignationByID(Int32 designationID)
{
//Func<T, bool> where, params Expression<Func<T, object>>[] navigationProperties
return _designationRepository.GetSingle(d => d.DesignationID == designationID);
//include related employees
}
public void AddDesignation(params Designation[] department)
{
/* Validation and error handling omitted */
try
{
_designationRepository.Add(department);
}
catch (Exception ex)
{
//bool false = BusinessLogicExceptionHandler.HandleException(ref ex);
if (false)
{
throw ex;
}
}
}
public void UpdateDesignation(params Designation[] department)
{
/* Validation and error handling omitted */
try
{
_designationRepository.Update(department);
}
catch (Exception ex)
{
//bool false = BusinessLogicExceptionHandler.HandleException(ref ex);
if (false)
{
throw ex;
}
}
}
public void RemoveDesignation(params Designation[] department)
{
/* Validation and error handling omitted */
try
{
_designationRepository.Remove(department);
}
catch (Exception ex)
{
throw ex;
////bool false = BusinessLogicExceptionHandler.HandleException(ref ex);
//if (false)
//{
// throw ex;
//}
}
}
public Boolean CheckDuplicate(Designation designation, Boolean IsInsert)
{
Boolean Result = true;
try
{
var c = _designationRepository.GetSingle(p => p.DesignationName.ToUpper() == designation.DesignationName.ToUpper());
if (!IsInsert)
{
if (c == null)
Result = true;
else if (c.DesignationID == designation.DesignationID)
Result = true;
else
Result = false;
}
else
{
if (c == null)
Result = true;
else
Result = false;
}
}
catch (Exception ex)
{
//bool false = BusinessLogicExceptionHandler.HandleException(ref ex);
if (false)
{
throw ex;
}
}
return Result;
}
public IList<Designation> GetDesignationList(Designation designation)
{
IList<Designation> fetchedClient = new List<Designation>();
try
{
//using (var Context = new Cubicle_EntityEntities())
//{
// IQueryable<Designation> query = Context.Designations;
// if (designation.DesignationName != string.Empty)
// query = query.Where(p => p.DesignationName.ToUpper().Contains(designation.DesignationName.ToUpper()));
// if (designation.DesignationCode != string.Empty)
// query = query.Where(p => p.DesignationCode.ToUpper().Contains(designation.DesignationCode.ToUpper()));
// fetchedClient = query.ToList();
//}
}
catch (Exception ex)
{
//bool false = BusinessLogicExceptionHandler.HandleException(ref ex);
if (false)
{
throw ex;
}
}
return fetchedClient;
}
public List<Designation> GetDistinctDesignationByDepartment(int DepartmentID)
{
List<Designation> List = null;
try
{
//using (var context = new Cubicle_EntityEntities())
//{
// List = (from u in context.Users
// join d in context.Designations on u.DesignationID equals d.DesignationID
// where u.DepartmentID == DepartmentID
// select d).Distinct().ToList<Designation>();
//}
}
catch (Exception ex)
{
//bool false = BusinessLogicExceptionHandler.HandleException(ref ex);
if (false)
{
throw ex;
}
}
return List;
}
public static IList<Designation> GetDesignationByDept(int Dept, int Project, int ClientAsset)
{
IList<Designation> list = null;
try
{
//using (var db = new Cubicle_EntityEntities())
//{
// list = (from dg in db.Designations
// join
// pt in db.ProjectTaskLists on dg.DesignationID equals pt.DesignationID
// join
// p in db.Projects on pt.ProjectID equals p.ProjectID
// where pt.ProjectID == (Project == 0 ? pt.ProjectID : Project)
// && pt.DepatmentID == (Dept == 0 ? pt.DepatmentID : Dept)
// && p.ClientAssetID == (ClientAsset == 0 ? p.ClientAssetID : ClientAsset)
// select dg).Distinct().ToList();
//}
}
catch (Exception ex)
{
}
return list;
}
}
}
|
3669c1fd6a5685f5ff4451fe83c7640c575536cb
|
C#
|
AnshukAggarwal/HTTP5204Assignment2
|
/PetGrooming/Controllers/SpeciesController.cs
| 2.859375
| 3
|
using System;
using System.Collections.Generic;
using System.Data;
//required for SqlParameter class
using System.Data.SqlClient;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using PetGrooming.Data;
using PetGrooming.Models;
using System.Diagnostics;
namespace PetGrooming.Controllers
{
public class SpeciesController : Controller
{
private PetGroomingContext db = new PetGroomingContext();
// GET: Species
public ActionResult List()
{ //this methods return the list of species.
//we can get the list by running a query
List<Species> species = db.Species.SqlQuery("Select * from Species").ToList();
return View(species);
}
public ActionResult Show(int? id)
{ //this methods shows a particular species.
//referrenced from the inclass example
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Species species = db.Species.SqlQuery("select * from species where speciesid=@SpeciesID", new SqlParameter("@SpeciesID", id)).FirstOrDefault();
if (species == null)
{
return HttpNotFound();
}
return View(species);
}
public ActionResult Add()
{
//this method simply returns a view where a user can add a species
return View();
}
[HttpPost]
public ActionResult Add(string SpeciesName)
{ //this method takes the input from the user, pulls that data from the input fields and adds it to the DB
string query = "insert into species (Name) values (@SpeciesName)";
SqlParameter param = new SqlParameter("@SpeciesName", SpeciesName);
db.Database.ExecuteSqlCommand(query, param);
return RedirectToAction("List");
}
public ActionResult Update(int id)
{
//this method shows a particular species which the user can update
Species selectedspecies = db.Species.SqlQuery("select * from species where speciesid =@SpeciesID", new SqlParameter("@SpeciesID", id)).FirstOrDefault();
return View(selectedspecies);
}
[HttpPost]
public ActionResult Update (int id, string SpeciesName)
{ //this method takes the input from the user, pulls that data from the input fields and adds it to the DB
string query= "update species set Name=@SpeciesName where SpeciesID=@SpeciesID";
SqlParameter[] sqlparams = new SqlParameter[2];
sqlparams[0] = new SqlParameter("@SpeciesName", SpeciesName);
sqlparams[1] = new SqlParameter("@SpeciesID", id);
db.Database.ExecuteSqlCommand(query, sqlparams);
return RedirectToAction("List");
}
public ActionResult Delete(int? id)
{
//this method shows a particular species which the user can delete
Species selectedspecies = db.Species.SqlQuery("select * from species where speciesid =@SpeciesID", new SqlParameter("@SpeciesID", id)).FirstOrDefault();
return View(selectedspecies);
}
[HttpPost]
public ActionResult Delete(int id)
{ //this method executes the query to delete the species record
string query = "Delete from species where speciesid= @SpeciesID";
SqlParameter sqlparam = new SqlParameter("@SpeciesID", id);
db.Database.ExecuteSqlCommand(query, sqlparam);
return RedirectToAction("List");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
e9af7f5ba95d82ae6ff2b033dbfcb09c10c72eef
|
C#
|
iamprovidence/My_Little_Programs
|
/EFCore.MongoDB/EFCore.MongoDB/MongoDbContext.cs
| 2.515625
| 3
|
using EFCore.MongoDB.Migrations;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using SimpleMigrations;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Reflection;
namespace EFCore.MongoDB
{
public abstract class MongoDbContext
{
private readonly MongoDbConfiguration _configuration;
private readonly IMongoDatabase _database;
public MongoDbContext(IOptions<MongoDbConfiguration> options)
{
_configuration = options.Value;
_database = _configuration.Open();
}
public IMongoCollection<TEntity> GetCollection<TEntity>()
where TEntity : class
{
var collectionName = typeof(TEntity).GetCustomAttribute<TableAttribute>().Name;
return _database.GetCollection<TEntity>(collectionName);
}
public void Migrate(Assembly migrationsAssembly)
{
var databaseProvider = new MongoDbDatabaseProvider(_configuration, _database);
var migrator = new SimpleMigrator<MongoDbConfiguration, MongoDbMigrationBase>(migrationsAssembly, databaseProvider);
migrator.Load();
migrator.MigrateToLatest();
}
protected abstract void OnModelCreating();
protected static void ApplyConfigurationsFromAssembly(Assembly assembly)
{
foreach (var configuration in LoadConfigurationsFromAssembly(assembly))
{
Activator.CreateInstance(configuration);
}
}
private static IEnumerable<Type> LoadConfigurationsFromAssembly(Assembly assembly)
{
return assembly
.GetTypes()
.Where(t => t.IsClass)
.Where(t => !t.IsAbstract)
.Where(t => t.BaseType != null)
.Where(t => t.BaseType.IsGenericType)
.Where(t => t.BaseType.GetGenericTypeDefinition() == typeof(EntityConfigurationBase<>));
}
}
}
|
b73637857ecb4138b6489aebd1c4ecf51f80d7fa
|
C#
|
thesparrow/egreetingcore
|
/halloween/Pages/Read.cshtml.cs
| 2.609375
| 3
|
using egreeting.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace egreeting.Pages
{
public class ReadModel: PageModel
{
//Database related - connect to our model
[BindProperty]
public Greetings Greetings { get; set; }
//Connection to db
private Database _dbContext { get; set; }
//Create the database connection through the constructor
public ReadModel(Database dbContext)
{
_dbContext = dbContext;
}
public IActionResult OnGet(int ID = 0)
{
if (ID > 0)
{
Greetings = _dbContext.Greetings.Find(ID);
}
if(Greetings == null)
return RedirectToPage("Index");
return Page();
}
}
}
|
78ef3b9d7b052d123ffaafa3f5cfbc384fbcd3f7
|
C#
|
ninerats/Launcher
|
/SampleApp/Launcher/Lancher.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Craftsmaneer.Lang;
namespace SampleApp.Launcher
{
public class Lancher
{
/// <summary>
/// bath to the base directory for the launcher application.
/// </summary>
private readonly string _rootPath;
public Lancher(string rootPath)
{
_rootPath = rootPath;
}
/// <summary>
/// replaces the running app with the specified version.
/// </summary>
/// <returns></returns>
public ReturnValue Upgrade(string appName, string targetVersion)
{
return ReturnValue.Wrap(() =>
{
var launcherExePath = Path.Combine(_rootPath, "Launcher.exe");
if (!File.Exists(launcherExePath)) throw new FileNotFoundException("Launcher.exe not folder in folder", _rootPath);
var startInfo = new ProcessStartInfo(launcherExePath)
{
WorkingDirectory = _rootPath,
UseShellExecute = true,
Arguments = string.Format("upgradeAndLaunch {0} {1} {2}",AppDomain.CurrentDomain.BaseDirectory, appName, targetVersion)
};
Debug.WriteLine(string.Format("path: {0}", startInfo.FileName));
Debug.WriteLine(string.Format("args: {0}", string.Join(" ", startInfo.Arguments)));
Process.Start(startInfo);
}, string.Format("Upgrading app '{0}' to version '{1}'", appName,targetVersion));
}
}
}
|
1892afd097e433206164511f96ef50fe89956cd3
|
C#
|
ChoiHyeonHo/CHH_PJT2
|
/CHH_PJT2/Util/Util/CommonUtil.cs
| 2.515625
| 3
|
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CHH_PJT2
{
class CommonUtil
{
public static void SetInitGridView(DataGridView dgv)
{
dgv.AutoGenerateColumns = false;
dgv.AllowUserToAddRows = false;
dgv.SelectionMode = DataGridViewSelectionMode.CellSelect;
}
public static void AddGridTextColumn(
DataGridView dgv,
string headerText,
string dataPropertyName,
int colWidth = 100,
bool visibility = true,
DataGridViewContentAlignment textAlign = DataGridViewContentAlignment.MiddleLeft)
{
DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
col.Name = dataPropertyName;
col.HeaderText = headerText;
col.DataPropertyName = dataPropertyName;
col.Width = colWidth;
col.DefaultCellStyle.Alignment = textAlign;
col.Visible = visibility;
col.ReadOnly = true;
dgv.Columns.Add(col);
}
public static void BindingComboBox(ComboBox cbo, System.Data.DataTable dt, string valueMember, string displayMember, bool blankItemAdd = true)
{
if (blankItemAdd)
{
DataRow dr = dt.NewRow();
dr[displayMember] = "";
dt.Rows.InsertAt(dr, 0);
dt.AcceptChanges();
}
cbo.ValueMember = valueMember;
cbo.DisplayMember = displayMember;
cbo.DataSource = dt;
}
}
}
|
b342f67b06d20972e015459f895750ad512d4b8a
|
C#
|
syberside/DynamicIsNotMagic
|
/DynamicIsNotMagic/DefaultAndOptionalParameters.cs
| 3.40625
| 3
|
using System;
using NUnit.Framework;
namespace DynamicIsNotMagic
{
[TestFixture]
public class DefaultAndOptionalParameters
{
public void SomeMethodWithDefaultParameters(string message=null)
{
Console.WriteLine(message??"Default messsage here");
}
public void SomeMethodWithOptionalParameters(string m1, string m2=null, string m3=null)
{
Console.WriteLine(m1??"M1 is null");
Console.WriteLine(m2??"M2 is null");
Console.WriteLine(m3??"M3 is null");
Console.WriteLine();
}
[Test]
public void CanUseDefaultParameters()
{
var dynamicObject = this as dynamic;
dynamicObject.SomeMethodWithDefaultParameters("Custom message here");
dynamicObject.SomeMethodWithDefaultParameters();
Console.WriteLine();
}
[Test]
public void CanUseOptionlParameters()
{
var dynamicObject = this as dynamic;
dynamicObject.SomeMethodWithOptionalParameters("some string",m3:"other string");
dynamicObject.SomeMethodWithOptionalParameters("some text");
dynamicObject.SomeMethodWithOptionalParameters();
}
}
}
|
fb131d4ebbcee11e833a903f634d06498e7118ca
|
C#
|
Jorka7a13/SoftUni_CSharpBasics
|
/04. Console-Input-Output-Homework/Problem 12. FallingRocks/FallingRocks.cs
| 3.125
| 3
|
// Implement the "Falling Rocks" game
using System;
using System.Diagnostics;
using System.Threading;
namespace FallingRocks
{
class FallingRocks
{
static Stone[,] array = new Stone[25, 80];
static int difficulty = 4;
static Random rnd = new Random();
static int x, y;
static bool playing = true;
static int score = 0;
static Stopwatch stopwatch = new Stopwatch();
static void GenerateLineOfRocks()
{
char[] rocks = { '^', '@', '*', '&', '+', '%', '$', '#', '!', '.', ';' };
int sizeOfRocks, posOfRock;
int numOfRocks = rnd.Next(1, difficulty);
for (int i = 0; i < numOfRocks; i++)
{
Stone stone = new Stone();
sizeOfRocks = rnd.Next(1, 4);
stone.color = rnd.Next(0, 4);
stone.sign = rocks[rnd.Next(0, rocks.GetLength(0) - 1)];
posOfRock = rnd.Next(0, 77);
for (int j = 0; j < sizeOfRocks; j++)
{
array[0, posOfRock] = stone;
writeStoneAtPos(stone, 0, posOfRock);
posOfRock++;
}
}
}
static void MoveRocksDown()
{
Stone[,] temp = new Stone[25, 80];
for (int i = 0; i < array.GetLength(0); i++)
for (int j = 0; j < array.GetLength(1); j++)
if (i != 24)
temp[i + 1, j] = array[i, j];
array = temp;
Console.MoveBufferArea(0, 0, y, 24, 0, 1); //Move rocks down a line
Console.MoveBufferArea(y + 3, 0, 80 - (y + 3), 24, y + 3, 1);
Console.MoveBufferArea(y, 0, 3, 23, y, 1);
}
static void CollisionDetection()
{
if (array[x, y] != null || array[x, y + 1] != null || array[x, y + 2] != null)
playing = false;
}
static void MoveDwarf()
{
x = Console.WindowTop + Console.WindowHeight - 1;
y = Console.WindowLeft + Console.WindowWidth / 2;
writeStrAtPos("(O)", x, y);
ConsoleKeyInfo key;
while (playing)
{
key = Console.ReadKey();
if (key.Key == ConsoleKey.LeftArrow)
{
if (y > 0)
{
Console.ForegroundColor = ConsoleColor.White;
writeStrAtPos("(O)", x, --y);
writeStrAtPos(" ", x, y + 3);
}
}
else if (key.Key == ConsoleKey.RightArrow)
{
if (y < Console.WindowLeft + Console.WindowWidth - 4)
{
Console.ForegroundColor = ConsoleColor.White;
writeStrAtPos("(O)", x, ++y);
writeStrAtPos(" ", x, y - 1);
}
}
}
}
static void writeStoneAtPos(Stone stone, int x, int y)
{
try
{
if (stone.color == 0)
Console.ForegroundColor = ConsoleColor.White;
else if (stone.color == 1)
Console.ForegroundColor = ConsoleColor.Yellow;
else if (stone.color == 2)
Console.ForegroundColor = ConsoleColor.Gray;
else if (stone.color == 3)
Console.ForegroundColor = ConsoleColor.Cyan;
else if (stone.color == 4)
Console.ForegroundColor = ConsoleColor.Green;
Console.SetCursorPosition(y, x);
Console.Write(stone.sign);
}
catch (ArgumentOutOfRangeException e)
{
Console.Clear();
Console.WriteLine(e.Message);
}
}
static void writeStrAtPos(string s, int x, int y)
{
try
{
Console.SetCursorPosition(y, x);
Console.Write(s);
}
catch (ArgumentOutOfRangeException e)
{
Console.Clear();
Console.WriteLine(e.Message);
}
}
static void Main(string[] args)
{
Console.Title = "Falling Rocks";
Console.BufferHeight = 25;
Console.BufferWidth = 80;
Thread t = new Thread(MoveDwarf);
t.Start();
System.Threading.Thread.Sleep(250);
stopwatch.Start();
while (playing)
{
GenerateLineOfRocks();
System.Threading.Thread.Sleep(150);
MoveRocksDown();
CollisionDetection();
score += 10;
}
stopwatch.Start();
Console.Clear();
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("GAME OVER!");
Console.WriteLine("Your score was: " + (score - 240));
Console.WriteLine("Yor time was: " + stopwatch.Elapsed.ToString("mm\\:ss\\.ff"));
Console.WriteLine("Press ESC to exit");
ConsoleKeyInfo key = Console.ReadKey();
while (key.Key != ConsoleKey.Escape)
key = Console.ReadKey();
}
}
}
|
eff1aa3fcbc12da5759784e481aa06b4ae450dfc
|
C#
|
bcorder/ProjectEuler
|
/Problem19.linq
| 3.265625
| 3
|
<Query Kind="Program" />
void Main()
{
DateTime day = new DateTime(1901, 1, 1);
int numSundays = 0;
while (day <= DateTime.Parse("12/31/2000"))
{
if (day.DayOfWeek.ToString() == "Sunday" && day.Date.ToString().Contains("/1/"))
{
numSundays++;
}
day = day.AddDays(1);
}
Console.WriteLine(numSundays);
}
|
75a24bbfc75c039441b61a032724e547cc24faeb
|
C#
|
uludagsercan/MvcBlogApplication
|
/BusinessLayer/ValidationRules/MessageValidator.cs
| 2.828125
| 3
|
using EntityLayer.Concrete;
using FluentValidation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BusinessLayer.ValidationRules
{
public class MessageValidator : AbstractValidator<Message>
{
public MessageValidator()
{
RuleFor(x => x.MessageSubject).NotEmpty().WithMessage("Konu alanını boş geçemezsiniz.");
RuleFor(x => x.MessageContent).NotEmpty().WithMessage("İçerik alanını boş geçemezsiniz.");
RuleFor(x => x.MessageSubject).MaximumLength(50).WithMessage("Konu alanı en fazla 50 karakterlidir");
RuleFor(x => x.ReceiverMail).MaximumLength(50).WithMessage("Alıcı alanı en fazla 50 karakterlidir");
RuleFor(x => x.MessageSubject).MinimumLength(3).WithMessage("Konu alanı en az 3 karakterlidir");
RuleFor(x => x.ReceiverMail).Must(CheckEmail).WithMessage("Lütfen alıcı mailini düzgün girdiğinizden emin olunuz ve alıcı mail adresi boş geçilemez");
}
private bool CheckEmail (string email)
{
if (email==null)
{
return false;
}
else
{
return true;
}
}
}
}
|
20f70ba44b370b509c01ae70906c516799f4381a
|
C#
|
cvakarna/test-project
|
/DeliveryServiceApp/Customers/CustomerServiceApi.cs
| 2.734375
| 3
|
using DeliveryServiceApp.Model;
using DeliveryServiceApp.Persistence;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
namespace DeliveryServiceApp.Customers
{
public class CustomerServiceApi : ICustomer
{
private readonly string _connectionString;
private readonly DeliveryServiceDBContext _context;
string tableName = "Customers";
public CustomerServiceApi(DeliveryServiceDBContext context)
{
this._context = context;
}
public async Task<Customer> GetCustomerDetailsAsync(string customerId)
{
Customer customer = _context.Customers.Where(cus => cus.Id == customerId).Include(op => op.OrderProducts).FirstOrDefault();
return customer;
}
public async Task OnCreateAsync(JObject customer)
{
//convert customer to object
Customer cusObj = customer.ToObject<Customer>();
_context.Customers.Add(cusObj);
await _context.SaveChangesAsync();
}
public async Task OnDeleteAsync(string customerId)
{
var custmer = new Customer { Id = customerId };
_context.Entry(custmer).State = EntityState.Deleted;
_context.SaveChanges();
}
public async Task OnUpdateAsync(JObject customer)
{
//convert customer obejct
var custmer = customer.ToObject<Customer>();
_context.Customers.Add(custmer);
_context.Entry(custmer).State = EntityState.Modified;
_context.SaveChanges();
}
}
}
|
6f533a655fe1302316dab01a1858b229da797b9a
|
C#
|
dragomanov/telerikacademy
|
/CSharp1/Homework/2. Primitive Data Types and Variables/10. Employee Record Declaration/EmployeeRecordDeclaration.cs
| 2.90625
| 3
|
using System;
class EmployeeRecordDeclaration
{
static void Main()
{
string firstName = "Antoni";
string lastName = "Dragomanov";
byte age = 26;
char gender = 'M'; // or bool isMale; for smaller size
uint id = 27560000;
Console.WriteLine("{0}\n{1}\n{2}\n{3}\n{4}", firstName, lastName, age, gender, id);
}
}
|
3a07157fa4efba7e64f87ba6f58e5eea9609020d
|
C#
|
qclijun/MyShocksocks
|
/MyShadowsocks-UI/ServerConverter.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace MyShadowsocks_UI {
public class ServerConverter : IMultiValueConverter {
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) {
string hostname = values[0] as string;
if(string.IsNullOrEmpty(hostname)) return "New Server";
int port = (int)values[1];
string remarks = values[2] as string;
return string.IsNullOrEmpty(remarks) ? hostname + ":" + port : remarks + "(" + hostname + ":" + port + ")";
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) {
throw new NotImplementedException();
}
}
}
|
38fa80f3a8df11c085e0287ee463509e3bd6eb65
|
C#
|
tomsius/LeetCodeRepo
|
/LeetCode/1394. Find Lucky Integer in an Array/Program.cs
| 3.78125
| 4
|
using System;
namespace _1394._Find_Lucky_Integer_in_an_Array
{
class Program
{
static void Main(string[] args)
{
int[] arr1 = { 2, 2, 3, 4 };
Console.WriteLine(FindLucky(arr1));
int[] arr2 = { 1, 2, 2, 3, 3, 3 };
Console.WriteLine(FindLucky(arr2));
int[] arr3 = { 2, 2, 2, 3, 3 };
Console.WriteLine(FindLucky(arr3));
int[] arr4 = { 5 };
Console.WriteLine(FindLucky(arr4));
int[] arr5 = { 7, 7, 7, 7, 7, 7, 7 };
Console.WriteLine(FindLucky(arr5));
}
public static int FindLucky(int[] arr)
{
Array.Sort(arr);
for (int i = arr.Length - 1; i >= 0; i--)
{
int numberFrequency = 1;
int number = arr[i];
while (i >= 1 && arr[i] == arr[i - 1])
{
numberFrequency++;
i--;
}
if (numberFrequency == number)
{
return number;
}
}
return -1;
}
}
}
|
ce88c9218e7723c25948230bc85368739c3ab7ca
|
C#
|
benadaephondelat/TicTacToe
|
/TicTacToeGame/TicTacToe.ComputerMinMax.Tests/MinMaxComputerTests.cs
| 2.59375
| 3
|
namespace TicTacToe.ComputerMinMax.Tests
{
using System;
using System.Linq;
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ComputerTests.DataMockHelper;
using Computer.Models;
using ComputerMinMax;
using TicTacToeCommon.Exceptions.Computer;
[TestClass]
public class MinMaxComputerTests
{
private DataMockHelper dataLayerMockHelper;
public MinMaxComputerTests()
{
this.dataLayerMockHelper = new DataMockHelper();
}
[TestMethod]
public void MinMaxComputer_Should_Have_Public_Method_Named_GetComputerMoveIndex()
{
ComputerGameModel model = this.dataLayerMockHelper.CreateNewHumanVsComputerGame();
MinMaxComputer computer = new MinMaxComputer();
bool result = computer.GetType()
.GetMethods(BindingFlags.Instance | BindingFlags.Public)
.Any(m => m.Name == "GetComputerMoveIndex");
Assert.IsTrue(result);
}
[TestMethod]
public void MinMaxComputer_GetComputerMoveIndex_Should_Return_Valid_Int_If_Model_Is_Valid()
{
try
{
ComputerGameModel model = this.dataLayerMockHelper.CreateNewHumanVsComputerGame();
MinMaxComputer computer = new MinMaxComputer();
int computerMove = computer.GetComputerMoveIndex(model);
}
catch
{
Assert.Fail();
}
Assert.IsTrue(true);
}
[TestMethod]
public void MinMaxComputer_GetComputerMoveIndex_Method_Should_Return_Int32()
{
ComputerGameModel model = this.dataLayerMockHelper.CreateNewHumanVsComputerGame();
MinMaxComputer computer = new MinMaxComputer();
Type computerType = computer.GetType();
MethodInfo method = computerType.GetTypeInfo()
.DeclaredMethods.FirstOrDefault(m => m.Name == "GetComputerMoveIndex");
Assert.IsNotNull(method);
Assert.IsTrue(method.ToString().Contains("Int32"));
}
[TestMethod]
public void MinMaxComputer_Should_Have_Private_Method_Named_GetComputerMove()
{
ComputerGameModel model = this.dataLayerMockHelper.CreateNewHumanVsComputerGame();
MinMaxComputer computer = new MinMaxComputer();
bool result = computer.GetType()
.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic)
.Any(m => m.Name == "GetComputerMove");
Assert.IsTrue(result);
}
[TestMethod]
public void MinMaxComputer_GetComputerMove_Method_Should_Return_Int32()
{
ComputerGameModel model = this.dataLayerMockHelper.CreateNewHumanVsComputerGame();
MinMaxComputer computer = new MinMaxComputer();
Type computerType = computer.GetType();
MethodInfo method = computerType.GetTypeInfo().DeclaredMethods
.FirstOrDefault(m => m.Name == "GetComputerMove");
Assert.IsNotNull(method);
Assert.IsTrue(method.ToString().Contains("Int32"));
}
[TestMethod]
public void MinMaxComputer_Should_Have_Private_Method_Named_ValidateGame()
{
ComputerGameModel model = this.dataLayerMockHelper.CreateNewHumanVsComputerGame();
MinMaxComputer computer = new MinMaxComputer();
bool result = computer.GetType().GetMethods(BindingFlags.Instance | BindingFlags.NonPublic)
.Any(m => m.Name == "ValidateGame");
Assert.IsTrue(result);
}
[TestMethod]
public void MinMaxComputer_ValidateGame_Method_Return_Type_Should_Be_Void()
{
ComputerGameModel model = this.dataLayerMockHelper.CreateNewHumanVsComputerGame();
MinMaxComputer computer = new MinMaxComputer();
Type computerType = computer.GetType();
var method = computerType.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic)
.FirstOrDefault(m => m.Name == "ValidateGame");
Assert.IsNotNull(method);
string returnTypeName = method.ReturnType.FullName;
bool result = returnTypeName.ToLower().Contains("void");
Assert.IsTrue(result);
}
[TestMethod]
[ExpectedException(typeof(ComputerException))]
public void MinMaxComputer_ValidateGame_Method_Should_Throw_ComputerException_If_Game_Is_Finished()
{
ComputerGameModel model = this.dataLayerMockHelper.CreateNewHumanVsComputerGame();
model.IsFinished = true;
MinMaxComputer computer = new MinMaxComputer();
computer.GetComputerMoveIndex(model);
}
[TestMethod]
[ExpectedException(typeof(ComputerException))]
public void MinMaxComputer_GetComputerMoveIndex_Should_Throw_ComputerException_If_All_Tiles_Are_Taken()
{
ComputerGameModel model = this.dataLayerMockHelper.CreateNewHumanVsComputerGame();
var takenTiles = this.dataLayerMockHelper.GenerateDefaultTilesList();
takenTiles.ForEach(x => { x.Value = "X"; x.IsEmpty = false; });
model.Tiles = takenTiles;
MinMaxComputer computer = new MinMaxComputer();
computer.GetComputerMoveIndex(model);
}
}
}
|
3cda56b26bf288e7307804f3f7aa325018795b41
|
C#
|
kevivm/Finance
|
/Finance/User.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Finance
{
public class User
{
public Dictionary<string, string> Myinfo = new Dictionary<string, string>();
private List<string> _billsPrivat24 = new List<string>();
private List<string> _billsPumb = new List<string>();
private List<string> _billsAlfabank = new List<string>();
internal User(Dictionary<string, string> info)
{
this.Myinfo = info;
}
//Show Start Menu. endless cycle
internal void StartMenu()
{
bool switchFlag = true;
while (switchFlag)
{
Console.Clear();
ConsoleHelper.UserStartMenu();
string myChoice = Console.ReadLine();
switch (myChoice)
{
case "1":
this.OpenAccountInBank();
switchFlag = false;
break;
case "0":
this.GetInfoAboutMe();
switchFlag = false;
break;
case "9":
Environment.Exit(0);
break;
default:
Console.Clear();
switchFlag = true;
break;
}
}
}
// register account in Privat24 overload method
private void RegisterInBank(Bank bank, string typeBill)
{
string bill = bank.OpenAccount();
this.SetBills(typeBill, bill);
this.ShowMessageStartMenu();
}
private void OpenAccountInBank()
{
beginToStart: Console.Clear();
ConsoleHelper.UserIWantToOpenAccountInBank();
string myChoice = Console.ReadLine();
switch (myChoice)
{
case "1":
Privat24 Privat24 = new Privat24(this);
this.RegisterInBank(Privat24, "Privat24");
break;
case "2":
Pumb Pumb = new Pumb(this);
this.RegisterInBank(Pumb, "Pumb");
break;
case "3":
AlfaBank AlfaBank = new AlfaBank(this);
this.RegisterInBank(AlfaBank, "AlfaBank");
break;
case "0":
StartMenu();
break;
default:
goto beginToStart;
break;
}
}
//add to LIST bill value
private void SetBills(string selectBank, string bill)
{
if (bill == "Credit" || bill == "Deposit" || bill == "Checking")
{
switch (selectBank)
{
case "Privat24":
this._billsPrivat24.Add(bill);
this._billsPrivat24 = this._billsPrivat24.Distinct().ToList();
break;
case "Pumb":
this._billsPumb.Add(bill);
this._billsPumb = this._billsPumb.Distinct().ToList();
break;
case "AlfaBank":
this._billsAlfabank.Add(bill);
this._billsAlfabank = this._billsAlfabank.Distinct().ToList();
break;
default:
break;
}
}
}
//0:Info
private void GetInfoAboutMe(bool flag = true)
{
Console.Clear();
if (flag)
{
Console.WriteLine("Name:" + Myinfo["Name"]);
Console.WriteLine("Passport:" + Myinfo["pasportNumber"]);
Console.WriteLine();
}
if (this._billsPrivat24.Count > 0)
{
Console.Write("privat24 bills: ");
foreach (string privat24 in this._billsPrivat24)
{
Console.Write(privat24 + " | ");
}
Console.WriteLine();
}
if (this._billsPumb.Count > 0)
{
Console.Write("Pumb bills: ");
foreach (string pumb in this._billsPumb)
{
Console.Write(pumb + " | ");
}
Console.WriteLine();
}
if (this._billsAlfabank.Count > 0)
{
Console.Write("AlfaBank bills: ");
foreach (string alfa in this._billsAlfabank)
{
Console.Write(alfa + " | ");
}
}
Console.WriteLine();
this.ShowMessageStartMenu();
}
private void ShowMessageStartMenu()
{
ConsoleHelper.UserShowMessageStartMenu();
StartMenu();
}
}
}
|
c8a160f09146653418cb41901e1acb3e0ed677bc
|
C#
|
Broghain/GTO7
|
/Assets/Scripts/Finite State Machines/FiniteStateMachine.cs
| 2.515625
| 3
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public enum StateID
{
None,
ReachedScreenEdge,
AttackingPlayer,
MovingToPosition,
InFormation,
Dead
}
[RequireComponent(typeof(Animator))]
public class FiniteStateMachine : MonoBehaviour {
private Animator stateMachine;
private List<FSMState> states = new List<FSMState>();
private Dictionary<int, StateID> stateDictionary = new Dictionary<int, StateID>();
public StateID currentStateID;
private FSMState currentState;
// Use this for initialization
public void InitializeStateMachine ()
{
stateMachine = GetComponent<Animator>();
//Cache all the hashes of the States in our State Machine (case sensitive!)
foreach (StateID state in (StateID[])System.Enum.GetValues(typeof(StateID)))
{
stateDictionary.Add(Animator.StringToHash("Base Layer." + state.ToString()), state);
}
}
public void UpdateStateMachine()
{
StateID nextStateID = stateDictionary[stateMachine.GetCurrentAnimatorStateInfo(0).fullPathHash];
if (nextStateID != currentStateID) //If state has changed
{
currentStateID = nextStateID;
foreach (FSMState state in states) //Get state
{
if (state.GetStateID() == currentStateID)
{
if (currentState != null)
{
currentState.ResetState();
}
currentState = state;
break;
}
}
}
if (currentState != null)
{
currentState.UpdateState(); //update current state
}
}
public void AddState(FSMState state)
{
states.Add(state);
}
//set values in mecanim state machine
public void SetValue(string paramName, bool value)
{
stateMachine.SetBool(paramName, value);
}
public void SetValue(string paramName, float value)
{
stateMachine.SetFloat(paramName, value);
}
public void SetValue(string paramName, int value)
{
stateMachine.SetInteger(paramName, value);
}
public void SetValue(string paramName)
{
stateMachine.SetTrigger(paramName);
}
}
|
a6e2b24e96a5c961a41f2da30b3fb8625d66ff5d
|
C#
|
jdd817/TankSim
|
/Tank/Talents/TalentAttribute.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tank.Talents
{
public class TalentAttribute:Attribute
{
public TalentAttribute() { }
public TalentAttribute(Type characterClass, int tier, int possition)
{
Class = characterClass;
Tier = tier;
Possition = possition;
}
public Type Class { get; set; }
public int Tier { get; set; }
public int Possition { get; set; }
}
}
|
99955be0088067b9ecd67a6bcffe3a5704fe59d7
|
C#
|
joshball/astrogrep
|
/AstroGrep/libAstroGrep/EncodingDetection/EncodingDetector.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace libAstroGrep.EncodingDetection
{
/// <summary>
/// Detect file encodings.
/// </summary>
/// <remarks>
/// AstroGrep File Searching Utility. Written by Theodore L. Ward
/// Copyright (C) 2002 AstroComma Incorporated.
///
/// This program is free software; you can redistribute it and/or
/// modify it under the terms of the GNU General Public License
/// as published by the Free Software Foundation; either version 2
/// of the License, or (at your option) any later version.
///
/// This program is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU General Public License for more details.
///
/// You should have received a copy of the GNU General Public License
/// along with this program; if not, write to the Free Software
/// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///
/// The author may be contacted at:
/// ted@astrocomma.com or curtismbeard@gmail.com
/// </remarks>
/// <history>
/// [Curtis_Beard] 02/12/2014 Created
/// </history>
public class EncodingDetector
{
/// <summary>
/// The available encoding detectors.
/// </summary>
[Flags]
public enum Options
{
KlerkSoftBom = 1,
KlerkSoftHeuristics = 2,
WinMerge = 4,
MozillaUCD = 8,
MLang = 16
}
/// <summary>
/// Wrapper class for use with DetectAll method.
/// </summary>
/// <history>
/// [Curtis_Beard] 12/01/2014 Created
/// </history>
public class EncodingValue
{
/// <summary>
/// The encoding found by detector
/// </summary>
public Encoding Encoding { get; set; }
/// <summary>
/// The dector used
/// </summary>
public Options Option { get; set; }
}
/// <summary>
/// Gets all detected encodings.
/// </summary>
/// <param name="bytes">Sample bytes to detect encoding</param>
/// <returns>List of EncodingValue object</returns>
/// <history>
/// [Curtis_Beard] 12/01/2014 Created
/// </history>
public static List<EncodingValue> DetectAll(byte[] bytes)
{
List<EncodingValue> values = new List<EncodingValue>();
EncodingValue value = new EncodingValue();
value.Encoding = DetectEncodingUsingKlerksSoftBom(bytes);
value.Option = Options.KlerkSoftBom;
values.Add(value);
value = new EncodingValue();
value.Encoding = DetectEncodingUsingKlerksSoftHeuristics(bytes);
value.Option = Options.KlerkSoftHeuristics;
values.Add(value);
value = new EncodingValue();
value.Encoding = DetectEncodingUsingWinMerge(bytes);
value.Option = Options.WinMerge;
values.Add(value);
value = new EncodingValue();
value.Encoding = DetectEncodingUsingMozillaUCD(bytes);
value.Option = Options.MozillaUCD;
values.Add(value);
value = new EncodingValue();
value.Encoding = DetectEncodingUsingMLang(bytes);
value.Option = Options.MLang;
values.Add(value);
return values;
}
/// <summary>
/// Detects the byte array's encoding based on options passed in.
/// </summary>
/// <param name="bytes">File sample byte array</param>
/// <param name="opts">Flags of encoding dectors to use</param>
/// <param name="defaultEncoding">Default encoding if nothing detected</param>
/// <returns>Encoding detected or default if not detected</returns>
/// <history>
/// [Curtis_Beard] 02/12/2014 Created
/// [Curtis_Beard] 12/01/2014 ADD: support for Mozilla encoding detection, remove KlerkSoftHeuristics as a default
/// </history>
public static Encoding Detect(byte[] bytes, out string usedEncoder, EncodingDetector.Options opts = Options.KlerkSoftBom | Options.WinMerge | Options.MozillaUCD | Options.MLang, Encoding defaultEncoding = null)
{
Encoding encoding = null;
// NOTE: this order determines which is run first, usually Mozilla is better than MLang
if ((opts & Options.KlerkSoftBom) == Options.KlerkSoftBom)
{
encoding = DetectEncodingUsingKlerksSoftBom(bytes);
if (encoding != null)
{
usedEncoder = Options.KlerkSoftBom.ToString();
return encoding;
}
}
if ((opts & Options.KlerkSoftHeuristics) == Options.KlerkSoftHeuristics)
{
encoding = DetectEncodingUsingKlerksSoftHeuristics(bytes);
if (encoding != null)
{
usedEncoder = Options.KlerkSoftHeuristics.ToString();
return encoding;
}
}
if ((opts & Options.WinMerge) == Options.WinMerge)
{
encoding = DetectEncodingUsingWinMerge(bytes);
if (encoding != null)
{
usedEncoder = Options.WinMerge.ToString();
return encoding;
}
}
if ((opts & Options.MozillaUCD) == Options.MozillaUCD)
{
encoding = DetectEncodingUsingMozillaUCD(bytes);
if (encoding != null)
{
usedEncoder = Options.MozillaUCD.ToString();
return encoding;
}
}
if ((opts & Options.MLang) == Options.MLang)
{
encoding = DetectEncodingUsingMLang(bytes);
if (encoding != null)
{
usedEncoder = Options.MLang.ToString();
return encoding;
}
}
// default encoding use since nothing was found
usedEncoder = "Default";
if (encoding == null)
{
encoding = defaultEncoding;
}
return encoding;
}
#region Private Methods
/// <summary>
/// Detects encoding using bom bytes.
/// </summary>
/// <param name="bytes">sample data</param>
/// <returns>Detected encoding or null if not detected</returns>
/// <history>
/// [Curtis_Beard] 02/12/2014 Created
/// </history>
private static Encoding DetectEncodingUsingKlerksSoftBom(byte[] bytes)
{
Encoding encoding = null;
if (bytes.Count() >= 4)
encoding = KlerksSoftEncodingDetector.DetectBOMBytes(bytes);
return encoding;
}
/// <summary>
/// Detects encoding using heuristics.
/// </summary>
/// <param name="bytes">sample data</param>
/// <returns>Detected encoding or null if not detected</returns>
/// <history>
/// [Curtis_Beard] 02/12/2014 Created
/// </history>
private static Encoding DetectEncodingUsingKlerksSoftHeuristics(byte[] bytes)
{
Encoding encoding = KlerksSoftEncodingDetector.DetectUnicodeInByteSampleByHeuristics(bytes);
return encoding;
}
/// <summary>
/// Detects encoding using MLang from Microsoft.
/// </summary>
/// <param name="bytes">sample data</param>
/// <returns>Detected encoding or null if not detected</returns>
/// <history>
/// [Curtis_Beard] 02/12/2014 Created
/// </history>
private static Encoding DetectEncodingUsingMLang(Byte[] bytes)
{
try
{
Encoding[] detected = EncodingTools.DetectInputCodepages(bytes, 1);
if (detected.Length > 0)
{
return detected[0];
}
}
catch { }
return null;
}
/// <summary>
/// Detects encoding using WinMerge algorithm.
/// </summary>
/// <param name="bytes">sample data</param>
/// <returns>Detected encoding or null if not detected</returns>
/// <history>
/// [Curtis_Beard] 02/12/2014 Created
/// </history>
private static Encoding DetectEncodingUsingWinMerge(Byte[] bytes)
{
return WinMergeEncodingDetector.DetectEncoding(bytes, bytes.Length);
}
/// <summary>
/// Detects encoding using mozilla universal character detector.
/// </summary>
/// <param name="bytes">sample data</param>
/// <returns>Detected encoding or null if not detected</returns>
/// <history>
/// [Curtis_Beard] 12/01/2014 Created
/// </history>
private static Encoding DetectEncodingUsingMozillaUCD(Byte[] bytes)
{
try
{
Ude.ICharsetDetector cdet = new Ude.CharsetDetector();
cdet.Feed(bytes, 0, bytes.Length);
cdet.DataEnd();
if (cdet.Charset != null)
{
return Encoding.GetEncoding(cdet.Charset);
}
}
catch { }
return null;
}
#endregion
}
}
|
c4856d795b3845213e6bf8534ef695b1c0833b2e
|
C#
|
etienne-p/UnityVolumetric
|
/Assets/Scripts/Volumetric/Util.cs
| 2.875
| 3
|
using UnityEngine;
using System.Collections;
namespace Volumetric
{
public class Util
{
public static bool IsPowerOfTwo (int x)
{
return x > 0 && (x & (x - 1)) == 0;
}
// Returns the bounding box (axis aligned) of a points set
public static Bounds PointCloudBounds(Vector3[] points)
{
Vector3 minVert = Vector3.one * float.MaxValue;
Vector3 maxVert = Vector3.one * float.MinValue;
for (int i = 0; i != points.Length; ++i)
{
minVert.x = Mathf.Min(minVert.x, points[i].x);
minVert.y = Mathf.Min(minVert.y, points[i].y);
minVert.z = Mathf.Min(minVert.z, points[i].z);
maxVert.x = Mathf.Max(maxVert.x, points[i].x);
maxVert.y = Mathf.Max(maxVert.y, points[i].y);
maxVert.z = Mathf.Max(maxVert.z, points[i].z);
}
Bounds rv = new Bounds();
rv.SetMinMax(minVert, maxVert);
return rv;
}
public static Mesh ReverseMeshNormals (Mesh mesh)
{
Vector3[] normals = mesh.normals;
for (int i = 0; i < normals.Length; i++)
normals [i] = -normals [i];
mesh.normals = normals;
for (int m = 0; m < mesh.subMeshCount; m++)
{
int[] triangles = mesh.GetTriangles (m);
for (int i = 0; i < triangles.Length; i += 3)
{
int temp = triangles [i + 0];
triangles [i + 0] = triangles [i + 1];
triangles [i + 1] = temp;
}
mesh.SetTriangles (triangles, m);
}
return mesh;
}
public static int Index3DTo1D (Vector3Int index, Vector3Int size)
{
return index.z * size.y * size.x + index.y * size.x + index.x;
}
public static Vector3Int Index1DTo3D (int index, Vector3Int size)
{
int ix = index % size.x;
int iy = ((index - ix) / size.x) % size.y;
int iz = (index - ix - iy * size.x) / (size.x * size.y);
return new Vector3Int (ix, iy, iz);
}
}
}
|
805cd84372510f0cce7f205983df3cc467af46d4
|
C#
|
bankin/TelerikAcademy
|
/C#II Homework/ExceptionHandling/03.FilePath/FilePath.cs
| 3.453125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace _03.FilePath
{
class FilePath
{
static void Main(string[] args)
{
Console.Write("Enter file path: ");
string path = Console.ReadLine();
try
{
StreamReader sr = new StreamReader(path);
using (sr)
{
Console.WriteLine(sr.ReadToEnd().ToString());
}
}
catch (ArgumentException)
{
Console.WriteLine("Wrong Input");
}
catch (FileNotFoundException)
{
Console.WriteLine("File not found");
}
catch (DirectoryNotFoundException)
{
Console.WriteLine("Directory not found");
}
}
}
}
|
948c66c9d85731c7f2f8fbe07bb9d63fb7e4af7d
|
C#
|
brohand/Occulta-Solemnis
|
/Cultist WIP/Assets/Scripts/Inventory.cs
| 2.578125
| 3
|
using UnityEngine;
using System.Collections;
public class Inventory : MonoBehaviour {
// Use this for initialization
public bool holding;
public bool itemFound;
public GameObject heldItem;
public GameObject currItem;
void Start () {
holding = false;
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown("Fire1"))
{
if (itemFound && !holding)
{
if(currItem.gameObject.GetComponent<itemScript>().inCircle == false)
pickUp(currItem);
}
else if (holding)
putDown();
}
}
void OnTriggerExit2D(Collider2D coll)
{
if(coll.gameObject.tag == "Item")
{
itemFound = false;
currItem = null;
}
}
void OnTriggerStay2D(Collider2D coll)
{
//print("collision");
if(coll.gameObject.tag == "Item")
{
itemFound = true;
currItem = coll.gameObject;
}
}
void OnTriggerEnter2D(Collider2D coll)
{
if(coll.gameObject.tag == "Ritual")
{
if (holding)
{
Invoke("putDown", 0.5f);
coll.gameObject.GetComponent<ItemDetection>().itemsPlaced++;
heldItem.gameObject.GetComponent<itemScript>().inCircle = true;
}
}
}
void pickUp(GameObject gameObj)
{
heldItem = gameObj;
holding = true;
heldItem.GetComponent<AudioSource>().Play();
gameObj.transform.Translate(0, 1000, 0); //Moves realllllyyyyy far away
}
void putDown()
{
if (heldItem != null && holding) {
heldItem.transform.position = transform.position;
heldItem.GetComponent<AudioSource>().Play();
holding = false;
heldItem = null;
}
}
}
|
e5f041c563b0079a11182c763a1248435bbf7bb7
|
C#
|
isel-leic-pc/s1819i-li51n
|
/dotnet/Aula-2018-10-24/Semaphore.cs
| 3.140625
| 3
|
/*
* A simple semaphore implemented as a monitor
* Jorge Martins, september 2019
*/
using SynchUtils;
using System;
using System.Threading;
namespace Aula_2018_10_24 {
public class Semaphore {
private Object monitor;
private volatile int permits;
private volatile int waiters;
private bool TryAcquire() {
/*
if (permits > 0) {
--permits;
return true;
}
return false;
*/
int observed;
while(true) {
observed = permits;
if (observed == 0) return false;
if (Interlocked.CompareExchange(
ref permits, observed - 1, observed) == observed)
return true;
}
}
public Semaphore(int initialPermits) {
if (initialPermits >= 0)
permits = initialPermits;
monitor = new Object();
}
public bool Acquire(int timeout) {
if (TryAcquire()) return true;
if (timeout == 0) return false;
TimeoutHolder th = new TimeoutHolder(timeout);
lock (monitor) {
waiters++;
try {
if (TryAcquire()) return true;
while (true) {
Monitor.Wait(th.Value);
if (TryAcquire()) {
return true;
}
if (th.Timeout) {
return false;
}
}
}
catch(ThreadInterruptedException) {
if (permits > 0)
Monitor.Pulse(monitor);
throw;
}
finally {
waiters--;
}
}
}
public void Release() {
Interlocked.Increment(ref permits);
if (waiters > 0) {
lock (monitor) {
if (waiters > 0)
Monitor.Pulse(monitor);
}
}
}
}
}
|
72ce0aee3679f858b1f0ad66ab4c4752be5b8efe
|
C#
|
pebblecode/pc-common
|
/src/PC.Framework/PC.Framework/Threading/RepeatingTask.cs
| 3.140625
| 3
|
using PebbleCode.Framework.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace PebbleCode.Framework.Threading
{
/// <summary>
/// Base class for classes requiring repeated callbacks
/// </summary>
public abstract class RepeatingTask : SimpleTask, IDisposable
{
private readonly TimeSpan _callbackInterval;
private Timer _timer;
private readonly object[] _timerLock = new object[0];
public DateTime NextRunTime { get; private set; }
/// <summary>
/// Constructor
/// </summary>
public RepeatingTask(TimeSpan callbackInterval)
{
_callbackInterval = callbackInterval;
}
/// <summary>
/// Start the updater. Will run every X seconds, starting with a call now.
/// </summary>
public virtual void Start()
{
Start(0);
}
/// <summary>
/// Starts the task, but delays the first run until the indicated time
/// </summary>
/// <param name="nextRunTime"></param>
public void Start(DateTime nextRunTime)
{
if (nextRunTime < DateTime.Now)
{
nextRunTime = nextRunTime.AddDays(1);
}
TimeSpan diff = nextRunTime - DateTime.Now;
Start((long)diff.TotalMilliseconds);
}
/// <summary>
/// Starts the task with a delay
/// </summary>
/// <param name="nextRunTime"></param>
public void Start(TimeSpan nextRunTime)
{
Start(DateTime.Now.Date.Add(nextRunTime));
}
/// <summary>
/// Start the updater. Will run every X seconds
/// </summary>
/// <param name="delayMillis">Number of milliseconds to delay before repeating for the first time</param>
public void Start(long delayMillis)
{
if (delayMillis < 0)
throw new ArgumentOutOfRangeException("delayMillis", "Must be non-negative");
lock (_timerLock)
{
if (_timer != null)
throw new InvalidOperationException("Only call start once!");
// Create a timer with an immediate callback
_timer = new Timer(OnTimerExpired, null, delayMillis, Timeout.Infinite);
}
//Cache the next system clock run time
NextRunTime = DateTime.Now.AddMilliseconds(delayMillis);
OnStarted();
}
/// <summary>
/// Stop the timer doing the updates
/// </summary>
public void Stop()
{
lock (_timerLock)
{
if (_timer != null)
{
_timer.Change(Timeout.Infinite, Timeout.Infinite);
_timer.Dispose();
_timer = null;
}
}
OnStopped();
}
/// <summary>
/// When timer expires, call derived class to do work
/// </summary>
/// <param name="state"></param>
private void OnTimerExpired(object state)
{
// Call derived class
try
{
PerformTask();
}
catch(Exception ex)
{
Logger.WriteUnexpectedException(ex, "Error in RepeatingTask.PerformTask", Category.General);
}
// Reset the timer
lock (_timerLock)
{
if (_timer != null)
{
_timer.Change(_callbackInterval, TimeSpan.FromMilliseconds(-1));
}
}
}
/// <summary>
/// Virtual method to allow derived classes to perform work after the timer is stopped.
/// </summary>
protected virtual void OnStopped()
{
}
/// <summary>
/// Virtual method to allow derived classes to perform work after the timer is started
/// </summary>
protected virtual void OnStarted()
{
}
public void Dispose()
{
Stop();
}
}
}
|
98114f2b4f88331fc81b7a835054fddaca2041f3
|
C#
|
theonej/N-Dexed.Deployment
|
/N-Dexed.Deployment.Security/Encryptors/RijndaelManagedEncryptor.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace N_Dexed.Deployment.Security.Encryptors
{
public class RijndaelManagedEncryptor: IEncryptor
{
private const string CRYPTO_KEY = "N-Dexed.Deployment";
private const string INITIAL_VECTOR = "ARandomStringThatContainsLotsOfCharactersUsedAsAnInitalVectorForEncryption";
public string EncryptValue(string value)
{
string returnValue = null;
if (!string.IsNullOrEmpty(value))
{
RijndaelManaged cryptoProvider = new RijndaelManaged
{
Key = GenerateHash(CRYPTO_KEY),
IV = GenerateHash(INITIAL_VECTOR)
};
ICryptoTransform transform = cryptoProvider.CreateEncryptor(cryptoProvider.Key, cryptoProvider.IV);
MemoryStream stream = new MemoryStream();
using (stream)
{
CryptoStream cryptoStream = new CryptoStream(stream, transform, CryptoStreamMode.Write);
using (cryptoStream)
{
byte[] data = Encoding.ASCII.GetBytes(value);
cryptoStream.Write(data, 0, data.Length);
cryptoStream.FlushFinalBlock();
cryptoStream.Close();
byte[] encryptedData = stream.ToArray();
returnValue = Convert.ToBase64String(encryptedData);
}
}
}
return returnValue;
}
public string DecryptValue(string encryptedValue)
{
string returnValue = null;
if (!string.IsNullOrEmpty(encryptedValue))
{
byte[] encryptedBytes = Convert.FromBase64String(encryptedValue);
RijndaelManaged cryptoProvider = new RijndaelManaged
{
Key = GenerateHash(CRYPTO_KEY),
IV = GenerateHash(INITIAL_VECTOR)
};
ICryptoTransform transform = cryptoProvider.CreateDecryptor(cryptoProvider.Key, cryptoProvider.IV);
MemoryStream stream = new MemoryStream(encryptedBytes);
using (stream)
{
CryptoStream cryptoStream = new CryptoStream(stream, transform, CryptoStreamMode.Read);
using (cryptoStream)
{
StreamReader reader = new StreamReader(cryptoStream);
using (reader)
{
returnValue = reader.ReadToEnd();
}
}
}
}
return returnValue;
}
#region Private Methods
private static byte[] GenerateHash(string value)
{
MD5 md5 = MD5.Create();
byte[] bytes = Encoding.ASCII.GetBytes(value);
byte[] hash = md5.ComputeHash(bytes);
return hash;
}
#endregion
}
}
|
7f93c82302efa68e6a935e1572fb0c972215e8d6
|
C#
|
uwfl/RandomCoding
|
/RandomUtilities/RandomUtilities/InputFile.cs
| 3.234375
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RandomUtilities
{
public class InputFile
{
public string FilePath { get; set; }
public string Filename { get; set; }
public string Extension { get; set; }
public string Content
{
get
{
if(File.Exists(FilePath))
return File.ReadAllText(FilePath);
return string.Empty;
}
}
public InputFile(string path)
{
FilePath = path;
Filename = Path.GetFileName(path);
Extension = Path.GetExtension(path);
}
public InputFile(string path, string filename)
{
FilePath = path;
Filename = filename;
Extension = Path.GetExtension(filename);
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (obj.GetType() != typeof(InputFile))
return false;
var other = obj as InputFile;
if (this.Filename != other.Filename)
return false;
if (this.FilePath != other.FilePath)
return false;
return true;
}
public override int GetHashCode()
{
int hash = 0;
foreach (var c in FilePath)
{
hash += (int)c;
}
foreach (var c in Filename)
{
hash += (int)c;
}
return hash;
}
public override string ToString()
{
return string.Format("Path: {0}, Filename: {1}, Extension: {2}.", FilePath, Filename, Extension);
}
}
}
|
4f06ccef57888d5ec77b16f662ea7a0ee6d3db84
|
C#
|
TehCheat/PoEHUD
|
/src/Models/Attributes/StaticOffsetFieldDebugAttribute.cs
| 2.765625
| 3
|
namespace PoeHUD.Models.Attributes
{
using System;
/// <summary>
/// Used by ImguiDebug plugin. Adds a slider to static field to fix some offset by dragging it
/// Implements the <see cref="System.Attribute" />
/// </summary>
/// <seealso cref="System.Attribute" />
public class StaticOffsetFieldDebugAttribute : Attribute
{
public int SliderMin = -1;
public int SliderMax;
public StaticOffsetFieldDebugAttribute()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="StaticOffsetFieldDebugAttribute"/> class.
/// </summary>
/// <param name="sliderMin">You can set the slider min max using this.</param>
public StaticOffsetFieldDebugAttribute(int sliderMin, int sliderMax)
{
SliderMin = sliderMin;
SliderMax = sliderMax;
}
}
}
|
57dfb5fd9d4b0cdd029d1a97e54865ef94692ac9
|
C#
|
sevimlikedicik/Introduction-to-Competitive-Programming
|
/IntroCompetitiveProgrammingCodes/Other/FindTheTownJudge.cs
| 3.609375
| 4
|
using System;
namespace IntroCompetitiveProgrammingCodes.Other
{
class FindTheTownJudge
{
static void Main(string[] args)
{
int[][] mtr = new int[][] { new int[] { 1, 3 }, new int[] { 2, 3 } };
Console.WriteLine(FindJudge(3, mtr));
Console.ReadKey();
}
public static int FindJudge(int N, int[][] trust)
{
int[] trusted = new int[N + 1];
bool[] trustsSomeone = new bool[N + 1];
for (int i = 0; i < trust.Length; i++)
{
trustsSomeone[trust[i][0]] = true;
trusted[trust[i][1]]++;
}
for (int i = 1; i <= N; i++)
{
if (trusted[i] == N - 1 && !trustsSomeone[i])
return i;
}
return -1;
}
}
}
|
97fc65655c544e88880d6e3d3528c8589de81a62
|
C#
|
madragonse/MAKARON_Client
|
/client_app/client_lib/Game.cs
| 2.65625
| 3
|
using packages;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace client_lib
{
public abstract class Game
{
public Bitmap bitmap;
protected Graphics grafika;
protected Pen pen;
protected SolidBrush brush;
/// <summary>
/// Wymiary w pixelach
/// </summary>
protected int height;
protected int width;
public Game(NetworkStream stream, int width, int height)
{
this.stream = stream;
this.width = width;
this.height = height;
this.pen = new Pen(Color.White, 1.0f);
this.brush = new SolidBrush(Color.White);
this.bitmap = new Bitmap(this.width, this.height);
this.grafika = Graphics.FromImage(bitmap);
}
//TEST
public Game(int width, int height)
{
this.width = width;
this.height = height;
this.pen = new Pen(Color.White, 1.0f);
this.brush = new SolidBrush(Color.White);
this.bitmap = new Bitmap(this.width, this.height);
this.grafika = Graphics.FromImage(bitmap);
}
private NetworkStream stream;
public abstract void update(Dictionary<string, bool> buttons, float deltatime);
public abstract void process(Queue q);
public abstract List<Package> getPackages();
//skaluje rozmiar generowanej bitmapy do nowego rozmiaty
public abstract void scale(int x, int y);
}
}
|
bd42ba61e05b0811b7276b4f0651849298e6b8cc
|
C#
|
beatrizcardc/API_Emprestimos
|
/Repository/UsuarioRepository.cs
| 2.671875
| 3
|
using API_Emprestimos.Models;
using System.Collections.Generic;
using System.Linq;
namespace API_Emprestimos.Repository
{
public class UsuarioRepository : AbstractRepository<Usuario>
{
public UsuarioRepository(BaseDbContext context, ContextoExecucao contexto) : base(context, contexto)
{
}
public Usuario Find(string email)
{
if (email == null)
return null;
return Entity.FirstOrDefault(x => x.EMAIL.ToLower().Trim() == email.ToLower().Trim());
}
internal List<Usuario> GetAll()
{
return Entity.ToList();
}
}
}
|
bd1dffb21247426ce833c49c7edaa78c9d87cae2
|
C#
|
Daakw/ITHSLab2
|
/ShapesLibrary/Circle.cs
| 3.234375
| 3
|
using System;
using System.Numerics;
namespace ShapesLibrary
{
public class Circle : Shape2D
{
public override float Circumference { get; }
public override Vector3 Center { get; }
public override float Area { get; }
public Circle(Vector2 center, float radius)
{
Center = new Vector3(center, 0f);
Area = radius * radius * MathF.PI;
Circumference = radius * 2 * MathF.PI;
stringRepresentation = $"“Circle @({center.X}, {center.Y}): r = {radius}”";
}
}
}
|
d1a9abbab5723a89864775692439847e995b77d9
|
C#
|
sonali-thakur/ContactRepo
|
/ContactMicroService/ContactMicroService/Model/Contact.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace ContactMicroService.Model
{
/// <summary>
/// COntact Model class
/// </summary>
public class Contact
{
/// <summary>
/// class property
/// </summary>
[Key]
public int ContactId { get; set; }
/// <summary>
/// class property
/// </summary>
[Required(ErrorMessage = "Please Enter First Name."),MaxLength(50)]
[Display(Name = "First Name")]
public string FirstName { get; set; }
/// <summary>
/// class property
/// </summary>
[Required(ErrorMessage = "Please Enter Last Name."), MaxLength(50)]
[Display(Name = "Last Name")]
public string LastName { get; set; }
/// <summary>
/// class property
/// </summary>
[Required(ErrorMessage = "Please Enter Email Address.")]
[Display(Name = "Email Address")]
[RegularExpression(@"^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$",ErrorMessage = "Please Enter Correct Email Address")]
public string Email { get; set; }
/// <summary>
/// class property
/// </summary>
[Required(ErrorMessage = "Please Enter Phone Number.")]
[StringLength(10,ErrorMessage ="",MinimumLength =10)]
[Display(Name = "Phone Number")]
[DataType(DataType.PhoneNumber)]
public string PhoneNumber { get; set; }
/// <summary>
/// class property
/// </summary>
[Required]
public bool Status { get; set; }
}
}
|
2b7637e07a1a18e83ba21e869c70afe3d694d1ed
|
C#
|
cjlpowers/Inaugura
|
/Inaugura/Backup/2/App_Code/VolumeGraph.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using ZedGraph;
namespace Inaugura.RealLeads.Graphing
{
public class VolumeGraph
{
#region Variables
private string mTitle = "Volume";
private string mXAxisTitle = "Date/Time";
private string mY1AxisTitle = "Number of Calls";
private string mY2AxisTitle = "Number of Web Hits";
private GraphPane mGraph;
#endregion
#region Properties
public string Title
{
get
{
return this.mTitle;
}
set
{
this.mTitle = value;
}
}
public string XAxisTitle
{
get
{
return this.mXAxisTitle;
}
set
{
this.mXAxisTitle = value;
}
}
public string Y1AxisTitle
{
get
{
return this.mY1AxisTitle;
}
set
{
this.mY1AxisTitle = value;
}
}
public string Y2AxisTitle
{
get
{
return this.mY2AxisTitle;
}
set
{
this.mY2AxisTitle = value;
}
}
#endregion
public VolumeGraph(CallVolume[] callVolumes, Volume[] webVolume)
{
this.mGraph = new GraphPane(new RectangleF(0, 0,100,100), "","","");
this.mGraph.Y2Axis.IsVisible = true;
PointPairList points = new PointPairList();
foreach(CallVolume volume in callVolumes)
{
points.Add(new PointPair(new XDate(volume.Time),volume.Value));
}
BarItem bar = this.mGraph.AddBar("Call Volume", points, System.Drawing.Color.FromArgb(59, 166, 0));
points = new PointPairList();
foreach (Volume volume in webVolume)
{
points.Add(new PointPair(new XDate(volume.Time), volume.Value));
}
bar = this.mGraph.AddBar("Web Volume", points, System.Drawing.Color.FromArgb(77, 77, 77));
bar.IsY2Axis = true;
}
public VolumeGraph(CallVolume[] callVolumes, Volume[] webVolume, DateTime scaleStart, DateTime scaleEnd) : this(callVolumes, webVolume)
{
this.mGraph.XAxis.MinAuto = false;
this.mGraph.XAxis.MaxAuto = false;
this.mGraph.XAxis.Min = new XDate(scaleStart);
this.mGraph.XAxis.Max = new XDate(scaleEnd);
}
public VolumeGraph(CallVolume[] callVolumes, Volume[] webVolumes, DateTime scaleStart, DateTime scaleEnd , TimeSpan barWidth) : this(callVolumes, webVolumes, scaleStart, scaleEnd)
{
TimeSpan span = scaleEnd - scaleStart;
this.mGraph.ClusterScaleWidth = barWidth.TotalMinutes / span.TotalMinutes;
}
public void Draw(System.Drawing.Graphics g)
{
this.mGraph.PaneRect = new System.Drawing.RectangleF(0,0,g.VisibleClipBounds.Width-1,g.VisibleClipBounds.Height-1);
this.mGraph.Title = this.Title;
this.mGraph.XAxis.Type = AxisType.Date;
this.mGraph.XAxis.Title = this.XAxisTitle;
this.mGraph.YAxis.Title = this.Y1AxisTitle;
this.mGraph.Y2Axis.Title = this.Y2AxisTitle;
this.mGraph.YAxis.IsOppositeTic = false;
this.mGraph.YAxis.IsMinorOppositeTic = false;
this.mGraph.Y2Axis.IsOppositeTic = false;
this.mGraph.Y2Axis.IsMinorOppositeTic = false;
this.mGraph.AxisFill = new Fill( Color.White, Color.FromArgb(227,242,219), -45F );
this.mGraph.PaneBorder.Color = Color.White;
this.mGraph.YAxis.IsShowGrid = true;
this.mGraph.YAxis.GridColor = Color.Gray;
this.mGraph.FontSpec.FontColor = Color.Gray;
this.mGraph.XAxis.TitleFontSpec.FontColor = this.mGraph.FontSpec.FontColor;
this.mGraph.YAxis.TitleFontSpec.FontColor = this.mGraph.FontSpec.FontColor;
this.mGraph.Y2Axis.TitleFontSpec.FontColor = this.mGraph.FontSpec.FontColor;
this.mGraph.YAxis.TitleFontSpec.FontColor = this.mGraph.FontSpec.FontColor;
this.mGraph.XAxis.ScaleFontSpec.Angle = 65F;
this.mGraph.XAxis.ScaleFormatAuto = true;
this.mGraph.Legend.Border.IsVisible = false;
mGraph.AxisChange(g);
if (this.mGraph.YAxis.Step < 1)
this.mGraph.YAxis.Step = 1;
mGraph.Draw(g);
}
public System.Drawing.Image CreateImage(int width, int height, System.Drawing.Imaging.ImageFormat format)
{
using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(width, height))
{
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp);
//g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
this.Draw(g);
// get the correct format
using (System.IO.MemoryStream mem = new System.IO.MemoryStream())
{
bmp.Save(mem, format);
return System.Drawing.Image.FromStream(mem);
}
}
}
}
}
|
f8984f58dbbf9f5da4ed4b74dd435af14b635dde
|
C#
|
dolittle/Bifrost
|
/Source/Bifrost/Security/AuthorizeTargetResult.cs
| 2.875
| 3
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) 2008-2017 Dolittle. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System.Collections.Generic;
using System.Linq;
namespace Bifrost.Security
{
/// <summary>
/// Represents the result of an authorization of a <see cref="ISecurityTarget"/>
/// </summary>
public class AuthorizeTargetResult
{
readonly List<AuthorizeSecurableResult> _authorizationFailures = new List<AuthorizeSecurableResult>();
/// <summary>
/// Instantiates an instance of <see cref="AuthorizeTargetResult"/> for the specificed <see cref="ISecurityTarget"/>
/// </summary>
/// <param name="target"><see cref="ISecurityTarget"/> that this <see cref="AuthorizeTargetResult"/> pertains to.</param>
public AuthorizeTargetResult(ISecurityTarget target)
{
Target = target;
}
/// <summary>
/// Gets the <see cref="ISecurityTarget"/> that this <see cref="AuthorizeTargetResult"/> pertains to.
/// </summary>
public ISecurityTarget Target { get; private set; }
/// <summary>
/// Gets the <see cref="AuthorizeSecurableResult"/> for each failed <see cref="ISecurable"/> on the <see cref="ISecurityTarget"/>
/// </summary>
public IEnumerable<AuthorizeSecurableResult> AuthorizationFailures
{
get { return _authorizationFailures.AsEnumerable(); }
}
/// <summary>
/// Indicates if the action instance has been authorized by the <see cref="ISecurityTarget"/>
/// </summary>
public virtual bool IsAuthorized
{
get { return !AuthorizationFailures.Any(); }
}
/// <summary>
/// Processes an <see cref="AuthorizeSecurableResult"/>, adding it to the collection of AuthorizationFailures if appropriate
/// </summary>
/// <param name="result">An <see cref="AuthorizeSecurableResult"/> for a <see cref="ISecurable"/></param>
public void ProcessAuthorizeSecurableResult(AuthorizeSecurableResult result)
{
if(!result.IsAuthorized)
_authorizationFailures.Add(result);
}
/// <summary>
/// Builds a collection of strings that show Target/Securable for each broken or erroring rule in<see cref="AuthorizeTargetResult"/>
/// </summary>
/// <returns>A collection of strings</returns>
public virtual IEnumerable<string> BuildFailedAuthorizationMessages()
{
return from result in AuthorizationFailures from message in result.BuildFailedAuthorizationMessages() select Target.Description + "/" + message;
}
}
}
|
f0480f6bbb793d843390acaf3c503747152dfcab
|
C#
|
GuilhermeMatheus/BasicSharp
|
/src/BasicSharp.Compiler/ILEmitter/Emitters/ModuleEmitter.cs
| 2.5625
| 3
|
using BasicSharp.Compiler.Analyzer;
using BasicSharp.Compiler.Parser.Extensions;
using BasicSharp.Compiler.Parser.Syntaxes;
using BasicSharp.Compiler.ILEmitter.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection.Emit;
namespace BasicSharp.Compiler.ILEmitter
{
public class ModuleEmitter : Emitter<ModuleDeclaration>
{
#region consts
const string MODULE_NAME = "<MODULE_NAME>";
const string CLASS_HEADER = @"
.class public auto ansi abstract sealed beforefieldinit <MODULE_NAME>
extends [mscorlib]System.Object {";
const string CTOR_HEADER = @"
.method private hidebysig specialname rtspecialname static
void .cctor () cil managed {";
#endregion
public ModuleEmitter(CompilationBag compilationBag)
: base(compilationBag) { }
public override void BuildString(StringBuilder builder, ModuleDeclaration node)
{
var classHeader = CLASS_HEADER.Replace(MODULE_NAME, node.Name.StringValue);
builder.AppendLine(classHeader);
var fieldEmitter = new FieldEmitter(compilationBag);
var fields = node.Members.Where(m => m.GetType() == typeof(FieldDeclaration))
.Cast<FieldDeclaration>();
builder.AppendLine();
foreach (var item in fields)
fieldEmitter.BuildString(builder, item);
builder.AppendLine();
buildConstructor(builder, fields, node.Name.StringValue);
var methods = node.Members.Where(m => m.GetType() == typeof(MethodDeclaration))
.Cast<MethodDeclaration>();
var methodEmitter = new MethodEmitter(compilationBag);
foreach (var item in methods)
methodEmitter.BuildString(builder, item);
builder.AppendLine("}"); //CloseBrace de ClassHeader
}
void buildConstructor(StringBuilder builder, IEnumerable<FieldDeclaration> fields, string className)
{
var hasDeclrAssignment = fields.SelectMany(f => f.Declaration.Declarators)
.Where(d => d.Assignment != null)
.Any();
if (!hasDeclrAssignment)
return;
builder.AppendLine(CTOR_HEADER);
var i = 0;
foreach (var item in fields)
{
var declarators = item.Declaration.Declarators.Where(d => d.Assignment != null);
if (!declarators.Any())
continue;
var type = item.Declaration.Type.GetCLRType();
var load_opcode = type.GetOpCodeToPushValue();
var msil_typeName = type.GetMsilTypeName();
var stsfld_opcode = OpCodes.Stsfld;
foreach (var d in declarators)
{
var load_value = Convert.ChangeType(d.Assignment.GetLiteralExpressionValue(), type);
if (type == typeof(bool))
load_value = ((bool)load_value) ? "1" : "0";
var load_TAC = new TacUnit
{
LabelPrefix = "IL_",
LabelIndex = ++i,
Op = load_opcode,
Value = load_value.ToString()
};
builder.AppendLine(load_TAC.ToString());
var stsfld_value = string.Format("{0} {1}::{2}", msil_typeName, className, d.Identifier.StringValue);
var stsfld_TAC = new TacUnit
{
LabelPrefix = "IL_",
LabelIndex = ++i,
Op = stsfld_opcode,
Value = stsfld_value
};
builder.AppendLine(stsfld_TAC.ToString());
}
}
var ret = new TacUnit
{
LabelPrefix = "IL_",
LabelIndex = ++i,
Op = OpCodes.Ret,
};
builder.AppendLine(ret.ToString());
builder.AppendLine("}"); //CloseBrace de CtorHeader
}
}
}
|
2c3fd9231d82dfb7466a0989d489e98d575be6dc
|
C#
|
AdmiralSnyder/VRUnityAudioRemoteControl
|
/VRProject/Tools/NugetLib/Packages.cs
| 2.5625
| 3
|
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Xml;
namespace NugetLib
{
public class Packages
{
public Dictionary<(string, string), Package> PackageByNameVersion = new Dictionary<(string, string), Package>();
public void GetDependencies(Downloader downloader, PackageDependency dependency)
{
var stack = new Stack<PackageDependency>();
stack.Push(dependency);
while(stack.Any())
{
var dep = stack.Pop();
if (!PackageByNameVersion.ContainsKey((dep.ID, dep.Version)))
{
var package = new Package(dep.ID, dep.Version);
downloader.GetNuPkg(package);
PackageByNameVersion[(dep.ID, dep.Version)] = package;
foreach (var pckDep in package.Dependencies)
{
stack.Push(pckDep);
}
}
}
}
}
public class Package
{
public Package(string name, string version)
{
Name = name;
Version = version;
}
public string Name { get; set; }
public string Version { get; set; }
public string Identifier => $"{Name}.{Version}";
public string NugetURL => $"{Name}/{Version}";
public List<string> LibFiles = new List<string>();
public List<PackageDependency> Dependencies = new List<PackageDependency>();
public string NuPkg { get; set; }
public override int GetHashCode() => Identifier.GetHashCode();
}
public class PackageDependency
{
public string TargetFramework { get; set; }
public string ID { get; set; }
public string Version { get; set; }
public string Exclude { get; set; }
}
public class Downloader
{
public string BaseFolder { get; set; }
public bool Unzip { get; set; } = true;
public void GetNuPkg(Package package)
{
using (var client = new WebClient())
{
// https://www.nuget.org/packages/Microsoft.AspNetCore.SignalR/1.1.0
// https://www.nuget.org/api/v2/package/Microsoft.AspNetCore.SignalR/1.1.0
package.NuPkg = Path.Combine(BaseFolder, $"{package.Identifier}.nupkg");
client.DownloadFile($"https://www.nuget.org/api/v2/package/{package.NugetURL}", package.NuPkg);
}
using (var archive = new ZipArchive(new FileStream(package.NuPkg, FileMode.Open), System.IO.Compression.ZipArchiveMode.Read))
{
foreach (var entry in archive.Entries)
{
if (entry.FullName.StartsWith("lib", StringComparison.InvariantCultureIgnoreCase))
{
package.LibFiles.Add(entry.FullName);
}
else if (entry.Name.EndsWith(".nuspec", StringComparison.InvariantCultureIgnoreCase))
{
using (var entryStream = entry.Open())
{
var doc = new XmlDocument();
doc.Load(entryStream);
var nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("nuspec", "http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd");
foreach (XmlNode groupNode in doc.SelectNodes("./nuspec:package/nuspec:metadata/nuspec:dependencies/*", nsmgr))
{
var targetFrameworkAttr = groupNode.Attributes.GetNamedItem("targetFramework");
if (targetFrameworkAttr != null)
{
var targetFramework = groupNode.Attributes["targetFramework"].Value;
if (!(targetFramework == ".NETStandard2.0"
|| targetFramework == "netcoreapp2.0"
|| targetFramework == "netcoreapp2.1")) continue;
foreach (XmlNode dependencyNode in groupNode.ChildNodes)
{
package.Dependencies.Add(new PackageDependency
{
TargetFramework = targetFramework,
ID = dependencyNode.Attributes["id"].Value,
Version = dependencyNode.Attributes["version"].Value,
Exclude = dependencyNode.Attributes["exclude"]?.Value,
});
}
}
else
{
}
}
}
}
}
if (Unzip)
{
var libDir = Path.Combine(BaseFolder, "Packages", package.Identifier);
Directory.CreateDirectory(libDir);
foreach (var libFile in package.LibFiles)
{
var entry = archive.GetEntry(libFile);
var libFileParts = libFile.Split('/');
var framework = libFileParts[1];
if (framework != "netstandard2.0")
{
continue;
}
Directory.CreateDirectory(Path.Combine(libDir, framework));
var filename = libFileParts[2];
using (var entryStream = entry.Open())
{
using (var outputstream = File.OpenWrite(Path.Combine(libDir, framework, filename)))
{
entryStream.CopyTo(outputstream);
}
}
}
}
}
}
}
}
|
a450a6231a2cbb4d3b77f8f76d12e4a5099b819a
|
C#
|
YurkoUA/DesignPatterns
|
/src/DesignPatterns/DesignPatterns/RemoteControlCommand/Commands/MacroCommand.cs
| 2.765625
| 3
|
using RemoteControlCommand.Interfaces;
namespace RemoteControlCommand.Commands
{
public class MacroCommand : ICommand
{
private readonly ICommand[] commands;
public MacroCommand(params ICommand[] commands)
{
this.commands = commands;
}
public void Execute()
{
for (var i = 0; i < commands.Length; i++)
{
commands[i].Execute();
}
}
public void Undo()
{
for (var i = commands.Length - 1; i >= 0; i--)
{
commands[i].Undo();
}
}
}
}
|
c7a5036dc9977a5d4a3cb0576223c09f7f5f924a
|
C#
|
SaiAvishkarSreerama/Preperations
|
/AviPreperation/Data Structures/HashTable/FindDuplicateTree.cs
| 3.53125
| 4
|
using System;
using System.Collections.Generic;
using System.Text;
/*
* Given a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of any one of them.
*
*Two trees are duplicate if they have the same structure with same node values.
*
*Example 1:
*
* 1
* / \
* 2 3
* / / \
* 4 2 4
* /
* 4
*The following are two duplicate subtrees:
*
* 2
* /
* 4
*and
*
* 4
*Therefore, you need to return above trees' root in the form of a list.
*/
namespace AviPreperation.Data_Structures.HashTable
{
//Definition for a binary tree node.
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
//Usign DFS
//Time Complexity - O(n^2), where N is the number of nodes in the tree. We visit each node once, but each creation of serial may take O(N) work.
//Space Complexity - O(n^2) - size of dictionary
//public class FindDuplicateNodesSol
//{
// static Dictionary<string, int> d;
// static List<TreeNode> list;
// public static IList<TreeNode> FindDuplicateSubtrees(TreeNode node)
// {
// d = new Dictionary<string, int>();
// list = new List<TreeNode>();
// //DFS Recusrsive function to find all possible trees
// Count(node);
// return list;
// }
// //It will return a string of node.val,left,right -using pre order traversal
// //if null nodes then node.val,#,# - called serialization of a tree
// public static string Count(TreeNode node)
// {
// if (node == null) return "#";
// string key = Count(node.left) + "," + node.val + "," + Count(node.right);
// if (d.ContainsKey(key))
// {
// d[key]++;
// }
// else
// {
// d.Add(key, 1);
// }
// if (d[key] == 2)
// list.Add(node);
// return key;
// }
// public static void Main()
// {
// var nodeA = new TreeNode(1);
// var nodeB1 = new TreeNode(2);
// var nodeB2 = new TreeNode(3);
// var nodeC1 = new TreeNode(4);
// var nodeC2 = new TreeNode(2);
// var nodeC3 = new TreeNode(4);
// var nodeD1 = new TreeNode(4);
// nodeA.left = nodeB1;
// nodeA.right = nodeB2;
// nodeB1.left = nodeC1;
// nodeB2.left= nodeC2;
// nodeB2.right = nodeC3;
// nodeC2.left = nodeD1;
// FindDuplicateSubtrees(nodeA);
// }
//}
//Usign DFS
//Time Complexity - O(n), where N is the number of nodes in the tree. We visit each node once..
//Space Complexity - O(n) - Every structure we use is using O(1) storage per node.
//Explanation:
/* 1. declare dictionary d, d_count, counter, list(return list)
* 2. Traverse the node to the end and get the traversal value let say 4,0,0(where 4 is node.val and 0 is if null left ot right)
* 3. Put the 4,0,0 in d as key and value is counter(intially 0) and then increment for others
* 4. Now put the value(0) of key(4,0,0) from d into d_count as key and value as 1 intitially(will be incremnt if duplicate comes)
* 5. Now go to another node, let say 2,(4,0,0), 0 ==> 2,1,0(where 1 is from d whcih is value of 4,0,0), then take its valu and put in d_count as key with counter(1) and ++it;
* 6. Repeat all, if duplicate happends d_Count will be incrementing its value for that key, after generating key itself check the duplicate in d_count and add to List if any.
*/
public class FindDuplicateNodesSol
{
static Dictionary<string, int> d;
static Dictionary<int, int> d_Count;
static List<TreeNode> list;
static int counter = 0;
public static IList<TreeNode> FindDuplicateSubtrees(TreeNode node)
{
d = new Dictionary<string, int>();
d_Count = new Dictionary<int, int>();
list = new List<TreeNode>();
//DFS Recusrsive function to find all possible trees
Serialize(node);
return list;
}
public static int Serialize(TreeNode node)
{
string key = "";
if (node == null)
key = "0";
else
{
key = node.val + "," + Serialize(node.left) + "," + Serialize(node.right);
int gen_Id = GenerateIdForKey(key);
if (d_Count.ContainsKey(gen_Id))
d_Count[gen_Id]++;
else
d_Count[gen_Id] = 1;
if (d_Count[gen_Id] == 2)
list.Add(node);
}
return GenerateIdForKey(key);
}
private static int GenerateIdForKey(string key)
{
if (!d.ContainsKey(key))
d[key] = counter++;
return d[key];
}
//public static void Main()
//{
// var nodeA = new TreeNode(1);
// var nodeB1 = new TreeNode(2);
// var nodeB2 = new TreeNode(3);
// var nodeC1 = new TreeNode(4);
// var nodeC2 = new TreeNode(2);
// var nodeC3 = new TreeNode(4);
// var nodeD1 = new TreeNode(4);
// nodeA.left = nodeB1;
// nodeA.right = nodeB2;
// nodeB1.left = nodeC1;
// nodeB2.left = nodeC2;
// nodeB2.right = nodeC3;
// nodeC2.left = nodeD1;
// FindDuplicateSubtrees(nodeA);
//}
}
}
|
53216b2135c07f34df19a5434d7295491a9a9285
|
C#
|
olaitanade/salesmanagerWPF
|
/SalesManager/Model/Admin.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SalesManager.Model
{
[Serializable]
class Admin
{
public String Name { get; set; }
public string Password { get; set; }
public string Rights { get; set; }//Admin or worker
//Making it a singleton
private static Admin instance = null;
//A static property that returns the single user object in memory
public static Admin Instance {
get
{
if (instance == null)
{
instance = new Admin();
}
return instance;
} }
//Other would be added later on.
}
}
|
33c120bd91d7c7eec9042d392414323badf91a4b
|
C#
|
aaronallen8455/PronomeMacOs
|
/Pronome/Visualizer/Bounce/BounceHelper.cs
| 2.828125
| 3
|
using System;
namespace Pronome.Mac.Visualizer.Bounce
{
public class BounceHelper
{
#region Static Public fields
/// <summary>
/// Number of bpms that have elapsed since last frame was drawn.
/// </summary>
static public double ElapsedBpm;
/// <summary>
/// Spacing between the lanes at the bottom of the screen.
/// </summary>
static public double BottomLaneSpacing;
/// <summary>
/// Size of padding on either side of ball.
/// </summary>
static public double BallPadding;
/// <summary>
/// The diameter of the ball elements.
/// </summary>
static public int BallSize;
/// <summary>
/// The height of the lanes in pxs.
/// </summary>
static public double LaneAreaHeight;
/// <summary>
/// Distance from horizon to top of window
/// </summary>
static public double BallAreaHeight;
/// <summary>
/// Space between the edge of screen and the top of the lanes
/// </summary>
static public double LanePadding;
/// <summary>
/// Spacing between the lanes at the top of the queue area. Setting this also sets ball size.
/// </summary>
static public double TopLaneSpacing;
/// <summary>
/// The total width. Also sets the bottomLaneSpacing
/// </summary>
/// <value>The width of the bottom.</value>
static public double BottomWidth;
/// <summary>
/// Gets or sets the width at the top of lanes.
/// </summary>
/// <value>The width of the top lane.</value>
static public double TopLaneWidth;
/// <summary>
/// Gets or sets the height of the drawing.
/// </summary>
/// <value>The height.</value>
static public double Height;
#endregion
#region Static protected properties
/// <summary>
/// Y value of the point where all lane lines converge
/// </summary>
static protected double Apex;
/// <summary>
/// Used by tick easing function.
/// </summary>
static protected double Factor;
/// <summary>
/// used by tick easing function.
/// </summary>
static protected double Denominator;
/// <summary>
/// The last recorded elapsedBPM, since beat started playing. Used to find the increment
/// </summary>
static protected double LastElapsedBpm;
#endregion
#region Static constructor
static BounceHelper()
{
Metronome.Instance.Started += Instance_Started;
}
#endregion
#region Static public methods
static public void SetDimensions(nfloat width, nfloat height)
{
BottomWidth = width;
BottomLaneSpacing = width / Metronome.Instance.Layers.Count;
Height = height;
LaneAreaHeight = height * UserSettings.GetSettings().BounceDivision;
BallAreaHeight = height - LaneAreaHeight;
TopLaneWidth = width - (width - height);
TopLaneSpacing = TopLaneWidth / Metronome.Instance.Layers.Count;
BallSize = (int)(TopLaneSpacing * .5);//(TopLaneSpacing - BallPadding * TopLaneSpacing * 2);
BallPadding = TopLaneSpacing / 2 - BallSize / 2;
LanePadding = (width - TopLaneWidth) / 2;
// used by easing function
Apex = LaneAreaHeight / LanePadding * (BottomWidth / 2) / LaneAreaHeight;
Factor = -Math.Log(1 - (1 / Apex), 2);
Denominator = -Math.Pow(2, -Factor) + 1;
}
/// <summary>
/// Gets the left and right lane slope.
/// </summary>
/// <returns>The lane slope.</returns>
/// <param name="index">Index.</param>
static public (double,double) GetLaneSlope(int index)
{
var lp = LanePadding;
var tls = TopLaneSpacing;
var bls = BottomLaneSpacing;
double run = LanePadding + TopLaneSpacing * index - BottomLaneSpacing * index;
double left = LaneAreaHeight / run;
run = LanePadding + TopLaneSpacing * (index + 1) - BottomLaneSpacing * (index + 1);
double right = LaneAreaHeight / run;
return (left, right);
}
static public double EasingFunction(double input)
{
if (UserSettings.GetSettings().BounceWidthPad <= .01)
{
return input;
}
var f = Factor;
var d = Denominator;
return (-1 / (Math.Pow(2, input * Factor)) + 1) / Denominator;
}
/// <summary>
/// Updates the elapsed bpm.
/// </summary>
static public void UpdateElapsedBpm()
{
double newElapsed = Metronome.Instance.ElapsedBpm;
ElapsedBpm = newElapsed - LastElapsedBpm;
LastElapsedBpm = newElapsed;
}
/// <summary>
/// Resets the elasped bpm.
/// </summary>
static public void ResetElaspedBpm()
{
ElapsedBpm = 0;
LastElapsedBpm = 0;//Metronome.Instance.ElapsedBpm;
}
#endregion
static void Instance_Started(object sender, Metronome.StartedEventArgs e)
{
if (e.PreviousState == Metronome.PlayStates.Stopped)
{
ElapsedBpm = 0;
}
}
}
}
|
65afefb5b60aa4928a4d327ee9881e34dc363965
|
C#
|
iceto77/CSharp-Fundamentals-in-SoftUni
|
/Objects and Classes - Lab/03. Songs/Program.cs
| 3.296875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace _03._Songs
{
class Program
{
static void Main(string[] args)
{
int numberOfSongs = int.Parse(Console.ReadLine());
List<Song> SongData = new List<Song>();
for (int i = 0; i < numberOfSongs; i++)
{
List<string> inputData = Console.ReadLine().Split("_").ToList();
Song curentSong = new Song(inputData[0], inputData[1], inputData[2]);
SongData.Add(curentSong);
}
string finalCommand = Console.ReadLine();
for (int i = 0; i < SongData.Count; i++)
{
if (finalCommand == "all")
{
Console.WriteLine(SongData[i].Name);
}
else if (finalCommand == SongData[i].TypeList)
{
Console.WriteLine(SongData[i].Name);
}
}
}
}
}
|
5a7c36bd91d731a7ec102a115a9fe3abb5fade18
|
C#
|
Godsown06/brothers_motors
|
/Stock Management System/Login.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Brothers_Motors
{
public partial class Login : Form
{
public Login()
{
InitializeComponent();
this.MaximumSize = this.Size;
this.MinimumSize = this.Size;
}
private void Login_Load(object sender, EventArgs e)
{
}
private void chkShowPassword_CheckedChanged(object sender, EventArgs e)
{
if (txtPassword.UseSystemPasswordChar == true) { txtPassword.UseSystemPasswordChar = false; }
else if (txtPassword.UseSystemPasswordChar == false) { txtPassword.UseSystemPasswordChar = true; }
}
private void lnkRegister_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
this.Dispose();
Newuser newuser = new Newuser();
newuser.Show();
}
private void lnkForgotPassword_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Forgotpassword forgotpassword = new Forgotpassword();
forgotpassword.ShowDialog();
}
private void Login_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
}
private void btnLogin_Click(object sender, EventArgs e)
{
if (txtUsername.Text == "" || txtUsername.Text == null)
{
MessageBox.Show("Username is required.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtUsername.Focus();
}
else if (txtPassword.Text == "" || txtPassword.Text == null)
{
MessageBox.Show("Password is required.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtPassword.Focus();
}
else
{
timerFadeOut.Start();
}
}
private void timerFadeOut_Tick(object sender, EventArgs e)
{
this.Opacity += -0.1;
if (this.Opacity <= 0)
{
timerFadeOut.Stop();
this.Dispose();
Dashboard dashboard = new Dashboard();
dashboard.Show();
}
}
}
}
|
61b9afccfb6b2dfbdd9e925ce6502f17e852463a
|
C#
|
rpwjanzen/blinken
|
/Blinken/Clock/Program.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace Clock
{
class Program
{
private static Timer m_clockTimer;
static void Main(string[] args)
{
RenderToLedSign(DateTime.Now.ToString("HH:mm"));
m_clockTimer = new Timer();
m_clockTimer.Interval = TimeSpan.FromSeconds(30).TotalMilliseconds;
m_clockTimer.Elapsed += (s,e) => RenderToLedSign(DateTime.Now.ToString("HH:mm"));
m_clockTimer.Start();
Console.WriteLine("Press <Enter> to exit.");
Console.ReadLine();
m_clockTimer.Stop();
m_clockTimer.Dispose();
}
private static void RenderToLedSign(string text)
{
const string uriText = "net.pipe://localhost/ledsign/sign";
NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
EndpointAddress endpointAddress = new EndpointAddress(uriText);
SignServiceReference.SignServiceClient client = new SignServiceReference.SignServiceClient(binding, endpointAddress);
client.SetText(text);
client.Close();
}
}
}
|
841ae75f50208d7a8026aae99e886c126078491e
|
C#
|
alp78/csharp
|
/Exercises/Ex_s4_e1.cs
| 3.703125
| 4
|
/*
Series 4: Polymorphism
Exercise 1: Design a database connection
To access a database, we need to open a connection to it first and close it once our job is done.
Connecting to a database depends on the type of the target database and the database
management system (DBMS). For example, connecting to a SQL Server database is different
from connecting to an Oracle database. But both these connections have a few things in
common:
• They have a connection string
• They can be opened
• They can be closed
• They may have a timeout attribute (so if the connection could not be opened within the
timeout, an exception will be thrown).
Your job is to represent these commonalities in a base class called DbConnection. This class
should have two properties:
ConnectionString : string
Timeout : TimeSpan
A DbConnection will not be in a valid state if it doesn’t have a connection string. So you need to
pass a connection string in the constructor of this class. Also, take into account the scenarios
where null or an empty string is sent as the connection string. Make sure to throw an exception
to guarantee that your class will always be in a valid state.
Our DbConnection should also have two methods for opening and closing a connection. We
don’t know how to open or close a connection in a DbConnection and this should be left to the
classes that derive from DbConnection. These classes (eg SqlConnection or OracleConnection)
will provide the actual implementation. So you need to declare these methods as abstract.
Derive two classes SqlConnection and OracleConnection from DbConnection and provide a
simple implementation of opening and closing connections using Console.WriteLine(). In the
real-world, SQL Server provides an API for opening or closing a connection to a database. But
for this exercise, we don’t need to worry about it.
*/
using System;
using System.Collections;
using System.Collections.Generic;
namespace ExercisesPolymorphism
{
public abstract class DbConnection
{
public string ConnectionString { get; set; }
public TimeSpan Timeout { get; set; }
// ctor with a string param -> will NOT be passed to derived classes
public DbConnection(string conString)
{
this.ConnectionString = conString;
}
// abstract methods for opening and closing DB
public abstract void OpenDb();
public abstract void CloseDb();
}
// dervied class from DbConnection
public class SqlConnection : DbConnection
{
// ctor with link
public SqlConnection(string conString) : base(conString)
{
this.ConnectionString = conString;
}
// override OpenDb
public override void OpenDb()
{
Console.WriteLine("Open SQL DB: {0}", this.ConnectionString);
}
// override CloseDb
public override void CloseDb()
{
Console.WriteLine("Close SQL DB: {0}", this.ConnectionString);
}
}
// dervied class from DbConnection
public class OracleConnection : DbConnection
{
// ctor with link
public OracleConnection(string conString) : base(conString)
{
this.ConnectionString = conString;
}
// override OpenDb
public override void OpenDb()
{
Console.WriteLine("Open Orcale DB: {0}", this.ConnectionString);
}
// override CloseDb
public override void CloseDb()
{
Console.WriteLine("Close Oracle DB: {0}", this.ConnectionString);
}
}
class Program
{
static void Main (string[] args)
{
var oracle = new OracleConnection("Oracle string.");
var sequel = new SqlConnection("Sequel string.");
oracle.OpenDb();
oracle.CloseDb();
sequel.OpenDb();
sequel.CloseDb();
}
}
}
|
2b8fecadcf7233acda449b075f3c30f581b609e8
|
C#
|
nishi1999/c-sharpp
|
/interface calculator/interface calculator/BasicCalculator.cs
| 3.921875
| 4
|
using System;
using System.Collections.Generic;
using System.Text;
namespace interface_calculator
{
class BasicCalculator:BasicCalculatorInterface
{
public int division(int x, int y)
{
Console.WriteLine("Division of {0} and {1} is: ", x, y);
int div = x / y;
return div;
}
public int multiplication(int x, int y)
{
Console.WriteLine("Multiplication of {0} and {1} is: ", x, y);
int m = x * y;
return m;
}
public int sub(int x, int y)
{
Console.WriteLine("Subtraction of {0} and {1} is: ", x, y);
int sub = x - y;
return sub;
}
public int sum(int x, int y)
{
Console.WriteLine("Summation of {0} and {1} is: ", x, y);
int sum = x + y;
return sum;
}
}
}
|
6db8db86a7a1adece279bc0a24204e11e83b472a
|
C#
|
tcrane-oulu/tron-clone-client
|
/Assets/Scripts/Packets/LoadGamePacket.cs
| 2.71875
| 3
|
namespace Packets
{
public class LoadGamePacket : IServerPacket
{
public PacketType Id
{
get { return PacketType.LoadGame; }
}
public int ClientId { get; set; }
public short MapSize { get; set; }
public void Read(PacketReader reader)
{
ClientId = reader.ReadInt32();
MapSize = reader.ReadInt16();
}
public override string ToString()
{
return string.Format("Id: {0}, MapSize: {1}", ClientId, MapSize);
}
}
}
|
3fc8e65f4082dff8e719a4ac61dd5c088a44bdc5
|
C#
|
knarf7112/SocketServer
|
/WebSocketServer/Client/StateObject.cs
| 2.984375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//
using System.Net.Sockets;
namespace WebSocketServer.Client
{
public class StateObject : ISateObject
{
private byte[] _buffer;
private Socket _client;
private AsyncCallback _callback;
#region Constructor
public StateObject()
{
}
public StateObject(byte[] buffer,Socket client, AsyncCallback callbackMethod)
{
this._buffer = buffer;
this._client = client;
this._callback = callbackMethod;
}
#endregion
/// <summary>
/// send data or receive buffer
/// </summary>
public byte[] Buffer
{
get
{
return this._buffer;
}
set
{
this._buffer = value;
}
}
/// <summary>
/// client socket object
/// </summary>
public Socket Client
{
get
{
return _client;
}
set
{
this._client = value;
}
}
/// <summary>
/// 要執行非同步的任務
/// </summary>
public AsyncCallback Callback
{
get { return _callback; }
set { this._callback = value; }
}
}
}
|
91d723dadb58bb62e79a09a6787c37d01e724833
|
C#
|
Alkasai/Ditch
|
/Sources/Ditch.Core/Models/UInt128.cs
| 2.84375
| 3
|
using System;
using System.IO;
using System.Numerics;
using Ditch.Core.Converters;
using Ditch.Core.Interfaces;
using Newtonsoft.Json;
namespace Ditch.Core.Models
{
[JsonConverter(typeof(CustomJsonConverter))]
public class UInt128 : ICustomJson, ICustomSerializer
{
public string Value { get; set; }
public UInt128() { }
public UInt128(string value)
{
Value = value;
}
#region ICustomJson
public void ReadJson(JsonReader reader, JsonSerializer serializer)
{
Value = serializer.Deserialize<string>(reader);
}
public void WriteJson(JsonWriter writer, JsonSerializer serializer)
{
writer.WriteValue(Value);
}
#endregion
#region ICustomSerializer
public void Serializer(Stream stream, IMessageSerializer serializeHelper)
{
var bi = BigInteger.Parse(Value);
var buf = bi.ToByteArray();
stream.Write(buf, 0, Math.Min(buf.Length, 16));
if (buf.Length < 16)
{
buf = new byte[16 - buf.Length];
stream.Write(buf, 0, buf.Length);
}
}
#endregion
}
}
|
fcf4bb998e26aab90e48c6e0b1dab06683f984e9
|
C#
|
punker76/Markdown-Edit
|
/src/MarkdownEdit/Models/StringExtensions.cs
| 3.015625
| 3
|
using System;
using System.Text;
using System.Text.RegularExpressions;
namespace MarkdownEdit.Models
{
public static class StringExtensions
{
public static string SurroundWith(this string text, string quote) => $"{quote}{text}{quote}";
public static string UnsurroundWith(this string text, string quote) => quote == null ? text : text.Trim(quote.ToCharArray());
public static string ReplaceSmartChars(this string smart)
{
var dumb = smart
.Replace('\u2013', '-')
.Replace('\u2014', '-')
.Replace('\u2015', '-')
.Replace('\u2017', '_')
.Replace('\u2018', '\'')
.Replace('\u2019', '\'')
.Replace('\u201a', ',')
.Replace('\u201b', '\'')
.Replace('\u201c', '\"')
.Replace('\u201d', '\"')
.Replace('\u201e', '\"')
.Replace("\u2026", "...")
.Replace('\u2032', '\'')
.Replace('\u2033', '\"');
return dumb;
}
public static int WordCount(this string text) => text == null ? 0 : Regex.Matches(text, @"[\S]+").Count;
public static string AddOffsetToFileName(this string file, int offset)
=> $"{file.StripOffsetFromFileName()}|{offset}";
public static string ReplaceDate(this string text)
{
var datePattern = new Regex(@"\$DATE(?:\(""(.+)""\))?\$");
return datePattern.Replace(text, match => DateTime.Now.ToString(match?.Groups[1].Value));
}
public static string StripOffsetFromFileName(this string file)
{
if (string.IsNullOrWhiteSpace(file)) return file;
var index = file.IndexOf('|');
return index >= 0 ? file.Substring(0, index) : file;
}
public static string ToSlug(this string value, bool toLower = false)
{
if (value == null) return "";
var normalised = value.Normalize(NormalizationForm.FormKD);
const int maxlen = 80;
var len = normalised.Length;
var prevDash = false;
var sb = new StringBuilder(len);
for (var i = 0; i < len; i++)
{
var c = normalised[i];
if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))
{
if (prevDash)
{
sb.Append('-');
prevDash = false;
}
sb.Append(c);
}
else if (c >= 'A' && c <= 'Z')
{
if (prevDash)
{
sb.Append('-');
prevDash = false;
}
// tricky way to convert to lowercase
if (toLower) sb.Append((char)(c | 32));
else sb.Append(c);
}
else if (c == ' ' || c == ',' || c == '.' || c == '/' || c == '\\' || c == '-' || c == '_' || c == '=')
{
if (!prevDash && sb.Length > 0)
{
prevDash = true;
}
}
else
{
var swap = ConvertEdgeCases(c, toLower);
if (swap != null)
{
if (prevDash)
{
sb.Append('-');
prevDash = false;
}
sb.Append(swap);
}
}
if (sb.Length == maxlen) break;
}
return sb.ToString();
}
private static string ConvertEdgeCases(char c, bool toLower)
{
string swap = null;
switch (c)
{
case 'ı':
swap = "i";
break;
case 'ł':
swap = "l";
break;
case 'Ł':
swap = toLower ? "l" : "L";
break;
case 'đ':
swap = "d";
break;
case 'ß':
swap = "ss";
break;
case 'ø':
swap = "o";
break;
case 'Þ':
swap = "th";
break;
}
return swap;
}
}
}
|
7ff9683e8f00ddabcae46d21326213c08bb6f77c
|
C#
|
XINCGer/Unity3DTraining
|
/DesignPatterns/TemplatePattern/TemplatePattern/NewMobilePhone.cs
| 2.984375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TemplatePattern
{
abstract class NewMobilePhone
{
public virtual void PowerOn()
{
Console.WriteLine(User() + "手机开机了!");
}
public virtual void PowerOff()
{
Console.WriteLine(User() + "手机关机了!");
}
public virtual void DialUp()
{
Console.WriteLine(User() + "手机拨号!");
}
public virtual void about()
{
Console.WriteLine(User() + "关于手机");
}
protected abstract string User();
}
class NewMobilePhoneA : NewMobilePhone
{
protected override string User()
{
return "大老板";
}
}
class NewMobilePhoneB : NewMobilePhone
{
protected override string User()
{
return "秘书";
}
}
class AndroidMobilePhone : NewMobilePhone
{
protected override string User()
{
return "Android系统手机";
}
}
class WPMobilePhone:NewMobilePhone
{
protected override string User()
{
return "WP系统手机";
}
}
}
|
a09b6a8065dd305e96bfbca323d615b5df0aea61
|
C#
|
mikerandrup/cs2php
|
/Lang.Php.Compiler/Source/_Definitions/PhpClassFieldDefinition.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lang.Php.Compiler.Source
{
/*
smartClass
option NoAdditionalFile
property Name string nazwa pola lub stałej
property IsStatic bool
property IsConst bool
property ConstValue IPhpValue
property Visibility Visibility
init Visibility.Public
smartClassEnd
*/
public partial class PhpClassFieldDefinition : IClassMember, ICodeRelated
{
#region Methods
// Public Methods
public void Emit(PhpSourceCodeEmiter emiter, PhpSourceCodeWriter writer, PhpEmitStyle style)
{
var v = visibility.ToString().ToLower();
if (isConst)
{
// const CONSTANT = 'constant value';
writer.WriteLnF("const {0} = {1};", name, constValue.GetPhpCode(style));
return;
}
string a = string.Format("{0}{1} {2}",
visibility.ToString().ToLower(),
isStatic ? " static" : "",
name
);
if (constValue != null)
a += " = " + constValue.GetPhpCode(style);
writer.WriteLn(a + ";");
}
public IEnumerable<ICodeRequest> GetCodeRequests()
{
return IPhpStatementBase.XXX(constValue);
}
#endregion Methods
}
}
// -----:::::##### smartClass embedded code begin #####:::::----- generated 2013-11-10 18:26
// File generated automatically ver 2013-07-10 08:43
// Smartclass.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0c4d5d36fb5eb4ac
namespace Lang.Php.Compiler.Source
{
public partial class PhpClassFieldDefinition
{
/*
/// <summary>
/// Tworzy instancję obiektu
/// </summary>
public PhpMethodFieldDefinition()
{
}
Przykłady użycia
implement INotifyPropertyChanged
implement INotifyPropertyChanged_Passive
implement ToString ##Name## ##IsStatic## ##IsConst## ##ConstValue## ##Visibility##
implement ToString Name=##Name##, IsStatic=##IsStatic##, IsConst=##IsConst##, ConstValue=##ConstValue##, Visibility=##Visibility##
implement equals Name, IsStatic, IsConst, ConstValue, Visibility
implement equals *
implement equals *, ~exclude1, ~exclude2
*/
#region Constants
/// <summary>
/// Nazwa własności Name; nazwa pola lub stałej
/// </summary>
public const string PROPERTYNAME_NAME = "Name";
/// <summary>
/// Nazwa własności IsStatic;
/// </summary>
public const string PROPERTYNAME_ISSTATIC = "IsStatic";
/// <summary>
/// Nazwa własności IsConst;
/// </summary>
public const string PROPERTYNAME_ISCONST = "IsConst";
/// <summary>
/// Nazwa własności ConstValue;
/// </summary>
public const string PROPERTYNAME_CONSTVALUE = "ConstValue";
/// <summary>
/// Nazwa własności Visibility;
/// </summary>
public const string PROPERTYNAME_VISIBILITY = "Visibility";
#endregion Constants
#region Methods
#endregion Methods
#region Properties
/// <summary>
/// nazwa pola lub stałej
/// </summary>
public string Name
{
get
{
return name;
}
set
{
value = (value ?? String.Empty).Trim();
name = value;
}
}
private string name = string.Empty;
/// <summary>
///
/// </summary>
public bool IsStatic
{
get
{
return isStatic;
}
set
{
isStatic = value;
}
}
private bool isStatic;
/// <summary>
///
/// </summary>
public bool IsConst
{
get
{
return isConst;
}
set
{
isConst = value;
}
}
private bool isConst;
/// <summary>
///
/// </summary>
public IPhpValue ConstValue
{
get
{
return constValue;
}
set
{
constValue = value;
}
}
private IPhpValue constValue;
/// <summary>
///
/// </summary>
public Visibility Visibility
{
get
{
return visibility;
}
set
{
visibility = value;
}
}
private Visibility visibility = Visibility.Public;
#endregion Properties
}
}
|
5c94d6fb7cbf1ea0e3c5230c5ba7586d41b157fc
|
C#
|
IsaVerdiyev/WeatherApplication
|
/WeatherApplication/Services/WeatherInfoGetter/OpenWeatherMapWeatherInfoGetter.cs
| 2.53125
| 3
|
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WeatherApplication.Model;
using WeatherApplication.Services.WeatherInfoGetter.Exceptions;
namespace WeatherApplication.Services.WeatherInfoGetter
{
class OpenWeatherMapWeatherInfoGetter : IWeatherInfoGetter
{
string firstPartOfRequestCurrent = "http://api.openweathermap.org/data/2.5/weather?&units=metric&q=";
string firstPartOfRequestForecast = "http://api.openweathermap.org/data/2.5/forecast?&units=metric&q=";
string secondPartOfRequest = "&APPID=";
string iconUrlFirstPart = "http://openweathermap.org/img/w/";
string iconsFolderPath = "OpenWeatherMapIcons//";
string apiKey;
public string IconsFolderPath => iconsFolderPath;
public OpenWeatherMapWeatherInfoGetter(string apiKey)
{
this.apiKey = apiKey;
}
public Weather GetCurrentWeatherOfCity(string city)
{
string response = GetCurrentWeatherResponseFromWeatherOpenMap(city);
return ParseJsonCurrentWeatherResponseIntoWeather(response);
}
public async Task<Weather> GetCurrentWeatherOfCityAsync(string city)
{
string response = await GetCurrentWeatherResponseFromWeatherOpenMapAsync(city);
return ParseJsonCurrentWeatherResponseIntoWeather(response);
}
public List<Weather> GetForecastWeathersOfCity(string city)
{
string response = GetForecastResponseFromWeatherOpenMap(city);
return ParseJsonForecastResponseIntoListOfWeathers(response);
}
public async Task<List<Weather>> GetForecastWeathersOfCityAsync(string city)
{
string response = await GetForecastResponseFromWeatherOpenMapAsync(city);
return ParseJsonForecastResponseIntoListOfWeathers(response);
}
string GetCurrentWeatherResponseFromWeatherOpenMap(string city)
{
WebClient client = new WebClient();
try
{
return client.DownloadString($"{ firstPartOfRequestCurrent}{ city}{secondPartOfRequest}{apiKey}");
}
catch (WebException ex)
{
if(ex.Response != null)
{
using(StreamReader reader = new StreamReader(ex.Response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
else
{
throw;
}
}
finally
{
client.Dispose();
}
}
async Task<string> GetCurrentWeatherResponseFromWeatherOpenMapAsync(string city)
{
WebClient client = new WebClient();
try
{
return await client.DownloadStringTaskAsync($"{ firstPartOfRequestCurrent}{ city}{secondPartOfRequest}{apiKey}");
}
catch (WebException ex)
{
if (ex.Response != null)
{
using (StreamReader reader = new StreamReader(ex.Response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
else
{
throw;
}
}
finally
{
client.Dispose();
}
}
string GetForecastResponseFromWeatherOpenMap(string city)
{
WebClient client = new WebClient();
try
{
return client.DownloadString($"{firstPartOfRequestForecast}{city}{secondPartOfRequest}{apiKey}");
}
catch (WebException ex)
{
if (ex.Response != null)
{
using (StreamReader reader = new StreamReader(ex.Response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
else
{
throw;
}
}
finally
{
client.Dispose();
}
}
async Task<string> GetForecastResponseFromWeatherOpenMapAsync(string city)
{
WebClient client = new WebClient();
try
{
return await client.DownloadStringTaskAsync($"{firstPartOfRequestForecast}{city}{secondPartOfRequest}{apiKey}");
}
catch (WebException ex)
{
if (ex.Response != null)
{
using (StreamReader reader = new StreamReader(ex.Response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
else
{
throw;
}
}
finally
{
client.Dispose();
}
}
List<Weather> ParseJsonForecastResponseIntoListOfWeathers(string jsonResponse)
{
JObject jObj = JObject.Parse(jsonResponse);
CheckForExceptions(jObj);
List<Weather> list = jObj["list"].Select(w => {
string icon = w.SelectToken("weather[0].icon").Value<string>();
DownloadIconIfNotExist(icon);
return new Weather
{
Temperature = w.SelectToken("main.temp").Value<double>(),
Date = w.SelectToken("dt_txt").Value<DateTime>(),
MaxTemperature = w.SelectToken("main.temp_max").Value<double>(),
MinTemperature = w.SelectToken("main.temp_min").Value<double>(),
Pressure = w.SelectToken("main.pressure").Value<double>(),
Humidity = w.SelectToken("main.humidity").Value<double>(),
WindSpeed = w.SelectToken("wind.speed").Value<double>(),
Description = w.SelectToken("weather[0].description").Value<string>(),
IconPath = $"{IconsFolderPath}{icon}.png"
};
}).ToList<Weather>();
return list;
}
Weather ParseJsonCurrentWeatherResponseIntoWeather(string jsonResponse)
{
JObject jObj = JObject.Parse(jsonResponse);
CheckForExceptions(jObj);
string icon = jObj["weather"][0]["icon"].Value<string>();
DownloadIconIfNotExist(icon);
Weather currentWeather = new Weather
{
Temperature = jObj["main"]["temp"].Value<double>(),
Date = DateTimeExtensions.GetDateFromSecondsSince1970(jObj["dt"].Value<int>()),
Description = jObj["weather"][0]["description"].Value<string>(),
MaxTemperature = jObj["main"]["temp_max"].Value<double>(),
MinTemperature = jObj["main"]["temp_min"].Value<double>(),
Humidity = jObj["main"]["humidity"].Value<double>(),
Pressure = jObj["main"]["pressure"].Value<double>(),
WindSpeed = jObj["wind"]["speed"].Value<double>(),
IconPath = $"{IconsFolderPath}{icon}.png"
};
return currentWeather;
}
void DownloadIconIfNotExist(string iconName)
{
if (!File.Exists($"{ IconsFolderPath}{iconName}.png"))
{
if (!Directory.Exists(IconsFolderPath))
{
Directory.CreateDirectory(IconsFolderPath);
}
using (WebClient client = new WebClient())
{
client.DownloadFileTaskAsync($"{iconUrlFirstPart}{iconName}.png", $"{IconsFolderPath}{iconName}.png");
}
}
}
void CheckForExceptions(JObject jObject)
{
if (jObject["cod"].Value<string>() == "404" /*&& jObj["message"].Value<string>() == "city not found"*/)
{
throw new CityNotFoundException();
}
else if (jObject["cod"].Value<string>() == "429")
{
throw new RequestLimitationExcedeedException();
}
else if (jObject["cod"].Value<string>() == "401")
{
throw new InvalidApiException(apiKey);
}
}
}
}
|
296aec8661afbd07804ecabd6a3349493b610c20
|
C#
|
Jacob0421/DB-System-Implementation
|
/MovieStore/Models/DirectorRepository.cs
| 3.09375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MovieStore.Models
{
public class DirectorRepository : IDirectorRepository
{
private readonly AppDbContext _context;
public DirectorRepository(AppDbContext context)
{
_context = context;
}
public Director AddDirector(string fNameIn, string lNameIn)
{
Director newDirector = new Director()
{
FName = fNameIn,
LName = lNameIn
};
_context.Directors.Add(newDirector);
_context.SaveChanges();
return newDirector;
}
public Director GetDirectorByName(string fNameIn, string lNameIn)
{
Director foundDirector = _context.Directors.FirstOrDefault(d => d.FName.ToLower() == fNameIn.ToLower() && d.LName.ToLower() == lNameIn);
return foundDirector;
}
}
}
|