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
|
|---|---|---|---|---|---|---|
2a1523dad46368b235018aaa84bb8bf8fa572d48
|
C#
|
willcurry/crypto-volume-bot
|
/WillCrypto/CoinTracker.cs
| 2.6875
| 3
|
using Discord;
using Discord.WebSocket;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace WillCrypto
{
internal class CoinTracker
{
private Coin _initalCoin;
private Coin _lastCoin;
private Coin _updatedCoin;
private ISocketMessageChannel _channel;
private ExchangeAPI _bittrex;
private Timer _timer;
private int _pings;
private int _strikes;
internal CoinTracker(Coin intialCoin, Coin updatedCoin, ISocketMessageChannel channel, ExchangeAPI bittrex)
{
_initalCoin = intialCoin;
_lastCoin = intialCoin;
_updatedCoin = updatedCoin;
_channel = channel;
_bittrex = bittrex;
_pings = 0;
_strikes = 0;
AutoResetEvent autoEvent = new AutoResetEvent(false);
_timer = new Timer(Track, autoEvent, 1000, 40000);
}
internal void Stop()
{
_timer.Dispose();
}
private void NotifyChannel()
{
string overallVolumeChange = Library.DoubleToPercentageString(Library.CalculateChange(_initalCoin.GetVolume(), _updatedCoin.GetVolume()));
string overallPriceChange = Library.DoubleToPercentageString(Library.CalculateChange(_initalCoin.GetLast(), _updatedCoin.GetLast()));
EmbedBuilder builder = new EmbedBuilder();
builder.AddInlineField("Volume (initial): ", _initalCoin.BaseVolume);
builder.AddInlineField("Volume (now): ", _updatedCoin.BaseVolume);
builder.AddInlineField("Price (initial): ", _initalCoin.Last);
builder.AddInlineField("Price (now): ", _updatedCoin.Last);
builder.AddInlineField("Volume Change: ", overallVolumeChange);
builder.AddInlineField("Price Change: ", overallPriceChange);
builder.WithThumbnailUrl("https://www.investfeed.com/media/images/crypto-icons/" + _initalCoin.GetName() + ".png");
builder.WithTitle(_initalCoin.MarketName);
builder.WithFooter("Pings: " + _pings + " | Strikes: " + _strikes);
builder.WithColor(Color.DarkPurple);
_channel.SendMessageAsync("", false, builder);
}
private void Track(Object stateInfo)
{
if (ShouldStop())
{
Stop();
return;
}
_pings++;
_lastCoin = _updatedCoin;
NotifyChannel();
UpdateCoin();
}
private bool ShouldStop()
{
if (FailsRequirements()) _strikes++;
return _pings > 2 && _strikes > 3;
}
private bool FailsRequirements()
{
double lastVolumeChange = Library.CalculateChange(_lastCoin.GetVolume(), _updatedCoin.GetVolume());
double lastPriceChange = Library.CalculateChange(_lastCoin.GetLast(), _updatedCoin.GetLast());
return lastPriceChange < Settings.PriceStrikeRequirement || lastVolumeChange < Settings.VolumeStrikeRequirement;
}
private async Task UpdateCoin()
{
_updatedCoin = await _bittrex.GetCoinInfo(_initalCoin.MarketName);
}
}
}
|
e17a54bf4a49df159bae2621715200d54058e8bd
|
C#
|
jakubaondrej/acr-akreditace
|
/InfoSystem/InfoSystem.Core/Redactions/RedactionService.cs
| 2.734375
| 3
|
using InfoSystem.Core.DataAbstraction;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace InfoSystem.Core.Redactions
{
public class RedactionService
{
private IRedactionRepository _redactionRepository;
public RedactionService(IRedactionRepository redactionService)
{
_redactionRepository = redactionService;
}
public async Task<int> CreateRedaction(RedactionCreateData redaction)
{
var existR = await _redactionRepository.GetRedactionByName(redaction.Name);
if (existR != null)
{
throw new Exception($"Redaction {redaction.Name} already exists!");
}
return await _redactionRepository.CreateRedaction(redaction);
}
public async Task<List<RedactionListing>> GetAll()
{
var list = await _redactionRepository.GetAllRedactions();
return list;
}
public async Task<RedactionDetail>GetRedactionById(int id)
{
return await _redactionRepository.GetRedactionById(id);
}
public async Task EditRedaction(int id, RedactionDetail redaction)
{
var existR = await _redactionRepository.GetRedactionById(redaction.Id);
if (existR == null)
{
throw new Exception($"Redaction {redaction.Name} does not exist!");
}
await _redactionRepository.EditRedaction(id, redaction);
}
public async Task DeleteRedaction(int id)
{
await _redactionRepository.Delete(id);
}
}
}
|
efe3f5befc40efcde5520b0e9724d51d6c43574d
|
C#
|
Charlaxy/SlackCatsWeb
|
/Bot.cs
| 2.890625
| 3
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using System.Text;
namespace SlackCatsWeb
{
static class Bot
{
static Bot()
{
Log = new StringBuilder();
Log.AppendLine("SlackCats v0.6");
Log.AppendLine();
Console.WriteLine(Log);
var thread = new Thread(new ThreadStart(Meow));
thread.Start();
}
static public StringBuilder Log
{
get;
private set;
}
static private void Meow()
{
var client = new WebClient();
var hash = new HashSet<string>();
while (true)
{
Thread.Sleep(5000);
var download = Environment.GetEnvironmentVariable("SlackCats_URL_Download");
if (String.IsNullOrEmpty(download))
{
Log.AppendLine("Missing Environment Variable: SlackCats_URL_Download");
continue;
}
var json = client.DownloadString(download);
var data = JsonConvert.DeserializeObject<History>(json);
if(data == null)
{
Log.AppendLine("NO DATA!");
continue;
}
if (!data.ok)
{
Log.AppendLine("BAD DATA!");
continue;
}
var upload = Environment.GetEnvironmentVariable("SlackCats_URL_Upload");
System.Array.Reverse(data.messages);
for (int i = 0; i < data.messages.Length; i++)
{
var ts = data.messages[i].ts;
if (hash.Contains(ts))
{
continue;
}
hash.Add(ts);
var text = data.messages[i].text;
var user = data.messages[i].user;
var test = "test";
Log.AppendLine(String.Format("{0} {1} {2}", user, text, test));
if (String.IsNullOrEmpty(upload))
{
Log.AppendLine("Missing Environment Variable: SlackCats_URL_Upload");
continue;
}
if (!text.Contains("meow") && !Regex.IsMatch(text, "m+e+o*w+", RegexOptions.IgnoreCase))
{
continue;
}
Thread.Sleep(100);
Log.AppendLine("SENDING MEOW!");
json = JsonConvert.SerializeObject(new
{
text = ":cat:",
username = "SlackMeower",
icon_emoji = ":cat:"
});
var status = client.UploadString(upload, "POST", json);
if (status == "ok")
{
continue;
}
Log.AppendLine("CHAT FAILED!");
}
}
}
// Chat History JSON Structure
class History
{
public bool ok;
public Message[] messages;
}
class Message
{
public string ts;
public string text;
public string user;
}
}
}
|
0d677e3ec5166c9f05b64327924a63921c95259e
|
C#
|
gaoyixin1989/MonitorBusinessSystem
|
/DataAccess/Channels/Env/Fill/AirHour/TEnvFillAirHourAccess.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using i3.ValueObject.Channels.Env.Fill.AirHour;
using System.Data;
namespace i3.DataAccess.Channels.Env.Fill.AirHour
{
/// <summary>
/// 功能:环境空气填报(小时)
/// 创建日期:2013-06-27
/// 创建人:刘静楠
/// </summary>
public class TEnvFillAirhourAccess : SqlHelper
{
#region 处理函数
/// <summary>
/// 获得查询结果总行数,用于分页
/// </summary>
/// <param name="tEnvFillAirhour">对象</param>
/// <returns>返回行数</returns>
public int GetSelectResultCount(TEnvFillAirhourVo tEnvFillAirhour)
{
string strSQL = "select Count(*) from T_ENV_FILL_AIRHOUR " + this.BuildWhereStatement(tEnvFillAirhour);
return Convert.ToInt32(SqlHelper.ExecuteScalar(strSQL));
}
/// <summary>
/// 对象明细
/// </summary>
/// <param name="id">ID</param>
/// <returns>对象</returns>
public TEnvFillAirhourVo Details(string id)
{
string strSQL = String.Format("select * from T_ENV_FILL_AIRHOUR where id='{0}'", id);
return SqlHelper.ExecuteObject(new TEnvFillAirhourVo(), strSQL);
}
/// <summary>
/// 对象明细
/// </summary>
/// <param name="tEnvFillAirhour">对象条件</param>
/// <returns>对象</returns>
public TEnvFillAirhourVo Details(TEnvFillAirhourVo tEnvFillAirhour)
{
string strSQL = String.Format("select * from T_ENV_FILL_AIRHOUR " + this.BuildWhereStatement(tEnvFillAirhour));
return SqlHelper.ExecuteObject(new TEnvFillAirhourVo(), strSQL);
}
/// <summary>
/// 获取对象List
/// </summary>
/// <param name="tEnvFillAirhour">对象</param>
/// <param name="iIndex">起始页码</param>
/// <param name="iCount">每页数目</param>
/// <returns>返回结果</returns>
public List<TEnvFillAirhourVo> SelectByObject(TEnvFillAirhourVo tEnvFillAirhour, int iIndex, int iCount)
{
string strSQL = String.Format("select * from T_ENV_FILL_AIRHOUR " + this.BuildWhereStatement(tEnvFillAirhour));
return SqlHelper.ExecuteObjectList(tEnvFillAirhour, BuildPagerExpress(strSQL, iIndex, iCount));
}
/// <summary>
/// 获取对象DataTable
/// </summary>
/// <param name="tEnvFillAirhour">对象</param>
/// <param name="iIndex">起始页码</param>
/// <param name="iCount">每页数目</param>
/// <returns>返回结果</returns>
public DataTable SelectByTable(TEnvFillAirhourVo tEnvFillAirhour, int iIndex, int iCount)
{
string strSQL = " select * from T_ENV_FILL_AIRHOUR {0} ";
strSQL = String.Format(strSQL, BuildWhereStatement(tEnvFillAirhour));
return SqlHelper.ExecuteDataTable(BuildPagerExpress(strSQL, iIndex, iCount));
}
/// <summary>
/// 根据对象获取全部数据,用Table承载
/// 数据量较小时使用【不推荐】
/// </summary>
/// <param name="tEnvFillAirhour"></param>
/// <returns></returns>
public DataTable SelectByTable(TEnvFillAirhourVo tEnvFillAirhour)
{
string strSQL = "select * from T_ENV_FILL_AIRHOUR " + this.BuildWhereStatement(tEnvFillAirhour);
return SqlHelper.ExecuteDataTable(strSQL);
}
/// <summary>
/// 根据对象特征获取单一对象
/// </summary>
/// <param name="tEnvFillAirhour">对象</param>
/// <returns></returns>
public TEnvFillAirhourVo SelectByObject(TEnvFillAirhourVo tEnvFillAirhour)
{
string strSQL = "select * from T_ENV_FILL_AIRHOUR " + this.BuildWhereStatement(tEnvFillAirhour);
return SqlHelper.ExecuteObject(new TEnvFillAirhourVo(), strSQL);
}
/// <summary>
/// 对象添加
/// </summary>
/// <param name="tEnvFillAirhour">对象</param>
/// <returns>是否成功</returns>
public bool Create(TEnvFillAirhourVo tEnvFillAirhour)
{
string strSQL = SqlHelper.BuildInsertExpress(tEnvFillAirhour, TEnvFillAirhourVo.T_ENV_FILL_AIRHOUR_TABLE);
return SqlHelper.ExecuteNonQuery(CommandType.Text, strSQL) > 0 ? true : false;
}
/// <summary>
/// 对象编辑
/// </summary>
/// <param name="tEnvFillAirhour">用户对象</param>
/// <returns>是否成功</returns>
public bool Edit(TEnvFillAirhourVo tEnvFillAirhour)
{
string strSQL = SqlHelper.BuildUpdateExpress(tEnvFillAirhour, TEnvFillAirhourVo.T_ENV_FILL_AIRHOUR_TABLE);
strSQL += string.Format(" where ID='{0}' ", tEnvFillAirhour.ID);
return SqlHelper.ExecuteNonQuery(CommandType.Text, strSQL) > 0 ? true : false;
}
/// <summary>
/// 对象编辑
/// </summary>
/// <param name="tEnvFillAirhour_UpdateSet">UpdateSet用户对象</param>
/// <param name="tEnvFillAirhour_UpdateWhere">UpdateWhere用户对象</param>
/// <returns>是否成功</returns>
public bool Edit(TEnvFillAirhourVo tEnvFillAirhour_UpdateSet, TEnvFillAirhourVo tEnvFillAirhour_UpdateWhere)
{
string strSQL = SqlHelper.BuildUpdateExpress(tEnvFillAirhour_UpdateSet, TEnvFillAirhourVo.T_ENV_FILL_AIRHOUR_TABLE);
strSQL += this.BuildWhereStatement(tEnvFillAirhour_UpdateWhere);
return SqlHelper.ExecuteNonQuery(CommandType.Text, strSQL) > 0 ? true : false;
}
/// <summary>
/// 对象删除
/// </summary>
/// <param name="Id">ID</param>
/// <returns>是否成功</returns>
public bool Delete(string Id)
{
string strSQL = String.Format("delete from T_ENV_FILL_AIRHOUR where ID='{0}'", Id);
return SqlHelper.ExecuteNonQuery(CommandType.Text, strSQL) > 0 ? true : false;
}
/// <summary>
/// 对象删除
/// </summary>
/// <param name="Id">ID</param>
/// <returns>是否成功</returns>
public bool Delete(TEnvFillAirhourVo tEnvFillAirhour)
{
string strSQL = "delete from T_ENV_FILL_AIRHOUR ";
strSQL += this.BuildWhereStatement(tEnvFillAirhour);
return SqlHelper.ExecuteNonQuery(CommandType.Text, strSQL) > 0 ? true : false;
}
#endregion
#region// 构造填报表需要显示的信息
/// <summary>
/// 构造填报表需要显示的信息
/// </summary>
/// <returns></returns>
public DataTable CreateShowDT()
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("code", typeof(String));
dt.Columns.Add("name", typeof(String));
dr = dt.NewRow();
dr["code"] = "YEAR";
dr["name"] = "年份";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["code"] = "POINT_ID";
dr["name"] = "监测点名称";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["code"] = "MONTH";
dr["name"] = "月份";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["code"] = "DAY";
dr["name"] = "日";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["code"] = "HOUR";
dr["name"] = "时";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["code"] = "TEMPERATRUE";
dr["name"] = "气温";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["code"] = "PRESSURE";
dr["name"] = "气压";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["code"] = "WIND_SPEED";
dr["name"] = "风速";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["code"] = "WIND_DIRECTION";
dr["name"] = "风向";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["code"] = "VISIBLITY";
dr["name"] = "能见度";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["code"] = "HUMIDITY";
dr["name"] = "相对湿度";
dt.Rows.Add(dr);
return dt;
}
#endregion
#region 构造条件
/// <summary>
/// 根据对象构造条件语句
/// </summary>
/// <param name="tEnvFillAirhour"></param>
/// <returns></returns>
public string BuildWhereStatement(TEnvFillAirhourVo tEnvFillAirhour)
{
StringBuilder strWhereStatement = new StringBuilder(" Where 1=1 ");
if (null != tEnvFillAirhour)
{
//主键ID
if (!String.IsNullOrEmpty(tEnvFillAirhour.ID.ToString().Trim()))
{
strWhereStatement.Append(string.Format(" AND ID = '{0}'", tEnvFillAirhour.ID.ToString()));
}
//监测点ID
if (!String.IsNullOrEmpty(tEnvFillAirhour.POINT_ID.ToString().Trim()))
{
strWhereStatement.Append(string.Format(" AND POINT_ID = '{0}'", tEnvFillAirhour.POINT_ID.ToString()));
}
//年度
if (!String.IsNullOrEmpty(tEnvFillAirhour.YEAR.ToString().Trim()))
{
strWhereStatement.Append(string.Format(" AND YEAR = '{0}'", tEnvFillAirhour.YEAR.ToString()));
}
//月份
if (!String.IsNullOrEmpty(tEnvFillAirhour.MONTH.ToString().Trim()))
{
strWhereStatement.Append(string.Format(" AND MONTH = '{0}'", tEnvFillAirhour.MONTH.ToString()));
}
//日
if (!String.IsNullOrEmpty(tEnvFillAirhour.DAY.ToString().Trim()))
{
strWhereStatement.Append(string.Format(" AND DAY = '{0}'", tEnvFillAirhour.DAY.ToString()));
}
//时
if (!String.IsNullOrEmpty(tEnvFillAirhour.HOUR.ToString().Trim()))
{
strWhereStatement.Append(string.Format(" AND HOUR = '{0}'", tEnvFillAirhour.HOUR.ToString()));
}
//气温
if (!String.IsNullOrEmpty(tEnvFillAirhour.TEMPERATRUE.ToString().Trim()))
{
strWhereStatement.Append(string.Format(" AND TEMPERATRUE = '{0}'", tEnvFillAirhour.TEMPERATRUE.ToString()));
}
//气压
if (!String.IsNullOrEmpty(tEnvFillAirhour.PRESSURE.ToString().Trim()))
{
strWhereStatement.Append(string.Format(" AND PRESSURE = '{0}'", tEnvFillAirhour.PRESSURE.ToString()));
}
//风速
if (!String.IsNullOrEmpty(tEnvFillAirhour.WIND_SPEED.ToString().Trim()))
{
strWhereStatement.Append(string.Format(" AND WIND_SPEED = '{0}'", tEnvFillAirhour.WIND_SPEED.ToString()));
}
//风向
if (!String.IsNullOrEmpty(tEnvFillAirhour.WIND_DIRECTION.ToString().Trim()))
{
strWhereStatement.Append(string.Format(" AND WIND_DIRECTION = '{0}'", tEnvFillAirhour.WIND_DIRECTION.ToString()));
}
//API指数
if (!String.IsNullOrEmpty(tEnvFillAirhour.VISIBLITY.ToString().Trim()))
{
strWhereStatement.Append(string.Format(" AND VISIBLITY = '{0}'", tEnvFillAirhour.VISIBLITY.ToString()));
}
//空气质量指数
if (!String.IsNullOrEmpty(tEnvFillAirhour.HUMIDITY.ToString().Trim()))
{
strWhereStatement.Append(string.Format(" AND HUMIDITY = '{0}'", tEnvFillAirhour.HUMIDITY.ToString()));
}
//备注1
if (!String.IsNullOrEmpty(tEnvFillAirhour.REMARK1.ToString().Trim()))
{
strWhereStatement.Append(string.Format(" AND REMARK1 = '{0}'", tEnvFillAirhour.REMARK1.ToString()));
}
//备注2
if (!String.IsNullOrEmpty(tEnvFillAirhour.REMARK2.ToString().Trim()))
{
strWhereStatement.Append(string.Format(" AND REMARK2 = '{0}'", tEnvFillAirhour.REMARK2.ToString()));
}
//备注3
if (!String.IsNullOrEmpty(tEnvFillAirhour.REMARK3.ToString().Trim()))
{
strWhereStatement.Append(string.Format(" AND REMARK3 = '{0}'", tEnvFillAirhour.REMARK3.ToString()));
}
//备注4
if (!String.IsNullOrEmpty(tEnvFillAirhour.REMARK4.ToString().Trim()))
{
strWhereStatement.Append(string.Format(" AND REMARK4 = '{0}'", tEnvFillAirhour.REMARK4.ToString()));
}
//备注5
if (!String.IsNullOrEmpty(tEnvFillAirhour.REMARK5.ToString().Trim()))
{
strWhereStatement.Append(string.Format(" AND REMARK5 = '{0}'", tEnvFillAirhour.REMARK5.ToString()));
}
}
return strWhereStatement.ToString();
}
#endregion
}
}
|
6e2bb907286becf0c83d16478a6f8193e7cb5b17
|
C#
|
GTRekter/Chamaeleon
|
/C# Programming III/Lab2/Samples/MemoryConcepts/Program.cs
| 3.59375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MemoryConcepts
{
class Program
{
static void Main(string[] args)
{
// Since p1 is not explicitly disposed, it will be cleaned up
// by the garbage collector when the program terminates
Person p1 = new Person(1, "Smith", "Jim", DateTime.Parse("5/15/1968"));
p1 = null; // Null does not force immediate disposal
// p2 is explicitly disposed so it will be cleaned up on the main thread
Person p2 = new Person(2, "Jones", "Jane", DateTime.Parse("2/12/1955"));
p2.Dispose();
// p3 is also explicitly disposed when the using clause terminates
using (Person p3 = new Person(3, "Davis", "Patrick", DateTime.Parse("8/5/1988")))
{
Console.WriteLine(p3);
} // p3.Dispose();
Console.WriteLine("{0}Program ending...{0}", Environment.NewLine);
}
}
}
|
7b723914affd6c481e497e50e31ec03b75ed17ca
|
C#
|
demonix/CertVerifier
|
/CertVerifierService/Task.cs
| 2.59375
| 3
|
using System.Diagnostics;
namespace CertVerifierService
{
public class Task
{
private readonly Stopwatch _timer = new Stopwatch();
private readonly object _taskData;
public Task(object taskData)
{
_taskData = taskData;
_timer.Start();
}
public Stopwatch Timer {get { return _timer; }}
public object TaskData { get { return _taskData; } }
}
}
|
16ea28eab8d5aebe46e1799662e48676c8e51684
|
C#
|
lwq420332613/AdvancedCode
|
/02特性/MyAttribute/MyAttribute/Student.cs
| 3.078125
| 3
|
using MyAttribute.Extension;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyAttribute
{
/// <summary>
/// 这里是注释,除了让人看懂这里写的是什么,
/// 对运行没有任何影响
/// </summary>
//[Obsolete("请不要使用这个了,请使用什么来代替", true)]//影响编译器的运行
//[Serializable]//可以序列化和反序列化 可以影响程序的运行
//MVC filter ORM table key display wcf
//[Custom]
//[Custom()]
//[Custom(123), Custom(123, Description = "1234")]
[Custom(123, Description = "1234", Remark = "2345")]//方法不行
public class Student
{
[CustomAttribute]
public int Id { get; set; }
[Leng(5,10)]//还有各种检查
public string Name { get; set; }
[Leng(20, 50)]
public string Accont { get; set; }
/// <summary>
/// 10001~999999999999
/// </summary>
[Long(10001, 999999999999)]
public long QQ { get; set; }
//private long _QQ2 = 0;//解决数据合法性,给属性增加了太多的事儿
//public long QQ2
//{
// get
// {
// return this._QQ2;
// }
// set
// {
// if (value > 10001 && value < 999999999999)
// {
// _QQ2 = value;
// }
// else
// {
// throw new Exception();
// }
// }
//}
//20:55中场休息+提问
/// 21:00 开始答疑
/// 答疑完继续,期间我会关掉声音
[CustomAttribute]
public void Study()
{
Console.WriteLine($"这里是{this.Name}跟着Eleven老师学习");
}
[Custom()]
[return: Custom()]
public string Answer([Custom]string name)
{
return $"This is {name}";
}
}
}
|
452c19e5e7446e14de587cf2a51866a6e6bf99cf
|
C#
|
Paul-Moura/Custom_Library
|
/SystemProperties.cs
| 2.6875
| 3
|
using System;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Windows.Forms;
namespace Custom
{
public static class SystemProperties
{
public static string CommonApplicationData
{
get
{
var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
Application.ProductName);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
return path;
}
}
public static string MAC_Address
{
get
{
return (from nic in NetworkInterface.GetAllNetworkInterfaces()
where nic.OperationalStatus == OperationalStatus.Up
select nic.GetPhysicalAddress().ToString()).FirstOrDefault();
}
}
}
}
|
74619992b9dcff9bbc7e52041683c31f25bbd5d8
|
C#
|
Arzana/DeJongUtils
|
/Utilities/Utilities/Core/IFullyDisposable.cs
| 2.84375
| 3
|
namespace DeJong.Utilities.Core
{
using System;
using System.Diagnostics.CodeAnalysis;
//
// Summary:
// Provides a mechanism for releasing unmanaged resources.To browse the .NET Framework
// source code for this type, see the Reference Source.
/// <summary>
/// Improves upon the mechanism for releasing unmanaged resources in the .NET Framework
/// with implementing more information and options whilst releasing.
/// </summary>
public interface IFullyDisposable : IDisposable
{
/// <summary>
/// Whether the object has been disposed.
/// </summary>
bool Disposed { get; }
/// <summary>
/// Whether the object is currently disposing.
/// </summary>
bool Disposing { get; }
}
}
|
62d3c9168b1d5e5d80f644be2c89160078fd5fa3
|
C#
|
MyDieu97/ISC_Back-end
|
/ISC_System_API/Controllers/StudentsController.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 ISC_System_API;
using ISC_System_API.Model;
using ISC_System_API.Respone;
namespace ISC_System_API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class StudentsController : ControllerBase
{
private readonly Context _context;
public StudentsController(Context context)
{
_context = context;
}
// GET: api/Students
[HttpGet]
public async Task<ActionResult<BaseRespone>> GetStudent()
{
return new BaseRespone
{
Message = "Get list success",
Data = await _context.Students.Include(item => item.USER)
.Include(item => item.UNIVERSITY)
.Include(item => item.MAJOR).
Select(item => new StudentInfo
{
Id = item.Id,
CERTIFICATION = item.CERTIFICATION,
DEPOSITS = item.DEPOSITS,
USER = item.USER,
MAJOR = item.MAJOR,
UNIVERSITY = item.UNIVERSITY,
READYWORKDATE = item.READYWORKDATE
}).ToListAsync()
};
}
// GET: api/Students/5
[HttpGet("{id}")]
public async Task<ActionResult<BaseRespone>> GetStudent(int id)
{
var student = await _context.Students.FindAsync(id);
if (student == null)
{
return new BaseRespone
{
ErrorCode = 1,
Message = "Not Found"
};
}
return new BaseRespone
{
Message = "Get success",
Data = student
};
}
// PUT: api/Students/5
[HttpPut("{id}")]
public async Task<BaseRespone> PutStudent(int id, Student student)
{
var updatedStudent = await _context.Students.FindAsync(id);
if (updatedStudent == null)
{
return new BaseRespone
{
ErrorCode = 1,
Message = "Not Found"
};
}
updatedStudent.MAJORID = student.MAJORID;
updatedStudent.UniverId = student.UniverId;
updatedStudent.READYWORKDATE = student.READYWORKDATE;
updatedStudent.USERID = student.USERID;
updatedStudent.USERID = student.USERID;
updatedStudent.CERTIFICATION = student.CERTIFICATION;
updatedStudent.DEPOSITS = student.DEPOSITS;
_context.Students.Update(updatedStudent);
await _context.SaveChangesAsync();
return new BaseRespone
{
Message = "Update success",
Data = student
};
}
// POST: api/Students
[HttpPost]
public async Task<ActionResult<BaseRespone>> PostStudent(Student student)
{
try
{
_context.Students.Add(student);
await _context.SaveChangesAsync();
return new BaseRespone
{
Message = "Added success",
Data = student
};
}
catch
{
return new BaseRespone
{
ErrorCode = 1,
Message = "Adding fail"
};
}
}
// DELETE: api/Students/5
[HttpDelete("{id}")]
public async Task<ActionResult<BaseRespone>> DeleteStudent(int id)
{
var student = await _context.Students.FindAsync(id);
if (student == null)
{
return new BaseRespone
{
ErrorCode = 1,
Message = "Delete fail"
};
}
_context.Students.Remove(student);
await _context.SaveChangesAsync();
return new BaseRespone
{
Message = "Delete success"
};
}
private bool StudentExists(int id)
{
return _context.Students.Any(e => e.Id == id);
}
}
}
|
d0c60fc1aa7e2d63c6f1e6ebe44e5164175f7b62
|
C#
|
rsampr/Frends.Community.AWS
|
/Frends.Community.AWS/Definitions.cs
| 3
| 3
|
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Amazon.SecurityToken.Model;
namespace Frends.Community.AWS
{
#region DownloadTask
/// <summary>
/// Input class, you can download whole directories or single files.
/// </summary>
[DisplayName("Input")]
public class DownloadInput
{
/// <summary>
/// Downloads all objects with this prefix.
/// Examples: folder, path/to/folder
/// </summary>
[DisplayFormat(DataFormatString = "Text")]
public string S3Directory { get; set; }
/// <summary>
/// String pattern to search files. Might not be exactly the same as in Windows.
/// </summary>
[DisplayFormat(DataFormatString = "Text")]
public string SearchPattern { get; set; }
/// <summary>
/// Directory to create folders and files to.
/// </summary>
[DisplayFormat(DataFormatString = "Text")]
public string DestinationPath { get; set; }
}
/// <summary>
/// </summary>
[DisplayName("Options")]
public class DownloadOptions
{
/// <summary>
/// Set to false to download files from current directory only.
/// </summary>
[DefaultValue(true)]
public bool DownloadFromCurrentDirectoryOnly { get; set; }
/// <summary>
/// Set to true to move files.
/// </summary>
[DefaultValue(false)]
public bool DeleteSourceFile { get; set; }
/// <summary>
/// Overwrite files.
/// </summary>
[DefaultValue(false)]
public bool Overwrite { get; set; }
/// <summary>
/// If search pattern does not match, throw error.
/// </summary>
[DefaultValue(true)]
public bool ThrowErrorIfNoMatches { get; set; }
}
#endregion
#region ListTask
/// <summary>
/// Input parameter class for ListObjectsAsync
/// </summary>
[DisplayName("Input")]
public class ListInput
{
/// <summary>
/// Object prefix ( folder path ).
/// Use this to set prefix for each file.
/// Default: null
/// </summary>
[DefaultValue(null)]
[DisplayFormat(DataFormatString = "Text")]
public string Prefix { get; set; }
/// <summary>
/// Delimiter.
/// Use in conjuction with prefix to limit results to specific level of the flat namespace hierarchy.
/// See: http://docs.aws.amazon.com/AmazonS3/latest/dev/ListingKeysHierarchy.html
/// </summary>
[DefaultValue(null)]
[DisplayFormat(DataFormatString = "Text")]
public string Delimiter { get; set; }
/// <summary>
/// Max number of keys returned.
/// </summary>
[DefaultValue(100)]
[DisplayFormat(DataFormatString = "Expression")]
public int MaxKeys { get; set; }
/// <summary>
/// A key to start the listing from.
/// Default: null
/// </summary>
[DefaultValue(null)]
[DisplayFormat(DataFormatString = "Text")]
public string StartAfter { get; set; }
/// <summary>
/// If previous response is truncated, use the ContinuationToken from that response here, to continue listing.
/// Default: null
/// </summary>
[DefaultValue(null)]
[DisplayFormat(DataFormatString = "Text")]
public string ContinuationToken { get; set; }
}
/// <summary>
/// Options class.
/// </summary>
[DisplayName("Options")]
public class ListOptions
{
/// <summary>
/// True will return full response, false will return object keys only.
/// </summary>
[DefaultValue(false)]
public bool FullResponse { get; set; }
/// <summary>
/// Throw error if reponse has no items in "S3Objects" array.
/// </summary>
[DefaultValue(true)]
public bool ThrowErrorIfNoFilesFound { get; set; }
}
#endregion
#region UploadTask
/// <summary>
/// Input filepath and filemask.
/// </summary>
[DisplayName("Input")]
public class UploadInput
{
/// <summary>
/// Path to folder.
/// ( c:\temp\ , \\network\folder )
/// </summary>
[DefaultValue(@"c:\temp\")]
[DisplayFormat(DataFormatString = "Text")]
public string FilePath { get; set; }
/// <summary>
/// Windows-style filemask, ( *.* , ?_file.*, foo_*.txt ).
/// Empty field = all files (*)
/// </summary>
[DefaultValue(@"*")]
[DisplayFormat(DataFormatString = "Text")]
public string FileMask { get; set; }
/// <summary>
/// S3 root directory. If directory does not exist, it will be created.
/// </summary>
[DefaultValue(@"")]
[DisplayFormat(DataFormatString = "Text")]
public string S3Directory { get; set; }
}
/// <summary>
/// Task behaviour.
/// Defaults work fine.
/// </summary>
[DisplayName("Options")]
public class UploadOptions
{
/// <summary>
/// Set to false to upload files from current directory only.
/// Filemask must not be empty.
/// </summary>
[DefaultValue(true)]
public bool UploadFromCurrentDirectoryOnly { get; set; }
/// <summary>
/// Set to true to create subdirectories in AWS.
/// Works with UploadFromCurrentDirectoryOnly = false.
/// </summary>
[DefaultValue(false)]
public bool PreserveFolderStructure { get; set; }
/// <summary>
/// Set to true to overwrite files with the same path and name
/// (aka object key).
/// </summary>
[DefaultValue(false)]
public bool Overwrite { get; set; }
/// <summary>
/// Deletes local source files after transfer.
/// </summary>
[DefaultValue(false)]
public bool DeleteSource { get; set; }
/// <summary>
/// If there are no files in the path matching the filemask supplied,
/// throw error.
/// </summary>
[DefaultValue(true)]
public bool ThrowErrorIfNoMatch { get; set; }
/// <summary>
/// If you wish, you can return object keys from S3
/// ( format: prefix/prefix/filename )
/// </summary>
[DefaultValue(false)]
public bool ReturnListOfObjectKeys { get; set; }
}
#endregion
#region TempCredTask
/// <summary>
/// Input parameters for Temporary Credentials.
/// </summary>
public class TempCredInput
{
/// <summary>
/// AWS Role parameter
/// Example: arn:aws:iam:::role/someRole
/// </summary>
[DisplayFormat(DataFormatString = "Text")]
[DefaultValue("arn:aws:iam:::role/frends")]
public string RoleArn { get; set; }
/// <summary>
/// External Id used to track requests.
/// </summary>
[DisplayFormat(DataFormatString = "Text")]
[DefaultValue("FRENDS")]
public string CredentialExternalId { get; set; }
/// <summary>
/// External Id used to track requests.
/// </summary>
[DisplayFormat(DataFormatString = "Text")]
[DefaultValue("FRENDS_{{#process.executionid}}")]
public string CredentialUniqueRequestId { get; set; }
/// <summary>
/// Credentials expire after this time (in seconds).
/// Note: Minimum and maximum allowed expiration are set by AWS and S3 configuration.
/// </summary>
[DefaultValue(3600)]
public int CredentialDurationSeconds { get; set; }
}
#endregion
#region Parameters for all!
/// <summary>
/// Parameter class with username and keys.
/// </summary>
public class Parameters
{
/// <summary>
/// AWS Bucketname
/// Example: yourbucket
/// </summary>
[DisplayName("Name of bucket")]
public string BucketName { get; set; }
/// <summary>
/// Key name for Amazon s3 File transfer aws_access_key_id
/// Use #env.variable.
/// </summary>
[PasswordPropertyText(true)]
[DisplayName("AWS Access Key ID")]
[DisplayFormat(DataFormatString = "Expression")]
public string AwsAccessKeyId { get; set; }
/// <summary>
/// Secret key name for Amazon s3 File transfer aws_secret_access_key
/// Use #env.variable.
/// </summary>
[PasswordPropertyText(true)]
[DisplayName("AWS Secret Access Key")]
[DisplayFormat(DataFormatString = "Expression")]
public string AwsSecretAccessKey { get; set; }
/// <summary>
/// Usage: The result of GetTemporaryCredentials-task.
/// </summary>
[DisplayName("Temporary Credentials")]
public dynamic AwsCredentials { get; set; }
/// <summary>
/// Region selection, default EUWest1.
/// </summary>
[DisplayName("Region")]
public Regions Region { get; set; }
}
#endregion
#region Enumerations
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
public enum Regions
{
EuWest1,
EuWest2,
EuCentral1,
ApNortheast1,
ApNortheast2,
ApSouth1,
ApSoutheast1,
ApSoutheast2,
CaCentral1,
CnNorth1,
SaEast1,
UsEast1,
UsEast2,
UsWest1,
UsWest2
}
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
#endregion
}
|
52957bd7cb2fab974e520239ae1370883a92885d
|
C#
|
microsoftgraph/msgraph-cli
|
/src/generated/Models/TermsAndConditionsAcceptanceStatus.cs
| 2.5625
| 3
|
using Microsoft.Kiota.Abstractions.Serialization;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System;
namespace ApiSdk.Models {
/// <summary>
/// A termsAndConditionsAcceptanceStatus entity represents the acceptance status of a given Terms and Conditions (T&C) policy by a given user. Users must accept the most up-to-date version of the terms in order to retain access to the Company Portal.
/// </summary>
public class TermsAndConditionsAcceptanceStatus : Entity, IParsable {
/// <summary>DateTime when the terms were last accepted by the user.</summary>
public DateTimeOffset? AcceptedDateTime { get; set; }
/// <summary>Most recent version number of the T&C accepted by the user.</summary>
public int? AcceptedVersion { get; set; }
/// <summary>Navigation link to the terms and conditions that are assigned.</summary>
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP3_1_OR_GREATER
#nullable enable
public ApiSdk.Models.TermsAndConditions? TermsAndConditions { get; set; }
#nullable restore
#else
public ApiSdk.Models.TermsAndConditions TermsAndConditions { get; set; }
#endif
/// <summary>Display name of the user whose acceptance the entity represents.</summary>
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP3_1_OR_GREATER
#nullable enable
public string? UserDisplayName { get; set; }
#nullable restore
#else
public string UserDisplayName { get; set; }
#endif
/// <summary>The userPrincipalName of the User that accepted the term.</summary>
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP3_1_OR_GREATER
#nullable enable
public string? UserPrincipalName { get; set; }
#nullable restore
#else
public string UserPrincipalName { get; set; }
#endif
/// <summary>
/// Creates a new instance of the appropriate class based on discriminator value
/// </summary>
/// <param name="parseNode">The parse node to use to read the discriminator value and create the object</param>
public static new TermsAndConditionsAcceptanceStatus CreateFromDiscriminatorValue(IParseNode parseNode) {
_ = parseNode ?? throw new ArgumentNullException(nameof(parseNode));
return new TermsAndConditionsAcceptanceStatus();
}
/// <summary>
/// The deserialization information for the current model
/// </summary>
public new IDictionary<string, Action<IParseNode>> GetFieldDeserializers() {
return new Dictionary<string, Action<IParseNode>>(base.GetFieldDeserializers()) {
{"acceptedDateTime", n => { AcceptedDateTime = n.GetDateTimeOffsetValue(); } },
{"acceptedVersion", n => { AcceptedVersion = n.GetIntValue(); } },
{"termsAndConditions", n => { TermsAndConditions = n.GetObjectValue<ApiSdk.Models.TermsAndConditions>(ApiSdk.Models.TermsAndConditions.CreateFromDiscriminatorValue); } },
{"userDisplayName", n => { UserDisplayName = n.GetStringValue(); } },
{"userPrincipalName", n => { UserPrincipalName = n.GetStringValue(); } },
};
}
/// <summary>
/// Serializes information the current object
/// </summary>
/// <param name="writer">Serialization writer to use to serialize this model</param>
public new void Serialize(ISerializationWriter writer) {
_ = writer ?? throw new ArgumentNullException(nameof(writer));
base.Serialize(writer);
writer.WriteDateTimeOffsetValue("acceptedDateTime", AcceptedDateTime);
writer.WriteIntValue("acceptedVersion", AcceptedVersion);
writer.WriteObjectValue<ApiSdk.Models.TermsAndConditions>("termsAndConditions", TermsAndConditions);
writer.WriteStringValue("userDisplayName", UserDisplayName);
writer.WriteStringValue("userPrincipalName", UserPrincipalName);
}
}
}
|
a14a74cdcb5327648a398e371dba2efd43ce67a1
|
C#
|
jenspettersson/Generation
|
/Generation.Excercise.Web/Generation.DiceGame.Tests/HighGuessTests.cs
| 2.9375
| 3
|
using System;
using System.Globalization;
using NUnit.Framework;
namespace Generation.DiceGame.Tests
{
[TestFixture]
public class HighGuessTests
{
[Test]
public void If_new_roll_is_higher_than_previous_roll_it_should_be_correct()
{
int previousRoll = 1;
int newRoll = 6;
var guess = new HighGuess(previousRoll, newRoll);
Assert.True(guess.Correct);
}
[Test]
public void If_new_roll_is_lower_than_previous_roll_it_should_not_be_correct()
{
int previousRoll = 6;
int newRoll = 1;
var guess = new HighGuess(previousRoll, newRoll);
Assert.False(guess.Correct);
}
}
}
|
481ead350bb7e703de601e3b1e015669e362e003
|
C#
|
shendongnian/download4
|
/latest_version_download2/216149-46685038-158144414-6.cs
| 2.78125
| 3
|
void Main()
{
var states = new Subject<bool>();
IObservable<int> query =
states
.Select(state => state
? Observable
.Interval(TimeSpan.FromSeconds(2.0))
.StartWith(-1L)
.SelectMany(n =>
Observable.FromAsync(() => GetStatusAsync()))
: Observable.Never<int>())
.Switch();
}
public async Task<int> GetStatusAsync()
{
return await Task.Factory.StartNew(() => 42);
}
|
9e4ebac9a234ac92057a482a435c85e1ef9ea706
|
C#
|
oivoodoo/RS485_Network_Demo_Library
|
/RS485_dll/Voodoo/Logs/LogFolderConverter.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Voodoo.Libraries.Logs
{
public class LogFolderConverter : log4net.Util.PatternConverter
{
///<summary>
///
/// Evaluate this pattern converter and write the output to a writer.
///
///</summary>
///
///<param name="writer"><see cref="T:System.IO.TextWriter" /> that will receive the formatted result.</param>
///<param name="state">The state object on which the pattern converter should be executed.</param>
///<remarks>
///
///<para>
///
/// Derived pattern converters must override this method in order to
/// convert conversion specifiers in the appropriate way.
///
///</para>
///
///</remarks>
///
protected override void Convert(TextWriter writer, object state)
{
writer.Write(Path.Combine(LogConfiguration.UserApplicationFolder, "RS485.log"));
}
}
}
|
5b0e1a31bb305845e01fca700390c52d0cf995eb
|
C#
|
tmbull/MyCollections
|
/MyCollections/BinarySearchTree.cs
| 3.4375
| 3
|
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
namespace MyCollections
{
public class BinarySearchTree<T> : IEnumerable<T>
{
private class Node
{
public Node(T value, Node? left = null, Node? right = null)
{
Value = value;
Left = left;
Right = right;
}
public T Value { get; }
public Node? Left;
public Node? Right;
}
private Node? _root;
public BinarySearchTree()
{
_root = null;
}
public BinarySearchTree(T root)
{
_root = new Node(root);
}
public void Insert(T value)
{
InsertRecursive(ref _root, value);
}
private static void InsertRecursive(ref Node? current, T value)
{
if (current == null)
{
current = new Node(value);
return;
}
var comparison = Comparer<T>.Default.Compare(value, current.Value);
if (comparison < 0)
{
InsertRecursive(ref current.Left, value);
}
else if (comparison > 0)
{
InsertRecursive(ref current.Right, value);
}
}
public bool Search(T value)
{
var comparer = Comparer<T>.Default;
var current = _root;
while (current != null)
{
var comparison = comparer.Compare(value, current.Value);
if (comparison == 0)
{
return true;
}
current = comparison < 0 ? current.Left : current.Right;
}
return false;
}
public IEnumerator<T> GetEnumerator()
{
return GetEnumerator(_root);
}
private IEnumerator<T> GetEnumerator(Node? current)
{
if (current == null)
{
yield break;
}
var stack = new Stack<Node>();
while (stack.Count > 0 || current != null)
{
if (current != null)
{
stack.Push(current);
current = current.Left;
}
else
{
current = stack.Pop();
yield return current.Value;
current = current.Right;
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerable<T> EnumeratePreOrder()
{
if (_root == null)
{
yield break;
}
var stack = new Stack<Node>();
stack.Push(_root);
while (stack.Count > 0)
{
var current = stack.Pop();
yield return current.Value;
if (current.Right != null)
{
stack.Push(current.Right);
}
if (current.Left != null)
{
stack.Push(current.Left);
}
}
}
public IEnumerable<T> EnumeratePostOrder()
{
if (_root == null)
{
yield break;
}
var stack = new Stack<Node>();
var current = _root;
Node? lastVisited = null;
while (stack.Count > 0 || current != null)
{
if (current != null)
{
stack.Push(current);
current = current.Left;
}
else
{
var peek = stack.Peek();
if (peek?.Right != null && lastVisited != peek.Right)
{
current = peek.Right;
}
else
{
lastVisited = stack.Pop();
yield return lastVisited.Value;
}
}
}
}
}
}
|
e8e4b21bc21a33fce3aaafe57111b6e9ce80f8de
|
C#
|
shendongnian/download4
|
/code6/1113935-29211491-86467755-4.cs
| 3.21875
| 3
|
static string GetFirstKeyFromValue(Dictionary<string,string> dict, string val)
{
if(!dict.ContainsValue(val))
return null; //return null because nothing matched.
return dict.FirstOrDefault(kv => kv.Value.Equals(val)).Key;
}
|
92cc25138c31c9cea4697376de285576af415f9d
|
C#
|
glantzsimon/sharedlibrary
|
/SharedLibrary/Extensions/ReflectionExtensions.cs
| 2.890625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Reflection;
using K9.SharedLibrary.Attributes;
using K9.SharedLibrary.Models;
using Microsoft.Ajax.Utilities;
namespace K9.SharedLibrary.Extensions
{
public static class ReflectionExtensions
{
/// <summary>
/// Copies all property values from one object to another
/// </summary>
/// <param name="objectToUpdate"></param>
/// <param name="newObject"></param>
/// <param name="updatePrimaryKey"></param>
public static void MapTo(this object newObject, object objectToUpdate)
{
foreach (var propInfo in objectToUpdate.GetType().GetProperties())
{
try
{
objectToUpdate.SetProperty(propInfo, newObject.GetProperty(propInfo.Name));
}
catch (Exception)
{
}
}
}
public static List<PropertyInfo> GetProperties(this Object item)
{
return item.GetType().GetProperties().ToList();
}
/// <summary>
/// Return a list of properties which are decorated with the specified attribute
/// </summary>
/// <param name="item"></param>
/// <param name="attributeType"></param>
/// <returns></returns>
public static List<PropertyInfo> GetPropertiesWithAttribute(this Object item, Type attributeType)
{
return (from prop in item.GetType().GetProperties() let attributes = prop.GetCustomAttributes(attributeType, true) where attributes.Any() select prop).ToList();
}
public static Dictionary<T, PropertyInfo> GetPropertiesAndAttributesWithAttribute<T>(this IEnumerable<PropertyInfo> propertyInfos) where T : Attribute
{
var dictionary = new Dictionary<T, PropertyInfo>();
propertyInfos.Select(p =>
{
var a = p.GetCustomAttributes(typeof(T), true).FirstOrDefault() as T;
return new
{
Property = p,
Attribute = a
};
}).Where(x => x.Attribute != null)
.ForEach(_ =>
{
dictionary.Add(_.Attribute, _.Property);
});
return dictionary;
}
public static Dictionary<T, PropertyInfo> GetPropertiesAndAttributesWithAttribute<T>(this Type type) where T : Attribute
{
return type.GetProperties().GetPropertiesAndAttributesWithAttribute<T>();
}
public static Dictionary<T, PropertyInfo> GetPropertiesAndAttributesWithAttribute<T>(this Object item) where T : Attribute
{
return item.GetType().GetProperties().GetPropertiesAndAttributesWithAttribute<T>();
}
/// <summary>
/// Return a list of properties which are decorated with the specified attribute
/// </summary>
/// <param name="properties"></param>
/// <param name="attributeTypes"></param>
/// <returns></returns>
public static List<PropertyInfo> GetPropertiesWithAttributes(this List<PropertyInfo> properties, params Type[] attributeTypes)
{
var items = new List<PropertyInfo>();
foreach (var attributeType in attributeTypes)
{
items.AddRange(from prop in properties let attributes = prop.GetCustomAttributes(attributeType, true) where attributes.Any() select prop);
}
return items.ToList();
}
public static object GetProperty(this object obj, PropertyInfo propertyInfo)
{
return propertyInfo.GetValue(obj, null);
}
public static object GetProperty(this object obj, string propertyName)
{
return obj.GetType().InvokeMember(propertyName, BindingFlags.GetProperty, null, obj, new object[] { });
}
public static bool HasProperty(this object obj, string propertyName)
{
return obj.GetProperties().Any(p => p.Name == propertyName);
}
public static bool HasAttribute(this Type type, Type attributeType)
{
return type.GetCustomAttributes(attributeType, true).Any();
}
public static void SetProperty(this object obj, string propertyName, object value)
{
var propInfo = obj.GetType().GetProperties().FirstOrDefault(p => p.Name == propertyName);
SetProperty(obj, propInfo, value);
}
public static void SetProperty(this object obj, PropertyInfo propertyInfo, object value)
{
if (propertyInfo != null)
{
object formattedValue;
// Check if the type is Nullable
if (propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
// Get underlying type, e.g. "int"
formattedValue = value == null ? null : Convert.ChangeType(value, propertyInfo.PropertyType.GetGenericArguments()[0]);
}
else
{
formattedValue = Convert.ChangeType(value, propertyInfo.PropertyType);
}
propertyInfo.SetValue(obj, formattedValue, null);
}
}
public static bool IsPrimaryKey(this PropertyInfo info)
{
return info.GetCustomAttributes(typeof(KeyAttribute), false).Any();
}
public static bool IsForeignKey(this PropertyInfo info)
{
return info.GetCustomAttributes(typeof(ForeignKeyAttribute), false).Any();
}
public static bool IsVirtualCollection(this PropertyInfo info)
{
return info.GetGetMethod().IsVirtual && info.PropertyType.IsGenericType &&
info.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>);
}
public static bool IsVirtual(this PropertyInfo info)
{
var methodInfo = info.GetGetMethod();
return methodInfo.IsVirtual && !methodInfo.IsFinal;
}
public static int GetStringLength(this PropertyInfo info)
{
var attr = info.GetCustomAttributes(typeof(StringLengthAttribute), false).FirstOrDefault();
if (attr != null)
{
return ((StringLengthAttribute)attr).MaximumLength;
}
return 0;
}
/// <summary>
/// If the property has a DisplayName attribute, return the value of this, else return the property name
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static string GetDisplayName(this PropertyInfo info)
{
var attr = info.GetCustomAttributes(typeof(DisplayAttribute), true).FirstOrDefault();
return attr == null ? info.Name : ((DisplayAttribute)attr).GetName();
}
public static bool IsDataBound(this PropertyInfo info)
{
return (!info.GetCustomAttributes(typeof(NotMappedAttribute), false).Any() || info.GetCustomAttributes(typeof(LinkedColumnAttribute), false).Any()) && info.CanWrite;
}
public static Type GetLinkedPropertyType(this Type type, string propertyName)
{
return type.GetProperty(propertyName).PropertyType;
}
public static string GetLinkedForeignTableName(this Type type, string foreignKeyColumn)
{
var firstOrDefault = type.GetProperties().FirstOrDefault(p => p.Name == foreignKeyColumn);
if (firstOrDefault != null)
{
var attribute = firstOrDefault.GetCustomAttributes(typeof(ForeignKeyAttribute), true).FirstOrDefault() as ForeignKeyAttribute;
if (attribute == null)
{
throw new Exception($"No ForeignKey attribute is set on property {foreignKeyColumn}");
}
return type.GetLinkedPropertyType(attribute.Name).Name;
}
throw new Exception($"Invalid property name {foreignKeyColumn}");
}
public static bool LimitedByUser(this Type type)
{
return type.GetCustomAttributes(typeof(LimitByUserIdAttribute), true).Any();
}
public static bool ImplementsIUserData(this Type type)
{
return typeof(IUserData).IsAssignableFrom(type);
}
public static string GetForeignKeyName(this Type type)
{
return $"{type.Name}Id";
}
public static T GetAttribute<T>(this Type type)
where T : Attribute
{
return type.GetCustomAttributes(typeof(T), true).FirstOrDefault() as T;
}
public static T GetAttribute<T>(this PropertyInfo propertyInfo)
where T : Attribute
{
return propertyInfo.GetCustomAttributes(typeof(T), true).FirstOrDefault() as T;
}
public static T GetAttribute<T>(this Enum value)
where T : Attribute
{
var type = value.GetType();
var name = Enum.GetName(type, value);
return type.GetField(name)
.GetCustomAttributes(false)
.OfType<T>()
.SingleOrDefault();
}
}
}
|
e5b3f1d646f6b9f758c848cdc1e44f105a0d2a6c
|
C#
|
umbersar/MazesForProgrammers
|
/MazesForProgrammers/Cell.cs
| 3.640625
| 4
|
using System;
using System.Collections.Generic;
using System.Text;
namespace MazesForProgrammers {
public class Cell {
public int Row { get; private set; }//x co-ordinate of the cell
public int Column { get; private set; }//y co-ordinate of the cell
public List<Cell> Links { get; private set; }
public Cell? North { get; set; }
public Cell? South { get; set; }
public Cell? East { get; set; }
public Cell? West { get; set; }
public Cell(int row, int column) {
this.Row = row;
this.Column = column;
this.Links = new List<Cell>();
}
//Linked cell is different from a neighbouring cell. A cell can be a neighbour without being linked.
public void Link(Cell cell, bool biDir = true) {
this.Links.Add(cell);
if (biDir)
cell.Link(this, false);
}
public void UnLink(Cell cell, bool biDir = true) {
this.Links.Remove(cell);
if (biDir)
cell.UnLink(this, false);
}
public bool IsLinked(Cell cell) {
return this.Links.Contains(cell);
}
public List<Cell> Neighbours() {
List<Cell> neighbours = new List<Cell>() { North, South, East, West };
return neighbours.FindAll(nr => nr != null);
}
}
}
|
213c46202fc3cea70ad27df3dc84a46004d90f71
|
C#
|
leonardoMeister/ControleEstoqueDao.DAO
|
/ProdutosDAO.cs
| 2.828125
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Common;
using System.Data;
namespace ControleEstoqueDao.DAO
{
public class Produtos
{
public int IdProduto { get; set; }
public string Nome { get; set; }
public int Status { get; set; }
public int AreaId { get; set; }
public decimal Valor { get; set; }
public int MarcaId { get; set; }
public string Modelo { get; set; }
public string Descricao { get; set; }
public byte[] Foto { get; set; }
public int QuantidadeEstoque { get; set; }
public Produtos()
{
}
public Produtos(int id, string nome)
{
this.Nome = nome;
this.IdProduto = id;
}
}
public class ProdutosDAO
{
private DbProviderFactory factory;
public ProdutosDAO()
{
}
/// <summary>
/// Fazendo Select no banco
/// </summary>
/// <param name="provider">Qual o banco provedor</param>
/// <param name="stringConexao">Conexao com o banco</param>
/// <param name="produtos">Objeto a selecionar</param>
/// <returns></returns>
public DataTable SelectDbProvider(string provider, string stringConexao, Produtos produto)
{
factory = DbProviderFactories.GetFactory(provider);
using (var conexao = factory.CreateConnection()) //Cria conexão
{
//Atribui a string de conexão
conexao.ConnectionString = stringConexao;
using (var comando = factory.CreateCommand()) //Cria comando
{
comando.Connection = conexao; //Atribui conexão
conexao.Open();
string auxSql = "";
if (produto.Nome != null && produto.Nome != "")
{
var nome = comando.CreateParameter();
nome.ParameterName = "@nome";
nome.Value = "%" + produto.Nome + "%";
comando.Parameters.Add(nome);
comando.CommandText = @"SELECT id_produto 'Id Produto', nome 'Produto', status 'Status', area_id 'Id Area Atuacao',
valor 'Valor', marca_id 'Id Marca', modelo 'Modelo', descricao 'Descricao' ,foto 'Foto',
quantidade_estoque 'Quantidade Estoque' FROM tb_produto WHERE nome like @nome";
}
else
{
if (produto.IdProduto != 0)
{
auxSql = $"where id_produto = '{produto.IdProduto}'";
}
//Criando query
comando.CommandText = @"SELECT id_produto 'Id Produto',nome 'Nome',status 'Status',
bb.area 'Area Atuação', valor 'Valor',
cc.marca 'Marca',
modelo 'Modelo',descricao 'Descricao',quantidade_estoque 'Quantidade Estoque', foto 'Foto', id_area 'Id Area'
FROM tb_produto aa
inner join tb_area_atuacao bb
on bb.id_area = aa.area_id
inner join tb_marca cc
on cc.id_marca = aa.marca_id" + " " + auxSql;
}
//Executa o script na conexão e retorna as linhas afetadas.
var sdr = comando.ExecuteReader();
DataTable linhas = new DataTable();
linhas.Load(sdr);
return linhas;
}
}
}
/// <summary>
/// Inserindo no banco os produtos
/// </summary>
/// <param name="provider"></param>
/// <param name="stringConexao"></param>
/// <param name="produtos"></param>
public void InserirDbProvider(string provider, string stringConexao, Produtos produtos)
{
factory = DbProviderFactories.GetFactory(provider);
using (var conexao = factory.CreateConnection()) //Cria conexão
{
//Atribui a string de conexão
conexao.ConnectionString = stringConexao;
using (var comando = factory.CreateCommand()) //Cria comando
{
//Atribui conexão
comando.Connection = conexao;
//Adiciona parâmetro (@campo e valor)
var nomeProdto = comando.CreateParameter();
nomeProdto.ParameterName = "@nomeProduto";
nomeProdto.Value = produtos.Nome;
comando.Parameters.Add(nomeProdto);
var statusProduto = comando.CreateParameter();
statusProduto.ParameterName = "@status";
statusProduto.Value = produtos.Status;
comando.Parameters.Add(statusProduto);
var areaId = comando.CreateParameter();
areaId.ParameterName = "@AreaId";
areaId.Value = produtos.AreaId;
comando.Parameters.Add(areaId);
var valor = comando.CreateParameter();
valor.ParameterName = "@Valor";
valor.Value = produtos.Valor;
comando.Parameters.Add(valor);
var marcaId = comando.CreateParameter();
marcaId.ParameterName = "@MarcaId";
marcaId.Value = produtos.MarcaId;
comando.Parameters.Add(marcaId);
var modelo = comando.CreateParameter();
modelo.ParameterName = "@Modelo";
modelo.Value = produtos.Modelo;
comando.Parameters.Add(modelo);
var foto = comando.CreateParameter();
foto.ParameterName = "@foto";
foto.Value = produtos.Foto;
comando.Parameters.Add(foto);
var descricao = comando.CreateParameter();
descricao.ParameterName = "@Descricao";
descricao.Value = produtos.Descricao;
comando.Parameters.Add(descricao);
var qtdEstoque = comando.CreateParameter();
qtdEstoque.ParameterName = "@QTDEstoque";
qtdEstoque.Value = produtos.QuantidadeEstoque;
comando.Parameters.Add(qtdEstoque);
//Abre conexão
conexao.Open();
if (produtos.IdProduto != 0)
{
var id = comando.CreateParameter();
id.ParameterName = "@id";
id.Value = produtos.IdProduto;
comando.Parameters.Add(id);
comando.CommandText = @"UPDATE tb_produto SET nome= @nomeProduto , status = @status , area_id = @AreaId ,
marca_id = @MarcaId , valor = @Valor , modelo = @Modelo , descricao = @Descricao ,
quantidade_estoque = @QTDEstoque , foto = @foto
WHERE id_produto = @Id; ";
}
else
{
//Script para inserir com os parâmetros adicionados
comando.CommandText = @"INSERT INTO tb_produto
(nome,status,area_id,valor,marca_id,modelo,descricao,quantidade_estoque,foto)
VALUES (@nomeProduto,@status,@AreaId,@Valor,@MarcaId,@Modelo,@Descricao, @QTDEstoque, @foto)";
}
//Executa o script na conexão e retorna o número de linhas afetadas.
var linhas = comando.ExecuteNonQuery();
//fecha conexão
conexao.Close();
}
}
}
public void RemoverDbProvider(string provider, string stringConexao, int id)
{
factory = DbProviderFactories.GetFactory(provider);
using (var conexao = factory.CreateConnection()) //Cria conexão
{
//Atribui a string de conexão
conexao.ConnectionString = stringConexao;
using (var comando = factory.CreateCommand()) //Cria comando
{
//Atribui conexão
comando.Connection = conexao;
//Abre conexão
conexao.Open();
//Script para inserir com os parâmetros adicionados
comando.CommandText = $"delete from tb_produto where id_produto = {id}";
//Executa o script na conexão e retorna o número de linhas afetadas.
var linhas = comando.ExecuteNonQuery();
//fecha conexão
conexao.Close();
}
}
}
}
}
|
a2ad1f806c79fdb8c8777967a8a938b8f391ffac
|
C#
|
Luxic/PathFollowing
|
/PathFollowing/PathFollowing/PathFollow.cs
| 3.203125
| 3
|
using System.Collections.Generic;
namespace PathFollowing
{
public class PathFollow
{
#region Fields
char[,] matrix;
public string Letters = "";
public string PathAsCharacters = "";
List<Direction> Directions = new List<Direction>() {
new Direction() { x = 0, y = -1, c = (char)Chars.Horizontal },
new Direction() { x = 0, y = 1, c = (char)Chars.Horizontal },
new Direction() { x = -1, y = 0, c = (char)Chars.Vertical },
new Direction() { x = 1, y = 0, c = (char)Chars.Vertical }
};
#endregion
#region Constructor
public PathFollow(char[,] matrix)
{
this.matrix = matrix;
}
#endregion
#region Methods
public void StartPathFollowing()
{
Node startPosition = findStartPosition();
Node node = FindPath(startPosition);
if (node.Character == (char)Chars.End)
getCharacters(startPosition);
}
private void getCharacters(Node node)
{
Node currentNode = node;
while (currentNode != null)
{
PathAsCharacters += currentNode.Character;
if (Helper.IsLetter(currentNode.Character) && currentNode.Character != (char)Chars.End)
Letters += currentNode.Character;
currentNode = currentNode.ChildNode;
}
}
private Node FindPath(Node node)
{
if (node.Character == (char)Chars.End || node.Character == (char)Chars.Empty || node == null)
return node;
Node nextNode = null;
foreach (Direction dir in Directions)
{
int x = node.x + dir.x;
int y = node.y + dir.y;
if (x < 0 || x >= matrix.GetLength(0) || y < 0 || y >= matrix.GetLength(1) || matrix[x, y] == ' ' || matrix[x, y] == (char)Chars.Start)
continue;
if (Helper.IsInDirection(matrix[x, y], dir.c))
{
if (Direction.Compare(node.direction, dir))
continue;
nextNode = followPath(x, y, dir, node);
break;
}
else
{
nextNode = new Node(x, y, matrix[x, y], dir);
node.ChildNode = nextNode;
}
}
return FindPath(nextNode);
}
private Node followPath(int x, int y, Direction dir, Node node)
{
if (matrix[x, y] != (char)Chars.Horizontal && matrix[x, y] != (char)Chars.Vertical)
{
Node retNode = new Node(x, y, matrix[x, y], dir);
node.ChildNode = retNode;
return retNode;
}
x += dir.x;
y += dir.y;
Node n = new Node(x, y, dir.c, dir);
node.ChildNode = n;
return followPath(x, y, dir, n);
}
private Node findStartPosition()
{
for (int x = 0; x < matrix.GetLength(0); x++)
for (int y = 0; y < matrix.GetLength(1); y++)
{
if (matrix[x, y] == (char)Chars.Start)
return new Node(x, y, matrix[x, y], null);
}
return null;
}
#endregion
}
}
|
a9fb5e437ddfb52ab3c333c95b496ae5893b9d53
|
C#
|
JaminTc/Mystuff
|
/FlooringProgram/FlooringProgram.Models/Orders.cs
| 2.984375
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using FlooringProgram.Models;
namespace FlooringProgram.Models
{
public class Orders
{
public int OrderNumber { get; set; }
public string CustomerName { get; set; }
public string State { get; set; }
public decimal TaxRate { get; set; }
public string ProductType { get; set; }
public decimal Area { get; set; }
public decimal CostPerSquareFoot { get; set; }
public decimal LaborCostPerSquareFoot { get; set; }
public decimal MaterialCost { get; set; }
public decimal LaborCost { get; set; }
public decimal Tax { get; set; }
public decimal Total { get; set; }
public void ShowNewOrder(List<Orders> newOrder)
{
foreach (var match in newOrder)
{
Console.WriteLine("");
Console.WriteLine("Order Number: {0}", match.OrderNumber);
Console.WriteLine("Customer Name: {0}", match.CustomerName);
Console.WriteLine("Customer State: {0}", match.State);
Console.WriteLine("State Tax Rate: {0}", match.TaxRate);
Console.WriteLine("Product Type: {0}", match.ProductType);
Console.WriteLine("Area: {0} sqFt", match.Area);
Console.WriteLine("Cost per square foot: {0:c}", match.CostPerSquareFoot);
Console.WriteLine("Labor cost per square foot: {0:c}", match.LaborCostPerSquareFoot);
Console.WriteLine("Overall material cost: {0:c}", match.MaterialCost);
Console.WriteLine("Overall Labor Cost: {0:c}", match.LaborCost);
Console.WriteLine("Total Tax: {0:c}", match.Tax);
Console.WriteLine("Total: {0:c}", match.Total);
Console.WriteLine("");
}
}
}
}
|
f0ebc2419da6ff5fb0c92cecee372d8bb0a13e6c
|
C#
|
pazhe/JiazheWeb
|
/Jiazhe.Web.DAL/Nhibernate/NHibernateDao.cs
| 2.6875
| 3
|
using NHibernate;
using NHibernate.Criterion;
using NHibernate.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Jiazhe.Web.DAL.Nhibernate
{
[Spring.Stereotype.Repository]
public class NHibernateDao<T> : IDAL.IdaoFather<T>
{
public ISessionFactory SessionFactory { get; set; }
/// <summary>
/// 获取Session
/// </summary>
public ISession Session
{
get
{
return SessionFactory.GetCurrentSession();
}
}
/// <summary>
/// 当前实体对应的表名
/// </summary>
public string TableName
{
get { return typeof(T).ToString().Substring(typeof(T).ToString().LastIndexOf('.') + 1); }
}
/// <summary>
/// 添加实体
/// </summary>
/// <param name="entity"></param>
public int Add(T entity)
{
using (ITransaction transaction = Session.BeginTransaction())
{
try
{
int id = (int)Session.Save(entity);
Session.Flush();
transaction.Commit();
return id;
}
catch (HibernateException)
{
transaction.Rollback();
throw;
}
}
}
/// <summary>
/// 修改实体
/// </summary>
/// <param name="entity"></param>
public void Update(T entity)
{
using (ITransaction transaction = Session.BeginTransaction())
{
try
{
Session.Update(entity);
Session.Flush();
transaction.Commit();
}
catch (HibernateException)
{
transaction.Rollback();
throw;
}
}
}
/// <summary>
/// 保存或修改实体
/// </summary>
/// <param name="customer"></param>
public void SaveOrUpdate(IList<T> list)
{
using (ITransaction transaction = Session.BeginTransaction())
{
try
{
foreach (var entity in list)
{
Session.SaveOrUpdate(entity);
}
Session.Flush();
transaction.Commit();
}
catch (HibernateException)
{
transaction.Rollback();
throw;
}
}
}
/// <summary>
/// 删除实体
/// </summary>
/// <param name="entity"></param>
public void Delete(T entity)
{
using (ITransaction transaction = Session.BeginTransaction())
{
try
{
Session.Delete(entity);
Session.Flush();
transaction.Commit();
}
catch (HibernateException)
{
transaction.Rollback();
throw;
}
}
}
/// <summary>
/// 按条件删除
/// </summary>
/// <param name="sqlWhere">删除条件</param>
public void Delete(string sqlWhere)
{
using (ITransaction transaction = Session.BeginTransaction())
{
try
{
Session.Delete(string.Format("from {0} Where {1}", TableName, sqlWhere));
Session.Flush();
transaction.Commit();
}
catch (HibernateException)
{
transaction.Rollback();
throw;
}
}
}
/// <summary>
/// 根据ID得到实体
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
///
public T Get(int id)
{
return Session.Get<T>(id);
}
/// <summary>
/// 根据ID得到实体
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
///
public T Load(int id)
{
return Session.Load<T>(id);
}
/// <summary>
/// 得到所有实体
/// </summary>
/// <returns></returns>
public IList<T> LoadAll()
{
return Session.Query<T>().ToList();
}
/// <summary>
/// 按条件排序得到前N条记录
/// </summary>
/// <param name="top">获取条数</param>
/// <param name="field">排序字段</param>
/// <param order="field">排序方式,升序asc,降序desc</param>
/// <returns></returns>
public IList<T> QueryTop(int top, string field, string order)
{
if (order == "asc")
{
return Session.CreateCriteria(typeof(T)).SetMaxResults(top).AddOrder(Order.Asc(field)).List<T>();
}
else
{
return Session.CreateCriteria(typeof(T)).SetMaxResults(top).AddOrder(Order.Desc(field)).List<T>();
}
}
/// <summary>
/// 根据条件得到实体
/// </summary>
/// <param name="sqlWhere">查询条件</param>
/// <returns></returns>
public IList<T> Where(string sqlWhere)
{
StringBuilder strSql = new StringBuilder(string.Format("from {0} c", TableName));
if (!string.IsNullOrEmpty(sqlWhere))
{
strSql.Append(string.Format(" where {0}", sqlWhere));
}
return Session.CreateQuery(strSql.ToString()).List<T>();
}
/// <summary>
/// 得到统计数量
/// </summary>
/// <param name="strWhere">查询条件</param>
/// <returns></returns>
public int GetRecordCount(string sqlWhere)
{
StringBuilder strSql = new StringBuilder(string.Format("select count(1) from {0} c", TableName));
if (!string.IsNullOrEmpty(sqlWhere))
{
strSql.Append(string.Format(" where {0}", sqlWhere));
}
return (int)Session.CreateSQLQuery(strSql.ToString()).UniqueResult();
}
/// <summary>
/// 分页获取数据列表
/// </summary>
/// <param name="PageSize">每页获取数据条数</param>
/// <param name="PageIndex">当前页是第几页</param>
/// <param name="strWhere">查询条件</param>
/// <returns></returns>
public IList<T> GetPageList(int PageSize, int PageIndex, string sqlWhere)
{
StringBuilder strSql = new StringBuilder();
strSql.Append(string.Format("select top {0} * from {1} where ID not in(select top ", PageSize,
TableName));
strSql.Append(PageSize * (PageIndex - 1));
strSql.Append(string.Format(" ID from {0}", TableName));
if (!string.IsNullOrEmpty(sqlWhere))
{
strSql.Append(string.Format(" where {0} ) and {0}", sqlWhere));
}
else
{
strSql.Append(")");
}
return Session.CreateSQLQuery(strSql.ToString()).AddEntity(typeof(T)).List<T>();
}
/// <summary>
/// 根据数据字典父编码和编码获取名称
/// </summary>
/// <param name="parentNumber">父编码</param>
/// <param name="number">编码</param>
/// <returns></returns>
public string GetName(string parentNumber, string number)
{
//string[] num = number.Split(',');
//List<string> list = new List<string>();
//list.AddRange(num);
//IQueryable<string> name = from q in Session.Query<T_Dictionary>()
// where q.ParentNumber == parentNumber && list.Contains(q.Number)
// orderby q.Number
// select q.Name;
//string nameStr = "";
//foreach (string n in name)
//{
// nameStr += n + ",";
//}
//return nameStr.Contains(",") ? nameStr.Substring(0, nameStr.Length - 1) : nameStr;
throw new NotImplementedException();
}
/// <summary>
/// 获取该父编码下最大编码
/// </summary>
/// <param name="parentNumber">父编码</param>
/// <returns></returns>
public int GetMaxNumber(string parentNumber)
{
string strSql =
string.Format(
"select case when MAX(cast(substring(Number,len(Number)-3,4) as int)) is null then 0 else MAX(cast(substring(Number,len(Number)-3,4) as int)) end from {0} where ParentNumber='{1}'",
TableName, parentNumber);
return ++Session.CreateQuery(strSql).List<int>()[0];
}
}
}
|
f3ca0ef0b3e18cfb13191a220d41102433aaff95
|
C#
|
danthomas/RoslynTest
|
/TestCli/Tasks/GitCheckout.cs
| 2.703125
| 3
|
using CommandLineInterface;
namespace TestCli.Tasks
{
public class GitCheckout : ITask<GitCheckout.Args>
{
private readonly IConsole _console;
public GitCheckout(IConsole console)
{
_console = console;
}
public void Run(Args args)
{
_console.WriteInfo("git checkout " + args.Branch);
}
public class Args
{
public string Branch { get; set; }
}
public ArgDefs<Args> ArgDefs => new ArgDefs<Args>()
.DefaultRequired(x => x.Branch);
}
}
|
1024c381b64a3e6ec18f70e2d400bcde875b4f9a
|
C#
|
tafo/Geeks
|
/Geeks.Practices/Arrays/Basic/CountIntersection.cs
| 3.6875
| 4
|
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Geeks.Practices.Helper;
namespace Geeks.Practices.Arrays.Basic
{
/// <summary>
/// The title is "Intersection of two arrays"
///
/// Given two arrays A and B respectively of size N and M.
/// The task is to print the count of elements in the intersection (or common elements) of the two arrays.
///
/// For this question,
/// Intersection of two arrays can be defined as the set containing distinct common elements between the two arrays.
///
/// Input:
/// The first line of input contains an integer T denoting the number of test cases.
/// The first line of each test case is N and M, N is the size of array A and M is size of array B.
/// The second line of each test case contains N input A[i].
/// The third line of each test case contains M input B[i].
///
/// Output:
/// Print the count of intersecting elements.
///
/// User Task:
/// The task is to complete the function NumberOfElementsInIntersection which takes 4 inputs
/// ie- array a, array b, n which is the size of array a, m which is the size of array b.
/// The function should return the count of the number of elements in the intersection.
///
/// Constraints:
/// 1 ≤ T ≤ 100
/// 1 ≤ N, M ≤ 10e5
/// 1 ≤ A[i], B[i] ≤ 10e5
///
/// Example:
/// Input:
/// 4
/// 5 3
/// 89 24 75 11 23
/// 89 2 4
/// 6 5
/// 1 2 3 4 5 6
/// 3 4 5 6 7
/// 4 4
/// 10 10 10 10
/// 20 20 20 20
/// 3 3
/// 10 10 10
/// 10 10 10
///
/// Output:
/// 1
/// 4
/// 0
/// 1
/// Explanation:
/// Test case 1: 89 is the only element in the intersection of two arrays.
/// Test case 2: 3 4 5 and 6 are the elements in the intersection of two arrays.
///
/// </summary>
[SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")]
[SuppressMessage("ReSharper", "PossibleNullReferenceException")]
public class CountIntersection
{
public static void RunLinq()
{
var testCount = int.Parse(Console.ReadLine());
while (testCount-- > 0)
{
Console.ReadLine();
var firstInput = Console.ReadLine().TrimEnd();
var secondInput = Console.ReadLine().TrimEnd();
var a = firstInput.Split(' ').Select(int.Parse).Distinct();
var b = secondInput.Split(' ').Select(int.Parse).Distinct();
Console.WriteLine(a.Intersect(b).Count());
}
}
public static void RunLoop()
{
var testCount = int.Parse(Console.ReadLine());
while (testCount-- > 0)
{
var split = Console.ReadLine().Split(' ');
var firstInput = Console.ReadLine().TrimEnd();
var secondInput = Console.ReadLine().TrimEnd();
var n = int.Parse(split[0]);
var m = int.Parse(split[1]);
var a = StringScanner.GetPositiveInt(firstInput, n);
var b = StringScanner.GetPositiveInt(secondInput, m);
Console.WriteLine(NumberOfElementsInIntersection(a, b, n, m));
}
}
/// <summary>
/// The signature of this method is specified by GfG
/// </summary>
public static int NumberOfElementsInIntersection(int[] a, int[] b, int n, int m)
{
Array.Sort(a);
Array.Sort(b);
n--;
m--;
var result = 0;
var previousIntersection = 0;
while (n >= 0 && m >= 0)
{
if (a[n] > b[m])
{
n--;
}
else if (a[n] == b[m] && a[n] != previousIntersection)
{
result++;
previousIntersection = a[n];
n--;
m--;
}
else
{
m--;
}
}
return result;
}
}
}
|
5787e365ca718e72f7133440dd107c8031deef44
|
C#
|
shendongnian/download4
|
/code3/518303-11923305-27892364-2.cs
| 2.515625
| 3
|
public class SQLDataAccessor<I, T> : IDataAccessorModel<I, T>
{
internal SQLDataAccessor(IResult<string> result)
{
_connectionString = "";
_result = result;
}
private readonly string _connectionString;
private IResult<string> _result;
public T AccessType { get { return new SqlServer(); } }
public I Instance { get; private set; }
public IResult<string> Add(I instance)
{
Instance = instance;
return _result;
}
public IResult<string> Get(I instance)
{
Instance = instance;
return _result;
}
public IResult<string> Delete(I instance)
{
Instance = instance;
return _result;
}
public IResult<string> Update(I instance)
{
Instance = instance;
return _result;
}
}
|
4d832ba8b7f59bb04563535b25d5a60524f3068c
|
C#
|
osipukr/Text-Editor
|
/App/MainForm.cs
| 2.734375
| 3
|
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace App
{
public interface IMainForm
{
string Path { get; }
string Content { get; set; }
void SetSymbolCount(int count);
void SetWordCount(int count);
event EventHandler FileOpenClick;
event EventHandler FileSaveClick;
event EventHandler ContentChanged;
event EventHandler ClosingForm;
}
public partial class MainForm : Form, IMainForm
{
public MainForm()
{
InitializeComponent();
butOpenFile.Click += ButOpenFile_Click;
butSaveFile.Click += ButSaveFile_Click;
textContent.TextChanged += TextContent_TextChanged;
butSelectFile.Click += ButSelectFile_Click;
numFont.ValueChanged += NumFont_ValueChanged;
FormClosing += MainForm_FormClosing;
}
private void ButOpenFile_Click(object sender, EventArgs e)
{
FileOpenClick?.Invoke(this, EventArgs.Empty);
if (!string.IsNullOrEmpty(Content)) textContent.ReadOnly = false;
}
private void ButSaveFile_Click(object sender, EventArgs e)
{
FileSaveClick?.Invoke(this, EventArgs.Empty);
}
private void TextContent_TextChanged(object sender, EventArgs e)
{
ContentChanged?.Invoke(this, EventArgs.Empty);
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
ClosingForm?.Invoke(this, EventArgs.Empty);
}
#region Events
#endregion
#region IMainForm
public string Path
{
get { return textFilePath.Text; }
}
public string Content
{
get { return textContent.Text; }
set { textContent.Text = value; }
}
public event EventHandler FileOpenClick;
public event EventHandler FileSaveClick;
public event EventHandler ContentChanged;
public event EventHandler ClosingForm;
public void SetSymbolCount(int count)
{
textSymbolCount.Text = count.ToString();
}
public void SetWordCount(int count)
{
textWordCount.Text = count.ToString();
}
#endregion
private void ButSelectFile_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog
{
Filter = "Текстовые файлы|*.txt|Все файлы|*.*"
};
if (dialog.ShowDialog() == DialogResult.OK)
{
textFilePath.Text = dialog.FileName;
ButOpenFile_Click(this, EventArgs.Empty);
}
}
private void NumFont_ValueChanged(object sender, EventArgs e)
{
textContent.Font = new Font("Microsoft Sans Serif", (int)numFont.Value);
}
}
}
|
52a705f8305bedb8339f6e4902d365fade9e95ae
|
C#
|
jrwdexter/PulseAudio.Service
|
/PulseAudio.ServiceWrapper/Worker.cs
| 2.546875
| 3
|
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
namespace PulseAudio.ServiceWrapper
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private readonly ServiceConfigInfo _serviceConfigInfo;
private Process _processInfo;
public Worker(IConfiguration config, ILogger<Worker> logger)
{
_serviceConfigInfo = config.GetSection("ServiceInformation").Get<ServiceConfigInfo>();
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
if (_processInfo == null)
{
var servicePath = Path.GetFullPath(_serviceConfigInfo.Service);
var executableFile = new FileInfo(servicePath);
if (executableFile.Directory?.Parent == null)
throw new FileNotFoundException("Could not find file to launch.");
Debug.Assert(executableFile.DirectoryName != null, "executableFile.DirectoryName != null");
var rootPath = executableFile.Directory.Parent.FullName;
_logger.LogInformation($"Starting application {servicePath}");
_logger.LogInformation($"Root path: {rootPath}");
var arguments = $"-p \"{rootPath}\\lib\\pulse-1.1\\modules\" -nF \"{rootPath}\\etc\\pulse\\default.pa\"";
_logger.LogInformation($"Launching pulse audio with args: {arguments}");
var startInfo = new ProcessStartInfo
{
FileName = servicePath,
Arguments = arguments,
RedirectStandardOutput = true,
RedirectStandardError = true,
WorkingDirectory = executableFile.DirectoryName,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
};
_processInfo = Process.Start(startInfo);
if (_processInfo == null)
throw new ApplicationException("Could not start Pulse Audio");
_logger.LogInformation("Process started with ID: {Id}", _processInfo.Id);
Thread.Sleep(30000);
}
while (!stoppingToken.IsCancellationRequested && !_processInfo.HasExited)
{
if (!_processInfo.Responding)
throw new ApplicationException(_processInfo.StandardError.ReadToEnd());
var stdLine = await _processInfo.StandardOutput.ReadLineAsync();
var errorLine = await _processInfo.StandardError.ReadLineAsync();
if (!string.IsNullOrEmpty(stdLine) || !string.IsNullOrEmpty(errorLine))
{
var line = errorLine ?? stdLine;
var (levelChar, message) = (line.Substring(0, 1), line.Substring(3));
LogLevel level;
switch (levelChar)
{
case "E":
level = LogLevel.Error;
break;
case "W":
level = LogLevel.Warning;
break;
case "I":
level = LogLevel.Information;
break;
case "D":
level = LogLevel.Debug;
break;
case "T":
level = LogLevel.Trace;
break;
default:
level = LogLevel.Information;
break;
}
_logger.Log(level, message);
}
await Task.Delay(1000, stoppingToken);
}
}
public override Task StopAsync(CancellationToken cancellationToken)
{
TryCloseSubprocess();
return base.StopAsync(cancellationToken);
}
public override void Dispose()
{
TryCloseSubprocess();
Log.CloseAndFlush();
base.Dispose();
}
private void TryCloseSubprocess()
{
if (_processInfo != null && !_processInfo.HasExited)
_processInfo.Close();
}
}
}
|
91357f9a14dd16392bfe0b2c517a62187ff2b6a9
|
C#
|
SenkoVlad/PortableManager
|
/Backend/Data/Repositories/Implementation/TaskTypeRepository.cs
| 2.546875
| 3
|
using Microsoft.EntityFrameworkCore;
using PortableManager.Web.Server.Data.Repositories.Interface;
using PortableManager.Web.Server.Models;
using PortableManager.Web.Server.Models.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Task = System.Threading.Tasks.Task;
namespace PortableManager.Web.Server.Data.Repositories.Implementation
{
public class TaskTypeRepository : ITaskTypeRepository
{
private DbContextFactory dbContext;
public TaskTypeRepository(DbContextFactory context)
{
dbContext = context;
}
public async Task<List<TaskType>> GetAllTaskTypeAsync()
{
var Context = dbContext.Create(typeof(TaskTypeRepository));
var taskType = await Context.TaskTypes.ToListAsync();
return taskType.Select(TaskType.Map).ToList();
}
public async Task<TaskType> GetTaskTypeByIdAsync(int id)
{
var Context = dbContext.Create(typeof(TaskTypeRepository));
TaskTypeDto taskTypeDto = await Context.TaskTypes.FirstOrDefaultAsync(item => item.Id == id);
if (taskTypeDto != null)
return TaskType.Map(taskTypeDto);
return await Task.FromResult(TaskType.Map(new TaskTypeDto()
{
Id = 0,
Name = ""
}));
}
public async Task<TaskType> GetTaskTypeByNameAsync(string name)
{
var Context = dbContext.Create(typeof(TaskTypeRepository));
TaskTypeDto taskTypeDto = await Context.TaskTypes.FirstOrDefaultAsync(item => item.Name == name.Trim());
if (taskTypeDto != null)
return TaskType.Map(taskTypeDto);
return TaskType.Map(new TaskTypeDto());
}
public async Task<TaskType> AddTaskTypeAsync(TaskType taskType)
{
if(taskType != null && !string.IsNullOrWhiteSpace(taskType.Name))
{
var taskTypeName = await GetTaskTypeByNameAsync(taskType.Name);
if(string.IsNullOrWhiteSpace(taskTypeName.Name))
{
var Context = dbContext.Create(typeof(TaskTypeRepository));
var taskTypeDto = new TaskTypeDto() { Name = taskType.Name };
await Context.TaskTypes.AddAsync(taskTypeDto);
await Context.SaveChangesAsync();
return await Task.FromResult(TaskType.Map(taskTypeDto));
}
}
return await Task.FromResult(new TaskType() {});
}
public async Task DeleteTaskTypeAsync(TaskType taskType)
{
if(taskType != null && !string.IsNullOrWhiteSpace(taskType.Name))
{
var Context = dbContext.Create(typeof(TaskTypeRepository));
var taskTypeForDelete = await Context.TaskTypes.FirstOrDefaultAsync(item => item.Name == taskType.Name);
if(taskTypeForDelete != null)
Context.TaskTypes.Remove(taskTypeForDelete);
await Context.SaveChangesAsync();
}
}
public async Task<int> UpdateTaskTypeAsync(TaskType taskType)
{
if(taskType != null && !string.IsNullOrWhiteSpace(taskType.Name))
{
var Context = dbContext.Create(typeof(TaskTypeRepository));
var taskTypeForUpdate = await Context.TaskTypes.FirstOrDefaultAsync(item => item.Id == taskType.Id);
if(taskTypeForUpdate != null)
{
taskTypeForUpdate.Name = taskType.Name;
Context.Entry(taskTypeForUpdate).State = EntityState.Modified;
return await Context.SaveChangesAsync();
}
}
return await Task.FromResult(0);
}
}
}
|
983094f13cbd73249d3a1a0bc07880199a235e3b
|
C#
|
henkmollema/Dommel
|
/src/Dommel.Json/JsonObjectTypeHandler.cs
| 2.5625
| 3
|
using System;
using System.Data;
using System.Text.Json;
using System.Text.Json.Serialization;
using Dapper;
namespace Dommel.Json;
internal class JsonObjectTypeHandler : SqlMapper.ITypeHandler
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip,
NumberHandling = JsonNumberHandling.AllowReadingFromString,
};
public void SetValue(IDbDataParameter parameter, object? value)
{
parameter.Value = value is null || value is DBNull
? DBNull.Value
: JsonSerializer.Serialize(value, JsonOptions);
parameter.DbType = DbType.String;
}
public object? Parse(Type destinationType, object? value) =>
value is string str ? JsonSerializer.Deserialize(str, destinationType, JsonOptions) : null;
}
|
1c7874c7d375a2036eb82cf7d89c7d88d6f806f1
|
C#
|
AbdelkhalekAmer/DesignPatterns
|
/StrategyPattern/Program.cs
| 3.171875
| 3
|
using System;
namespace StrategyPattern
{
class Program
{
static void Main(string[] args)
{
// Generate random customer in the service and get discount based on delegate passed by the client code.
Console.WriteLine(new CustomerPaymentService().CalculateDiscount((customer) => customer.MembershipType == MembershipTypeEnum.Pro ? 25 : 0));
Console.WriteLine(new CustomerPaymentService().CalculateDiscount((customer) => customer.MembershipType == MembershipTypeEnum.Premium ? 40 : 0));
}
}
}
|
d2f85ac5e5b8efd1c0a3797d455daa19db3ee028
|
C#
|
woghd8503/Second_BitCamp
|
/_098_Polymorphism_Address/CompanyAddress.cs
| 3.03125
| 3
|
using _61_AddressClass;
using System;
using System.Collections.Generic;
using System.Text;
namespace _98_polymorphism_Address
{
class CompanyAddress : Address
{
public string Company { get; set; }
public string Job { get; set; }
public override void showInfo(int order)
{
base.showInfo(order);
Console.WriteLine("회사 : " + this.Company);
Console.WriteLine("업무 : " + this.Job);
}
public override void showInfo()
{
base.showInfo();
Console.WriteLine("회사 : " + this.Company);
Console.WriteLine("업무 : " + this.Job);
}
}
}
|
85fd3eb32dee279877cda94f88bc6134193e24d4
|
C#
|
zizidzhelil/Recipes
|
/src/Cooking/Writers/Implementation/Writer.cs
| 3.21875
| 3
|
using System;
using System.Data;
using System.Text;
namespace Cooking.Writers.Implementation
{
public class Writer : IWriter
{
public void Write(DataTable reportData)
{
StringBuilder reportBuilder = new StringBuilder();
foreach (DataRow row in reportData.Rows)
{
int i;
object[] array = row.ItemArray;
for (i = 0; i < array.Length - 1; i++)
{
reportBuilder.Append(array[i].ToString() + ": ");
}
reportBuilder.AppendLine(array[i].ToString());
}
Console.WriteLine(reportBuilder.ToString());
}
}
}
|
03a68a0f94062b627e572473f8d78ce9b7b0b59f
|
C#
|
shendongnian/download4
|
/latest_version_download2/227938-50323960-173501002-2.cs
| 2.734375
| 3
|
JObject jsonObj= JObject.parse(strJSON);
JObject PKTDL=jsonObj["PKTDTL"] as JObject;
IList<string> keys = PKTDL.Properties().Select(p => p.Name).ToList(); // this gives column names
StringBuilder sb=new StringBuilder();
string headers="";
foreach(string key in keys)
{
headers+=","+key;
}
sb.AppendLine(headers.TrimStart(','));
foreach(JObject j in jsonObj["PKTDTL"]) //if jobject doesnt work try "JToken j"
{
string values="";
foreach(string key in keys)
{
values+=","+jsonObj["PKTDTL"][key];
}
sb.AppendLine(values.TrimStart(','));
}
File.WriteAllText(filePath, sb.ToString());
|
b5c4a7804bf4dee18287b628472452fcb8888fb2
|
C#
|
Diana-Tkacheva/Lab_1_sem3
|
/Lab_5_sem3/LevDistance.cs
| 3.75
| 4
|
using System;
namespace Lab_5_sem3
{
public class LevDistance
{
public static int GetDistance(string source, string destination)
{
if (source == null || destination == null)
{
return -1;
}
int lenSrc = source.Length;
int lenDst = destination.Length;
if (lenSrc == 0 && lenDst == 0)
{
return 0;
}
if (lenSrc == 0)
{
return lenDst;
}
if (lenDst == 0)
{
return lenSrc;
}
string strSrc = source.ToUpper();
string strDst = destination.ToUpper();
int[,] matrix = new int[lenSrc + 1, lenDst + 1];
for(int i = 0; i <= lenSrc; i++)
{
matrix[i, 0] = i;
}
for(int j = 0; j <= lenDst; j++)
{
matrix[0, j] = j;
}
for (int i = 1; i <= lenSrc; i++)
{
for (int j = 1; j <= lenDst; j++)
{
int chEqual = 1;
if (strSrc[i - 1] == strDst[j - 1])
{
chEqual = 0;
}
int ins = matrix[i, j - 1] + 1;
int del = matrix[i - 1, j] + 1;
int change = matrix[i - 1, j - 1] + chEqual;
matrix[i, j] = Math.Min(Math.Min(ins, del), change);
if ((i > 1) && (j > 1) && (strSrc[i - 1] == strDst[j - 2]) && (strSrc[i - 2] == strDst[j - 1]))
{
matrix[i, j] = Math.Min(matrix[i, j], matrix[i - 2, j - 2] + chEqual);
}
}
}
return matrix[lenSrc, lenDst];
}
}
}
|
0a9783bab4abe400a7a58bcd4f706770461d997f
|
C#
|
watashi/AlgoSolution
|
/timus/ac/10/1068.cs
| 2.703125
| 3
|
//原来天皇的题目在这里有原型-_-b
//P.S. the sample is so hd
using System;
class Sum //1068. Sum
{
static void Main(string[] args)
{
int ans = 0;
int n = Int32.Parse(Console.ReadLine());
if (n >= 1)
{
for (int i = 1; i <= n; i++)
ans += i;
}
else
{
for (int i = 1; i >= n; i--)
ans += i;
}
Console.WriteLine(ans);
}
}
//ID Date Author Problem Language Judgement result Test # Execution time Memory used
//1873236 14:31:58 16 Nov 2007 watashi 1068 C# Accepted 0.109 1 913 KB
/*
id => 4677347
date => 18:03:2615 Dec 2012
user => watashi
pname => Sum
lang => C#
status => Accepted
testid =>
time => 0.125
mem => 1 968 KB
pid => 1068
*/
|
aa5fa67a14d0c7572b01ea82d9612a7e6b948552
|
C#
|
DakEnviy/homm
|
/HOMM/Objects/Unit.cs
| 3.03125
| 3
|
using System.Collections.Generic;
using System.Linq;
using HOMM.BattleObjects;
namespace HOMM.Objects
{
public class Unit
{
private readonly string _name;
private readonly int _hitPoints;
private readonly int _attack;
private readonly int _defence;
private readonly (int, int) _damage;
private readonly float _initiative;
private readonly ISet<UnitProperty> _properties;
public Unit(string name, int hitPoints, int attack, int defence, (int, int) damage, float initiative, params UnitProperty[] properties)
{
_name = name;
_hitPoints = hitPoints;
_attack = attack;
_defence = defence;
_damage = damage;
_initiative = initiative;
_properties = properties.ToHashSet();
}
public ISet<string> GetSkillNames()
=> _properties
.Select(prop => prop.GetSkill())
.Where(skillName => skillName != null)
.ToHashSet();
public bool ContainsSkill(string skillName)
=> _properties
.Select(prop => prop.GetSkill())
.Contains(skillName);
public bool ContainsSkill(Skill skill)
=> ContainsSkill(skill.GetName());
public string GetName() => _name;
public int GetHitPoints() => _hitPoints;
public int GetAttack() => _attack;
public int GetDefence() => _defence;
public (int, int) GetDamage() => _damage;
public float GetInitiative() => _initiative;
public ISet<UnitProperty> GetProperties() => _properties;
}
}
|
dadab9e21e0156d5421aaf703a4258cbf5685082
|
C#
|
dotyoda/Library
|
/Library/Presenters/LoginPresenter.cs
| 2.875
| 3
|
using Library.Models;
using Library.Views;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Library.Presenters
{
class LoginPresenter
{
public LoginPresenter(FrmLogin form)
{
this.form = form;
}
public readonly FrmLogin form;
public void Auth(string username, string password)
{
if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) {
form.ShowError("Preencha todos os campos");
return;
}
try
{
form.Login = Librarian.Auth(username, password);
if (!form.Login)
form.ShowError("Login inválido");
else
form.Close();
} catch (Exception error)
{
Console.WriteLine(error);
form.ShowError("Não foi possível realizar o login");
}
}
}
}
|
cb7bb2cbc4a12c9bac12266ad4fc840fef53a73d
|
C#
|
itagile-csd/ngt-team-alex
|
/NerdGolfTracker/Operationen/Hilfe.cs
| 2.609375
| 3
|
using System.Collections.Generic;
using NerdGolfTracker.Befehle;
namespace NerdGolfTracker.Operationen
{
public class Hilfe : IOperation
{
private IBefehleListe _befehleListe;
public Hilfe(IBefehleListe befehleListe)
{
_befehleListe = befehleListe;
}
public string FuehreAus(IScorecard scorecard)
{
var hilfstexte = _befehleListe.Befehle().ConvertAll(HilfstextFuer);
return "Ich helfe dir beim Fuehren der Scorecard. Ich reagiere auf folgende Befehle: "
+ System.Environment.NewLine +
string.Join(System.Environment.NewLine, hilfstexte)
+ ".";
}
public string HilfstextFuer(IBefehl befehl)
{
return string.Format(" * \"{0}\" [{1}] {2}", befehl.Kommando, befehl.KurzKommando,befehl.Erklaerung);
}
}
}
|
52cfce70f5df68d7e06448fbce1b6c97551d0438
|
C#
|
Delsus78/notebookcsharp
|
/TestStorage/TestStorage.cs
| 2.578125
| 3
|
using System;
using Logic;
using Storage;
using Xunit;
namespace TestStorage
{
public class TestStorage
{
/// <summary>
/// en on recupere le test des moyennes (ajoutant tout un tas de modules et d'unite + exams)
/// puis on test une sauvegarde entre temps (avec donc un ajout d'un IStockage)
/// </summary>
[Fact]
public void TestSave()
{
IStockage stockage = new JsonStockage();
Notebook nb = stockage.Load();
// UE 1
Unit u = new Unit();
nb.AddUnit(u);
Module m1 = new Module();
m1.Coef = 2;
m1.Name = "Maths";
Exam e1 = new Exam();
Exam e2 = new Exam();
// Ajout des exams pour le premier module
e1.Module = m1;
e1.Coef = 1;
e1.Score = 15;
nb.Exams.Add(e1);
// Ajout pour le 2eme module
e2.Module = m1;
e2.Coef = 2;
e2.Score = 10;
nb.Exams.Add(e2);
u.AddModule(m1);
// UE 2
Unit u2 = new Unit();
nb.AddUnit(u2);
Module m3 = new Module();
Module m4 = new Module();
m3.Coef = 1;
m4.Coef = 1;
m3.Name = "Anglais";
m4.Name = "ExprCom";
Exam e4 = new Exam();
Exam e5 = new Exam();
Exam e6 = new Exam();
// Ajout des exams pour le premier module
e4.Module = m3;
e4.Coef = 4;
e4.Score = 14;
nb.Exams.Add(e4);
// Ajout pour le 2eme module
e5.Module = m4;
e5.Coef = 1;
e5.Score = 15;
nb.Exams.Add(e5);
e6.Module = m4;
e6.Coef = 1;
e6.Score = 15;
nb.Exams.Add(e6);
u2.AddModule(m3);
u2.AddModule(m4);
// on vient une premiere fois sauvegarder cette instance
stockage.Update(nb);
// on rcupre le notebook sauvegard
Notebook savedNB = stockage.Load();
// puis on test si les deux correspondes
Assert.Equal(nb,savedNB);
}
}
}
|
2cd8fdd0d1166aeddc39adb004ee728e35dc4df2
|
C#
|
mcteach21/FormationCSharpCDI
|
/WinFormsApp/Principale.cs
| 2.609375
| 3
|
using System;
using System.Windows.Forms;
namespace WinFormsApp
{
public partial class Principale : Form
{
public Principale()
{
//Méthode du designer pour 'dessin' Fenêtre..
//..Toujours en premier!!!
InitializeComponent();
//..code autre
}
private void Form1_Load(object sender, EventArgs e)
{
//MessageBox.Show("Chargement Fenêtre!");
}
private void btnQuitter_Click(object sender, EventArgs e)
{
//Fermer Fenêtre courante (this) de type 'Form1'!!
this.Close();
}
private void btnModal_Click(object sender, EventArgs e)
{
AutreFenetre fen = new AutreFenetre();
this.Visible = false;
fen.Show(this);
}
private void cmenuQuitter_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnMessageOuvrir_Click(object sender, EventArgs e)
{
string message = "Il fait bo aujourd'hui!";
MessageFenetre fen = new MessageFenetre(message);
// Si propriété 'Modifiers' de lblMessage = public
//fen.lblMessage.Text = message;
fen.Show();
}
private void Principale_DoubleClick(object sender, EventArgs e)
{
panel1.Visible = false;
panel1.Height = 0;
}
}
}
|
96a962b3b7be3e71e2bb317f4aea9ea7f98ddbb2
|
C#
|
soopercool101/BrawlCrate
|
/BrawlLib/Internal/Windows/Controls/NumericInputBox.cs
| 2.671875
| 3
|
using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows.Forms;
namespace BrawlLib.Internal.Windows.Controls
{
public class NumericInputBox : TextBox
{
public float _previousValue;
public float? _value;
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public float Value
{
get
{
if (_value == null)
{
Apply();
}
return _value.Value;
}
set
{
_value = value; //Clamp(_minValue, _maxValue);
UpdateText();
}
}
public NumericInputBox()
{
UpdateText();
}
public float MinimumValue
{
get => _minValue;
set => _minValue = value;
}
public float MaximumValue
{
get => _maxValue;
set => _maxValue = value;
}
public bool Integral
{
get => _integral;
set => _integral = value;
}
public bool Integer
{
get => _integer;
set => _integer = value;
}
public float _minValue = float.MinValue;
public float _maxValue = float.MaxValue;
public bool _integral;
public bool _integer;
public event EventHandler ValueChanged;
protected override void OnLostFocus(EventArgs e)
{
Apply();
base.OnLostFocus(e);
}
protected override void OnKeyDown(KeyEventArgs e)
{
float val;
switch (e.KeyCode)
{
case Keys.D0:
case Keys.D1:
case Keys.D2:
case Keys.D3:
case Keys.D4:
case Keys.D5:
case Keys.D6:
case Keys.D7:
case Keys.D8:
case Keys.D9:
case Keys.NumPad0:
case Keys.NumPad1:
case Keys.NumPad2:
case Keys.NumPad3:
case Keys.NumPad4:
case Keys.NumPad5:
case Keys.NumPad6:
case Keys.NumPad7:
case Keys.NumPad8:
case Keys.NumPad9:
if (Text.IndexOf('-') == 0 && SelectionStart == 0 && SelectionLength == 0)
{
e.SuppressKeyPress = true;
}
break;
case Keys.Back:
break;
case Keys.Left:
if (float.TryParse(Text, out val))
{
if (e.Control)
{
Text = (val - 90f).Clamp(_minValue, _maxValue).ToString();
Apply();
e.Handled = true;
e.SuppressKeyPress = true;
}
if (e.Shift)
{
Text = (val - 180f).Clamp(_minValue, _maxValue).ToString();
Apply();
e.Handled = true;
e.SuppressKeyPress = true;
}
}
break;
case Keys.Right:
if (float.TryParse(Text, out val))
{
if (e.Control)
{
Text = (val + 90f).Clamp(_minValue, _maxValue).ToString();
Apply();
e.Handled = true;
e.SuppressKeyPress = true;
}
if (e.Shift)
{
Text = (val + 180f).Clamp(_minValue, _maxValue).ToString();
Apply();
e.Handled = true;
e.SuppressKeyPress = true;
}
}
break;
case Keys.Up:
if (float.TryParse(Text, out val))
{
if (e.Shift || _integral)
{
Text = (val + 1.0f).Clamp(_minValue, _maxValue).ToString();
}
else
{
Text = (val + 0.1f).Clamp(_minValue, _maxValue).ToString();
}
Apply();
}
e.Handled = true;
e.SuppressKeyPress = true;
break;
case Keys.Down:
if (float.TryParse(Text, out val))
{
if (e.Shift || _integral)
{
Text = (val - 1.0f).Clamp(_minValue, _maxValue).ToString();
}
else
{
Text = (val - 0.1f).Clamp(_minValue, _maxValue).ToString();
}
Apply();
}
e.Handled = true;
e.SuppressKeyPress = true;
break;
case Keys.Subtract:
case Keys.OemMinus:
if (SelectionStart != 0 || Text.Contains('-') && !SelectedText.Contains('-'))
{
e.SuppressKeyPress = true;
}
break;
case Keys.Decimal:
if (CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator.Contains(","))
{
goto case Keys.Oemcomma;
}
goto case Keys.OemPeriod;
case Keys.OemPeriod:
if (Text.IndexOf('.') != -1 || Integer)
{
e.SuppressKeyPress = true;
}
break;
case Keys.Oemcomma:
if (!CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator.Contains(",") ||
Text.IndexOf(',') != -1 || Integer)
{
e.SuppressKeyPress = true;
}
break;
case Keys.Escape:
UpdateText();
e.SuppressKeyPress = true;
break;
case Keys.Enter:
Apply();
e.Handled = true;
e.SuppressKeyPress = true;
break;
case Keys.X:
if (e.Control)
{
if (float.TryParse(Text, out val))
{
val = float.NaN;
Text = val.ToString();
Apply();
}
}
break;
case Keys.V:
case Keys.C:
if (!e.Control)
{
goto default;
}
break;
case Keys.Delete:
break;
default:
e.Handled = true;
e.SuppressKeyPress = true;
break;
}
base.OnKeyDown(e);
}
private void UpdateText()
{
if (_value == float.NaN)
{
Text = "";
}
else
{
Text = _value.ToString();
}
}
private void Apply()
{
float val = _value ?? 0.0f;
int val2 = (int) val;
if (_value != null && val.ToString() == Text)
{
return;
}
if (Text == "")
{
val = float.NaN;
}
else if (!_integral)
{
float.TryParse(Text, out val);
val = val.Clamp(_minValue, _maxValue);
}
else
{
int.TryParse(Text, out val2);
val2 = val2.Clamp(_minValue == float.MinValue ? int.MinValue : (int)_minValue, _maxValue == float.MaxValue ? int.MaxValue : (int)_maxValue);
}
if (!_integral)
{
if (_value != val)
{
_previousValue = _value ?? 0.0f;
_value = val;
ValueChanged?.Invoke(this, null);
}
}
else
{
if (_value != val2)
{
_previousValue = _value ?? 0.0f;
_value = val2;
ValueChanged?.Invoke(this, null);
}
}
UpdateText();
}
}
}
|
fd27bef6b29374acf66fbf437da9fc4d80ad3248
|
C#
|
JMPennington/Capstone
|
/com.WanderingTurtle/com.WanderingTurtle/BookingManager.cs
| 2.921875
| 3
|
using com.WanderingTurtle.Common;
using com.WanderingTurtle.DataAccess;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
namespace com.WanderingTurtle.BusinessLogic
{
//markup for data object to bind
[DataObject(true)]
public class BookingManager
{
/// <summary>
/// Tony Noel
/// Created: 15/2/13
/// RetrieveListItemList- a method used to retrieve a list of ItemListingDetails (a subclass of Booking) through the data access layer, from the database
/// The information returned is specifically that human-readable elements needed to make a booking like event name, description, etc
/// </summary>
/// <remarks>
/// Pat Banks
/// Updated: 2015/03/30
/// Added DataCache
/// </remarks>
/// <returns>Returns a list of ItemListingDetails objects from database(From the ItemListing and EventItem tables).</returns>
[DataObjectMethod(DataObjectMethodType.Select)]
public List<ItemListingDetails> RetrieveActiveItemListingDetailsList()
{
double cacheExpirationTime = 5; //how long the cache should live (minutes)
var now = DateTime.Now;
try
{
if (DataCache._currentItemListingDetailsList == null)
{
RefreshItemListingDetailsListCacheData();
return DataCache._currentItemListingDetailsList;
}
//check time. If less than 5 min, return cache
if (now > DataCache._ItemListingDetailsListTime.AddMinutes(cacheExpirationTime))
{
RefreshItemListingDetailsListCacheData();
return DataCache._currentItemListingDetailsList;
}
return DataCache._currentItemListingDetailsList;
}
catch (Exception)
{
var ax = new ApplicationException("There was a problem accessing the server. \nPlease contact your system administrator.");
throw ax;
}
}
/// <summary>
/// Pat Banks
/// Created: 2015/03/30
///
/// Refreshes the data cache
/// </summary>
private void RefreshItemListingDetailsListCacheData()
{
//data hasn't been retrieved yet. get data, set it to the cache and return the result.
var activeEventListings = BookingAccessor.GetItemListingDetailsList();
//calculating the quantity of available tickets for each listing
foreach (ItemListingDetails lIO in activeEventListings)
{
lIO.QuantityOffered = AvailableQuantity(lIO.MaxNumGuests, lIO.CurrentNumGuests);
}
DataCache._currentItemListingDetailsList = activeEventListings;
DataCache._ItemListingDetailsListTime = DateTime.Now;
}
/// <summary>
/// Pat Banks
/// Created: 2015/03/11
///
/// Retrieves Event Listing information for the one selected item listing
/// Information is human readable with data from joined tables
/// </summary>
/// <param name="itemListID">ItemList ID matching an ItemListingDetails record</param>
/// <returns>an ItemListingDetails containing the item listing information</returns>
public ItemListingDetails RetrieveItemListingDetailsList(int itemListID)
{
var now = DateTime.Now;
double cacheExpirationTime = 5;
try
{
if (DataCache._currentItemListingDetailsList == null)
{
return BookingAccessor.GetItemListingDetails(itemListID);
}
//check time. If less than 5 min, return event from cache
if (now > DataCache._ItemListingDetailsListTime.AddMinutes(cacheExpirationTime))
{
//get event from DB
var requestedEvent = BookingAccessor.GetItemListingDetails(itemListID);
return requestedEvent;
}
else
{
//get event from cached list
var list = DataCache._currentItemListingDetailsList;
ItemListingDetails requestedEvent = new ItemListingDetails();
requestedEvent = list.Where(e => e.ItemListID == itemListID).FirstOrDefault();
if (requestedEvent != null)
{
return requestedEvent;
}
throw new ApplicationException("Event not found.");
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Pat Banks
/// Created: 2015/03/19
///
/// Takes data from the presentation layer and determines the results of attempting to add a booking
/// </summary>
/// <param name="bookingToAdd">Booking information from presentation Layer form</param>
/// <returns>Results of adding the booking</returns>
public ResultsEdit AddBookingResult(Booking bookingToAdd)
{
if (bookingToAdd.Quantity == 0)
{
return ResultsEdit.QuantityZero;
}
try
{
//calls method to add a booking and update itemListing Table with current number of guests
int result = BookingAccessor.AddBooking(bookingToAdd);
if (result == 2)
{
//update cache
RefreshItemListingDetailsListCacheData();
return ResultsEdit.Success;
}
return ResultsEdit.DatabaseError;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Tony Noel
/// Created: 2015/02/05
///
/// EditBooking- a method used to update a booking through the data access layer to be added to the database
/// As the BookingID number will not change or be updated in the database the method uses the same booking ID number to search
/// the database through the Retrieve Booking method. This will pull the originally record into an object "oldOne". Then the
/// original record and the new booking object that was passed to the method can both be passed to upDateBooking to be updated.
/// </summary>
/// <param name="newOne">Takes an input of a booking object</param>
/// <returns> Returns an int- the number of rows affected, if add is successful</returns>
public int EditBooking(Booking newOne)
{
Booking oldOne = RetrieveBooking(newOne.BookingID);
var numRows = BookingAccessor.UpdateBooking(oldOne, newOne);
return numRows;
}
/// <summary>
/// Tony Noel
/// Created: 2015/02/05
///
/// RetrieveBooking- a method used to request a booking from the data access layer and database
/// </summary>
/// <param name="bookingId">Takes an input of an int- the BookingID number to locate the requested record.</param>
/// <returns>Output is a booking object to hold the booking record.</returns>
[DataObjectMethod(DataObjectMethodType.Select)]
public Booking RetrieveBooking(int bookingId)
{
try
{
return BookingAccessor.GetBooking(bookingId);
}
catch (Exception)
{
var ax = new ApplicationException("There was a problem accessing your data.");
throw ax;
}
}
/// <summary>
/// Tony Noel
/// Updated: 2015/03/10
///
/// Method to calculate the cancellation fee using the CalculateTime method * TotalCharge
/// </summary>
/// <param name="bookingToCancel">The BookingDetails object to be cancelled</param>
/// <returns>the actual fee in $ that will be charged for cancelling a booking</returns>
public decimal CalculateCancellationFee(BookingDetails bookingToCancel)
{
decimal feePercent = CalculateTime(bookingToCancel);
return feePercent * bookingToCancel.TotalCharge;
}
/// <summary>
/// Tony Noel
/// Created: 2015/03/04
///
/// A method to compare two different dates and determine a cancellation fee amount.
/// Stores today's date, then subtracts todays date from the start date of the event
/// Uses a TimeSpan object which represents an interval of time and is able to perform calculations on time.
/// The difference of days is stored on an double and used to test conditions.
/// </summary>
/// <remarks>
/// Pat Banks
/// Updated: 2015/03/07
/// Tony Noel
/// Updated: 2015/03/10
/// </remarks>
/// <param name="bookingStartTime">The BookingDetails being refunded for</param>
/// <returns>Decimal containing the total cancellation fee % amount</returns>
public decimal CalculateTime(BookingDetails bookingStartTime)
{
decimal feePercent;
//TimeSpan is used to calculate date differences
TimeSpan ts = bookingStartTime.StartDate - DateTime.Now;
//The .TotalDays gets the amount of days inbetween returns a double to account for partial days
double difference = ts.TotalDays;
//if event is more than 3 days away, there is no fee charged
if (difference >= 3)
{
feePercent = 0m;
}
//if event is between 1 and 3 days, 1/2 the total price is charged
else if (difference < 3 && difference > 1)
{
feePercent = 0.5m;
}
//if event is less than 1 day away, guest pays for entire amount
else
{
feePercent = 1.0m;
}
return feePercent;
}
/// <summary>
/// Tony Noel
/// Created: 2015/03/10
///
/// Calculates the extended price of for the order of quantity of tickets multiplied by the unit price
/// </summary>
/// <param name="price">price of one ticket</param>
/// <param name="quantity">number of tickets</param>
/// <returns>The extended price</returns>
public decimal CalcExtendedPrice(decimal price, int quantity)
{
return quantity * price;
}
/// <summary>
/// Tony Noel
/// Created: 2015/03/10 - Moved to Booking Manager
///
/// Calculates the total charge of discount * Extended price
/// </summary>
/// <param name="discount">percentage from form</param>
/// <param name="extendedPrice">ticket price * quantity</param>
/// <returns></returns>
public decimal CalcTotalCharge(decimal discount, decimal extendedPrice)
{
decimal amtToPayPercent = (decimal)(1 - discount);
return amtToPayPercent * extendedPrice;
}
/// <summary>
/// Tony Noel
/// Created: 2015/03/10 - Moved to Booking Manager, as it does a calculation.
/// </summary>
/// <param name="maxQuantity">The maximum amount of people who can sign up for a booking</param>
/// <param name="currentQuantity">The current amount of people signed up for a booking</param>
/// <returns>An int reflecting how many people can still sign up</returns>
public int AvailableQuantity(int maxQuantity, int currentQuantity)
{
int availableQuantity;
availableQuantity = maxQuantity - currentQuantity;
return availableQuantity;
}
/// <summary>
/// Tony Noel
/// Created: 2015/03/10
///
/// A helper method to calculate the quantity of guests being added onto a booking compared to the original
/// amount reserved for the booking. Returns the difference between the two.
/// </summary>
/// <param name="newQuantity">updated number of people attending</param>
/// <param name="currentQuantity">current quantity of people attending</param>
/// <returns>Number of spots different</returns>
public int SpotsReservedDifference(int newQuantity, int currentQuantity)
{
int quantity = newQuantity - currentQuantity;
return quantity;
}
/// <summary>
/// Pat Banks
/// Created: 2015/03/19
///
/// Checks if a booking can be edited by performing logical checks if booking is too old or cancelled
/// </summary>
/// <param name="bookingToCheck">The BookingDetails object to crossreference against</param>
/// <returns>An enumerated result depicting pass or fail</returns>
public ResultsEdit CheckToEditBooking(BookingDetails bookingToCheck)
{
if (bookingToCheck.StartDate < DateTime.Now)
{
return ResultsEdit.CannotEditTooOld;
}
return bookingToCheck.Quantity == 0 ? ResultsEdit.Cancelled : ResultsEdit.OkToEdit;
}
/// <summary>
/// Pat Banks
/// Created: 2015/03/19
///
/// Gives the results of cancelling a booking to the preseantation layer
/// </summary>
/// <param name="bookingToCancel">The bookingDetails object to cancel</param>
/// <returns>An enumerated result depicting pass or fail</returns>
public ResultsEdit CancelBookingResults(BookingDetails bookingToCancel)
{
try
{
//update the numbers
bookingToCancel.Quantity = 0;
bookingToCancel.TicketPrice = 0;
bookingToCancel.ExtendedPrice = 0;
bookingToCancel.Discount = 0;
int result = EditBooking(bookingToCancel);
//result should be 2 - one for the booking, one to update the number of guests for the item listing
if (result == 2)
{
//refresh Data Cache
RefreshItemListingDetailsListCacheData();
return ResultsEdit.Success;
}
return ResultsEdit.ChangedByOtherUser;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Pat Banks
/// Created: 2015/03/19
///
/// Gives the results of editing a booking to the presentation layer
/// </summary>
/// <remarks>
/// Pat Banks
/// Updated: 2015/03/30
///
/// Updated to include data cache refresh
/// </remarks>
/// <param name="originalQty">The amount of people who could sign up</param>
/// <param name="editedBooking">The Booking object with the updated information</param>
/// <returns>An enumerated result depicting pass or fail</returns>
public ResultsEdit EditBookingResult(int originalQty, Booking editedBooking)
{
try
{
//A variable to hold the difference between the number of guests on the original reservation, and the old reservation
int numGuestsDifference = SpotsReservedDifference(editedBooking.Quantity, originalQty);
// creates an ItemListing object by retrieving the record of the specific object based on it's ItemListID
ItemListingDetails originalItem = RetrieveItemListingDetailsList(editedBooking.ItemListID);
//assigned the difference of the MaxNumGuests - currentNum of guests
int quantityOffered = AvailableQuantity(originalItem.MaxNumGuests, originalItem.CurrentNumGuests);
//If the quantity offered is 0, and the new quantity is going up from the original amount booked, alerts the staff and returns.
if (quantityOffered == 0 && (numGuestsDifference > editedBooking.Quantity))
{
return ResultsEdit.ListingFull;
}
//Method to check the number of guests added to a reservation against the available quantity for the event
if (numGuestsDifference > quantityOffered)
{
return ResultsEdit.ListingFull;
}
if (editedBooking.Quantity == 0)
{
return ResultsEdit.QuantityZero;
}
//send the changes to the database
int numRows = EditBooking(editedBooking);
if (numRows == 2)
{
//refresh Data Cache
RefreshItemListingDetailsListCacheData();
return ResultsEdit.Success;
}
return ResultsEdit.ChangedByOtherUser;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Pat Banks
/// Created: 2015/03/30
///
/// Passes data to the Accessor to verify that the pin is not being used.
/// </summary>
/// <param name="inPIN">The pin to crossreference against</param>
/// <returns>A HotelGuest object whose pin matches the one passed</returns>
public HotelGuest CheckValidPIN(string inPIN)
{
try
{
//retrieve guest
return BookingAccessor.VerifyHotelGuestPin(inPIN);
}
catch (Exception ax)
{
throw ax;
}
}
/// <summary>
/// Matt Lapka
/// Created: 2015/04/14
/// Retrieves numbers from a specific event listing
/// Not cached since it will differ each time
/// </summary>
/// <param name="itemListID">The ID of event listing</param>
/// <returns>Names of hotel guests, room numbers, and quantities of tickets for each booking related to that item listing</returns>
public List<BookingNumbers> RetrieveBookingNumbers(int itemListID)
{
try
{
return BookingAccessor.GetBookingNumbers(itemListID);
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Pat Banks
/// Created: 2015/04/26
///
/// Checks if anyone is signed up for an event
/// </summary>
/// <param name="itemListID">The ID of the event listing to check against</param>
/// <returns>An enumerated result indicating yes or no</returns>
public ResultsArchive CheckListingArchive(int itemListID)
{
var bookings = RetrieveBookingNumbers(itemListID);
var numbers = bookings.Sum(booking => booking.Quantity);
return numbers > 0 ? ResultsArchive.CannotArchive : ResultsArchive.OkToArchive;
}
}
}
|
5f8e0614f1698d7dd28da51e3a0a2930ccd393d9
|
C#
|
Quaggles/RyanQuagliataUnity
|
/Sirenix.OdinInspector.Attributes/Attributes/ShowIfAttribute.cs
| 2.875
| 3
|
//-----------------------------------------------------------------------// <copyright file="ShowIfAttribute.cs" company="Sirenix IVS"> // Copyright (c) Sirenix IVS. All rights reserved.// </copyright>//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// <copyright file="ShowIfAttribute.cs" company="Sirenix IVS">
// Copyright (c) Sirenix IVS. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Sirenix.OdinInspector
{
using System;
/// <summary>
/// <para>ShowIf is used on any property and can hide the property in the inspector.</para>
/// <para>Use this to hide irrelevant properties based on the current state of the object.</para>
/// </summary>
/// <example>
/// <para>This example shows a component with fields hidden by the state of another field.</para>
/// <code>
/// public class MyComponent : MonoBehaviour
/// {
/// public bool ShowProperties;
///
/// [ShowIf("showProperties")]
/// public int MyInt;
///
/// [ShowIf("showProperties", false)]
/// public string MyString;
///
/// public SomeEnum SomeEnumField;
///
/// [ShowIf("SomeEnumField", SomeEnum.SomeEnumMember)]
/// public string SomeString;
/// }
/// </code>
/// </example>
/// <example>
/// <para>This example shows a component with a field that is hidden when the game object is inactive.</para>
/// <code>
/// public class MyComponent : MonoBehaviour
/// {
/// [ShowIf("MyVisibleFunction")]
/// public int MyHideableField;
///
/// private bool MyVisibleFunction()
/// {
/// return this.gameObject.activeInHierarchy;
/// }
/// }
/// </code>
/// </example>
/// <seealso cref="EnableIfAttribute"/>
/// <seealso cref="DisableIfAttribute"/>
/// <seealso cref="HideIfAttribute"/>
[DontApplyToListElements]
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)]
public sealed class ShowIfAttribute : Attribute
{
/// <summary>
/// Name of a bool field, property or function to show or hide the property.
/// </summary>
public string MemberName;
/// <summary>
/// Whether or not to slide the property in and out when the state changes.
/// </summary>
public bool Animate;
/// <summary>
/// The optional member value.
/// </summary>
public object Value;
/// <summary>
/// Shows a property in the inspector, if the specified member returns true.
/// </summary>
/// <param name="memberName">Name of a bool field, property or function to show or hide the property.</param>
/// <param name="animate">Whether or not to slide the property in and out when the state changes.</param>
public ShowIfAttribute(string memberName, bool animate = true)
{
this.MemberName = memberName;
this.Animate = animate;
}
/// <summary>
/// Shows a property in the inspector, if the specified member returns the specified value.
/// </summary>
/// <param name="memberName">Name of a bool field, property or method to test the value of.</param>
/// <param name="optionalValue">The value the member should equal for the property to shown.</param>
/// <param name="animate">Whether or not to slide the property in and out when the state changes.</param>
public ShowIfAttribute(string memberName, object optionalValue, bool animate = true)
{
this.MemberName = memberName;
this.Value = optionalValue;
this.Animate = animate;
}
}
}
|
53f26756e8d6d36f4756bc9139e1ca85f3307bd2
|
C#
|
stefism/Projects
|
/01 C# Basic/09VlojeniExercise/NewHouse/Program.cs
| 3.71875
| 4
|
using System;
namespace NewHouse
{
class Program
{
static void Main(string[] args)
{
string typeOfFlowers = Console.ReadLine();
double numberOfFlowers = double.Parse(Console.ReadLine());
double budget = double.Parse(Console.ReadLine());
double price = 0;
switch (typeOfFlowers)
{
case "Roses":
price = numberOfFlowers * 5;
if (numberOfFlowers > 80)
{
price = price - (price * 0.10);
}
break;
case "Dahlias":
price = numberOfFlowers * 3.80;
if (numberOfFlowers > 90)
{
price = price - (price * 0.15);
}
break;
case "Tulips":
price = numberOfFlowers * 2.80;
if (numberOfFlowers > 80)
{
price = price - (price * 0.15);
}
break;
case "Narcissus":
price = numberOfFlowers * 3;
if (numberOfFlowers < 120)
{
price = price + (price * 0.15);
}
break;
case "Gladiolus":
price = numberOfFlowers * 2.50;
if (numberOfFlowers < 80)
{
price = price + (price * 0.20);
}
break;
}
double leftMoney = budget - price;
if (budget >= price)
{
Console.WriteLine($"Hey, you have a great garden with {numberOfFlowers} {typeOfFlowers} and {Math.Abs(leftMoney):F2} leva left.");
}
else
{
Console.WriteLine($"Not enough money, you need {Math.Abs(leftMoney):F2} leva more.");
}
}
}
}
|
a1f92f58a4bccdcd48ad7237c2461f62f2557526
|
C#
|
yasinatilkan60/Northwind-Backend
|
/NorthwindBackend/Core/Extensions/ClaimsPrincipalExtensions.cs
| 3.1875
| 3
|
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Text;
using System.Linq;
namespace Core.Extensions
{
// Extension yazılacağı için public static yazılmıştır.
public static class ClaimsPrincipalExtensions
{
// Buradaki yaklaşım Claims Principal'ın (mevcut kullanıcı) sadece rollerine değil başka bilgilerine de erişmek üzerine kurulacaktır.
public static List<string> Claims(this ClaimsPrincipal claimsPrincipal, string claimType)
{
// this ClaimsPrincipal claimsPrincipal extend edilecek ve claimType için filtreleme yapılacak.
var result = claimsPrincipal?.FindAll(claimType)?.Select(x => x.Value).ToList(); // her bir claim type'ın key ve value değeri vardır.
return result;
}
// Rolleri döndürelim.
public static List<string> ClaimRoles(this ClaimsPrincipal claimsPrincipal) // claims principal extend edilir.
{
return claimsPrincipal?.Claims(ClaimTypes.Role);
}
//Artık kullanıcı ClaimsPrincipalExtensions.ClaimsRoles dediğinde roller gelecektir.
}
}
|
a7c5370b7a25021e0b6b4f8ba6b67b07c943b4f3
|
C#
|
JoseRochaVidrio/SistemaCaritas
|
/Sistema Caritas/Almacen.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SQLite;
using BarcodeLib;
namespace CaritasVentas
{
public partial class Almacen : Form
{
public Almacen()
{
InitializeComponent();
}
private void button3_Click_1(object sender, EventArgs e)
{
int cant = 0;
bool cantidad = Int32.TryParse(textBox6.Text, out cant);
float vent = 0.0F;
bool venta = float.TryParse(textBox7.Text, out vent);
float comp = 0.0F;
bool compra = float.TryParse(textBox8.Text, out comp);
if (textBox1.Text != "" && cantidad == true && compra == true && venta == true)
{
try
{
bool existeprov = false;
///create the connection string
string appPath2 = Path.GetDirectoryName(Application.ExecutablePath);
///create the connection string
string connString = @"Data Source= " + appPath2 + @"\DBpinc.s3db ;Version=3;";
//create the database query
string query = "SELECT * FROM Proveedor Where Nombreproveedor = '" + textBox5.Text + "'";
//create an OleDbDataAdapter to execute the query
System.Data.SQLite.SQLiteDataAdapter dAdapter = new System.Data.SQLite.SQLiteDataAdapter(query, connString);
//create a command builder
System.Data.SQLite.SQLiteCommandBuilder cBuilder = new System.Data.SQLite.SQLiteCommandBuilder(dAdapter);
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
//fill the DataTable
dAdapter.Fill(dTable);
dAdapter.Update(dTable);
for (int i = 0; i < dTable.Rows.Count; i++)
{
DataRow Row = dTable.Rows[i];
if (Row["Nombreproveedor"].ToString() == textBox5.Text)
{
existeprov = true;
}
}
if (existeprov == true)
{
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
System.Data.SQLite.SQLiteConnection sqlConnection1 =
new System.Data.SQLite.SQLiteConnection(@"Data Source=" + appPath + @"\DBPInc.s3db ;Version=3;");
System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand();
cmd.CommandType = System.Data.CommandType.Text;
//comando sql para insercion
cmd.CommandText = "INSERT INTO Almacen Values ('" + Int64.Parse(textBox4.Text) + "', '" + textBox1.Text + "', '" + float.Parse(textBox7.Text) + "', '" + float.Parse(textBox8.Text) + "', '" + Int32.Parse(textBox6.Text) + "' ,'" + textBox5.Text + "', '" + DateTime.Now.ToShortDateString() + "')";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
sqlConnection1 = new System.Data.SQLite.SQLiteConnection(@"Data Source=" + appPath + @"\DBstk.s3db ;Version=3;");
cmd = new System.Data.SQLite.SQLiteCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO Existencia Values('"+Int64.Parse(textBox4.Text)+"', '"+Int64.Parse(textBox13.Text)+"')";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
textBox4.Text = "";
textBox5.Text = "";
textBox6.Text = "";
textBox7.Text = "";
textBox8.Text = "";
textBox1.Text = "";
textBox13.Text = "";
}
else
{
MessageBox.Show("El Proveedor Especificado no existe");
}
}
catch
{
MessageBox.Show("Ya existe un articulo con esa ID");
}
}
else
{
if (textBox1.Text != "")
{
MessageBox.Show("No ha desginado un nombre para el articulo");
}
else if (cantidad == false)
{
MessageBox.Show("La cantidad puesta no es valida");
}
else if (compra == false)
{
MessageBox.Show("La cantidad puesta no es valida en el campo de compra");
}
else if (venta == false)
{
MessageBox.Show("La cantidad puesta no es valida en el campo de venta");
}
}
}
int cantidadtotal = 0;
private void textBox12_TextChanged_1(object sender, EventArgs e)
{
///create the connection string
string appPath2 = Path.GetDirectoryName(Application.ExecutablePath);
///create the connection string
string connString = @"Data Source= " + appPath2 + @"\DBpinc.s3db ;Version=3;";
//create the database query
string query = "SELECT * FROM Almacen Where ArticuloID = '" + textBox12.Text + "'";
//create an OleDbDataAdapter to execute the query
System.Data.SQLite.SQLiteDataAdapter dAdapter = new System.Data.SQLite.SQLiteDataAdapter(query, connString);
//create a command builder
System.Data.SQLite.SQLiteCommandBuilder cBuilder = new System.Data.SQLite.SQLiteCommandBuilder(dAdapter);
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
//fill the DataTable
dAdapter.Fill(dTable);
dAdapter.Update(dTable);
label27.Text = "";
textBox10.Text = "";
textBox9.Text = "";
for (int i = 0; i < dTable.Rows.Count; i++)
{
DataRow Row = dTable.Rows[i];
label27.Text = Row["Cantidadexistencia"].ToString();
cantidadtotal = Int32.Parse(Row["Cantidadexistencia"].ToString());
textBox10.Text = Row["Precioventa"].ToString();
textBox9.Text = Row["Preciocompra"].ToString();
}
///create the connection string
appPath2 = Path.GetDirectoryName(Application.ExecutablePath);
///create the connection string
connString = @"Data Source= " + appPath2 + @"\DBstk.s3db ;Version=3;";
//create the database query
query = "SELECT * FROM Existencia Where ArticuloID = '" + textBox12.Text + "'";
//create an OleDbDataAdapter to execute the query
dAdapter = new System.Data.SQLite.SQLiteDataAdapter(query, connString);
//create a command builder
cBuilder = new System.Data.SQLite.SQLiteCommandBuilder(dAdapter);
//create a DataTable to hold the query results
dTable = new DataTable();
//fill the DataTable
dAdapter.Fill(dTable);
dAdapter.Update(dTable);
for (int i = 0; i < dTable.Rows.Count; i++)
{
DataRow Row = dTable.Rows[i];
textBox14.Text = Row["Limite"].ToString();
}
}
private void button4_Click_1(object sender, EventArgs e)
{
int result;
bool accept = Int32.TryParse(textBox11.Text, out result);
if (accept == true && textBox10.Text != "" && textBox9.Text != "" && textBox12.Text != "")
{
cantidadtotal += Int32.Parse(textBox11.Text);
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
System.Data.SQLite.SQLiteConnection sqlConnection1 =
new System.Data.SQLite.SQLiteConnection(@"Data Source=" + appPath + @"\DBPInc.s3db ;Version=3;");
System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand();
cmd.CommandType = System.Data.CommandType.Text;
//comando sql para insercion
cmd.CommandText = "UPDATE Almacen Set Fechaadquisicion = '" + DateTime.Now.ToShortDateString() + "', Cantidadexistencia = '" + cantidadtotal + "', Precioventa = '" + float.Parse(textBox10.Text) + "', Preciocompra = '" + float.Parse(textBox9.Text) + "' Where ArticuloID = '" + Int64.Parse(textBox12.Text) + "'";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
sqlConnection1 = new System.Data.SQLite.SQLiteConnection(@"Data Source=" + appPath + @"\DBstk.s3db ;Version=3;");
cmd = new System.Data.SQLite.SQLiteCommand();
cmd.CommandType = System.Data.CommandType.Text;
//comando sql para insercion
cmd.CommandText = "UPDATE Existencia Set Limite = '" + Int64.Parse(textBox14.Text) + "' WHERE ArticuloID = '"+Int64.Parse(textBox12.Text)+"'";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
textBox12.Text = "";
textBox11.Text = "";
textBox10.Text = "";
textBox9.Text = "";
label27.Text = "0";
textBox14.Text = "";
}
else
{
if (textBox12.Text == "")
{
MessageBox.Show("No ha introducido un articulo para actualizar");
}
else
{
MessageBox.Show("Introduzca una cantidad valida");
}
}
}
private void button7_Click(object sender, EventArgs e)
{
textBox4.Text = "";
textBox5.Text = "";
textBox6.Text = "";
textBox7.Text = "";
textBox8.Text = "";
textBox1.Text = "";
textBox12.Text = "";
textBox11.Text = "";
textBox10.Text = "";
textBox9.Text = "";
label27.Text = "";
}
private void textBox4_TextChanged(object sender, EventArgs e)
{
}
private void tabPage3_Click(object sender, EventArgs e)
{
}
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
if (tabControl1.SelectedIndex == 2)
{
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
//create the connection string
string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + appPath + @"\DBpinc.s3db";
//create the database query
string query = "SELECT * From Almacen";
//create an OleDbDataAdapter to execute the query
System.Data.SQLite.SQLiteDataAdapter dAdapter = new System.Data.SQLite.SQLiteDataAdapter(query, connString);
//create a command builder
System.Data.SQLite.SQLiteCommandBuilder cBuilder = new System.Data.SQLite.SQLiteCommandBuilder(dAdapter);
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
//fill the DataTable
dAdapter.Fill(dTable);
BindingSource bSource = new BindingSource();
bSource.DataSource = dTable;
dataGridView1.DataSource = bSource;
dAdapter.Update(dTable);
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
int i = 0;
foreach (DataGridViewColumn c in dataGridView1.Columns)
{
i += c.Width;
}
dataGridView1.Width = i + dataGridView1.RowHeadersWidth + 2;
}
else if (tabControl1.SelectedIndex == 3)
{
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
//create the connection string
string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + appPath + @"\DBpinc.s3db";
//create the database query
string query = "SELECT ArticuloID, Nombrearticulo From Almacen";
//create an OleDbDataAdapter to execute the query
System.Data.SQLite.SQLiteDataAdapter dAdapter = new System.Data.SQLite.SQLiteDataAdapter(query, connString);
//create a command builder
System.Data.SQLite.SQLiteCommandBuilder cBuilder = new System.Data.SQLite.SQLiteCommandBuilder(dAdapter);
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
//fill the DataTable
dAdapter.Fill(dTable);
BindingSource bSource = new BindingSource();
bSource.DataSource = dTable;
dataGridView2.DataSource = bSource;
dAdapter.Update(dTable);
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
int i = 0;
foreach (DataGridViewColumn c in dataGridView2.Columns)
{
i += c.Width;
}
dataGridView2.Width = i + dataGridView2.RowHeadersWidth + 2;
BarcodeLib.Barcode barcode = new BarcodeLib.Barcode()
{
IncludeLabel = true,
Alignment = AlignmentPositions.CENTER,
Width = 300,
Height = 100,
RotateFlipType = RotateFlipType.RotateNoneFlipNone,
BackColor = Color.White,
ForeColor = Color.Black,
};
try
{
Image img = barcode.Encode(TYPE.CODE128B, dataGridView2.SelectedRows[0].Cells[0].Value.ToString());
pictureBox1.Image = img;
}
catch
{
}
}
}
private void button1_Click(object sender, EventArgs e)
{
if (dataGridView1.Rows.Count != 0)
{
DialogResult resultado = MessageBox.Show("Esta seguro que desea eliminar?", "Seguro?", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
if (resultado == DialogResult.Yes)
{
Int64 articuloID = Int64.Parse(dataGridView1.SelectedRows[0].Cells[0].Value.ToString());
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
System.Data.SQLite.SQLiteConnection sqlConnection1 =
new System.Data.SQLite.SQLiteConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + appPath + @"\DBpinc.s3db");
System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "Delete From Almacen Where [ArticuloID] = " + articuloID+"";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
appPath = Path.GetDirectoryName(Application.ExecutablePath);
sqlConnection1 =
new System.Data.SQLite.SQLiteConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + appPath + @"\DBstk.s3db");
cmd = new System.Data.SQLite.SQLiteCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "Delete From Existencia Where [ArticuloID] = " + articuloID + "";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
appPath = Path.GetDirectoryName(Application.ExecutablePath);
//create the connection string
string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + appPath + @"\DBpinc.s3db";
//create the database query
string query = "Select * From Almacen";
//create an OleDbDataAdapter to execute the query
System.Data.SQLite.SQLiteDataAdapter dAdapter = new System.Data.SQLite.SQLiteDataAdapter(query, connString);
//create a command builder
System.Data.SQLite.SQLiteCommandBuilder cBuilder = new System.Data.SQLite.SQLiteCommandBuilder(dAdapter);
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
//fill the DataTable
dAdapter.Fill(dTable);
BindingSource bSource = new BindingSource();
bSource.DataSource = dTable;
dataGridView1.DataSource = bSource;
dAdapter.Update(dTable);
}
}
else
{
MessageBox.Show("Tiene que elegir un articulo para borrarlo");
}
}
private void Almacen_Load(object sender, EventArgs e)
{
comboBox1.SelectedIndex = 0;
comboBox2.SelectedIndex = 0;
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
//create the connection string
string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + appPath + @"\DBpinc.s3db";
//create the database query
string query = "SELECT * From Almacen Where Nombrearticulo like '%"+textBox2.Text+"%'";
//create an OleDbDataAdapter to execute the query
System.Data.SQLite.SQLiteDataAdapter dAdapter = new System.Data.SQLite.SQLiteDataAdapter(query, connString);
//create a command builder
System.Data.SQLite.SQLiteCommandBuilder cBuilder = new System.Data.SQLite.SQLiteCommandBuilder(dAdapter);
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
//fill the DataTable
dAdapter.Fill(dTable);
BindingSource bSource = new BindingSource();
bSource.DataSource = dTable;
dataGridView1.DataSource = bSource;
dAdapter.Update(dTable);
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void tabPage4_Click(object sender, EventArgs e)
{
}
private void dataGridView2_Click(object sender, EventArgs e)
{
BarcodeLib.Barcode barcode = new BarcodeLib.Barcode()
{
IncludeLabel = true,
Alignment = AlignmentPositions.CENTER,
Width = 300,
Height = 100,
RotateFlipType = RotateFlipType.RotateNoneFlipNone,
BackColor = Color.White,
ForeColor = Color.Black,
};
Image img = barcode.Encode(TYPE.CODE128B, dataGridView2.SelectedRows[0].Cells[0].Value.ToString());
pictureBox1.Image = img;
}
private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
System.Drawing.Printing.PrintDocument doc = new System.Drawing.Printing.PrintDocument();
System.Drawing.Printing.PrintDocument doc2 = new System.Drawing.Printing.PrintDocument();
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
float x = e.MarginBounds.Left;
float y = e.MarginBounds.Top;
Bitmap bmp = new Bitmap(this.pictureBox1.Width, this.pictureBox1.Height);
this.pictureBox1.DrawToBitmap(bmp, new Rectangle(0, 0, this.pictureBox1.Width, this.pictureBox1.Height));
//e.Graphics.DrawImage((Image)bmp, x, y);
for (int i = 0; i <= Int32.Parse(comboBox1.Text) - 1; i++)
{
if (i <= 1)
{
e.Graphics.DrawImage((Image)bmp, x, y);
}
else if (i == 2 || i == 3)
{
e.Graphics.DrawImage((Image)bmp, x, y + 120);
}
else if (i == 4 || i == 5)
{
e.Graphics.DrawImage((Image)bmp, x, y + 240);
}
else if (i == 6 || i == 7)
{
e.Graphics.DrawImage((Image)bmp, x, y + 360);
}
else if (i == 8 || i == 9)
{
e.Graphics.DrawImage((Image)bmp, x, y + 480);
}
else if (i == 10 || i == 11)
{
e.Graphics.DrawImage((Image)bmp, x, y + 600);
}
else if (i == 12 || i == 13)
{
e.Graphics.DrawImage((Image)bmp, x, y + 720);
}
else if (i == 14 || i == 15)
{
e.Graphics.DrawImage((Image)bmp, x, y + 840);
}
if ((i + 1) % 2 != 0)
{
x += 350;
}
else
{
x = e.MarginBounds.Left;
}
}
}
private void button8_Click(object sender, EventArgs e)
{
doc.PrintPage += this.printDocument1_PrintPage;
PrintPreviewDialog ppdlg = new PrintPreviewDialog();
ppdlg.Document = doc;
((Form)ppdlg).WindowState = FormWindowState.Maximized;
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
System.Drawing.Icon ico = new System.Drawing.Icon(appPath + @"\Img\caritasico.ico");
((Form)ppdlg).Icon = ico;
ppdlg.ShowDialog();
}
private void button9_Click(object sender, EventArgs e)
{
doc.PrintPage += this.printDocument1_PrintPage;
PrintDialog dlgSettings = new PrintDialog();
dlgSettings.Document = doc;
if (dlgSettings.ShowDialog() == DialogResult.OK)
{
doc.Print();
}
}
private void button8_MouseHover(object sender, EventArgs e)
{
toolTip1.SetToolTip(button8, "Vista Previa");
}
private void button9_MouseHover(object sender, EventArgs e)
{
toolTip1.SetToolTip(button9, "Ventana de Dialogo de Impresion");
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
//create the connection string
string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + appPath + @"\DBpinc.s3db";
string query = "";
if (textBox3.Text != "")
{
if (comboBox2.SelectedIndex == 0)
{
//create the database query
query = "SELECT ArticuloID, Nombrearticulo From Almacen Where ArticuloID like '%" + textBox3.Text + "%'";
}
else if (comboBox2.SelectedIndex == 1)
{
query = "SELECT ArticuloID, Nombrearticulo From Almacen Where Nombrearticulo like '%" + textBox3.Text + "%'";
}
}
else
{
query = "SELECT ArticuloID, Nombrearticulo From Almacen";
}
//create an OleDbDataAdapter to execute the query
System.Data.SQLite.SQLiteDataAdapter dAdapter = new System.Data.SQLite.SQLiteDataAdapter(query, connString);
//create a command builder
System.Data.SQLite.SQLiteCommandBuilder cBuilder = new System.Data.SQLite.SQLiteCommandBuilder(dAdapter);
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
//fill the DataTable
dAdapter.Fill(dTable);
BindingSource bSource = new BindingSource();
bSource.DataSource = dTable;
dataGridView2.DataSource = bSource;
dAdapter.Update(dTable);
}
string[] codigos = new string[16];
int jcodigo = 0;
private void button5_Click(object sender, EventArgs e)
{
try
{
codigos[jcodigo] = dataGridView2.SelectedRows[0].Cells[0].Value.ToString();
jcodigo++;
doc2.PrintPage += this.printDocument2_PrintPage;
label9.Text = jcodigo.ToString();
}
catch
{
MessageBox.Show("Se ha llegado al limite de codigo de barras para la hoja.");
}
}
int icodigo = 0;
float xe;
float ye;
private void printDocument2_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
if (icodigo < 1)
{
xe = e.MarginBounds.Left;
ye = e.MarginBounds.Top;
}
BarcodeLib.Barcode barcode = new BarcodeLib.Barcode()
{
IncludeLabel = true,
Alignment = AlignmentPositions.CENTER,
Width = 300,
Height = 100,
RotateFlipType = RotateFlipType.RotateNoneFlipNone,
BackColor = Color.White,
ForeColor = Color.Black,
};
Image img = barcode.Encode(TYPE.CODE128B, codigos[icodigo].ToString());
pictureBox1.Image = img;
Bitmap bmp = new Bitmap(this.pictureBox1.Width, this.pictureBox1.Height);
this.pictureBox1.DrawToBitmap(bmp, new Rectangle(0, 0, this.pictureBox1.Width, this.pictureBox1.Height));
//e.Graphics.DrawImage((Image)bmp, x, y);
if (icodigo <= 1)
{
e.Graphics.DrawImage((Image)bmp, xe, ye);
}
else if (icodigo == 2 || icodigo == 3)
{
if (icodigo == 2)
{
ye = ye + 120;
}
e.Graphics.DrawImage((Image)bmp, xe, ye);
}
else if (icodigo == 4 || icodigo == 5)
{
if (icodigo == 4)
{
ye = ye + 120;
}
e.Graphics.DrawImage((Image)bmp, xe, ye);
}
else if (icodigo == 6 || icodigo == 7)
{
if (icodigo == 6)
{
ye = ye + 120;
}
e.Graphics.DrawImage((Image)bmp, xe, ye);
}
else if (icodigo == 8 || icodigo == 9)
{
if (icodigo == 8)
{
ye = ye + 120;
}
e.Graphics.DrawImage((Image)bmp, xe, ye);
}
else if (icodigo == 10 || icodigo == 11)
{
if (icodigo == 10)
{
ye = ye + 120;
}
e.Graphics.DrawImage((Image)bmp, xe, ye);
}
else if (icodigo == 12 || icodigo == 13)
{
if (icodigo == 12)
{
ye = ye + 120;
}
e.Graphics.DrawImage((Image)bmp, xe, ye);
}
else if (icodigo == 14 || icodigo == 15)
{
if (icodigo == 14)
{
ye = ye + 120;
}
e.Graphics.DrawImage((Image)bmp, xe, ye);
}
if ((icodigo + 1) % 2 != 0)
{
xe += 350;
}
else
{
xe = e.MarginBounds.Left;
}
icodigo++;
}
private void button6_Click(object sender, EventArgs e)
{
PrintPreviewDialog ppdlg = new PrintPreviewDialog();
ppdlg.Document = doc2;
((Form)ppdlg).WindowState = FormWindowState.Maximized;
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
System.Drawing.Icon ico = new System.Drawing.Icon(appPath + @"\Img\caritasico.ico");
((Form)ppdlg).Icon = ico;
ppdlg.ShowDialog();
icodigo = 0;
}
private void button10_Click(object sender, EventArgs e)
{
doc2 = new System.Drawing.Printing.PrintDocument();
icodigo = 0;
jcodigo = 0;
label9.Text = "0";
}
}
}
|
36b4fc23ce47e365efcebac518e5de2d1120e974
|
C#
|
fredatgithub/LinqToCsvLibrary
|
/LinqToCsvLibrary/CsvFile.cs
| 2.59375
| 3
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace LinqToCsvLibrary
{
public class CsvFile : IDisposable
{
#region Static Members
public static CsvDefinition DefaultCsvDefinition { get; set; }
public static bool UseLambdas { get; set; }
public static bool UseTasks { get; set; }
public static bool FastIndexOfAny { get; set; }
static CsvFile()
{
// Choosing default Field Separator is a hard decision
// In theory the C of CSV means Comma separated
// In Windows though many people will try to open the csv with Excel which is horrid with real CSV.
// As the target for this library is Windows we go for Semi Colon.
DefaultCsvDefinition = new CsvDefinition
{
EndOfLine = "\r\n",
FieldSeparator = ';',
TextQualifier = '"'
};
UseLambdas = true;
UseTasks = true;
FastIndexOfAny = true;
}
#endregion
internal protected Stream BaseStream;
protected static DateTime DateTimeZero = new DateTime();
public static IEnumerable<T> Read<T>(CsvSource csvSource) where T : new()
{
var csvFileReader = new CsvFileReader<T>(csvSource);
return (IEnumerable<T>)csvFileReader;
}
public char FieldSeparator { get; private set; }
public char TextQualifier { get; private set; }
public IEnumerable<String> Columns { get; private set; }
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
// overriden in derived classes
}
}
public class CsvFile<T> : CsvFile
{
private readonly char fieldSeparator;
private readonly string fieldSeparatorAsString;
private readonly char[] invalidCharsInFields;
private readonly StreamWriter streamWriter;
private readonly char textQualifier;
private readonly String[] columns;
private Func<T, object>[] getters;
readonly bool[] isInvalidCharInFields;
#if !NET_3_5
private int linesToWrite;
private readonly BlockingCollection<string> csvLinesToWrite = new BlockingCollection<string>(5000);
private readonly Thread writeCsvLinesTask;
private Task addAsyncTask;
#endif
public CsvFile(CsvDestination csvDestination)
: this(csvDestination, null)
{
}
public CsvFile()
{
}
public CsvFile(CsvDestination csvDestination, CsvDefinition csvDefinition)
{
if (csvDefinition == null)
{
csvDefinition = DefaultCsvDefinition;
}
columns = (csvDefinition.Columns ?? InferColumns(typeof(T))).ToArray();
fieldSeparator = csvDefinition.FieldSeparator;
fieldSeparatorAsString = fieldSeparator.ToString(CultureInfo.InvariantCulture);
textQualifier = csvDefinition.TextQualifier;
streamWriter = csvDestination.StreamWriter;
invalidCharsInFields = new[] { '\r', '\n', textQualifier, fieldSeparator };
isInvalidCharInFields = new bool[256];
foreach (var c in invalidCharsInFields)
{
isInvalidCharInFields[c] = true;
}
WriteHeader();
CreateGetters();
#if !NET_3_5
if (CsvFile.UseTasks)
{
writeCsvLinesTask = new Thread((o) => WriteCsvLines());
writeCsvLinesTask.Start();
}
addAsyncTask = Task.Factory.StartNew(() => { });
#endif
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
// free managed resources
#if !NET_3_5
addAsyncTask.Wait();
if (csvLinesToWrite != null)
{
csvLinesToWrite.CompleteAdding();
}
if (writeCsvLinesTask != null)
{
writeCsvLinesTask.Join();
}
#endif
streamWriter.Close();
}
}
protected static IEnumerable<string> InferColumns(Type recordType)
{
var columns = recordType
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(pi => pi.GetIndexParameters().Length == 0
&& pi.GetSetMethod() != null
&& !Attribute.IsDefined(pi, typeof(CsvIgnorePropertyAttribute)))
.Select(pi => pi.Name)
.Concat(recordType
.GetFields(BindingFlags.Public | BindingFlags.Instance)
.Where(fi => !Attribute.IsDefined(fi, typeof(CsvIgnorePropertyAttribute)))
.Select(fi => fi.Name))
.ToList();
return columns;
}
#if !NET_3_5
private void WriteCsvLines()
{
int written = 0;
foreach (var csvLine in csvLinesToWrite.GetConsumingEnumerable())
{
streamWriter.WriteLine(csvLine);
written++;
}
Interlocked.Add(ref linesToWrite, -written);
}
#endif
public void Append(T record)
{
if (CsvFile.UseTasks)
{
#if !NET_3_5
var linesWaiting = Interlocked.Increment(ref linesToWrite);
Action<Task> addRecord = (t) =>
{
var csvLine = ToCsv(record);
csvLinesToWrite.Add(csvLine);
};
if (linesWaiting < 10000)
{
addAsyncTask = addAsyncTask.ContinueWith(addRecord);
}
else
{
addRecord(null);
}
#else
throw new NotImplementedException("Tasks");
#endif
}
else
{
var csvLine = ToCsv(record);
streamWriter.WriteLine(csvLine);
}
}
private static Func<T, object> FindGetter(string c, bool staticMember)
{
var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.IgnoreCase | (staticMember ? BindingFlags.Static : BindingFlags.Instance);
Func<T, object> func = null;
PropertyInfo propertyInfo = typeof(T).GetProperty(c, flags);
FieldInfo fi = typeof(T).GetField(c, flags);
if (UseLambdas)
{
Expression expr = null;
ParameterExpression parameter = Expression.Parameter(typeof(T), "r");
Type type = null;
if (propertyInfo != null)
{
type = propertyInfo.PropertyType;
expr = Expression.Property(parameter, propertyInfo.Name);
}
else if (fi != null)
{
type = fi.FieldType;
expr = Expression.Field(parameter, fi.Name);
}
if (expr != null)
{
Expression<Func<T, object>> lambda;
if (type.IsValueType)
{
lambda = Expression.Lambda<Func<T, object>>(Expression.TypeAs(expr, typeof(object)), parameter);
}
else
{
lambda = Expression.Lambda<Func<T, object>>(expr, parameter);
}
func = lambda.Compile();
}
}
else
{
if (propertyInfo != null)
{
func = o => propertyInfo.GetValue(o, null);
}
else if (fi != null)
{
func = o => fi.GetValue(o);
}
}
return func;
}
private void CreateGetters()
{
var list = new List<Func<T, object>>();
foreach (var columnName in columns)
{
Func<T, Object> func = null;
var propertyName = (columnName.IndexOf(' ') < 0 ? columnName : columnName.Replace(" ", ""));
func = FindGetter(columnName, false) ?? FindGetter(columnName, true);
list.Add(func);
}
getters = list.ToArray();
}
public string ToCsv(T record)
{
if (record == null)
{
throw new ArgumentException("Cannot be null", "record");
}
string[] csvStrings = new string[getters.Length];
for (int i = 0; i < getters.Length; i++)
{
var getter = getters[i];
object fieldValue = getter == null ? null : getter(record);
csvStrings[i] = ToCsvString(fieldValue);
}
return string.Join(fieldSeparatorAsString, csvStrings);
}
private string ToCsvString(object oneObject)
{
if (oneObject != null)
{
string valueString = oneObject as string ?? Convert.ToString(oneObject, CultureInfo.CurrentUICulture);
if (RequiresQuotes(valueString))
{
var csvLine = new StringBuilder();
csvLine.Append(textQualifier);
foreach (char c in valueString)
{
if (c == textQualifier)
{
csvLine.Append(c); // double the double quotes
}
csvLine.Append(c);
}
csvLine.Append(textQualifier);
return csvLine.ToString();
}
else
{
return valueString;
}
}
return string.Empty;
}
private bool RequiresQuotes(string valueString)
{
if (CsvFile.FastIndexOfAny)
{
var len = valueString.Length;
for (int i = 0; i < len; i++)
{
char c = valueString[i];
if (c <= 255 && isInvalidCharInFields[c])
{
return true;
}
}
return false;
}
else
{
return valueString.IndexOfAny(invalidCharsInFields) >= 0;
}
}
private void WriteHeader()
{
var csvLine = new StringBuilder();
for (int i = 0; i < columns.Length; i++)
{
if (i > 0)
{
csvLine.Append(fieldSeparator);
}
csvLine.Append(ToCsvString(columns[i]));
}
streamWriter.WriteLine(csvLine.ToString());
}
}
}
|
f51a7393e8aae841c34c482852b6de291e73a74a
|
C#
|
fablecode/ygo-api
|
/src/Application/ygo.application/Commands/AddArchetype/AddArchetypeCommandValidator.cs
| 3.15625
| 3
|
using System;
using FluentValidation;
namespace ygo.application.Commands.AddArchetype
{
public class AddArchetypeCommandValidator : AbstractValidator<AddArchetypeCommand>
{
private const string LinkMustBeUriMessage = "Link '{PropertyValue}' must be a valid URI. eg: http://www.SomeWebSite.com.au";
public AddArchetypeCommandValidator()
{
RuleFor(a => a.ArchetypeNumber)
.GreaterThan(0);
RuleFor(a => a.Name)
.NotNull()
.NotEmpty();
RuleFor(a => a.ProfileUrl)
.NotNull()
.NotEmpty()
.Must(LinkMustBeAUri)
.WithMessage(LinkMustBeUriMessage);
RuleFor(a => a.ImageUrl)
.Must(LinkMustBeAUri)
.WithMessage(LinkMustBeUriMessage)
.When(a => !string.IsNullOrWhiteSpace(a.ImageUrl));
}
private static bool LinkMustBeAUri(string link)
{
if (string.IsNullOrWhiteSpace(link))
{
return false;
}
return Uri.TryCreate(link, UriKind.Absolute, out var outUri)
&& (outUri.Scheme == Uri.UriSchemeHttp || outUri.Scheme == Uri.UriSchemeHttps);
}
}
}
|
647f952b588538e3462bdac682db67c13e2953d3
|
C#
|
itselhosayny/product-management-api
|
/ProductManagement.Domain/Validation/Result.cs
| 2.5625
| 3
|
namespace ProductManagement.Domain.Validation
{
public class Result
{
public Status Status { get; set; }
public string Error { get; set; }
public static Result Success()
{
return new Result { Status = Status.Success };
}
public static Result Failure(string error)
{
return new Result
{
Error = error,
Status = Status.Failure
};
}
}
public enum Status
{
Success,
Failure
}
}
|
65311af4147c9123a621e52ac373b1c9e350a741
|
C#
|
the-Dust/ASPKnowledgeBase
|
/DataAccess/Context/EfDbContext.cs
| 2.65625
| 3
|
using DataAccess.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess.Context
{
public class EfDbContext : DbContext
{
public EfDbContext() : base("EfDbContext")
{
}
public DbSet<Theme> Themes { get; set; }
public DbSet<QuestionLine> Questions { get; set; }
}
public class EfDbInitializer : DropCreateDatabaseAlways<EfDbContext>
{
protected override void Seed(EfDbContext context)
{
context.Themes.AddRange(new List<Theme> {
new Theme { Description = "Спорт" },
new Theme { Description = "Политика" },
new Theme { Description = "Космос" },
});
context.SaveChanges();
context.Questions.AddRange(new List<QuestionLine> {
new QuestionLine { Date = DateTime.Now, IsPublic = true, Author = "Петя",
Email ="petya@mail.ru", ThemeId = 1, Question="Это тестовый вопрос про спорт", Answer = "Это тестовый ответ про спорт"},
new QuestionLine { Date = DateTime.Now, IsPublic = true, Author = "Вася",
Email ="vasya@mail.ru", ThemeId = 2, Question="Это тестовый вопрос про политику", Answer = "Это тестовый ответ про политику"},
new QuestionLine { Date = DateTime.Now, IsPublic = true, Author = "Дима",
Email ="dima@mail.ru", ThemeId = 3, Question="Это тестовый вопрос про космос", Answer = "Это тестовый ответ про космос"}
});
context.SaveChanges();
}
}
}
|
a9d4689fe4e7b0ee76fb909aefef8999e8a075c0
|
C#
|
lbildzinkas/TrainTicketMachine
|
/TrainTicketMachine.Tests/TrieStationRepositoryTests.cs
| 3
| 3
|
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TrainTicketMachine.DataStructures;
using TrainTicketMachine.Repos;
namespace TrainTicketMachine.Tests
{
[TestClass]
public class TrieStationRepositoryTests
{
[TestMethod]
public void GivenTextShouldReturnCorrectStationsAndNextChars()
{
//Given
var stationSource = new List<string>() {"DARTFORD", "DARTMOUTH"};
var charSource = new List<char>() {'F', 'M'};
var trie = new Trie();
trie.InsertRange(new List<string>() { "DARTFORD", "DARTMOUTH", "TOWER HILL", "DERBY" });
var trieStationRepository = new TrieStationRepository(trie);
var text = "DART";
//When
var stations = trieStationRepository.MatchStationNamesStartingWith(text);
var chars = trieStationRepository.GetNextPossibleCharacters(text);
//Then
Assert.IsTrue(stations.ToList().TrueForAll(r => stationSource.Contains(r)));
Assert.IsTrue(chars.ToList().TrueForAll(c => charSource.Contains(c)));
}
[TestMethod]
public void GivenTextShouldReturnCorrectStationsAndNoNextChars()
{
//Given
var stationSource = new List<string>() { "LIVERPOOL", "LIVERPOOL LIME STREET" };
var charSource = new List<char>() { };
var trie = new Trie();
trie.InsertRange(new List<string>() { "LIVERPOOL", "LIVERPOOL LIME STREET", "PADDINGTON" });
var trieStationRepository = new TrieStationRepository(trie);
var text = "LIVERPOOL";
//When
var stations = trieStationRepository.MatchStationNamesStartingWith(text);
var chars = trieStationRepository.GetNextPossibleCharacters(text);
//Then
Assert.IsTrue(stations.ToList().TrueForAll(r => stationSource.Contains(r)));
Assert.IsTrue(chars.ToList().TrueForAll(c => charSource.Contains(c)));
}
[TestMethod]
public void GivenTextShouldNotReturnStationsOrCharacters()
{
//Given
var stationSource = new List<string>() { };
var charSource = new List<char>() {};
var trie = new Trie();
trie.InsertRange(new List<string>() { "EUSTON", "LONDON BRIDGE", "VICTORIA" });
var trieStationRepository = new TrieStationRepository(trie);
var text = "KINGS CROSS";
//When
var stations = trieStationRepository.MatchStationNamesStartingWith(text);
var chars = trieStationRepository.GetNextPossibleCharacters(text);
//Then
Assert.IsTrue(stations.ToList().TrueForAll(r => stationSource.Contains(r)));
Assert.IsTrue(chars.ToList().TrueForAll(c => charSource.Contains(c)));
}
}
}
|
86e480f8c851519c052d5a86896c8bdda28133c2
|
C#
|
SquallB/Check_n_Cook
|
/Check_n_Cook/Model/DishType.cs
| 3.625
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Json;
namespace Check_n_Cook.Model
{
/// <summary>
/// Represents to type of a dish (desert for exemple).
/// </summary>
public class DishType
{
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>
/// The name.
/// </value>
public String Name { get; set; }
/// <summary>
/// The instances. Allows not to have multiple instances of the same type of dish.
/// </summary>
private static Dictionary<String, DishType> instances = new Dictionary<String, DishType>();
/// <summary>
/// Initializes a new instance of the <see cref="DishType"/> class. It is private because "GetInstance" is used to get an instance of the class from the outside.
/// </summary>
/// <param name="name">The name.</param>
private DishType(String name)
{
this.Name = name;
}
/// <summary>
/// Gets an instance of the class, with the given name.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
public static DishType GetInstance(String name)
{
DishType instance;
if (instances.ContainsKey(name))
{
instance = instances[name];
}
else
{
instance = new DishType(name);
instances.Add(name, instance);
}
return instance;
}
/// <summary>
/// Determines whether the specified <see cref="System.Object" />, is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
if (obj is DishType)
{
return this.Name.Equals(((DishType)obj).Name);
}
else
{
return false;
}
}
/// <summary>
/// Checks if an instance with the specified name exists.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>true if the instance exists, false otherwise</returns>
public static bool Exists(String name)
{
return instances.ContainsKey(name);
}
/// <summary>
/// Creates and returns a JSON Object of the instance.
/// </summary>
/// <returns>a JSON object of the instance</returns>
public JsonObject ToJsonObject()
{
JsonObject jsonObject = new JsonObject();
jsonObject.SetNamedValue("Name", JsonValue.CreateStringValue(this.Name));
return jsonObject;
}
/// <summary>
/// Stringifies this instance and returns a JSON string of the insance.
/// </summary>
/// <returns>a JSON string of the instance</returns>
public String Stringify()
{
return this.ToJsonObject().Stringify();
}
}
}
|
4ec7f4dc9b49a12c5903f4ce678434e3324855ae
|
C#
|
shendongnian/download4
|
/latest_version_download2/87456-47166059-160094937-1.cs
| 3.3125
| 3
|
I've added a couple of re-factorings:
1. DBNull is not seen as isnullorempty so added the (value as string)
2. Passing a datatable row[column] that was created dynamically at runtime (like: row["PropertyName"]) will not see this as a string with typeof(T) due to the fact that the column type base is object. So added an extra check for typeof(object) and if not null test that the ToString() is empty value. I haven't tested this fully so may not work for all types of data columns.
public static bool CheckNullOrEmpty<T>(T value)
{
// note: this does not see DBNull as isnullorempty.
if (typeof(T) == typeof(string))
{
if (!string.IsNullOrEmpty(value as string))
{
return string.IsNullOrEmpty(value.ToString().Trim());
}
else
{
return true;
}
}
else if (typeof(T) == typeof(object))
{
// note: datatable columns are always seen as object at runtime with generic T regardless of how they are dynamically typed?
if (value != null) {
return string.IsNullOrEmpty(value.ToString().Trim());
}
}
return value == null || value.Equals(default(T));
}
|
db1dab3f313dc08e16cf6798ad51f0ba61ab6557
|
C#
|
shendongnian/download4
|
/first_version_download2/529107-49292082-168995156-2.cs
| 2.59375
| 3
|
public Task<HttpResponseMessage> UploadAsFormDataContent(string url, byte[] image)
{
MultipartFormDataContent form = new MultipartFormDataContent
{
{ new ByteArrayContent(image, 0, image.Length), "file", "pic.jpeg" }
};
HttpClient client = new HttpClient();
return client.PostAsync(url, form);
}
|
caeb73b97e6e1a0e2f9dfdc66a869f8004ba0858
|
C#
|
KrastevIT/SoftUni
|
/02.Technology Fundamentals with C# - January 2019/Lab and Exercise/Methods - Lab/08 Math Power/Program.cs
| 3.484375
| 3
|
using System;
using System.Numerics;
namespace _08_Math_Power
{
class Program
{
static void Main(string[] args)
{
double number = double.Parse(Console.ReadLine());
int pow = int.Parse(Console.ReadLine());
PrintPowerNumber(number, pow);
}
static void PrintPowerNumber(double number, int powNumber)
{
double rezult =Math.Pow(number, powNumber);
Console.WriteLine((decimal)rezult);
}
}
}
|
92cf31381bf0ed6e4fbd94d63b4f5d13cbdbde65
|
C#
|
tddold/Telerik-Academy
|
/ASP.NET Web Forms/01. Introduction-to-ASP.NET/01. Introduction to ASP.NET/01.Calculator(ASP.NET Web Forms)/Calculator.aspx.cs
| 2.859375
| 3
|
namespace _01.Calculator_ASP.NET_Web_Forms_
{
using System;
using System.Web.UI;
public partial class Calculator : Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.btnSum.Text = "Sum";
}
protected void btnSum_Click(object sender, EventArgs e)
{
double firstNumber;
double.TryParse(this.btnFirstNumber.Text, out firstNumber);
this.btnFirstNumber.Text = firstNumber.ToString();
double secondNumber;
double.TryParse(this.btnSecondNumber.Text, out secondNumber);
this.btnSecondNumber.Text = secondNumber.ToString();
this.btnResult.Text = (firstNumber + secondNumber).ToString();
}
}
}
|
6808d789c8755df6fe4dd52f3fe95465d4dfdf72
|
C#
|
dungnguyentien0409/competitive-programming
|
/C#/1103. Distribute Candies to People.cs
| 3.234375
| 3
|
/*
* Link: https://leetcode.com/problems/distribute-candies-to-people/submissions/
* Author: Dung Nguyen Tien (Chris)
*/
public class Solution {
public int[] DistributeCandies(int candies, int num_people) {
var res = new int[num_people];
int i = 0;
while(candies > 0) {
res[i % num_people] += Math.Min(candies, i + 1);
candies -= (i + 1);
i++;
}
return res;
}
}
|
9c44c5fc6efe849c7ab3f60f9b343a1cc607b434
|
C#
|
Tenebrie/WebServer
|
/RPGEditor/Classes/Data/LocationSelector.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RPGEditor
{
public class LocationSelectorEntry
{
public String Link { get; set; }
public Int32 Chance { get; set; }
public String Condition { get; set; }
public String Action { get; set; }
public LocationSelectorEntry()
{
Chance = 1;
}
public LocationSelectorEntry(LocationSelectorEntry Original)
{
Link = Original.Link;
Chance = Original.Chance;
Condition = Original.Condition;
Action = Original.Action;
}
}
public class LocationSelector : GenericRPGObject
{
public String Guid { get; set; }
public List<LocationSelectorEntry> Options { get; set; }
public LocationSelector()
{
Options = new List<LocationSelectorEntry>();
}
public void CloneFrom(LocationSelector Original)
{
Guid = Original.Guid;
foreach (LocationSelectorEntry D in Original.Options)
Options.Add(new LocationSelectorEntry(D));
}
}
}
|
88cf8fe5fce5784304f593a555cfa906148c326d
|
C#
|
IanAWP/MRRCesiumTiler
|
/DecomposeTile/Generators/AbstractGenerator.cs
| 2.640625
| 3
|
using MapInfo.RasterEngine.IO;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Tiler;
namespace TileGen.Generators
{
public abstract class AbstractGenerator : IGenerator
{
public void GetJobSize(IRasterDataset dataset, int maxDesiredLevel, out int maxActualLevel, out int numTiles)
{
double xMin, yMin, xMax, yMax;
maxActualLevel = 0;
RasterInfo r = dataset.Info;
xMin = r.FieldInfo[0].Envelope.XMin;
xMax = r.FieldInfo[0].Envelope.XMax;
yMin = r.FieldInfo[0].Envelope.YMin;
yMax = r.FieldInfo[0].Envelope.YMax;
var sourceSample = dataset.Info.FieldInfo[0].CellSizeX.Decimal;
int total = 0;
bool atMax = false;
int zoom = 0;
while (!atMax)
{
var southWestTile = PointToTile.LatLonToTile(zoom, yMin, xMin);
var northEastTile = PointToTile.LatLonToTile(zoom, yMax, xMax);
var dx = northEastTile.X - southWestTile.X;
var dy = northEastTile.Y - southWestTile.Y;
//copy paste quick+ dirty code to determine whether we are creating this zoom level
var boundingBox = PointToTile.TileBounds(zoom, northEastTile.X, northEastTile.Y);
var tileSample = (boundingBox.Max.Lon - boundingBox.Min.Lon) / 64;
if (tileSample < (sourceSample / 2.0) || zoom > maxDesiredLevel)
{
atMax = true;
}
else
{
maxActualLevel = zoom;
zoom++;
total += ((dx + 1) * (dy + 1));
}
}
numTiles = total;
}
protected byte GetChildQuads(int zoom, int tX, int tY, Dictionary<string, string> existingTiles)
{
byte childQuadSwitch = 0;
var ct = GetChildTiles(tX, tY, zoom);
if (existingTiles.ContainsKey(ct[0])) childQuadSwitch += 1;
if (existingTiles.ContainsKey(ct[1])) childQuadSwitch += 2;
if (existingTiles.ContainsKey(ct[2])) childQuadSwitch += 4;
if (existingTiles.ContainsKey(ct[3])) childQuadSwitch += 8;
// b = 15;
return childQuadSwitch;
}
protected List<string> GetChildTiles(int tx, int ty, int zoom)
{
var boundingBox = PointToTile.TileBounds(zoom, tx, ty);
var s = new List<string>();
var v = PointToTile.LatLonToTile(zoom + 1, boundingBox.Min.Lat, boundingBox.Min.Lon);
var x = PointToTile.LatLonToTile(zoom + 1, boundingBox.Max.Lat, boundingBox.Max.Lon);
s.Add($"{zoom + 1}/{v.X + 0}/{v.Y + 0}");
s.Add($"{zoom + 1}/{v.X + 1}/{v.Y + 0}");
s.Add($"{zoom + 1}/{v.X + 0}/{v.Y + 1}");
s.Add($"{zoom + 1}/{v.X + 1}/{v.Y + 1}");
return s;
}
/// <summary>
/// Get zoom dependent position of WGS84 coords in grid cell coordinates. May be negative if outside the grid.
/// </summary>
/// <param name="dWorldX"></param>
/// <param name="dWorldY"></param>
/// <param name="dataset"></param>
/// <param name="nX"></param>
/// <param name="nY"></param>
/// <param name="resolution"></param>
/// <returns></returns>
protected bool GetCellPosition(double dWorldX, double dWorldY, IRasterDataset dataset, out int nX, out int nY, int resolution = 0)
{
var fieldInfo = dataset.Info.FieldInfo[0];
ulong nColumns = fieldInfo.Width;
ulong nRows = fieldInfo.Height;
double dCellSizeX = fieldInfo.CellSizeX.Decimal;
double dCellSizeY = fieldInfo.CellSizeY.Decimal;
double dOriginX = fieldInfo.OriginX.Decimal;
double dOriginY = fieldInfo.OriginY.Decimal;
double multiplyer = Math.Pow(2, resolution);
dCellSizeX = dCellSizeX * multiplyer;
dCellSizeY = dCellSizeY * multiplyer;
// if we are outside the grid border then get virtual coordinates anyway
bool bExternal = false;
bExternal |= (dWorldX < dOriginX);
bExternal |= (dWorldY < dOriginY);
bExternal |= (dWorldX >= dOriginX + (double)(nColumns * dCellSizeX));
bExternal |= (dWorldY >= dOriginY + (double)(nRows * dCellSizeY));
nX = (int)Math.Floor((dWorldX - dOriginX) / dCellSizeX);
nY = (int)Math.Floor((dWorldY - dOriginY) / dCellSizeY);
return bExternal;
}
abstract public bool CreateTile(int tx, int ty, int zoom, IRasterDataset dataset, byte[] tile);
public void CreateAllTiles(IRasterDataset dataset, int maxZoom, IOutput output, System.IProgress<int> progress = null)
{
double xMin, yMin, xMax, yMax;
var bytes = 65 * 65 * 2;
byte zero = 0;
int count = 0;
RasterInfo r = dataset.Info;
xMin = r.FieldInfo[0].Envelope.XMin;
xMax = r.FieldInfo[0].Envelope.XMax;
yMin = r.FieldInfo[0].Envelope.YMin;
yMax = r.FieldInfo[0].Envelope.YMax;
Dictionary<string, string> existingTiles = new Dictionary<string, string>();
for (int zoom = maxZoom; zoom >= 0; zoom--)
{
//only generate tiles within the extents of the data
var southWestTile = PointToTile.LatLonToTile(zoom, yMin, xMin);
var northEastTile = PointToTile.LatLonToTile(zoom, yMax, xMax);
var dx = northEastTile.X - southWestTile.X;
var dy = northEastTile.Y - southWestTile.Y;
var boundingBox = PointToTile.TileBounds(zoom, northEastTile.X, northEastTile.Y);
var tileSample = (boundingBox.Max.Lon - boundingBox.Min.Lon) / 64;
var sourceSample = dataset.Info.FieldInfo[0].CellSizeX.Decimal;
ThreadLocal<byte[]> terrainTileLocal = new ThreadLocal<byte[]>(() => new byte[(bytes + 2)]);
Console.WriteLine($"{(dx+1)*dy}");
Parallel.For(0, dx + 1, (easterlyOffset) =>
{
Parallel.For(0, dy+1, (northerlyOffset) =>
{
int tX = southWestTile.X + easterlyOffset;
int tY = southWestTile.Y + northerlyOffset;
var terrainTile = terrainTileLocal.Value;
byte childQuadSwitch = zero;
if (zoom != maxZoom) { childQuadSwitch = GetChildQuads(zoom, tX, tY, existingTiles); }
//always create tiles with child tiles
bool create = childQuadSwitch > 0 || (zoom == maxZoom);
if (create)
{
bool created = false;
created = CreateTile(tX, tY, zoom, dataset, terrainTile);
if (zoom == maxZoom)
{
create = created;
}
}
if (create)
{
terrainTile[bytes] = childQuadSwitch;
terrainTile[bytes + 1] = 0;//We'll say it's all land for now
output.WriteTile(zoom, tX, tY, terrainTile);
existingTiles.Add($"{zoom}/{tX}/{tY}", "");
}
progress?.Report(++count);
});
});
}
}
}
}
|
29ce361d6d0dfb6b4a166a234dc3be3c6faf7315
|
C#
|
quocthang0507/ImageClassificationWebAppWithML.NET
|
/ImageClassification.Predict/Program.cs
| 2.765625
| 3
|
using ImageClassification.DataModels;
using Microsoft.ML;
using Microsoft.ML.Data;
using System;
using System.IO;
using System.Linq;
using System.Text;
namespace ImageClassification.Predict
{
internal class Program
{
private static void Main()
{
Console.OutputEncoding = Encoding.UTF8;
const string assetsRelativePath = @"../../../assets";
string assetsPath = GetAbsolutePath(assetsRelativePath);
// Please copy the ML Model in Train Project to here and change below paths
string imagesFolderPathForPredictions = Path.Combine(assetsPath, "inputs", "predictions");
string imageClassifierModelZipFilePath = Path.Combine(assetsPath, "inputs", "model", "imageClassifier.zip");
try
{
MLContext mlContext = new MLContext(seed: 1);
Console.WriteLine($"Loading model from: {imageClassifierModelZipFilePath}");
// Load the model
ITransformer loadedModel = mlContext.Model.Load(imageClassifierModelZipFilePath, out DataViewSchema modelInputSchema);
// Create prediction engine to try a single prediction (input = ImageData, output = ImagePrediction)
PredictionEngine<InMemoryImageData, ImagePrediction> predictionEngine = mlContext.Model.CreatePredictionEngine<InMemoryImageData, ImagePrediction>(loadedModel);
//Predict the first image in the folder
System.Collections.Generic.IEnumerable<InMemoryImageData> imagesToPredict = FileUtils.LoadInMemoryImagesFromDirectory(imagesFolderPathForPredictions, false);
InMemoryImageData imageToPredict = imagesToPredict.First();
// Measure #1 prediction execution time.
System.Diagnostics.Stopwatch watch = System.Diagnostics.Stopwatch.StartNew();
ImagePrediction prediction = predictionEngine.Predict(imageToPredict);
// Stop measuring time.
watch.Stop();
long elapsedMs = watch.ElapsedMilliseconds;
Console.WriteLine("First Prediction took: " + elapsedMs + "mlSecs");
// Measure #2 prediction execution time.
System.Diagnostics.Stopwatch watch2 = System.Diagnostics.Stopwatch.StartNew();
ImagePrediction prediction2 = predictionEngine.Predict(imageToPredict);
// Stop measuring time.
watch2.Stop();
long elapsedMs2 = watch2.ElapsedMilliseconds;
Console.WriteLine("Second Prediction took: " + elapsedMs2 + "mlSecs");
// Get the highest score and its index
float maxScore = prediction.Score.Max();
////////
// Double-check using the index
int maxIndex = prediction.Score.ToList().IndexOf(maxScore);
VBuffer<ReadOnlyMemory<char>> keys = default;
predictionEngine.OutputSchema[3].GetKeyValues(ref keys);
ReadOnlyMemory<char>[] keysArray = keys.DenseValues().ToArray();
ReadOnlyMemory<char> predictedLabelString = keysArray[maxIndex];
////////
Console.WriteLine($"Image Filename : [{imageToPredict.ImageFileName}], " +
$"Predicted Label : [{prediction.PredictedLabel}], " +
$"Probability : [{maxScore}] "
);
//Predict all images in the folder
//
Console.WriteLine("");
Console.WriteLine("Predicting several images...");
foreach (InMemoryImageData currentImageToPredict in imagesToPredict)
{
ImagePrediction currentPrediction = predictionEngine.Predict(currentImageToPredict);
Console.WriteLine(
$"Image Filename : [{currentImageToPredict.ImageFileName}], " +
$"Predicted Label : [{currentPrediction.PredictedLabel}], " +
$"Probability : [{currentPrediction.Score.Max()}]");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.WriteLine("Press any key to end the app..");
Console.ReadKey();
}
public static string GetAbsolutePath(string relativePath)
=> FileUtils.GetAbsolutePath(typeof(Program).Assembly, relativePath);
}
}
|
1497a5dd0b0ba45d9ecd176d160eefc47058f302
|
C#
|
hallhall/paralell
|
/Assets/Scripts/common/common.cs
| 2.75
| 3
|
using UnityEngine;
using System.Collections;
namespace common {
//共通メソッド
public static class common_method {
//タッチされたオブジェクトが指定の名前通りならtrue
public static bool is_touch(string _obj_name) {
if (Input.GetMouseButtonDown(0)) {
Vector3 _aTapPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 aTapPoint = _aTapPoint;
Collider2D[] aCollider2dAll = Physics2D.OverlapPointAll(aTapPoint);
if (aCollider2dAll.Length > 0) {
foreach (Collider2D aCollider2d in aCollider2dAll) {
if (aCollider2d) {
GameObject obj = aCollider2d.transform.gameObject;
//
//Debug.Log(obj.name);
//
if (obj.name == _obj_name) return true;
}
}
}
}
return false;
}
//タッチ判定(3d)
public static bool is_touch_3d(string _obj_name) {
if (Input.GetMouseButtonDown(0)) {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit = new RaycastHit();
if (Physics.Raycast(ray, out hit)) {
GameObject obj = hit.collider.gameObject;
//
Debug.Log(obj.name);
//
if (_obj_name == obj.name) return true;
}
}
return false;
}
//タッチ判定(複数、返り値は成功すれば文字列。失敗すれば空文字)
public static string is_touch_3d_str(string[] _objs_name) {
if (Input.GetMouseButtonDown(0)) {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit = new RaycastHit();
if (Physics.Raycast(ray, out hit)) {
GameObject obj = hit.collider.gameObject;
//
//Debug.Log(obj.name);
//
foreach (string _obj_name in _objs_name) {
if (_obj_name == obj.name) return _obj_name;
}
}
}
return "";
}
}
}
|
8251cf988b2153917b1cf9ede9a042a894ddbbb7
|
C#
|
sysrpl/Bare.Game.Net
|
/Tests/Test02/Test02Window.cs
| 2.515625
| 3
|
using System;
using System.Runtime.InteropServices;
using Bare;
using Bare.Devices;
using Bare.Geometry;
using Bare.Graphics;
using static System.Console;
using static Bare.Game;
using static Bare.Interop.GLES20;
namespace Tests
{
public class Test02Window : Window
{
public static void Test()
{
WriteLine("Bare Game DataBuffer Tests");
WriteLine("--------------------------");
Run(new Test02Window());
}
[StructLayout(LayoutKind.Sequential)]
public struct VecColor
{
public Vec3 Point;
public Vec3 Color;
public VecColor(float x, float y, float z, float r, float g, float b)
{
Point.v0 = x;
Point.v1 = y;
Point.v2 = z;
Color.v0 = r;
Color.v1 = g;
Color.v2 = b;
}
}
ShaderProgram program;
ShaderSource vertex;
ShaderSource fragment;
DataBuffer<VecColor> verts;
protected override void ContextCreated()
{
verts = new DataBuffer<VecColor>();
verts.Add(new VecColor(0.0f, 0.5f, 0.0f, 1, 0, 0));
verts.Add(new VecColor(-0.5f, -0.5f, 0.0f, 0, 1, 0));
verts.Add(new VecColor(0.5f, -0.5f, 0.0f, 0, 0, 1));
program = new ShaderProgram();
vertex = new VertexShader();
vertex.Compile(
@"#version 100
precision mediump float;
attribute vec3 point;
attribute vec3 color;
varying vec3 c;
void main() {
c = color;
gl_Position = vec4(point, 1);
}");
fragment = new FragmentShader();
fragment.Compile(
@"#version 100
precision mediump float;
varying vec3 c;
void main() {
gl_FragColor = vec4(c, 1);
}");
program.Attach(vertex);
program.Attach(fragment);
program.Link();
WriteLine(program);
}
protected override void ContextDestroyed()
{
vertex.Dispose();
fragment.Dispose();
program.Dispose();
verts.Dispose();
}
protected override void Logic(EventList events, Stopwatch stopwatch)
{
foreach (var e in events)
{
if (e is KeyboardEvent)
{
var k = e as KeyboardEvent;
if (k.Code == KeyCode.Escape)
Quit();
}
}
if (stopwatch.Seconds > 10)
Quit();
}
private static float Flip(float f)
{
f = f - (float)Math.Floor(f);
f = f * 2;
if (f > 1) f = 2 - f;
return f;
}
protected override void Render(Stopwatch stopwatch)
{
glViewport(0, 0, ClientWidth, ClientHeight);
float i = (float)(stopwatch.Time * 60);
float r = Flip(0.5f + i / 400.0f);
float g = Flip(0.3f + i / 680.0f);
float b = Flip(0.8f + i / 840.0f);
glClearColor(r, g, b, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(program.Handle);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, verts.SizeOf, verts.Seek(0));
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, verts.SizeOf, verts.Next());
glDrawArrays(GL_TRIANGLES, 0, 3);
SwapBuffers();
}
}
}
|
3a39ff96f0405aa4542b79eb33510764b9d5ce12
|
C#
|
jia-von/entity-framework-code-first-migration
|
/CodeFirstPractice/Models/Shelves.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace CodeFirstPractice.Models
{
[Table("Shelves")] // A table called “Shelves” with:
public partial class Shelves
{
// An int primary key called ID.
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column("id", TypeName = "int(10)")]
public int ID { get; set; }
[Column("shelf_materials_id", TypeName = "int(10)")]
public int ShelfMaterialID { get; set; }
// A varchar of length 50 called “Name”.
[Column("name", TypeName = "varchar(50)")]
[Required]
public string Name { get; set; }
// A foreign key to ShelfMaterial(ID) called “ShelfMaterialID”.
[ForeignKey(nameof(ShelfMaterialID))]
// The requisite virtual properties and constructors for references.
[InverseProperty(nameof(Models.ShelfMaterials.Shelves))]
public virtual ShelfMaterials ShelfMaterials { get; set; }
}
}
|
bde9c726ec8eedf08959c41f90ec669d9fd03ad4
|
C#
|
edom18/UnityGoalAgentSample
|
/Assets/GoalAgentSample/Scripts/AI/Goals/Brain.cs
| 2.859375
| 3
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace AI
{
/// <summary>
/// ゴールを統括するルートゴール
/// </summary>
public class Brain<T> : CompositeGoal<T> where T : AIBase
{
// プランナー
private IPlanner _planner;
// 現在選択されているプラン
private PlanBase _currentPlan;
// 短期記憶しているオブジェクトを保持
private List<Memory> _shortMemories = new List<Memory>();
// 長期記憶しているオブジェクトを保持
private List<Memory> _longMemories = new List<Memory>();
/// <summary>
/// 記憶しているすべてのオブジェクトを返す
/// </summary>
private List<Memory> AllMemories
{
get
{
List<Memory> allMemories = new List<Memory>();
allMemories.AddRange(_shortMemories);
allMemories.AddRange(_longMemories);
return allMemories;
}
}
#region Constructor
// コンストラクタ
public Brain(T owner) : base(owner)
{
// NOTE:
// 他キャラのAIを作成する場合はBrainの派生クラスを作成し、
// そちらのコンストラクタ内で、生成するプランナーを変更する
_planner = new CharaPlanner(owner);
}
#endregion
#region Public members
/// <summary>
/// プランを記憶に保持
/// </summary>
/// <param name="planObject"></param>
public void Memorize(PlanObject planObject)
{
// 重複しているプランは追加しない
if (HasMemory(planObject))
{
return;
}
_shortMemories.Add(MakeMemory(planObject));
}
/// <summary>
/// メモリコントロール
/// すでに達成したプランなど、記憶から消すべきオブジェクトをリストから削除する
/// </summary>
public void MemoryControl()
{
var targets = from m in _shortMemories
where m.Target != null
select m;
var newList = targets.ToList();
_shortMemories = newList;
}
#endregion
#region Private members
/// <summary>
/// プランリストから最適なプランを評価、取得する
/// </summary>
/// <returns></returns>
PlanBase EvaluatePlans()
{
List<PlanBase> plans = EnumeratePlans();
return _planner.Evaluate(plans);
}
/// <summary>
/// 短期・長期記憶双方に保持しているプランを列挙する
/// </summary>
/// <returns></returns>
List<PlanBase> EnumeratePlans()
{
var plans = new List<PlanBase>();
foreach (var m in AllMemories)
{
plans.Add(m.Plan);
}
return plans;
}
/// <summary>
/// プランに応じてゴールを選択する
/// </summary>
/// <param name="plan"></param>
/// <returns></returns>
IGoal GetGoalByPlan(PlanBase plan)
{
switch (plan.GoalType)
{
// あたりを探し回る
case GoalType.Wander:
{
return new GoalWander<T>(_owner);
}
// エネルギー/パワーを得る
case GoalType.GetEnergy:
case GoalType.GetPower:
{
var memory = FindMemory(plan);
return new GoalGetItem<T>(_owner, memory.Target);
}
// 敵を攻撃
case GoalType.Attack:
{
var memory = FindMemory(plan);
return new GoalAttackTarget<T>(_owner, memory.Target);
}
}
return new Goal<T>(_owner);
}
/// <summary>
/// 選択中のプランからプランを変更する
/// </summary>
/// <param name="newPlan"></param>
void ChangePlan(PlanBase newPlan)
{
Debug.Log("Change plan to " + newPlan);
_currentPlan = newPlan;
RemoveAllSubgoals();
var goal = GetGoalByPlan(newPlan);
AddSubgoal(goal);
}
/// <summary>
/// プランオブジェクトからメモリオブジェクトを生成する
/// </summary>
Memory MakeMemory(PlanObject planObject)
{
var memory = new Memory(planObject);
return memory;
}
/// <summary>
/// 対象プランから記憶オブジェクトを検索
/// </summary>
Memory FindMemory(PlanBase plan)
{
return AllMemories.Find(m => m.Plan == plan);
}
/// <summary>
/// 記憶にあるプランか
/// </summary>
bool HasMemory(PlanObject planObject)
{
var memory = AllMemories.Find(m => m.Plan == planObject.Plan);
return memory != null;
}
/// <summary>
/// 記憶にあるメモリか
/// </summary>
bool HasMemory(Memory memory)
{
var storeMem = AllMemories.Find(m => m == memory);
return storeMem != null;
}
#endregion
#region Override Goal class
public override void Activate()
{
base.Activate();
RemoveAllSubgoals();
// なにもないときにあたりを歩き回るプランを設定しておく
var memory = new Memory();
memory.Plan = new PlanWander();
_longMemories.Add(memory);
}
public override Status Process()
{
ActivateIfInactive();
PlanBase selectedPlan = EvaluatePlans();
bool needsChangePlan = (selectedPlan != null) && (_currentPlan != selectedPlan);
if (needsChangePlan)
{
ChangePlan(selectedPlan);
}
return ProcessSubgoals();
}
public override void Terminate()
{
base.Terminate();
}
#endregion
}
}
|
b136afbc406fcac91a46d352492670f3399f522f
|
C#
|
UnclespaceGroup/ApiCosmetic_ver2
|
/ApiCosmetic_ver2/Controllers/CountryController.cs
| 2.671875
| 3
|
using ApiCosmetic_ver2.Models.Context;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace ApiCosmetic_ver2.Controllers
{
public class CountryController : ApiController
{
Context db = new Context();
public HttpResponseMessage Get()
{
List<Country> a = db.Countries.ToList();
a.Sort();
return Request.CreateResponse(HttpStatusCode.OK, a);
}
public string Get(int id)
{
return "ok";
}
[Authorize]
public void Post([FromBody]Country value)
{
db.Countries.Add(value);
db.SaveChanges();
}
[Authorize]
public void Put(int id, [FromBody]Country value)
{
var country = db.Countries.Find(id);
if (country != null && value != null)
{
if (value.Name != null) country.Name = value.Name;
if (value.Image != null) country.Image = value.Image;
db.SaveChanges();
}
}
[Authorize]
public void Delete(int id)
{
Country country = db.Countries.Find(id);
if (country != null)
{
db.Countries.Remove(country);
db.SaveChanges();
}
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}
|
9a8c8386f1d3ee9d322dba712e60a00a3b6e4e17
|
C#
|
thexa4/projectera
|
/Project ERA/Project ERA/Data/AvatarBody.cs
| 2.84375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ERAUtils;
namespace ProjectERA.Data
{
internal class AvatarBody : IResetable
{
#region Private fields
private Byte _opacity, _graphicHue;
private Byte _skintoneId,
_hairtypeId, _haircolorId,
_eyetypeId, _eyecolorId;
private String _graphicName;
#endregion
#region Properties
/// <summary>
/// Skintone Id
/// </summary>
internal Byte SkintoneId
{
get { return _skintoneId; }
set { _skintoneId = value; }
}
/// <summary>
/// Hair Type Id
/// </summary>
internal Byte HairtypeId
{
get { return _hairtypeId; }
set { _hairtypeId = value; }
}
/// <summary>
/// Hair Color Id
/// </summary>
internal Byte HaircolorId
{
get { return _haircolorId; }
set { _haircolorId = value; }
}
/// <summary>
/// Eye Type id
/// </summary>
internal Byte EyetypeId
{
get { return _eyetypeId; }
set { _eyetypeId = value; }
}
/// <summary>
/// Eye Color id
/// </summary>
internal Byte EyecolorId
{
get { return _eyecolorId; }
set { _eyecolorId = value; }
}
/// <summary>
/// Body Opacity
/// </summary>
internal Byte Opacity
{
get { return _opacity; }
set { _opacity = value; }
}
/// <summary>
/// Graphics Hue
/// </summary>
internal Byte GraphicHue
{
get { return _graphicHue; }
set { _graphicHue = value; }
}
/// <summary>
/// Graphics Assetname
/// </summary>
internal String GraphicName
{
get { return _graphicName; }
set { _graphicName = value; }
}
#endregion
/// <summary>
/// Empty Constructor
/// </summary>
public AvatarBody()
{
}
/// <summary>
/// Constructor with predefined data
/// </summary>
/// <param name="skintoneId">Skin tone ID</param>
/// <param name="hairtypeId">Hair type ID</param>
/// <param name="haircolorId">Hair color ID</param>
/// <param name="eyetypeId">Eye type ID</param>
/// <param name="eyecolorId">Eye color ID</param>
/// <param name="opacity">Opacity</param>
/// <param name="graphicsHue">Graphics Hue</param>
/// <param name="graphicsName">Graphics Name</param>
internal AvatarBody(Byte skintoneId, Byte hairtypeId, Byte haircolorId, Byte eyetypeId, Byte eyecolorId,
Byte opacity, Byte graphicsHue, String graphicsName)
{
this.SkintoneId = skintoneId;
this.HairtypeId = hairtypeId;
this.HaircolorId = haircolorId;
this.EyecolorId = eyecolorId;
this.EyetypeId = eyetypeId;
this.Opacity = opacity;
this.GraphicHue = graphicsHue;
this.GraphicName = graphicsName;
}
/// <summary>
/// Reset Body
/// </summary>
public void Clear()
{
this.SkintoneId = 0;
this.HairtypeId = 0;
this.HaircolorId = 0;
this.EyetypeId = 0;
this.EyecolorId = 0;
this.Opacity = 0;
this.GraphicHue = 0;
this.GraphicName = String.Empty;
}
}
}
|
674d7f5f614725aa0778cbbd3e6862e803161228
|
C#
|
BeastNaylor/Demic
|
/DemicTest/LocationTests.cs
| 2.5625
| 3
|
using Demic.Classes;
using Demic.Enums;
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DemicTest
{
[TestClass]
public class LocationTests
{
[TestMethod]
public void CompareSameLocationWithDifferentDisease()
{
var locOne = new Location("TESTLOCONE", DiseaseColour.Black);
var locTwo = new Location("TESTLOCONE", DiseaseColour.Blue);
Assert.AreEqual<bool>(true, locOne.Equals(locTwo));
}
}
}
|
0d2cc68417d973214c0009f73a24dcde6dc57e98
|
C#
|
formation-csharp/3.Heritage
|
/Heritage/Program.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Heritage
{
class Program
{
static void Main(string[] args)
{
Personne p1 = new Personne("Madani");
Stagiaire s1 = new Stagiaire("Chami");
Formateur f1 = new Formateur("ESSARRAJ");
Console.WriteLine(p1);
Console.WriteLine(s1);
Console.WriteLine(f1);
Console.ReadKey();
}
}
}
|
cf6bc6f65ce67846c280b2ad73c21013931c932c
|
C#
|
Tung-Neo/C--Lap02
|
/Snippet 11.cs
| 2.953125
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Sesson_4
{
class Snippet_11
{
static void code()
{
int num;
Console.WriteLine("Even Numbers");
for(num = 1; num <= 11; num++)
{
if((num % 2) == 0)
{
Console.WriteLine(num);
}
}
}
}
}
|
277892ac947b46a2322b808b2e75fcaa4979c595
|
C#
|
hamadakio/DesignPatterns
|
/Estrutural/Flyweight/Program.cs
| 3.046875
| 3
|
using System;
namespace Flyweight
{
class Program
{
static void Main(string[] args)
{
//Foco em reaproveitamento de objetos sem necessidade de instanciar varias vezes
Console.WriteLine("===# Flyweight #===");
FabricaFlyweight fabrica = new FabricaFlyweight();
string cor = string.Empty;
Tartaruga tartaruga;
while (true)
{
Console.WriteLine("Qual Tartaruga enviar para a tela :");
cor = Console.ReadLine();
Console.WriteLine("");
tartaruga = fabrica.GetTartaruga(cor);
tartaruga.Mostrar(cor);
Console.WriteLine("===============================");
}
}
}
}
|
bd2c6c53417639f71317ff690ba6c610c56d7394
|
C#
|
stepaside/Nemo
|
/src/Nemo/Serialization/ObjectJsonSerializer.cs
| 2.953125
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Nemo.Collections.Extensions;
using Nemo.Utilities;
namespace Nemo.Serialization
{
public static class ObjectJsonSerializer
{
public static string ToJson<T>(this T dataEntity)
where T : class
{
var output = new StringBuilder(1024);
using (var writer = new StringWriter(output))
{
new JsonSerializationWriter().WriteObject(dataEntity, null, writer);
}
return output.ToString();
}
public static void ToJson<T>(this T dataEntity, TextWriter writer)
where T : class
{
new JsonSerializationWriter().WriteObject(dataEntity, null, writer);
}
public static string ToJson<T>(this IEnumerable<T> dataEntitys)
where T : class
{
var output = new StringBuilder(1024);
using (var writer = new StringWriter(output))
{
new JsonSerializationWriter().WriteObject(dataEntitys.ToList(), null, writer);
}
return output.ToString();
}
public static void ToJson<T>(this IEnumerable<T> dataEntitys, TextWriter writer)
where T : class
{
new JsonSerializationWriter().WriteObject(dataEntitys.ToList(), null, writer);
}
public static T FromJson<T>(this string json)
where T : class
{
return (T)json.FromJson(typeof(T));
}
public static object FromJson(this string json, Type objectType)
{
var value = Json.Parse(json);
return JsonSerializationReader.ReadObject(value, objectType);
}
}
}
|
136bb802f91dbcbf2e8fcdcea73f1bad3d6eaa46
|
C#
|
mkbiltek/kids.bmi.ir
|
/Kids.BMI.ir/Kids.Utility/MarkupParser/MarkupTag.cs
| 2.953125
| 3
|
// #define TEST_KNOWN_INLINE_TAGS
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
namespace MarkupParser
{
/// <summary>
/// This class represents an individual tag element from the markup text.
/// </summary>
public class MarkupTag
{
private static readonly string INLINE_ENDSWITH_TEXT = "/>",
COMMENT_BEGINS_WITH_TEXT = "<!--";
private bool inline = false, comment = false;
private int tagIndexBegin, tagLength, tagNameIndexBegin, tagNameLength, nestingLevel;
private string tagCache = null, tagNameCache = null, innerTextCache = null;
private List<MarkupAttribute> attributes = new List<MarkupAttribute>();
private List<MarkupTag> children = new List<MarkupTag>();
private MarkupTag parent = null, closingTag = null;
private MarkupDocument document = null;
private NameValueCollection attributeCache = null;
/// <summary>
/// This is the only constructor for this class.
/// </summary>
/// <param name="document">The owning MarkupDocument object.</param>
/// <param name="tagIndexBegin">The index in the document text at which this tag begins.</param>
/// <param name="tagLength">The text length of this tag.</param>
/// <param name="tagNameIndexBegin">The index in the document text at which the name of this tag begins.</param>
/// <param name="tagNameLength">The text length of the name of this tag.</param>
internal MarkupTag(MarkupDocument document, int tagIndexBegin, int tagLength, int tagNameIndexBegin, int tagNameLength)
{
this.document = document;
this.tagIndexBegin = tagIndexBegin;
this.tagLength = tagLength;
this.tagNameIndexBegin = tagNameIndexBegin;
this.tagNameLength = tagNameLength;
string text = this.Text.Trim();
inline = text.EndsWith(INLINE_ENDSWITH_TEXT) || MarkupDocument.IsKnownInlineTag(Tag, document.StringComparison);
comment = text.StartsWith(COMMENT_BEGINS_WITH_TEXT);
ParseAttributes();
}
/// <summary>
/// Internal function that determines if this tag contains a specific index position in the document text; similar to a hit-test.
/// </summary>
/// <param name="indexPosition">The position to be tested.</param>
/// <returns>True or false to indicate whether the supplied index is within the textual boundaries of this tag.</returns>
internal bool Contains(int indexPosition)
{
return this.tagIndexBegin <= indexPosition && indexPosition <= tagIndexBegin + tagLength;
}
/// <summary>
/// The MarkupDocument object to which this tag belongs.
/// </summary>
public MarkupDocument Document
{
get { return document; }
}
/// <summary>
/// The text string of the tag from the document text.
/// </summary>
public string Text
{
get
{
if (document.UseCaching)
{
if (tagCache == null)
tagCache = document.Text.Substring(tagIndexBegin, tagLength);
return tagCache;
}
else
return document.Text.Substring(tagIndexBegin, tagLength);
}
}
/// <summary>
/// The name of the tag.
/// </summary>
public string Tag
{
get
{
if (document.UseCaching)
{
if (tagNameCache == null)
tagNameCache = document.Text.Substring(tagNameIndexBegin, tagNameLength);
return tagNameCache;
}
else
return document.Text.Substring(tagNameIndexBegin, tagNameLength);
}
}
public override string ToString()
{
return Text;
}
/// <summary>
/// Returns a NameValueCollection of the tag's attributes.
/// </summary>
/// <returns></returns>
public NameValueCollection Attributes
{
get
{
NameValueCollection attributeCacheTemp = null;
if (document.UseCaching)
{
if (attributeCache == null)
{
attributeCache = new NameValueCollection(attributes.Count);
foreach (MarkupAttribute a in attributes)
{
attributeCache.Add(a.Name, a.Value);
}
}
attributeCacheTemp = attributeCache;
}
else
{
attributeCacheTemp = new NameValueCollection(attributes.Count);
foreach (MarkupAttribute a in attributes)
{
attributeCacheTemp.Add(a.Name, a.Value);
}
}
return attributeCacheTemp;
}
}
/// <summary>
/// Whether or not this is considered an inline tag (i.e. a tag that does not have a corresponsing closing tag).
/// </summary>
public bool Inline
{
get { return inline; }
internal set { inline = value; }
}
/// <summary>
/// Whether or not this tag is considered a comment.
/// </summary>
public bool Comment
{
get { return comment; }
}
/// <summary>
/// Whether this tag is considered a closing tag.
/// </summary>
public bool IsClosingTag
{
get { return (Tag.Length > 0 && Tag[0] == '/'); }
}
/// <summary>
/// Internal function that analyzes the tag text and identifies the attributes of the tag.
/// </summary>
private void ParseAttributes()
{
int indexBegin, length, nameIndexBegin, nameLength, valueIndexBegin, valueLength;
indexBegin = length = nameIndexBegin = nameLength = valueIndexBegin = valueLength = 0;
foreach (Match m in MarkupRegexHelper.ParseTagAttributes(Text))
{
if (m.Length > 0 && m.Groups.Count >= 3 && m.Groups[1].Length > 0 && m.Groups[2].Length > 0)
{
indexBegin = m.Index;
length = m.Length;
nameIndexBegin = m.Groups[1].Index;
nameLength = m.Groups[1].Length;
valueIndexBegin = m.Groups[2].Index;
valueLength = m.Groups[2].Length;
indexBegin += tagIndexBegin;
nameIndexBegin += tagIndexBegin;
valueIndexBegin += tagIndexBegin;
attributes.Add(new MarkupAttribute(this, indexBegin, length, nameIndexBegin, nameLength, valueIndexBegin, valueLength));
}
}
}
/// <summary>
/// MarkupTags that are considered children of (contained within) this tag in the document hierarchy. If there are no children it is a leaf tag in the document.
/// </summary>
public List<MarkupTag> Children
{
get { return children; }
}
/// <summary>
/// The MarkupTag that is the parent of this tag (this tag is contained within the parent tag). If there is no parent it is a root tag in the document.
/// </summary>
public MarkupTag Parent
{
get { return parent; }
internal set { parent = value; }
}
/// <summary>
/// String indexer that indexes into the tag's Children collection and returns an array of MarkupTags matching the supplied tag name (case-insensitive).
/// </summary>
/// <param name="tagName">The name of the desired tag.</param>
/// <returns>An array of matching MarkupTags (empty if none were found).</returns>
public MarkupTag[] this[string tagName]
{
get
{
List<MarkupTag> retval = new List<MarkupTag>();
foreach (MarkupTag tag in children)
{
if (tag.Tag.Equals(tagName, document.StringComparison))
retval.Add(tag);
}
return retval.ToArray();
}
}
/// <summary>
/// Integer indexer that indexes into the tag's Children collection.
/// </summary>
/// <param name="index">The index of the desired item.</param>
/// <returns>The MarkupTag at the supplied index.</returns>
public MarkupTag this[int index]
{
get { return children[index]; }
}
/// <summary>
/// A reference to this tag's closing tag. Will be null for items that have no closing tag (inline tags, comments, etc.)
/// </summary>
public MarkupTag ClosingTag
{
get { return closingTag; }
internal set { closingTag = value; }
}
/// <summary>
/// The 0-based level of this tag in the document hierarchy.
/// </summary>
public int NestingLevel
{
get { return nestingLevel; }
internal set { nestingLevel = value; }
}
/// <summary>
/// The text contained within this tag and it's closing tag. This will be an empty string is the tag has no closing tag.
/// </summary>
public string InnerText
{
get
{
string retval = String.Empty;
if (document.UseCaching)
{
if (innerTextCache == null)
{
innerTextCache = String.Empty;
if (closingTag != null) // this should limit it to only normal opening tags
{
int innerTextIndexBegin = (tagIndexBegin + tagLength), innerTextLength = closingTag.tagIndexBegin - innerTextIndexBegin;
if (innerTextLength > 0)
innerTextCache = document.Text.Substring(innerTextIndexBegin, innerTextLength);
}
}
retval = innerTextCache;
}
else
{
if (closingTag != null) // this should limit it to only normal opening tags
{
int innerTextIndexBegin = (tagIndexBegin + tagLength), innerTextLength = closingTag.tagIndexBegin - innerTextIndexBegin;
if (innerTextLength > 0)
retval = document.Text.Substring(innerTextIndexBegin, innerTextLength);
}
}
return retval;
}
}
/// <summary>
/// Returns the MarkupAttribute with the supplied name (case-insensitive), or null if not found.
/// </summary>
/// <param name="attributeName">The name of the desired attribute.</param>
/// <returns>The MarkupAttribute that was found.</returns>
public MarkupAttribute GetAttribute(string attributeName)
{
MarkupAttribute retval = null;
foreach (MarkupAttribute a in attributes)
{
if (a.Name.Equals(attributeName, document.StringComparison))
{
retval = a;
break;
}
}
return retval;
}
/// <summary>
/// Attempts to get the attribute of the supplied name.
/// </summary>
/// <param name="attributeName">The name of the desired attributes.</param>
/// <param name="attribute">The attribute parameter that will be filled by the operation.</param>
/// <returns>True or false to indicate success or failure.</returns>
public bool TryGetAttribute(string attributeName, out MarkupAttribute attribute)
{
attribute = GetAttribute(attributeName);
return attribute != null;
}
/// <summary>
/// Internal function to clear this tag's cache and the cache of all child tags.
/// </summary>
internal void ClearCache()
{
tagCache = tagNameCache = innerTextCache = null;
if (attributeCache != null)
{
attributeCache.Clear();
attributeCache = null;
}
foreach (MarkupTag childTag in children)
{
childTag.ClearCache();
}
}
}
}
|
dcb5f5077160b6ce04d2abed6097eb32880c4107
|
C#
|
ShunsukeH/AtCoder_Practice
|
/AGC032/AGC032A/Program.cs
| 3.453125
| 3
|
using System;
using System.Linq;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
int[] b = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
int[] res = new int[n];
for (int i = 0; i < n; i++)
{
for (int j = b.Length - 1; j >= 0; j--)
{
if (b[j] == j + 1)
{
res[i] = b[j];
b = b.Where((e, k) => k != j).ToArray();
break;
}
}
}
if (b.Length != 0)
{
Console.WriteLine(-1);
}
else
{
foreach (var item in res.Reverse())
{
Console.WriteLine(item);
}
}
}
}
}
|
fff8d86e5a4e459deac9812edb9ac2a84d834422
|
C#
|
vector-man/VisualRomSuite
|
/VRS.UI/Controls/WOutlookBar/Items.cs
| 2.5625
| 3
|
using System;
using System.Collections;
namespace VRS.UI.Controls.WOutlookBar
{
/// <summary>
/// Summary description for Item.
/// </summary>
public class Items : ArrayList
{
private Bar m_pBar = null;
public Items(Bar ownerBar) : base()
{
m_pBar = ownerBar;
}
#region function Add
public Item Add(string caption,int imageIndex)
{
Item item = new Item(this);
item.Caption = caption;
item.ImageIndex = imageIndex;
base.Add(item);
this.Bar.Bars.WOutlookBar.UpdateAll();
return item;
}
#endregion
public new Item this[int nIndex]
{
get{ return (Item)base[nIndex]; }
}
#region Properties Implementation
#region Internal Properties
internal Bar Bar
{
get{ return m_pBar; }
}
#endregion
#endregion
}
}
|
48f5eef65652e645eca2c2f6e3646c7a8e91c172
|
C#
|
ksarioglu/Client
|
/Program.cs
| 3.40625
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
/* Client Code to consume web service to encrypt and has message content. Client decrypts encrypted massage in the code.
* Written by Kübra SARIOĞLU-YBU CENG 1105012001*/
namespace ClientToDecrypt
{
class Program
{
static void Main(string[] args)
{
ServiceReference1.Service1Client Client = new ServiceReference1.Service1Client();
Console.WriteLine("Type message");
string content= Console.ReadLine();
String hashOfTheMessage= Client.HashMessage(content);
using (RijndaelManaged myRijndael = new RijndaelManaged())
{
byte[] encrypted = Client.EncryptStringToBytes(content, myRijndael.Key, myRijndael.IV);
string roundtrip = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.IV);
//Display the original data and the decrypted data.
Console.WriteLine("Original Content: {0}", content);
Console.WriteLine("Hash of the message: {0}",hashOfTheMessage); //decrypt
Console.WriteLine("Decrypted message: {0}", roundtrip); //decrypt
Console.Read();
}
}
/*Client's decrypt methpd*/
static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
}
}
|
8127ea86000bde3c3dda89bcbb54dbda23962cb0
|
C#
|
aloneguid/parquet-dotnet
|
/src/Parquet/Encodings/ParquetDictionaryEncoder.cs
| 2.9375
| 3
|
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Linq;
namespace Parquet.Encodings {
static class ParquetDictionaryEncoder {
public static bool TryExtractDictionary(Type elementType,
Array data, int offset, int count,
out Array? dictionaryArray,
out int[]? rentedIndexes,
double threshold = 0.8) {
dictionaryArray = null;
rentedIndexes = null;
if(elementType != typeof(string) || count == 0)
return false;
string[] src = (string[])data;
HashSet<string> distinctSet = Distinct(src, offset, count);
double factor = distinctSet.Count / (double)count;
if(factor > threshold)
return false;
// extract indexes
string[] dictionary = distinctSet.ToArray();
dictionaryArray = dictionary;
var valueToIndex = new Dictionary<string, int>(StringComparer.Ordinal);
for(int i = 0; i < dictionary.Length; i++)
valueToIndex[dictionary[i]] = i;
rentedIndexes = ArrayPool<int>.Shared.Rent(count);
for(int isrc = offset, itgt = 0; isrc < offset + count; isrc++, itgt++)
rentedIndexes[itgt] = valueToIndex[src[isrc]];
return true;
}
private static HashSet<string> Distinct(string[] strings, int offset, int count) {
/*
* Use "Ordinal" comparison as it's the fastest (13 times faster than invariant).
* .NET standard 2.0 does not have pre-allocated hash version which give a tiny performance boost.
* Interestingly, hashcode based hash for strings is slower.
*/
#if NETSTANDARD2_0
var hs = new HashSet<string>(StringComparer.Ordinal);
#else
// pre-allocation is a tiny performance boost
var hs = new HashSet<string>(strings.Length, StringComparer.Ordinal);
#endif
for(int i = offset; i < offset + count; i++)
hs.Add(strings[i]);
return hs;
}
}
}
|
5134cec2be3b7ff31fdf4a85b1e7abf17d113990
|
C#
|
compjradm/Treinamvc
|
/JRCOM_TreinaDados/Model/ConBanco.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Windows.Forms;
namespace JRCOM_TreinaDados.Model
{
class ConBanco
{
private string servidor;
private string bancoDados;
private string usuario;
private string senha;
private MySqlConnection conexao;
public ConBanco(string bd, string usr, string pss, string svr = "localhost"){
PreparaConexao(bd, usr, pss, svr);
servidor = svr;
bancoDados = bd;
usuario = usr;
senha = pss;
}
private void PreparaConexao(string bd, string usr, string pss, string svr = "localhost") {
string connectionString = "SERVER=" + svr + ";" + "DATABASE=" + bd + ";" + "UID=" + usr + ";" + "PASSWORD=" + pss + ";";
conexao = new MySqlConnection(connectionString);
}
private bool AbreConexao(){
try{
conexao.Open();
return true;
}
catch (MySqlException ex){
{
switch (ex.ErrorCode)
{
case 0:
MessageBox.Show("Falha ao conectar no servidor de dados.");
break;
case 1045:
MessageBox.Show("A combinacao de usuario e senha nao existe. Tente novamente.");
break;
}
}
return false;
}
}
private bool FechaConexao(){
try{
conexao.Close();
return true;
}
catch (MySqlException ex){
MessageBox.Show(ex.Message);
return false;
}
}
public void InsereLinha(string tabela, List<string> campos, List<string> valores) {
string query = "INSERT INTO " + tabela + " (";
foreach (string item in campos)
{
query += item;
query += ", ";
}
query = query.Remove(query.Length - 2);
query += ") VALUES(";
foreach (string item in valores)
{
query += item;
query += ", ";
}
query = query.Remove(query.Length - 2);
query += ")";
if (this.AbreConexao() == true){
MySqlCommand cmd = new MySqlCommand(query, conexao);
cmd.ExecuteNonQuery();
this.FechaConexao();
}
}
public void UpdateLine(string tabela, List<string> campos, List<string> valores, string filtro = ""){
string query = "UPDATE " + tabela + " SET ";
string temp1, temp2;
while (campos.Count > 0)
{
temp1 = campos.First();
temp2 = valores.First();
query += temp1 + "=" + "'" + temp2 + "'";
campos.RemoveAt(0);
valores.RemoveAt(0);
if (campos.Count > 0)
query += ", ";
}
if (filtro != "")
query += "WHERE " + filtro;
if (this.AbreConexao() == true){
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = query;
cmd.Connection = conexao;
cmd.ExecuteNonQuery();
this.FechaConexao();
}
}
public void ApagaLinha(string tabela, string filtro){
string query = "DELETE FROM " + tabela + " WHERE " + filtro;
if (this.AbreConexao() == true){
MySqlCommand cmd = new MySqlCommand(query, conexao);
cmd.ExecuteNonQuery();
this.FechaConexao();
}
}
public List< string >[] Select(string tabela, List<string> campos, string filtro = "", string outrosParam = ""){
string query = "SELECT * FROM " + tabela;
int qtReg = campos.Count;
if (filtro != "")
query += " WHERE " + filtro;
if (outrosParam != "")
query += " " + outrosParam;
List<string>[] list = new List<string>[qtReg];
for (int i = 0; i < qtReg; i++)
{
list[i] = new List<string>();
}
if (this.AbreConexao() == true){
MySqlCommand cmd = new MySqlCommand(query, conexao);
MySqlDataReader dataReader = cmd.ExecuteReader();
switch (tabela)
{
case "city":
while (dataReader.Read())
{
list[0].Add(dataReader["city_id"] + "");
list[1].Add(dataReader["city"] + "");
list[2].Add(dataReader["country_id"] + "");
list[3].Add(dataReader["last_update"] + "");
}
break;
}
dataReader.Close();
this.FechaConexao();
return list;
}else{
return list;
}
}
}
}
|
149c234229515e7cde33a5d7a594c7695fde29a9
|
C#
|
carloscastro313/Programacion-2
|
/GuiaDeEjerciciones_01/Ejercicio_16/Program.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ejercicio_16Entidades;
namespace Ejercicio_16
{
class Program
{
static void Main(string[] args)
{
byte nota1;
byte nota2;
Alumno alumno1= new Alumno();
alumno1.apellido = "Castro";
alumno1.nombre = "lucia";
alumno1.legajo = 203421;
Console.WriteLine("Ingresar Nota: ");
nota1 = byte.Parse(Console.ReadLine());
Console.WriteLine("Ingresar Nota: ");
nota2 = byte.Parse(Console.ReadLine());
alumno1.Estudiar(nota1, nota2);
alumno1.CalcularFinal();
Console.WriteLine(alumno1.mostrar());
Alumno alumno2 = new Alumno();
alumno1.apellido = "Castro";
alumno1.nombre = "Marcos";
alumno1.legajo = 255341;
Console.WriteLine("Ingresar Nota: ");
nota1 = byte.Parse(Console.ReadLine());
Console.WriteLine("Ingresar Nota: ");
nota2 = byte.Parse(Console.ReadLine());
alumno1.Estudiar(nota1, nota2);
alumno1.CalcularFinal();
Console.WriteLine(alumno1.mostrar());
}
}
}
|
cdaf245f00d3b430db00e12a945274f8d6e7173c
|
C#
|
YuukiTsuchida/UniUtils
|
/Assets/Scripts/IO/Writer.cs
| 3.25
| 3
|
using System.IO;
namespace UniUtil
{
namespace IO
{
/**
* <summary>
* 書き込み用FileStreamラッパークラス.
* </summary>
*/
public static class Writer
{
/// <summary>
/// ファイルストリームを作成する.
/// </summary>
/// <param name="filePath"> フルパス.</param>
/// <param name="mode"> 書き込みのタイプ.</param>
/// <returns> ファイルストリーム </returns>
private static FileStream CreateStream( string filePath, FileMode mode )
{
FileInfo fileInfo = new FileInfo( filePath );
return fileInfo.Open( mode, FileAccess.Write );
}
/// <summary>
/// データを書き込む.
/// </summary>
/// <param name="filePath"> フルパス.</param>
/// <param name="writeData"> 書き込みデータ.</param>
/// <param name="mode"> 書き込みのタイプ.</param>
/// <returns>書き込み可否</returns>
public static bool Write( string filePath, byte[] writeData, FileMode mode )
{
// ディレクトリ存在チェック
string directoryPath = Path.GetDirectoryName( filePath );
if( !System.IO.File.Exists( directoryPath ) )
{
Directory.CreateDirectory( directoryPath );
}
FileStream fileStream = null;
bool result = true;
try
{
fileStream = CreateStream( filePath, mode ) ;
using( BinaryWriter binaryWriter = new BinaryWriter( fileStream ) )
{
// BinaryStraam側でFileStreamのdisposeを呼ぶのでnullに
fileStream = null;
binaryWriter.Write( writeData );
}
}
catch( IOException exception )
{
Debug.LogError( exception.GetType() + "\n" + exception.Message );
result = false;
}
finally
{
if( fileStream != null )
{
fileStream.Dispose();
}
}
return result;
}
/// <summary>
/// ファイルを作成してデータを書き込む(既に存在する場合は上書き).
/// </summary>
/// <param name="filePath"> フルパス.</param>
/// <param name="writeData"> 書き込みデータ.</param>
/// <returns>書き込み可否</returns>
public static bool Create( string filePath, byte[] writeData )
{
return Write( filePath, writeData, FileMode.Create );
}
/// <summary>
/// ファイルを作成してデータを書き込む(既に存在する場合は上書き).
/// </summary>
/// <param name="filePath"> フルパス.</param>
/// <param name="writeData"> 書き込みデータ.</param>
/// <returns>書き込み可否</returns>
public static bool Create( string filePath, string writeData )
{
byte[] bytesWriteData = System.Text.Encoding.UTF8.GetBytes( writeData );
return Create( filePath, bytesWriteData );
}
/// <summary>
/// ファイルに追記を行う(存在しない場合新規に作成する).
/// </summary>
/// <param name="filePath"> フルパス.</param>
/// <param name="writeData"> 書き込みデータ.</param>
/// <returns>書き込み可否</returns>
public static bool Append( string filePath, byte[] writeData )
{
return Write( filePath, writeData, FileMode.Append );
}
/// <summary>
/// ファイルに追記を行う(存在しない場合新規に作成する).
/// </summary>
/// <param name="filePath"> フルパス.</param>
/// <param name="writeData"> 書き込みデータ.</param>
/// <returns>書き込み可否</returns>
public static bool Append( string filePath, string writeData )
{
byte[] bytesWriteData = System.Text.Encoding.UTF8.GetBytes( writeData );
return Append( filePath, bytesWriteData );
}
}
}
}
|
133e1c86ec9158217950cebd486bf9de54620c5b
|
C#
|
mrkcass/SuffixTreeExplorer
|
/SuffixTree/csharsuffixtree/suffixtree/Node.cs
| 3.125
| 3
|
/* Node.cs
* To Do: add comments
*
*
* This is a suffix tree algorithm for .NET written in C#. Feel free to use it as you please!
* This code was derived from Mark Nelson's article located here: http://marknelson.us/1996/08/01/suffix-trees/
* Have Fun
*
* Zikomo A. Fields 2008
*
*/
using System.Collections.Generic;
namespace ThirdParty_SuffixTree
{
public class Node
{
public int suffixNode;
public int edgeIn;
public Node()
{
suffixNode = -1;
edgeIn = -1;
}
public Node(int idx)
{
suffixNode = idx;
edgeIn = -1;
}
public Node(int idx, int inputEdge)
{
suffixNode = idx;
edgeIn = inputEdge;
}
public void addChild(Node child)
{
if (!children.ContainsKey(child.suffixNode))
children.Add(child.suffixNode, child);
}
public Dictionary<int,Node>.Enumerator childIterator()
{
return children.GetEnumerator();
}
public int childCount()
{
return children.Count;
}
Dictionary<int, Node> children = new Dictionary<int, Node>();
public static int Count = 1;
}
}
|
fc0b0368e331738df8037802f733ef80e39df891
|
C#
|
KirillPlotnikov/WpfApp
|
/Semestralka/MeetingCentre.cs
| 3.15625
| 3
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace Semestralka
{
public class MeetingCentre : INotifyPropertyChanged
{
private string name;
private string code;
private string description;
public ObservableCollection<MeetingRoom> meetingRooms;
public event PropertyChangedEventHandler PropertyChanged;
public string Name {
get { return name; }
set
{
if(value.Length >= 2 && value.Length <= 100)
{
name = value;
OnPropertyChanged("Name");
}
}
}
public string Code
{
get { return code; }
set
{
if (ValidateCode(value))
{
code = value;
OnPropertyChanged("Code");
}
}
}
public string Description
{
get { return description; }
set
{
if(value.Length >= 10 && value.Length <= 300)
{
description = value;
OnPropertyChanged("Description");
}
}
}
public string Error => throw new NotImplementedException();
public bool ValidateCode(string value)
{
string validChars = "qwertyuiopasdfghjklzxcvbnm0123456789.-:_";
if(value.Length >= 5 && value.Length <= 50)
{
bool valid = value.ToLower().All(c => validChars.Contains(c));
return valid;
}
else
{
throw new Exception("Message");
}
}
public MeetingCentre(string name, string code, string description)
{
this.Name = name;
this.Code = code;
this.Description = description;
meetingRooms = new ObservableCollection<MeetingRoom>();
}
public void AddMeetingRoom(MeetingRoom m) => meetingRooms.Add(m);
public void OnPropertyChanged([CallerMemberName]string prop = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
public override string ToString()
{
return $"Name: {this.Name} Code: {this.Code}";
}
}
}
|
c6dc547475d549e5efbbbbbdcfa4f4ceaca361fe
|
C#
|
nguyenngocduybao/QLTVVer2
|
/FirstVer29062018/QLTV/Data/DAO/TheDocGiaDAO.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Data.Dtos;
using Data.Model;
using Data.DTO;
namespace Data.DAO
{
public class TheDocGiaDAO
{
#region Instance
private static TheDocGiaDAO instance;
public static TheDocGiaDAO Instance
{
get
{
if (instance == null) instance = new TheDocGiaDAO(); return DAO.TheDocGiaDAO.instance;
}
private set
{
DAO.TheDocGiaDAO.instance = value;
}
}
#endregion
#region Count
// Count ID
public int IDPlus()
{
using (var db = new QuanLyThuVienEntities())
{
var query = ((from b in db.THEDOCGIAs select b.IDDocGia).Max()).ToString();
int ID = Int32.Parse(query);
int idplus = ++ID;
return idplus;
}
}
// Count NgayHetHan "TheDocGia"
public DateTime countHanThe(DateTime NgayLap)
{
DateTime HanThe;
HanThe = NgayLap.AddMonths(6);
return HanThe;
}
#endregion
#region getlist"TheDocGiaDTO" All"DocGia"and User
public List<TheDocGiaDTO> getAllDocGiaAndUser()
{
using (var db = new QuanLyThuVienEntities())
{
var resultQuery = (from a in db.THEDOCGIAs
join b in db.USERS on a.IDDocGia equals b.IDDocGia
select new TheDocGiaDTO()
{
IDDocGia = a.IDDocGia,
HoTenDG = a.HoTenDG,
DiaChiDG = a.DiaChiDG,
EmailDG = a.EmailDG,
NgaySinhDG = a.NgaySinhDG,
NgayLapThe = a.NgayLapThe,
NgayHetHan = a.NgayHetHan,
Password = b.Pwd,
IDLoaiDocGia = a.IDLoaiDG,
UserName = b.UserName,
TongNo = a.TongNo,
}).ToList<TheDocGiaDTO>();
var result = (from a in resultQuery
select new TheDocGiaDTO()
{
IDDocGia = a.IDDocGia,
HoTenDG = a.HoTenDG,
DiaChiDG = a.DiaChiDG,
EmailDG = a.EmailDG,
NgaySinhDG = a.NgaySinhDG,
NgayLapThe = a.NgayLapThe,
NgayHetHan = a.NgayHetHan,
Password = a.Password,
TenLoaiDocGia = HelperDAO.Instance.checkLoaiDocGiaFromID(a.IDLoaiDocGia),
UserName = a.UserName,
TongNo = a.TongNo,
}).ToList<TheDocGiaDTO>();
if (result.Count > 0)
return result;
return new List<TheDocGiaDTO>();
}
}
#endregion
#region getListData TheDocGiaDtos
//getListData IDDocGia From"THeDocGia"
public List<TheDocGiaDtos> GetFormTheDocGia(int ID)
{
using (var db = new QuanLyThuVienEntities())
{
var Result = (from m in db.THEDOCGIAs
where m.IDDocGia.Equals(ID)
select new TheDocGiaDtos()
{
IDDocGia = m.IDDocGia,
HoTenDG = m.HoTenDG,
DiaChiDG = m.DiaChiDG,
EmailDG = m.EmailDG,
NgayLapThe=m.NgayLapThe,
NgaySinhDG=m.NgaySinhDG,
IDLoaiDocGia=m.IDLoaiDG,
}).ToList<TheDocGiaDtos>();
return Result;
}
}
// getListData HoTenDG From"TheDocGia"
public List<TheDocGiaDtos> getFormTheDocGiaToHoTenDG(string HoTenDG)
{
using (var db = new QuanLyThuVienEntities())
{
var result = (from m in db.THEDOCGIAs
where m.HoTenDG.ToUpper().Contains(HoTenDG.ToUpper())
select new TheDocGiaDtos()
{
IDDocGia = m.IDDocGia,
DiaChiDG = m.DiaChiDG,
EmailDG = m.EmailDG,
NgayLapThe = m.NgayLapThe,
NgaySinhDG = m.NgaySinhDG,
HoTenDG = m.HoTenDG,
IDLoaiDocGia = m.IDLoaiDG,
HetHan = m.NgayHetHan,
TongNo=m.TongNo,
}).ToList<TheDocGiaDtos>();
return result;
}
}
#endregion
#region getListSearch TheDocGiaDTO
//getListSearch HoTenDG From "THEDOCGIA"
public List<TheDocGiaDTO> getFromTheDocGiaSearchHoTenDG(string TenDG)
{
using (var db = new QuanLyThuVienEntities())
{
var Result = (from a in db.THEDOCGIAs
where a.HoTenDG.ToUpper().Contains(TenDG.ToUpper())
select new TheDocGiaDtos()
{
IDDocGia=a.IDDocGia,
HoTenDG = a.HoTenDG,
EmailDG = a.EmailDG,
NgaySinhDG = a.NgaySinhDG,
NgayLapThe = a.NgayLapThe,
HetHan = a.NgayHetHan,
IDLoaiDocGia = a.IDLoaiDG,
DiaChiDG = a.DiaChiDG,
TongNo = a.TongNo,
}).ToList<TheDocGiaDtos>();
var Resultkq = (from b in Result
join c in db.USERS on b.IDDocGia equals c.IDDocGia
select new TheDocGiaDTO()
{
IDDocGia=b.IDDocGia,
HoTenDG = b.HoTenDG,
EmailDG = b.EmailDG,
NgaySinhDG = b.NgaySinhDG,
NgayLapThe = b.NgayLapThe,
NgayHetHan = b.HetHan,
IDLoaiDocGia=b.IDLoaiDocGia,
DiaChiDG = b.DiaChiDG,
TongNo = b.TongNo,
Password=c.Pwd,
UserName=c.UserName,
}).ToList<TheDocGiaDTO>();
var ListSearchTenDG = (from a in Resultkq
select new TheDocGiaDTO()
{
IDDocGia = a.IDDocGia,
HoTenDG = a.HoTenDG,
EmailDG = a.EmailDG,
NgaySinhDG = a.NgaySinhDG,
DiaChiDG = a.DiaChiDG,
NgayLapThe = a.NgayLapThe,
NgayHetHan = a.NgayHetHan,
TenLoaiDocGia = HelperDAO.Instance.checkLoaiDocGiaFromID(a.IDLoaiDocGia),
Password = a.Password,
IDLoaiDocGia = a.IDLoaiDocGia,
UserName = a.UserName,
TongNo = a.TongNo,
}).ToList<TheDocGiaDTO>();
if (ListSearchTenDG.Count > 0)
return ListSearchTenDG;
return new List<TheDocGiaDTO>();
}
}
//getListSearch EmailDG from "THEDOCGIA"
public List<TheDocGiaDTO> getFormTheDocGiaSearchEmailDG(string EmailDG)
{
using (var db = new QuanLyThuVienEntities())
{
var result = (from a in db.THEDOCGIAs
where a.EmailDG.ToUpper().Contains(EmailDG.ToUpper())
select new TheDocGiaDtos()
{
IDDocGia=a.IDDocGia,
HoTenDG = a.HoTenDG,
DiaChiDG = a.DiaChiDG,
NgayLapThe = a.NgayLapThe,
HetHan = a.NgayHetHan,
TongNo = a.TongNo,
NgaySinhDG = a.NgaySinhDG,
IDLoaiDocGia=a.IDLoaiDG,
EmailDG = a.EmailDG,
}).ToList<TheDocGiaDtos>();
var Resultkq=(from b in result
join c in db.USERS on b.IDDocGia equals c.IDDocGia
select new TheDocGiaDTO()
{
IDDocGia=b.IDDocGia,
HoTenDG=b.HoTenDG,
EmailDG = b.EmailDG,
NgaySinhDG = b.NgaySinhDG,
NgayLapThe = b.NgayLapThe,
NgayHetHan = b.HetHan,
IDLoaiDocGia=b.IDLoaiDocGia,
DiaChiDG = b.DiaChiDG,
TongNo = b.TongNo,
Password=c.Pwd,
UserName=c.UserName,
}).ToList<TheDocGiaDTO>();
var listSearchEmail = (from a in Resultkq
select new TheDocGiaDTO()
{
IDDocGia = a.IDDocGia,
HoTenDG = a.HoTenDG,
EmailDG = a.EmailDG,
NgaySinhDG = a.NgaySinhDG,
DiaChiDG = a.DiaChiDG,
NgayLapThe = a.NgayLapThe,
NgayHetHan = a.NgayHetHan,
TenLoaiDocGia = HelperDAO.Instance.checkLoaiDocGiaFromID(a.IDLoaiDocGia),
Password = a.Password,
IDLoaiDocGia = a.IDLoaiDocGia,
UserName = a.UserName,
TongNo = a.TongNo,
}).ToList<TheDocGiaDTO>();
if (listSearchEmail.Count > 0)
return listSearchEmail;
return new List<TheDocGiaDTO>();
}
}
//getListSearch DiaChiDG from "THEDOCGIA"
public List<TheDocGiaDTO> getFormTheDocGiaSearchDiaChiDG(string DiaChiDG)
{
using (var db = new QuanLyThuVienEntities())
{
var Result = (from a in db.THEDOCGIAs
where a.DiaChiDG.ToUpper().Contains(DiaChiDG.ToUpper())
select new TheDocGiaDtos()
{
IDDocGia = a.IDDocGia,
HoTenDG = a.HoTenDG,
EmailDG = a.EmailDG,
DiaChiDG = a.DiaChiDG,
HetHan = a.NgayHetHan,
NgayLapThe = a.NgayLapThe,
NgaySinhDG = a.NgaySinhDG,
IDLoaiDocGia=a.IDLoaiDG,
TongNo = a.TongNo,
}).ToList<TheDocGiaDtos>();
var Resultkq = (from b in Result
join c in db.USERS on b.IDDocGia equals c.IDDocGia
select new TheDocGiaDTO()
{
IDDocGia=b.IDDocGia,
HoTenDG = b.HoTenDG,
EmailDG = b.EmailDG,
NgaySinhDG = b.NgaySinhDG,
NgayLapThe = b.NgayLapThe,
NgayHetHan = b.HetHan,
IDLoaiDocGia=b.IDLoaiDocGia,
DiaChiDG = b.DiaChiDG,
TongNo = b.TongNo,
Password=c.Pwd,
UserName=c.UserName,
}).ToList<TheDocGiaDTO>();
var listSearchDiaChi = (from a in Resultkq
select new TheDocGiaDTO()
{
IDDocGia = a.IDDocGia,
HoTenDG = a.HoTenDG,
EmailDG = a.EmailDG,
NgaySinhDG = a.NgaySinhDG,
DiaChiDG = a.DiaChiDG,
NgayLapThe = a.NgayLapThe,
NgayHetHan = a.NgayHetHan,
TenLoaiDocGia = HelperDAO.Instance.checkLoaiDocGiaFromID(a.IDLoaiDocGia),
Password = a.Password,
IDLoaiDocGia = a.IDLoaiDocGia,
UserName = a.UserName,
TongNo = a.TongNo,
}).ToList<TheDocGiaDTO>();
if (listSearchDiaChi.Count > 0)
return listSearchDiaChi;
return new List<TheDocGiaDTO>();
}
}
////getListSearch NgayLapThe from "THEDOCGIA"
public List<TheDocGiaDTO> getFormTheDocGiaSearchNgayLapThe(DateTime Ngaylap)
{
using (var db = new QuanLyThuVienEntities())
{
var Result = (from a in db.THEDOCGIAs
where a.NgayLapThe.Equals(Ngaylap)
select new TheDocGiaDtos()
{
IDDocGia = a.IDDocGia,
HoTenDG = a.HoTenDG,
EmailDG = a.EmailDG,
DiaChiDG = a.DiaChiDG,
HetHan = a.NgayHetHan,
NgayLapThe = Ngaylap,
IDLoaiDocGia=a.IDLoaiDG,
NgaySinhDG = a.NgaySinhDG,
TongNo = a.TongNo,
}).ToList<TheDocGiaDtos>();
var Resultkq = (from b in Result
join c in db.USERS on b.IDDocGia equals c.IDDocGia
select new TheDocGiaDTO()
{
IDDocGia=b.IDDocGia,
HoTenDG = b.HoTenDG,
EmailDG = b.EmailDG,
NgaySinhDG = b.NgaySinhDG,
NgayLapThe = b.NgayLapThe,
NgayHetHan = b.HetHan,
IDLoaiDocGia=b.IDLoaiDocGia,
DiaChiDG = b.DiaChiDG,
TongNo = b.TongNo,
Password=c.Pwd,
UserName=c.UserName,
}).ToList<TheDocGiaDTO>();
var listSearchNgayLap = (from a in Resultkq
select new TheDocGiaDTO()
{
IDDocGia = a.IDDocGia,
HoTenDG = a.HoTenDG,
EmailDG = a.EmailDG,
NgaySinhDG = a.NgaySinhDG,
DiaChiDG = a.DiaChiDG,
NgayLapThe = a.NgayLapThe,
NgayHetHan = a.NgayHetHan,
TenLoaiDocGia = HelperDAO.Instance.checkLoaiDocGiaFromID(a.IDLoaiDocGia),
Password = a.Password,
IDLoaiDocGia = a.IDLoaiDocGia,
UserName = a.UserName,
TongNo = a.TongNo,
}
).ToList<TheDocGiaDTO>();
if (listSearchNgayLap.Count > 0)
return listSearchNgayLap;
return new List<TheDocGiaDTO>();
}
}
//getListSearch NgaySinhDG from "TheDocGia"
public List<TheDocGiaDTO> getFormTheDocGiaSearchNgaySinhDG(DateTime NgaySinh)
{
using (var db = new QuanLyThuVienEntities())
{
var Result = (from a in db.THEDOCGIAs
where a.NgayLapThe.Equals(NgaySinh)
select new TheDocGiaDtos()
{
IDDocGia = a.IDDocGia,
HoTenDG = a.HoTenDG,
EmailDG = a.EmailDG,
DiaChiDG = a.DiaChiDG,
HetHan = a.NgayHetHan,
NgayLapThe = a.NgayLapThe,
IDLoaiDocGia = a.IDLoaiDG,
NgaySinhDG = NgaySinh,
TongNo = a.TongNo,
}).ToList<TheDocGiaDtos>();
var Resultkq = (from b in Result
join c in db.USERS on b.IDDocGia equals c.IDDocGia
select new TheDocGiaDTO()
{
IDDocGia=b.IDDocGia,
HoTenDG = b.HoTenDG,
EmailDG = b.EmailDG,
NgaySinhDG = b.NgaySinhDG,
NgayLapThe = b.NgayLapThe,
NgayHetHan = b.HetHan,
IDLoaiDocGia=b.IDLoaiDocGia,
DiaChiDG = b.DiaChiDG,
TongNo = b.TongNo,
Password=c.Pwd,
UserName=c.UserName,
}).ToList<TheDocGiaDTO>();
var listSearchNgaySinh = (from a in Resultkq
select new TheDocGiaDTO()
{
IDDocGia = a.IDDocGia,
HoTenDG = a.HoTenDG,
EmailDG = a.EmailDG,
NgaySinhDG = a.NgaySinhDG,
DiaChiDG = a.DiaChiDG,
NgayLapThe = a.NgayLapThe,
NgayHetHan = a.NgayHetHan,
TenLoaiDocGia = HelperDAO.Instance.checkLoaiDocGiaFromID(a.IDLoaiDocGia),
Password = a.Password,
IDLoaiDocGia = a.IDLoaiDocGia,
UserName = a.UserName,
TongNo = a.TongNo,
}
).ToList<TheDocGiaDTO>();
if (listSearchNgaySinh.Count > 0)
return listSearchNgaySinh;
return new List<TheDocGiaDTO>();
}
}
//get list Search UserName
public List<TheDocGiaDTO> getFormTheDocGiaSearchUserName(string Username)
{
using (var db = new QuanLyThuVienEntities())
{
var Result = (from a in db.THEDOCGIAs
join b in db.USERS on a.IDDocGia equals b.IDDocGia
where b.UserName.ToUpper().Contains(Username.ToUpper())
select new TheDocGiaDTO()
{
IDDocGia = a.IDDocGia,
HoTenDG = a.HoTenDG,
EmailDG = a.EmailDG,
DiaChiDG = a.DiaChiDG,
NgayHetHan = a.NgayHetHan,
NgayLapThe = a.NgayLapThe,
IDLoaiDocGia = a.IDLoaiDG,
NgaySinhDG = a.NgaySinhDG,
TongNo = a.TongNo,
Password = b.Pwd,
UserName = b.UserName,
}).ToList<TheDocGiaDTO>();
var Resultkq = (from b in Result
join c in db.USERS on b.IDDocGia equals c.IDDocGia
select new TheDocGiaDTO()
{
IDDocGia = b.IDDocGia,
HoTenDG = b.HoTenDG,
EmailDG = b.EmailDG,
NgaySinhDG = b.NgaySinhDG,
NgayLapThe = b.NgayLapThe,
NgayHetHan = b.NgayHetHan,
IDLoaiDocGia = b.IDLoaiDocGia,
DiaChiDG = b.DiaChiDG,
TongNo = b.TongNo,
Password = c.Pwd,
UserName = c.UserName,
}).ToList<TheDocGiaDTO>();
var listSearchUserName = (from a in Resultkq
select new TheDocGiaDTO()
{
IDDocGia = a.IDDocGia,
HoTenDG = a.HoTenDG,
EmailDG = a.EmailDG,
NgaySinhDG = a.NgaySinhDG,
DiaChiDG = a.DiaChiDG,
NgayLapThe = a.NgayLapThe,
NgayHetHan = a.NgayHetHan,
TenLoaiDocGia = HelperDAO.Instance.checkLoaiDocGiaFromID(a.IDLoaiDocGia),
Password = a.Password,
IDLoaiDocGia = a.IDLoaiDocGia,
UserName = a.UserName,
TongNo = a.TongNo,
}
).ToList<TheDocGiaDTO>();
if (listSearchUserName.Count > 0)
return listSearchUserName;
return new List<TheDocGiaDTO>();
}
}
#endregion
}
}
|
ff313e9a9003eec79c07012f870b305f4821ef39
|
C#
|
Gnico10/is-LaSandwicheria
|
/La Sandwicheria/La Sandwicheria.Capa Transversal/Sesion.cs
| 2.546875
| 3
|
using La_Sandwicheria.Modelo.Dominio;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace La_Sandwicheria.Capa_Transversal
{
public class Sesion
{
public string Usuario { get; set; }
public string Contraseña { get; set; }
public Cajero Cajero { get; set; }
public Sesion(string usuario, string contraseña, Cajero cajero)
{
Usuario = usuario;
Contraseña = contraseña;
Cajero = cajero;
}
public Cajero ObtenerCajero(string usuario, string contraseña)
{
if (usuario == Usuario && contraseña == Contraseña)
{
return Cajero;
}
return null;
}
}
}
|
bc6dd79da4eb45cb47978862ecd679d8ce2179c6
|
C#
|
YorkCodeDojo/MarsLander-July2019
|
/David_Gareth_cSharp/MarsLander/Rover.cs
| 3.328125
| 3
|
using System;
namespace MarsLander
{
public class Rover
{
public Coordinate Location { get; private set; }
public Direction Direction { get; private set; }
public Rover(Direction startDirection = default)
{
Direction = startDirection;
}
public void TurnLeft()
{
switch (Direction)
{
case Direction.North:
Direction = Direction.West;
break;
case Direction.West:
Direction = Direction.South;
break;
case Direction.South:
Direction = Direction.East;
break;
case Direction.East:
Direction = Direction.North;
break;
default:
break;
}
}
public void TurnRight()
{
TurnLeft();
TurnLeft();
TurnLeft();
}
public bool TryMove(Func<Coordinate, bool> CanEnter)
{
var newLocation = Location;
switch (Direction)
{
case Direction.North:
newLocation = Location.WithY(Location.Y + 1);
break;
case Direction.West:
newLocation = Location.WithX(Location.X - 1);
break;
case Direction.South:
newLocation = Location.WithY(Location.Y - 1);
break;
case Direction.East:
newLocation = Location.WithX(Location.X + 1);
break;
default:
break;
}
if (CanEnter(newLocation))
{
Location = newLocation;
return true;
}
return false;
}
}
public enum Direction
{
North,
West,
South,
East
}
}
|
ccceba66bc8ecf87052814f36d98dda0b9c7423a
|
C#
|
KeithVanderzanden/GuitarArranger
|
/GuitarArranger/GuitarArranger/Models/Note.cs
| 3.125
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Web;
namespace GuitarArranger.Models
{
public class Note
{
public List<Tone> Tones{ get; set; }
public List<TabTone> TabTones { get; set; }
public string Beat { get; set; }
public Note()
{
Tones = new List<Tone>();
TabTones = new List<TabTone>();
Beat = "";
}
public Note(List<Tone> tones, List<TabTone> tabTones, string beat)
{
Tones = tones;
TabTones = tabTones;
Beat = beat;
}
public string getNoteContent()
{
StringBuilder sb = new StringBuilder();
sb.Append(Beat + "-");
foreach (var tone in Tones)
{
sb.Append(tone.ToString());
}
return sb.ToString();
}
public string getNoteTabContent()
{
StringBuilder sb = new StringBuilder();
sb.Append(Beat + "-");
foreach (var tone in TabTones)
{
sb.Append(tone.ToString());
}
return sb.ToString();
}
public void setContent(string content)
{
Tones.Clear();
string[] tones = content.Split('-');
tones = tones.Take(tones.Count() - 1).ToArray();
if (tones.Count() > 0)
{
Beat = tones[0];
for (int i = 1; i <= tones.Count() - 2; i += 2)
{
Tone t = new Tone(tones[i], tones[i + 1]);
Tones.Add(t);
}
}
}
public void setTabContent(string tabContent)
{
TabTones.Clear();
string[] tones = tabContent.Split('-');
tones = tones.Take(tones.Count() - 1).ToArray();
if (tones.Count() > 3)
{
for (int i = 1; i < tones.Count() - 2; i += 3)
{
TabTone t = new TabTone(tones[i], tones[i + 1], tones[i + 2]);
TabTones.Add(t);
}
}
}
}
}
|
4aca69ab4ad0d371cde206a8e31a18f83dbdb958
|
C#
|
GuillaumeCreusot/SaleVeau
|
/Fichier.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace SaleVeau
{
public static class Fichier
{
/// <summary>
/// Obtenir le chemain d'accés du directory Save
/// </summary>
/// <returns></returns>
public static string ObtenirPathSave()
{
//emplacement de l'exe
string path = Environment.CurrentDirectory;
//retour en arrière
path = Path.GetDirectoryName(path);
path = Path.GetDirectoryName(path);
//emplacement fichier sauvegarde
path += "\\Save";
return path;
}
/// <summary>
/// Chargement des données relatives à la partie
/// </summary>
/// <param name="path"></param>
/// <param name="grilles"></param>
/// <param name="tabsInt"></param>
/// <param name="coords"></param>
/// <param name="goodDir"></param>
/// <param name="diff"></param>
/// <param name="tour"></param>
public static void LireSavePartie(string path, int[][,] grilles, int[][] tabsInt
, int[][] coords, bool[] goodDir, ref int diff, ref int tour)
{
//ouverture du StreamReader
StreamReader sr = new StreamReader(path);
string line;
int c = 0;
//grilles
do
{
line = sr.ReadLine();
for (int i = 0; i < grilles[c].GetLength(0); i++)
{
for (int j = 0; j < grilles[c].GetLength(1); j++)
{
grilles[c][i, j] = Convert.ToInt32(line[i * 10 + j]) - 48;
}
}
c++;
} while (c < grilles.GetLength(0));
//tableaux int
int i2 = 0;
c = 0;
do
{
line = sr.ReadLine();
i2 = 0;
for (int i = 0; i < tabsInt[c].GetLength(0); i++)
{
if(line[i2] == '-')
{
tabsInt[c][i] = Convert.ToInt32(line[i2]+line[i2+1]-95);
i2++;
}
else
{
tabsInt[c][i] = Convert.ToInt32(line[i]) - 48;
}
i2++;
}
c++;
} while (c < tabsInt.Length);
//coords
i2 = 0;
line = sr.ReadLine();
for(int i=0; i < coords.GetLength(0); i++)
{
coords[i][0] = line[i2]-48;
coords[i][1] = line[i2 + 1]-48;
i2 += 2;
}
//bool[]
line = sr.ReadLine();
for(int i =0; i<goodDir.Length; i++)
{
if(line[4*i] == 'F')
{
goodDir[i] = false;
}
else
{
goodDir[i] = true;
}
}
//paramètres
diff = Convert.ToInt32(sr.ReadLine());
tour = Convert.ToInt32(sr.ReadLine());
//fermeture
sr.Close();
}
/// <summary>
/// Sauvegarde des données relatives à la partie
/// </summary>
/// <param name="path"></param>
/// <param name="grilles"></param>
/// <param name="tabsInt"></param>
/// <param name="coords"></param>
/// <param name="goodDir"></param>
/// <param name="diff"></param>
/// <param name="tour"></param>
public static void EcrireSavePartie(string path, int[][,] grilles, int[][] tabsInt, int[][] coords, bool[] goodDir
, int diff, int tour)
{
//ouverture du StreamWriter
StreamWriter sw = new StreamWriter(path);
int c = 0;
string line;
//grilles
do
{
line = "";
for (int i = 0; i < grilles[c].GetLength(0); i++)
{
for (int j = 0; j < grilles[c].GetLength(1); j++)
{
line += grilles[c][i, j];
}
}
sw.WriteLine(line);
c++;
} while (c < grilles.GetLength(0));
c = 0;
//tableaux
do
{
line = "";
for (int i = 0; i < tabsInt[c].GetLength(0); i++)
{
line += tabsInt[c][i];
}
sw.WriteLine(line);
c++;
} while (c < tabsInt.Length);
//coords
line = "";
for(int i = 0; i<coords.GetLength(0); i++)
{
line += "" + coords[i][0] + coords[i][1];
}
sw.WriteLine(line);
//bool[]
line = "";
for(int i = 0; i<goodDir.Length; i++)
{
line += goodDir[i];
}
sw.WriteLine(line);
//paramètre
sw.WriteLine(diff);
sw.WriteLine(tour);
sw.Close();
}
/// <summary>
/// Sauvegarde des paramètres
/// </summary>
/// <param name="path"></param>
/// <param name="saveEachTurn"></param>
public static void EcrireSaveParametre(string path, bool saveEachTurn)
{
//ouverture StreamWriter
StreamWriter sw = new StreamWriter(path);
//saveEachTurn
sw.WriteLine(saveEachTurn);
sw.Close();
}
/// <summary>
/// chargement des paramètres
/// </summary>
/// <param name="path"></param>
/// <param name="saveEachTurn"></param>
public static void LireSaveParametre(string path, ref bool saveEachTurn)
{
//ouverture StreamReader
StreamReader sr = new StreamReader(path);
//saveEachTurn
saveEachTurn = Convert.ToBoolean(sr.ReadLine());
sr.Close();
}
/// <summary>
/// Obtenir les noms des fichiers dans le directory situé à <paramref name="pathSave"/>
/// </summary>
/// <param name="pathSave"></param>
/// <returns></returns>
public static string[] ObtenirNomFichierdansSaveDirectory(string pathSave)
{
FileInfo[] files = ObtenirFichierDansSaveDirectory(pathSave);
string[] result = new string[files.Length];
for (int i = 0; i < files.Length; i++)
{
result[i] = files[i].Name;
}
return result;
}
/// <summary>
/// Obtenir le chemin d'accés à partir du nom du fichier <paramref name="name"/> et du chemin d'accés du dossier <paramref name="pathSave"/>
/// </summary>
/// <param name="pathSave"></param>
/// <param name="name"></param>
/// <returns></returns>
public static string ObtenirPathAvecNom(string pathSave, string name)
{
return pathSave + "\\" + name;
}
public static FileInfo[] ObtenirFichierDansSaveDirectory(string pathSave)
{
DirectoryInfo dir = new DirectoryInfo(pathSave);
FileInfo[] files = dir.GetFiles();
return files;
}
/// <summary>
/// Vérifie si le dossier est vide
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static bool EtreDirectoryVide(string path)
{
return (Fichier.ObtenirFichierDansSaveDirectory(path).Length == 0);
}
/// <summary>
/// Création d'un nouveau fichier
/// s'il existe déjà un fichier portant le nom <paramref name="name"/> ajout d'un "-" à la fin du nom
/// </summary>
/// <param name="name"></param>
/// <param name="pathSave"></param>
/// <returns></returns>
public static string CreerNouveauFichier(string name, string pathSave)
{
string[] nameFiles = Fichier.ObtenirNomFichierdansSaveDirectory(pathSave);
while (nameFiles.Contains(name + ".txt"))
{
name += "-";
}
name += ".txt";
Console.WriteLine(name);
FileStream f = File.Create(pathSave + "\\" + name);
f.Close();
return name;
}
}
}
/*
77777..77777..7...........................7..7777777777...77777....777777777777777...77777 7777777
77777..777777..7..77..777..77777...77777777..77777777777..777....777777777777777...7777777 7777777
77777..777777......7...777..77777..77777777..777777777777......7777777777777777...77777777 7777777
77777..7777777....777...77...7777..77777777..777777777......7777777.77777.777...7777777777 7777777
77777..777777777.........77..7777...7777777..77.........77777777.77777..777....77777777777 7777777
*/
|
2b2003d3b7e46fe78bce858e6a4ea52333a50abb
|
C#
|
TheTeamTeam/CourseProject
|
/CourseProject/CourseProject.Data/UnitsOfWork/UnitOfWork.cs
| 2.8125
| 3
|
using System;
namespace CourseProject.Data.UnitsOfWork
{
public class UnitOfWork : IUnitOfWork
{
private readonly IAdsHubDbContext dbContext;
public UnitOfWork(IAdsHubDbContext dbContext)
{
if (dbContext == null)
{
throw new ArgumentNullException("DbContext cannot be null.");
}
this.dbContext = dbContext;
}
public void Commit()
{
this.dbContext.SaveChanges();
}
// TODO: Deicde whether to leave the empty method
public void Dispose()
{
}
}
}
|
1778576e03eb4974c0f0639bb15860550b8b3f72
|
C#
|
ondfisk/C5.Concurrent
|
/C5.Concurrent/C5.Concurrent/IShared.cs
| 3.140625
| 3
|
using System;
namespace C5.Concurrent
{
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IShared<T>
{
/// <summary>
/// Atomically set this reduction variable to the given updated value if the current value equals the expected value.
/// </summary>
/// <param name="expect"></param>
/// <param name="update"></param>
/// <returns></returns>
bool CompareAndSet(T expect, T update);
/// <summary>
/// Set this reduction variable to the given value and return the previous value.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
T GetAndSet(T value);
/// <summary>
/// Combine this reduction variable with the given value using the given operation.
/// </summary>
/// <param name="value"></param>
/// <param name="action"></param>
/// <returns></returns>
T Reduce(T value, Action<T> action);
/// <summary>
/// Gets or sets the value.
/// </summary>
/// <value>
/// The value.
/// </value>
T Value { get; set; }
/// <summary>
/// Returns a string version of this reduction variable.
/// </summary>
/// <returns></returns>
string ToString();
/// <summary>
/// Atomically set this reduction variable to the given updated value if the current value equals the expected value.
/// </summary>
/// <param name="expect"></param>
/// <param name="update"></param>
/// <returns></returns>
bool WeakCompareAndSet(T expect, T update);
}
}
|
5e981563279ef7f05cc734352508f2cf87257e15
|
C#
|
PedroDircksen/Triangulos
|
/Triangulos/ControladorTriangulo.cs
| 3.078125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Triangulos
{
public class ControladorTriangulo
{
public bool Validar(Triangulo triangulo)
{
bool trianguloValido = true;
if(triangulo.lado1 > triangulo.lado2 + triangulo.lado3 || triangulo.lado2 > triangulo.lado1 + triangulo.lado3 || triangulo.lado3 > triangulo.lado2 + triangulo.lado1)
{
trianguloValido = false;
}
return trianguloValido;
}
public string Nomear(Triangulo triangulo)
{
string tipoTriangulo;
if(triangulo.lado1 == triangulo.lado2 && triangulo.lado2 == triangulo.lado3)
{
tipoTriangulo = "Equilátero";
}
else if(triangulo.lado1 != triangulo.lado2 && triangulo.lado1 != triangulo.lado3 && triangulo.lado2 != triangulo.lado3)
{
tipoTriangulo = "Escaleno";
}
else
{
tipoTriangulo = "Isósceles";
}
return tipoTriangulo;
}
public void Registrar(double lado1, double lado2, double lado3, Triangulo triangulo)
{
triangulo.lado1 = lado1;
triangulo.lado2 = lado2;
triangulo.lado3 = lado3;
}
}
}
|
4cdb18068da43e4f4d6ba9ff2b3394c2582c9577
|
C#
|
alexanderstrib/OperationalTransformation
|
/OperationalTransformation/Operations.cs
| 3.25
| 3
|
using System;
using System.Collections.Generic;
using OperationalTransformation.Builders;
namespace OperationalTransformation
{
public class Operations
{
private readonly OperationsTableBuilder _operationsTableBuilder;
public Operations()
{
_operationsTableBuilder = new OperationsTableBuilder();
}
public List<string> GetOperations(string original, string changes)
{
var originalLength = original.Length;
var changesLength = changes.Length;
var editsTable = _operationsTableBuilder.Build(original, changes);
var operations = new List<string>();
var operationsString = editsTable[changesLength][originalLength].ToString();
if (string.IsNullOrEmpty(operationsString)) return operations;
for (var i = operationsString.Length - 1; i >= 0; i -= 2)
{
operations.Add(string.Format("{0}{1}", operationsString[i - 1], operationsString[i]));
}
return operations;
}
public static OperationType Type(string operation)
{
switch (operation[0])
{
case 'r':
return OperationType.Retain;
case 'd':
return OperationType.Delete;
case 'i':
return OperationType.Insert;
default:
throw new Exception(string.Format("Invalid edit type {0}", operation));
}
}
public static string Insert(char val)
{
return string.Format("i{0}", val);
}
public static string Delete(char val)
{
return string.Format("d{0}", val);
}
public static string Retain(int n)
{
return string.Format("r{0}", + n);
}
}
}
|
1e4334e76dd7f284b447817ad45f8a2b74b5997c
|
C#
|
amris2000/MasterThesis
|
/MasterThesis/Models/NonLinearRate.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MasterThesis
{
/* --- General information
* The contents of this file is not used within
* the masters thesis.
*/
public interface INonLinearRateModel
{
void IncrementByTimeStep();
void ImpliedVolatility();
void SimulatePath();
void IncrementUnderlying();
void ValueEuropeanPayoff();
}
public class BlackScholes : INonLinearRateModel
{
public double vol;
public double rate;
public double t;
public double mat;
public double spot;
public void IncrementByTimeStep() { }
public void ImpliedVolatility() { }
public void SimulatePath() { }
public void ValueEuropeanPayoff() { }
public void IncrementUnderlying() { }
}
public class Heston
{
public double Spot;
public double Strike;
public double Mat;
public double Lambda;
public double Eps;
public double MeanRv;
public double Rho;
public Heston(double spot, double mat, double lambda, double eps, double meanRv, double rho)
{
this.Spot = spot;
this.Mat = mat;
this.Lambda = lambda;
this.Eps = eps;
this.MeanRv = meanRv;
this.Rho = rho;
}
private double CondM(double vt, double k, double dt)
{
return (vt - 1) * Math.Exp(-k * dt) + 1;
}
private double CondV(double vt, double k, double dt)
{
return vt*Eps*Eps / k * (Math.Exp(-k*dt) - Math.Exp(-2.0*k*dt)) + Eps * Eps / (2.0 * k) * (1 - Math.Exp(-k * dt)) * (1 - Math.Exp(-k * dt));
}
private double LocalLnY(double vt, double k, double dt)
{
return Math.Sqrt(Math.Log(CondV(vt, k, dt) / (Math.Pow(CondM(vt, k, dt), 2.0)) + 1));
}
}
public static class ClosedForm
{
public static double BsCallPrice(double spot, double vol, double mat, double strike, double rate)
{
double std = Math.Sqrt(mat) * vol;
double halfVar = (rate + vol * vol * 0.5) * mat;
double d1 = (Math.Log(spot / strike) + halfVar) / std;
double d2 = d1 - std;
return spot * MyMath.NormalCdf(d1) - strike * MyMath.NormalCdf(d2) * Math.Exp(-rate * mat);
}
public static double BachelierCallPrice(double spot, double lambda, double mat, double strike)
{
double d = (spot - strike) / (lambda * Math.Sqrt(mat));
double NormalPdf = 1.0; // calculate this
return MyMath.NormalCdf(d) * (spot - strike) + lambda * Math.Sqrt(mat) * NormalPdf;
}
}
public static class Sampler
{
public static double[] GenerateCorrelatedNormals(Random rand, double corr)
{
double A = corr;
double B = Math.Sqrt(1 - corr * corr);
double out1 = rand.NextDouble();
double temp = rand.NextDouble();
double out2 = A * out1 + B * temp;
return new double[2] { MyMath.U2G(out1), MyMath.U2G(out2) };
}
}
public class Sabr
{
public double Sigma0;
public double Mat;
public double Alpha;
public double Beta;
public double Rho;
private Random rand;
public Sabr(double sigma0, double mat, double alpha, double beta, double rho)
{
Sigma0 = sigma0;
Mat = mat;
Alpha = alpha;
Beta = beta;
Rho = rho;
rand = new Random(1234);
}
private double IncrementUnderlying(double value, double vol, double dt, double random)
{
return value + Math.Exp(vol) * Math.Pow(value, Beta) * Math.Sqrt(dt) * random;
}
private double IncrementLogVol(double logVol, double dt, double random)
{
// The logarithm of v
return logVol - 0.5*Alpha*Alpha*dt + Alpha*Math.Sqrt(dt) * random;
}
public double GeneratePath(double initialSpot, double mat, double timeSteps)
{
double dt = mat / timeSteps;
double spot = initialSpot;
double logVol = Math.Log(Sigma0);
for (int i = 0; i<timeSteps; i++)
{
double[] randoms = Sampler.GenerateCorrelatedNormals(rand, Rho);
spot = IncrementUnderlying(spot, logVol, dt, randoms[0]);
logVol = IncrementLogVol(logVol, dt, randoms[1]);
}
return spot;
}
public double CallPrice(double spot, double strike, double mat, double rate, int paths, int timeSteps)
{
double sum = 0.0;
double spotT;
for (int i = 0; i<paths; i++)
{
spotT = GeneratePath(spot, mat, timeSteps);
sum += Math.Max(spotT - strike, 0);
}
return Math.Exp(-rate*mat)* sum / paths;
}
public double ImpliedVolatility(double spot, double strike, double mat, double rate, double price)
{
double tol = 0.0000001;
int n = 0;
int nMax = 100;
double volQuess = Sigma0;
double b = 1.0;
double a = 0.0001;
double c = 0.0;
double fc = 0.0;
double fa = 0.0;
double signFc, signFa;
while (n<nMax)
{
n = n + 1;
c = (a + b) * 0.5;
fc = ClosedForm.BsCallPrice(spot, c, mat, strike, rate) - price;
fa = ClosedForm.BsCallPrice(spot, a, mat, strike, rate) - price;
if ((b - a) * 0.5 < tol)
{
return c;
}
signFc = -1;
signFa = -1;
if (fc > 0)
signFc = 1;
if (fa > 0)
signFa = 1;
if (signFa == signFc)
a = c;
else
b = c;
}
throw new InvalidOperationException("Bi-section algorithm did not converge in " + nMax + " iterations.");
}
}
public class Freia
{
private double _lambda;
private double _level;
private double _rho;
private double _s0;
private double _z0;
private double _epsilon;
private double _alpha;
private double _backbone;
private double _mix;
private double _beta;
public Freia(double lambda, double level, double rho, double s0, double z0, double epsilon,
double alpha, double backbone, double mix, double beta)
{
// Still missing shift parameter
_lambda = lambda;
_level = level;
_rho = rho;
_s0 = s0;
_z0 = z0; // Usually = 1
_epsilon = epsilon;
_alpha = alpha; // Usually = 1
_backbone = backbone;
_mix = mix; // CEV parameter
_beta = beta;
}
public double ImpliedVol(double impliedVol, double strike)
{
double testVal = 0.0;
return testVal;
}
private double incrementSt(double st, double zt, double timeStep, Random random)
{
double w = random.NextDouble();
double help1 = Math.Sqrt(zt) * _lambda * Math.Pow((_s0 / _level), _backbone - 1);
double help2 = _mix * st + (1 - _mix) * _s0;
double ds = help1 * help2 * Math.Sqrt(timeStep) * w;
return st + ds;
}
private double incrementPt(double zt, double timeStep, Random random)
{
double w = random.NextDouble();
double dz = _beta * (_alpha - zt) * timeStep + _epsilon * Math.Sqrt(zt) * Math.Sqrt(timeStep) * w;
return zt + dz;
}
private double simulatePath(double maturity, int timeSteps, Random random)
{
double timeStep = maturity / timeSteps;
double valueSpot = _s0;
double valueZ = _z0;
for (int i = 0; i < timeSteps; i++)
{
valueZ = incrementPt(valueZ, timeStep, random);
valueSpot = incrementSt(valueSpot, valueZ, timeStep, random);
}
return valueSpot;
}
public double callValue(double maturity, double strike, int paths, int timeSteps)
{
double[] values = new double[paths];
Random random = new Random(1234);
for (int i = 0; i < paths; i++)
values[i] = Math.Max(simulatePath(maturity, timeSteps, random) - strike, 0);
return values.Average();
}
}
}
|
dab34b379bef2bd5cb35be0bad6caae8bc1f3c31
|
C#
|
dhon2407/LSW-alpha
|
/LittleSimWorld/Assets/Scripts/Inventory/Containers/Storage.cs
| 2.578125
| 3
|
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
namespace InventorySystem
{
public abstract class Storage : MonoBehaviour
{
public abstract void Open(ItemList data);
public abstract void Close();
public ItemList Itemlist => GetItemlist();
public List<ItemSlot> ItemSlots => GetItemSlots();
public bool IsOpen => !closed;
public int FreeSlot => GetFreeSlot();
protected abstract void SetupDropEvents();
protected List<Droppable> itemCells = new List<Droppable>();
protected Vector3 showScale;
protected ItemList itemList;
protected bool closed;
public void Show()
{
transform.localScale = showScale;
closed = false;
}
public void Hide()
{
transform.localScale = Vector3.zero;
closed = true;
}
protected virtual void Awake()
{
itemCells = new List<Droppable>();
showScale = transform.localScale;
UpdateItemCells();
Hide();
}
public bool IsFull(ItemCode currentItemCode)
{
foreach (var item in itemCells)
{
if (item.Type == Droppable.CellType.TrashBin)
continue;
var itemSlot = item.GetSlot();
if (item.Empty ||
(currentItemCode == itemSlot.CurrentItemCode && itemSlot.Stackable && !itemSlot.MaxStack))
return false;
}
return true;
}
public bool CanFit(ItemSlot itemSlot)
{
int slotToTake = 0;
if (Contains(itemSlot.CurrentItemCode, false))
{
var existingSlot = SlotOf(itemSlot.CurrentItemCode, false);
var maxStack = existingSlot.CurrentItemData.maxStack;
if ((itemSlot.Quantity + existingSlot.Quantity) > maxStack)
{
int excess = (itemSlot.Quantity + existingSlot.Quantity) - maxStack;
slotToTake += Mathf.CeilToInt((float)excess / maxStack);
}
}
else
{
slotToTake++;
}
return slotToTake <= FreeSlot;
}
protected virtual void Start()
{
SetupDropEvents();
}
protected int GetFreeSlot()
{
return itemCells.Count(cell => cell.Type != Droppable.CellType.TrashBin &&
cell.Empty && cell.gameObject.activeSelf);
}
protected void MoveToExistingItem(Droppable cell)
{
var itemSlot = cell.GetSlot();
var containingCells = FindCells(itemSlot.CurrentItemCode);
foreach (var containingCell in containingCells)
if (!containingCell.Equals(cell))
itemSlot.Add(containingCell.GetSlot());
}
protected List<Droppable> FindCells(ItemCode itemCode)
{
var cellsContaining = new List<Droppable>();
foreach (var cell in itemCells)
{
if (cell.Type == Droppable.CellType.TrashBin)
continue;
var itemSlot = cell.GetSlot();
if (!cell.Empty && itemCode == itemSlot.CurrentItemCode &&
itemSlot.Stackable && !itemSlot.MaxStack)
cellsContaining.Add(cell);
}
return cellsContaining;
}
protected bool Contains(ItemCode itemCode, bool includeFullStack)
{
foreach (var cell in itemCells)
{
if (cell.Type == Droppable.CellType.TrashBin)
continue;
var itemSlot = cell.GetSlot();
if (!cell.Empty && itemCode == itemSlot.CurrentItemCode)
{
if (includeFullStack || itemSlot.Stackable && !itemSlot.MaxStack)
return true;
}
}
return false;
}
protected ItemSlot SlotOf(ItemCode itemCode, bool includeFullStack)
{
foreach (var cell in itemCells)
{
if (cell.Type == Droppable.CellType.TrashBin)
continue;
var itemSlot = cell.GetSlot();
if (!cell.Empty && itemCode == itemSlot.CurrentItemCode)
{
if (includeFullStack || itemSlot.Stackable && !itemSlot.MaxStack)
return cell.GetSlot();
}
}
return null;
}
protected ItemSlot NextEmptyCell()
{
foreach (var item in itemCells)
{
if (item.Type == Droppable.CellType.TrashBin)
continue;
if (item.Empty)
return Inventory.CreateSlot(item.transform);
}
throw new UnityException("No available slot.");
}
protected void SetMaxSlot(int slots)
{
var grid = itemCells[0].transform.parent.GetComponent<GridLayoutGroup>();
if (grid != null)
grid.constraintCount = Mathf.Clamp(slots, 4, 8);
for (int i = 0; i < itemCells.Count; i++)
itemCells[i].gameObject.SetActive(i < slots);
}
private void UpdateItemCells()
{
itemCells.Clear();
foreach (var cell in GetComponentsInChildren<Droppable>())
itemCells.Add(cell);
}
private ItemList GetItemlist()
{
itemList.Items.Clear();
foreach (var cell in itemCells)
{
if (cell.Type == Droppable.CellType.TrashBin)
continue;
var itemSlot = cell.GetSlot();
itemList.Items.Add(new ItemList.ItemInfo
{
itemCode = (cell.Empty) ? ItemCode.None : itemSlot.CurrentItemCode,
count = (cell.Empty) ? 0 : itemSlot.Quantity
});
}
return itemList;
}
private List<ItemSlot> GetItemSlots()
{
List<ItemSlot> slots = new List<ItemSlot>();
foreach (var cell in itemCells)
{
if (cell.Type == Droppable.CellType.TrashBin)
continue;
slots.Add(cell.GetSlot());
}
return slots;
}
}
}
|
1e4bee31922eff121349ca6382e4a1c461b9d7e7
|
C#
|
nofuture-git/31g
|
/trunk/Code/NoFuture/Util/NfConsole/InvokeCmdBase.cs
| 2.734375
| 3
|
using System.Diagnostics;
using System.Text;
using Newtonsoft.Json;
namespace NoFuture.Util.NfConsole
{
/// <summary>
/// A concrete implementation of the calling assembly side's
/// invocation of a command on a remote console.exe.
/// </summary>
public abstract class InvokeCmdBase
{
protected static readonly JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
protected static string ConvertJsonFromBuffer(byte[] buffer)
{
var decoder = Encoding.UTF8.GetDecoder();
var jsonChars = new char[decoder.GetCharCount(buffer, 0, buffer.Length)];
decoder.GetChars(buffer, 0, buffer.Length, jsonChars, 0);
var jsonStringBldr = new StringBuilder();
jsonStringBldr.Append(jsonChars);
return jsonStringBldr.ToString();
}
protected internal bool IsMyProcessRunning(int pid)
{
if (pid == 0)
return false;
var proc = Process.GetProcessById(pid);
proc.Refresh();
return !proc.HasExited;
}
}
}
|
5d26b432338f06f478dc260d6e36e6e6c1e951a1
|
C#
|
tomkennedycode/random-lyric-twitter-bot
|
/Services/YoutubeService.cs
| 2.8125
| 3
|
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using yungleanlyrics.Interfaces;
using Google.Apis.Services;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
using System.Linq;
namespace yungleanlyrics.Services
{
public class YoutubeService : IYoutubeService
{
private readonly ILogger<YoutubeService> _log;
private readonly IConfiguration _config;
public YoutubeService(ILogger<YoutubeService> logger, IConfiguration config)
{
_log = logger;
_config = config;
}
public string GetSongURL(string song)
{
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = _config.GetValue<string>("YoutubeAPIKey"),
ApplicationName = this.GetType().ToString()
});
var searchListRequest = youtubeService.Search.List("snippet");
searchListRequest.Q = song;
searchListRequest.MaxResults = 5;
// Call the search.list method to retrieve results matching the specified query term.
var searchListResponse = searchListRequest.Execute();
// Get top rate video - with our search query, i am confident that it'll find the correct video
SearchResult youtubeVideo = searchListResponse.Items.FirstOrDefault();
return $"https://www.youtube.com/watch?v={youtubeVideo.Id.VideoId}";
}
}
}
|
ab183423c82b3cdb6ef9573de90fd3c1185b9c6b
|
C#
|
ZeroInfinite/hdinsight-storm-dotnet-event-correlation
|
/CorrelationTopology/CorrelationTopology/Spout.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using Microsoft.SCP;
using Microsoft.SCP.Rpc.Generated;
namespace CorrelationTopology
{
public class Spout : ISCPSpout
{
//Context for this component
private Context context;
//Random numbers
private Random r = new Random();
//Emulate 100 user sessions
private Session[] sessions = new Session[100];
//Is this a transactional topology?
//i.e. do we need to replay failed tuples?
private bool enableAck = false;
//If so, we need to keep track using sequence IDs
private long seqId = 0;
//And a place to cache the original so we can replay later
private Dictionary<long, object> cachedTuples = new Dictionary<long, object>();
/// <summary>
/// Return a new instance of the spout
/// </summary>
/// <param name="context">Context for this topology</param>
public Spout(Context context)
{
this.context = context;
//Declare the ouput, which is two strings and a long for this example
Dictionary<string, List<Type>> outputSchema = new Dictionary<string, List<Type>>();
outputSchema.Add("default", new List<Type>() { typeof(string), typeof(string), typeof(long) });
this.context.DeclareComponentSchema(new ComponentStreamSchema(null, outputSchema));
//Create initial sessions
for (int i = 0; i < sessions.Length; i++)
{
this.sessions[i] = new Session();
}
//Are ack's enabled in the context?
if (Context.Config.pluginConf.ContainsKey(Constants.NONTRANSACTIONAL_ENABLE_ACK))
{
//If so, we need to be transactional
enableAck = (bool)(Context.Config.pluginConf[Constants.NONTRANSACTIONAL_ENABLE_ACK]);
}
}
/// <summary>
/// Get an instance of this component
/// </summary>
/// <param name="context">Context for the topology</param>
/// <param name="parms"></param>
/// <returns></returns>
public static Spout Get(Context context, Dictionary<string, Object> parms)
{
return new Spout(context);
}
/// <summary>
/// Emit a set of tuples
/// </summary>
/// <param name="parms"></param>
public void NextTuple(Dictionary<string, Object> parms)
{
//get a random session
int sessionIdx = r.Next(sessions.Length);
Session session = this.sessions[sessionIdx];
//Check timeout between emits for each session state
//to simulate real-world user session behavior.
DateTime now = DateTime.Now;
//If the timeout has happened, emit
if (session.ended)
{
//New values containing the session ID, state, and datetime (as UNIX time)
Values emitValues = new Values(session.id.ToString(), session.state, TypeHelper.ToUnixTime(now));
//If acks are enabled
if (enableAck)
{
//Add to the spout cache so that the tuple can be re-emitted on fail
cachedTuples.Add(seqId, emitValues);
//Emit the tuples with the current sequence ID
this.context.Emit(Constants.DEFAULT_STREAM_ID, emitValues, seqId);
//Increment the sequence
seqId++;
}
else
{
//If no acks, just fire and forget
this.context.Emit(Constants.DEFAULT_STREAM_ID, emitValues);
}
//If this was an end event, recycle the session entry with a new session
if (session.state == "END")
{
this.sessions[sessionIdx] = new Session();
}
else
{
//If not END, then it was START and we need to set to END
this.sessions[sessionIdx].state = "END";
//Set the lastEmitted time so we can wait for timeout
this.sessions[sessionIdx].emitted = now;
}
}
}
/// <summary>
/// Handle ack's for the specified tuple
/// </summary>
/// <param name="seqId">the sequence ID</param>
/// <param name="parms"></param>
public void Ack(long seqId, Dictionary<string, Object> parms)
{
if (enableAck)
{
//Remove the successfully acked tuple from the cache.
cachedTuples.Remove(seqId);
}
}
/// <summary>
/// Handle failed tuples
/// </summary>
/// <param name="seqId">the sequence ID</param>
/// <param name="parms"></param>
public void Fail(long seqId, Dictionary<string, Object> parms)
{
if (enableAck)
{
//Re-emit the failed tuple again - only if it exists
if (cachedTuples.ContainsKey(seqId))
{
this.context.Emit(Constants.DEFAULT_STREAM_ID, new Values(cachedTuples[seqId]), seqId);
}
}
}
}
}
|
79dbadaf71a68de0acf5211765ba4d99aca41b0f
|
C#
|
Emmabyrne36/ProjectEulerSolutions
|
/ProjectEuler/AlternativeSolutions.cs
| 3.515625
| 4
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ProjectEuler
{
class AlternativeSolutions
{
#region ProjectEuler2
public static int Fib(int n)
{
return n <= 1 ? n : Fib(n - 1) + Fib(n - 2);
}
public static List<int> series = new List<int>();
public static void FibSeries(int n)
{
bool result = true;
while (result)
{
result = FibTemp(1, 2, 1, n);
}
}
public static bool FibTemp(int a, int b, int counter, int length)
{
if (counter <= length)
{
if (a % 2 == 0 && !(a >= 4000000) && !(b >= 4000000))
{
series.Add(a);
FibTemp(b, a + b, counter + 1, length);
}
else
{
return false;
}
}
return true;
}
#endregion
#region ProjectEuler3
public static long ProjEuler3OtherSolution()
{
long n = 600851475143;
while (true)
{
long p = SmallestFactor(n);
if (p < n)
{
n /= p;
}
else
{
return n;
}
}
}
// Returns the smallest factor of n, which is in the range [2, n]. The result is always prime.
public static long SmallestFactor(long n) // from online solution
{
if (n <= 1)
{
n = 1;
}
for (long i = 2, end = Convert.ToInt64(Math.Sqrt(n)); i <= end; i++)
{
if (n % i == 0)
{
return i;
}
}
return n;
}
#endregion
#region ProjectEuler4
public static bool IsPalindrome2(int n)
{
char[] characterArray = n.ToString().ToCharArray();
for (int i = 0; i <= (characterArray.Length / 2); i++)
{
if (characterArray[i] != characterArray[(characterArray.Length - 1) - i])
{
return false;
}
}
return true;
}
#endregion
#region ProjectEuler6
public static double ProjEuler6()
{
return GetSquareOfSum(100) - GetSumOfSquares(100);
}
public static double GetSumOfSquares(int n)
{
double totalSum = 0;
for (int i = 1; i <= n; i++)
{
totalSum += Math.Pow(i, 2);
}
return totalSum;
}
public static double GetSquareOfSum(int n)
{
double totalSquare = 0;
for (int i = 0; i <= n; i++)
{
totalSquare += i;
}
return Math.Pow(totalSquare, 2);
}
public static double ProjectEuler6()
{
double totalSumOfSquares = 0;
double totalSquareOfSums = 0;
for (int i = 1; i <= 100; i++)
{
totalSumOfSquares += i * i;
totalSquareOfSums += i;
}
return (totalSquareOfSums*totalSquareOfSums) - totalSumOfSquares;
}
#endregion
}
}
|
3711550d2fb4c4bb183da69dc1c77fcdabcf3630
|
C#
|
Cactus-Blade/Cactus.Blade.Core
|
/Core/System.Int64/System.BitConverter/Int64.Int64BitsToDouble.cs
| 3.390625
| 3
|
using System;
public static partial class Extension
{
/// <summary>
/// Converts the specified 64-bit signed integer to a double-precision floating point number.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>A double-precision floating point number whose value is equivalent to .</returns>
public static double Int64BitsToDouble(this long value)
{
return BitConverter.Int64BitsToDouble(value);
}
}
|
21eebb05e2dd3329d26b5c27c68df47a108b4ed4
|
C#
|
Sethcbs/SwampTrollPortfolioProject
|
/PortfolioProjectFiles/PlantMonsterHealth.cs
| 2.625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlantMonsterHealth : MonoBehaviour
{
public int currentHealth;
public int maxHealth = 100;
public Animator animator;
public GameObject plant;
public float deathDelayTime;
private void Start()
{
currentHealth = maxHealth;
}
public void DealDamage(int damage)
{
//when called, subtract the damage inputted from the objects current health value.
currentHealth -= damage;
//trigger animation
animator.SetTrigger("gotHit");
//if the health value is less than or equal to zero, deactivate collider, start death animation, wait until animation is done, then deactivate the whole game object.
if(currentHealth <= 0)
{
StartCoroutine(DeathDelay());
}
IEnumerator DeathDelay()
{
GetComponent<BoxCollider>().enabled = false;
animator.SetBool("isDead", true);
yield return new WaitForSeconds(deathDelayTime);
plant.SetActive(false);
}
}
}
|
d8f56cae6caf540327db75bee8669851e2f5ec3a
|
C#
|
Rafigi/web-api-testing
|
/Example.Api/Middlewares/ExceptionMiddleware.cs
| 2.75
| 3
|
using System;
using System.Net;
using System.Threading.Tasks;
using Example.Api.Utils;
using Example.Common.Exceptions;
using Microsoft.AspNetCore.Http;
using Serilog;
namespace Example.Api.Middlewares
{
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
public ExceptionMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext httpContext)
{
try
{
await _next(httpContext);
}
catch (Exception ex)
{
Log.Error($"Exception: {ex}");
await HandleExceptionAsync(httpContext, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.ContentType = "application/json";
switch (exception)
{
case BadRequestException _:
context.Response.StatusCode = (int) HttpStatusCode.BadRequest;
break;
case ConflictException _:
context.Response.StatusCode = (int) HttpStatusCode.Conflict;
break;
case ForbiddenException _:
context.Response.StatusCode = (int) HttpStatusCode.Forbidden;
break;
case NotFoundException _:
context.Response.StatusCode = (int) HttpStatusCode.NotFound;
break;
case NotImplementedException _:
context.Response.StatusCode = (int) HttpStatusCode.NotImplemented;
break;
case UnauthorizedException _:
context.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
break;
case UnprocessableEntityException _:
context.Response.StatusCode = (int) HttpStatusCode.UnprocessableEntity;
break;
default:
context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
break;
}
return context.Response.WriteAsync(
new ErrorResponse
{
StatusCode = context.Response.StatusCode,
Message = exception.Message
}.ToString()
);
}
}
}
|