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
|
|---|---|---|---|---|---|---|
b90ee3b0a433a4966a363d2d8d3c7f70dc819f34
|
C#
|
thcl-0407/NetCore_API_BlogApplication
|
/Services/PostService.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DAL;
using DAL.Entities;
using Microsoft.EntityFrameworkCore;
using Services.Entities;
using DTO.ReadDTO;
using DTO.WriteDTO;
namespace Services
{
public class PostService : IPostService
{
private BlogApplicationDbContext db;
public PostService(BlogApplicationDbContext dbContext)
{
db = dbContext;
}
/*Thêm Một Post Mới*/
public async Task<CustomResponse> Create(PostWriteDTO postWrite)
{
if (postWrite == null)
{
return new CustomResponse(false, "Post is Null");
}
if (postWrite.isPropertiesNull())
{
return new CustomResponse(false, "Post properties is Null");
}
if (postWrite.isPropertiesEmpty())
{
return new CustomResponse(false, "Post properties is Empty");
}
try
{
//Init a Post
Post post = new Post();
post.TitlePost = postWrite.TitlePost;
post.SummaryPost = postWrite.SummaryPost;
post.ContentPost = postWrite.ContentPost;
post.DateCreate = DateTime.Now;
post.DateUpdate = DateTime.Now;
post.UserID = new Guid(postWrite.UserID);
//Init ID cho Image
Guid NewImageID = Guid.NewGuid();
post.ImageID = NewImageID;
//Init a Image
ImageGallery image = new ImageGallery();
image.Base64Code = postWrite.EncodeImage;
image.ImageID = NewImageID;
bool task_add_image = db.ImageGalleries.AddAsync(image).IsCompleted;
if (task_add_image)
{
await db.Posts.AddAsync(post);
await db.SaveChangesAsync();
}
}
catch (Exception e)
{
return new CustomResponse(false, e.Message);
}
return new CustomResponse(true, "Thêm Post Thành Công");
}
/*Cập Nhật Một Bài Post*/
public async Task<CustomResponse> Update(PostWriteDTO postWrite, string UserID)
{
if (postWrite == null)
{
return new CustomResponse(false, "Post is Null");
}
postWrite.UserID = UserID;
if (postWrite.isPropertiesNullWithoutEndcode())
{
return new CustomResponse(false, "Post properties is Null");
}
if (postWrite.isPropertiesEmptyWithoutEndcode())
{
return new CustomResponse(false, "Post properties is Empty");
}
try
{
Post CurPost = db.Posts.FirstOrDefaultAsync(p => p.PostID == postWrite.PostID).Result;
//Tìm Thấy Post Cần Cập Nhật
if (CurPost != null)
{
//Fix Post Không Chính Chủ
if (!CurPost.UserID.Equals(new Guid(UserID)))
{
return new CustomResponse(false, "Bạn Không Có Quyền Cập Nhật Post Này");
}
//Có Cập Nhật Hình Ảnh
if (postWrite.EncodeImage.Length > 0)
{
ImageGallery new_image = new ImageGallery
{
ImageID = Guid.NewGuid(),
Base64Code = postWrite.EncodeImage
};
bool add_image_task = db.ImageGalleries.AddAsync(new_image).IsCompleted;
if (add_image_task)
{
CurPost.TitlePost = postWrite.TitlePost;
CurPost.SummaryPost = postWrite.SummaryPost;
CurPost.ContentPost = postWrite.ContentPost;
CurPost.DateUpdate = DateTime.Now;
CurPost.ImageID = new_image.ImageID;
}
else
{
return new CustomResponse(false, "Không Thể Cập Nhật Hình Ảnh Vào Lúc Này");
}
}
//Không Cập Nhật Hình Ảnh
else
{
CurPost.TitlePost = postWrite.TitlePost;
CurPost.SummaryPost = postWrite.SummaryPost;
CurPost.ContentPost = postWrite.ContentPost;
CurPost.DateUpdate = DateTime.Now;
}
//Done and Save Change All Modifies
await db.SaveChangesAsync();
}
//Tìm Không Thấy Post Cần Cập Nhật
else
{
return new CustomResponse(false, "Post Không Tồn Tại");
}
}
catch (Exception e)
{
return new CustomResponse(false, e.Message);
}
return new CustomResponse(true, "Cập Nhật Thành Công");
}
/*Xoá Một Bài Post*/
public async Task<CustomResponse> Remove(int postID, string UserID)
{
if (postID == null)
{
throw new ArgumentNullException();
}
if (postID > int.MaxValue || postID < int.MinValue)
{
throw new ArgumentOutOfRangeException();
}
try
{
IQueryable<Comment> Comments = from PostComment in db.PostComments
join Comment in db.Comments on PostComment.CommentID equals Comment.CommentID
where PostComment.PostID == postID
select Comment;
Post post = db.Posts.FirstOrDefaultAsync(p => p.PostID == postID).Result;
if (post != null)
{
//Post Chính Chủ => Được Xoá
if (post.UserID.Equals(new Guid(UserID)))
{
db.RemoveRange(Comments);
db.Posts.Remove(post);
await db.SaveChangesAsync();
}
//Post Vãng Lai
else
{
return new CustomResponse(false, "Bạn Không Có Quyền Xoá Post Này");
}
return new CustomResponse(true, "Xoá Post Thành Công");
}
else
{
return new CustomResponse(false, "Post Không Tồn Tại");
}
}
catch (Exception e)
{
return new CustomResponse(false, e.Message);
}
}
/*Get A Post*/
public async Task<PostReadDTO> GetPost(int? PostID)
{
if (PostID == null)
{
throw new ArgumentNullException();
}
if(PostID > int.MaxValue || PostID < int.MinValue)
{
throw new ArgumentOutOfRangeException();
}
PostReadDTO post_result = (from ImageGallery in db.ImageGalleries
join Post in db.Posts on ImageGallery.ImageID equals Post.ImageID
join User in db.Users on Post.UserID equals User.UserID
where Post.PostID == PostID
select new PostReadDTO
{
PostID = Post.PostID,
TitlePost = Post.TitlePost,
ContentPost = Post.ContentPost,
SummaryPost = Post.SummaryPost,
ImageID = ImageGallery.ImageID.ToString(),
EncodeImage = ImageGallery.Base64Code,
DateCreated = Post.DateCreate,
UserID = User.UserID.ToString(),
UserName = User.UserName,
}).FirstOrDefaultAsync().Result;
return post_result;
}
/*Get Base64Image A Post*/
public async Task<string> GetBase64ImageAsync(int? PostID)
{
if (PostID == null)
{
throw new ArgumentNullException();
}
try
{
Guid ImageID = db.Posts.Where(p => p.PostID == PostID).FirstOrDefault().ImageID;
Task<ImageGallery> task_image = db.ImageGalleries.Where(ig => ig.ImageID.Equals(ImageID)).FirstOrDefaultAsync();
return task_image.Result.Base64Code;
}
catch (Exception e)
{
return String.Empty;
}
return String.Empty;
}
/*Get Tất Cả Bài Post*/
public async Task<List<PostReadDTO>> GetAll()
{
List<PostReadDTO> post_result = (from ImageGallery in db.ImageGalleries
join Post in db.Posts on ImageGallery.ImageID equals Post.ImageID
join User in db.Users on Post.UserID equals User.UserID
select new PostReadDTO
{
PostID = Post.PostID,
TitlePost = Post.TitlePost,
SummaryPost = Post.SummaryPost,
EncodeImage = ImageGallery.Base64Code,
ImageID = ImageGallery.ImageID.ToString(),
DateCreated = Post.DateCreate,
UserID = User.UserID.ToString(),
UserName = User.UserName,
}).ToListAsync<PostReadDTO>().Result;
return post_result;
}
/*Get Danh Sách Bài Viết Của Một User*/
public Task<List<PostReadDTO>> GetPosts(string UserID)
{
if (UserID == null)
{
throw new NullReferenceException();
}
if (UserID.Trim().Length == 0)
{
throw new ArgumentException();
}
Task<List<PostReadDTO>> post_result = (from ImageGallery in db.ImageGalleries
join Post in db.Posts on ImageGallery.ImageID equals Post.ImageID
join User in db.Users on Post.UserID equals User.UserID
where Post.UserID.ToString().Equals(UserID)
select new PostReadDTO
{
PostID = Post.PostID,
TitlePost = Post.TitlePost,
ContentPost = Post.ContentPost,
SummaryPost = Post.SummaryPost,
ImageID = ImageGallery.ImageID.ToString(),
EncodeImage = ImageGallery.Base64Code,
DateCreated = Post.DateCreate,
UserID = User.UserID.ToString(),
UserName = User.UserName,
}).ToListAsync();
return post_result;
}
public Task<List<PostReadDTO>> GetPostsByTitle(string Key_Title)
{
if (Key_Title == null)
{
throw new NullReferenceException();
}
if (Key_Title.Trim().Length == 0)
{
throw new ArgumentException();
}
Task<List<PostReadDTO>> post_result = (from ImageGallery in db.ImageGalleries
join Post in db.Posts on ImageGallery.ImageID equals Post.ImageID
join User in db.Users on Post.UserID equals User.UserID
where Post.TitlePost.Contains(Key_Title)
select new PostReadDTO
{
PostID = Post.PostID,
TitlePost = Post.TitlePost,
ContentPost = Post.ContentPost,
SummaryPost = Post.SummaryPost,
ImageID = ImageGallery.ImageID.ToString(),
EncodeImage = ImageGallery.Base64Code,
DateCreated = Post.DateCreate,
UserID = User.UserID.ToString(),
UserName = User.UserName,
}).ToListAsync();
return post_result;
}
}
}
|
37e6dd539aeeae9225436ab1edcce9b05b76e911
|
C#
|
BobFrapples/TeaseAI
|
/TeaseAI.Services/CommandProcessor/GotoDommeLevelCommandProcessor.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using TeaseAI.Common;
using TeaseAI.Common.Constants;
using TeaseAI.Common.Data;
using TeaseAI.Common.Events;
using TeaseAI.Common.Interfaces;
namespace TeaseAI.Services.CommandProcessor
{
public class GotoDommeLevelCommandProcessor : CommandProcessorBase
{
public GotoDommeLevelCommandProcessor(LineService lineService
, IBookmarkService bookmarkService) : base(Keyword.GotoDommeApathy, lineService)
{
_lineService = lineService;
_bookmarkService = bookmarkService;
}
public override Result<Session> PerformCommand(Session session, string line)
{
var workingSession = session.Clone();
var result = _bookmarkService.FindBookmark(workingSession.CurrentScript.Lines.ToList(), GetDommeLevelBookmark(workingSession.Domme.DomLevel))
.OnSuccess(ln => workingSession.CurrentScript.LineNumber = ln)
.Map(ln => workingSession)
.OnSuccess(sesh => OnCommandProcessed(sesh));
return result;
}
protected override Result ParseCommandSpecific(Script script, string personalityName, string line)
{
var errors = new List<string>();
foreach (var dommeLevel in new List<int> { 1, 2, 3, 4, 5 })
{
var findBookmark = _bookmarkService.FindBookmark(script.Lines, GetDommeLevelBookmark(dommeLevel));
if (findBookmark.IsFailure)
errors.Add(findBookmark.Error.Message);
}
if (errors.Count == 0)
return Result.Ok();
return Result.Fail(string.Join(Environment.NewLine, errors));
}
private string GetDommeLevelBookmark(int dommeLevel) => "(DommeLevel" + dommeLevel.ToString() + ")";
private readonly LineService _lineService;
private readonly IBookmarkService _bookmarkService;
}
}
|
154a48b547ede613420041041a7e37956a95454e
|
C#
|
chedan1992/bellali
|
/QinGuo/trunk/Program/快洗车App/trunk/Aspx.DataAccess/BaseDAL.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using QINGUO.DataAccessBase;
using QINGUO.Common;
using Dapper;
using QINGUO.DataAccessBase;
namespace QINGUO.DAL
{
public class BaseDAL<T> where T : class,new()
{
protected IDapperHelperSql<T> dabase = new DapperHelper<T>();
/// <summary>
/// 新增
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public virtual int Insert(T t)
{
try
{
int influenceCount = dabase.Insert(t);
return influenceCount;
}
catch (Exception ex)
{
return 0;
}
}
/// <summary>
/// 修改
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public virtual int Update(T t)
{
try
{
int influenceCount = dabase.Update(t);
return influenceCount;
}
catch (Exception ex)
{
return 0;
}
}
/// <summary>
/// 删除
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="primaryKeyValue">主键值</param>
/// <returns></returns>
public virtual int Delete(object primaryKeyValue)
{
try
{
int influenceCount = dabase.Delete(primaryKeyValue);
return influenceCount;
}
catch (Exception ex)
{
return 0;
}
}
/// <summary>
/// 软删除
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="primaryKeyValue">主键值</param>
/// <returns></returns>
public virtual int DeleteStatus(object primaryKeyValue)
{
try
{
int influenceCount = dabase.DeleteStatus(primaryKeyValue);
return influenceCount;
}
catch (Exception ex)
{
return 0;
}
}
/// <summary>
/// 删除
/// </summary>
/// <param name="primaryKeyValue"></param>
/// <param name="type"></param>
/// <returns></returns>
public virtual int Delete(T t)
{
try
{
int influenceCount = dabase.Delete(t);
return influenceCount;
}
catch (Exception ex)
{
return 0;
}
}
#region 轻量级分页
/// <summary>
/// 单表分页 单表查询
/// </summary>
/// <returns></returns>
public Page<T> GetPage(int pageIndex, int pageSize)
{
return dabase.GetPage(pageIndex, pageSize);
}
/// <summary>
/// 越过几条拿几条 单表查询
/// </summary>
/// <param name="pageIndex">当前页</param>
/// <param name="pageSize">当前页容量</param>
/// <returns></returns>
public List<T> GetSkipTakePage(int pageIndex, int pageSize)
{
return dabase.GetSkipTakePage(pageIndex, pageSize);
}
/// <summary>
/// 分页Fetch机制
/// </summary>
/// <returns></returns>
public List<T> GetFetchPage(int pageIndex, int pageSize)
{
return dabase.GetFetchPage(pageIndex, pageSize);
}
#endregion
/// <summary>
/// 获取分页查询集合,返回json
/// </summary>
/// <param name="search">查询类</param>
/// <returns></returns>
public virtual string QueryPageToJson(Search search)
{
return dabase.QueryPageToJson(search);
}
/// <summary>
/// 获取分页查询集合,返回DataSet
/// </summary>
/// <param name="total">记录条数</param>
/// <param name="search">查询类</param>
/// <returns></returns>
public virtual DataSet QueryPageToDataSet(out int total, Search search)
{
return dabase.QueryPageToDataSet(out total, search);
}
/// <summary>
/// 获取查询集合,返回List
/// </summary>
/// <typeparam name="T">集合类</typeparam>
/// <returns></returns>
public virtual List<T> QueryToAll()
{
return dabase.QueryToAll();
}
/// <summary>
/// 根据主键,获取类集合
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="primaryKeyValue">主键值</param>
/// <returns></returns>
public virtual T LoadData(object primaryKeyValue)
{
return dabase.LoadData(primaryKeyValue);
}
/// <summary>
/// 根据条件查询集合
/// </summary>
/// <param name="tabName">表名</param>
/// <param name="where">条件( and field=value and field=value)</param>
/// <param name="filedOrder">字段(filed1,filed2,filed2)或者(top 4 ,filed1,filed as name)...等sql语句就可以(""表示查询所有)</param>
/// <param name="top">获取多少条,默认0</param>
/// <returns>DataSet</returns>
public virtual DataSet GetList(string tabName, string where, string filedOrder, int? top)
{
object[] paras = new object[3];
paras[0] = tabName;
paras[1] = where;
if (filedOrder == "" || string.IsNullOrEmpty(filedOrder))
{
filedOrder = @" * ";
}
if (top > 0)
{
filedOrder = " top " + top + filedOrder;
}
paras[2] = filedOrder;
DataSet ds = dabase.ExecuteDataSetForMsSql("Get_Model", paras);
return ds;
}
/// <summary>
/// 是否存在该记录
/// </summary>
/// <param name="tabName">表名</param>
/// <param name="where">条件(field = value and field=value)</param>
/// <param name="count">返回的条数(共有几条数据)</param>
/// <returns>返回ture or false</returns>
public virtual bool Exists(string tabName, string where, out int count)
{
DataParameters pms = new DataParameters();
pms.Add("@TabName", tabName);
pms.Add("@Where", where);
DataRow dr = dabase.ExecuteDataRow("Proc_Exists", pms, CommandType.StoredProcedure);
count = Convert.ToInt32(dr[0]);
if (count >= 1)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 是否存在该记录
/// </summary>
/// <param name="tabName">表名</param>
/// <param name="where">条件(field = value and field=value)</param>
/// <param name="count">返回的条数(共有几条数据)</param>
/// <returns>返回ture or false</returns>
public virtual int ExecuteNonQueryByText(string sql)
{
try
{
int r = dabase.ExecuteNonQueryByText(sql);;
dabase.CommitTransaction();
return r;
}
catch (Exception ex)
{
dabase.RollbackTransaction();
return 0;
}
}
/// <summary>
/// 返回数据集
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public virtual DataSet ExecuteDataSet(string sql)
{
return dabase.ExecuteDataSet(sql);
}
}
}
|
ec963265593e2305cda2f53e471bc6f9120d8de5
|
C#
|
YumengSun1990/VCards
|
/FolkerKinzel.VCards/Intls/Converters/InterestLevelConverter.cs
| 3.015625
| 3
|
using FolkerKinzel.VCards.Models.Enums;
using System;
using System.Diagnostics;
namespace FolkerKinzel.VCards.Intls.Converters
{
internal static class InterestLevelConverter
{
internal static class Values
{
internal const string High = "high";
internal const string Medium = "medium";
internal const string Low = "low";
}
internal static InterestLevel? Parse(string val)
{
Debug.Assert(val != null);
Debug.Assert(StringComparer.Ordinal.Equals(val, val.ToLowerInvariant()));
return val switch
{
Values.High => InterestLevel.High,
Values.Medium => InterestLevel.Medium,
Values.Low => InterestLevel.Low,
_ => null
};
}
internal static string? ToVCardString(this InterestLevel? interest)
{
return interest switch
{
InterestLevel.High => Values.High,
InterestLevel.Medium => Values.Medium,
InterestLevel.Low => Values.Low,
_ => null
};
}
}
}
|
ac462506fde2bad7f2a6073eca53ef54c3066e74
|
C#
|
sandermvanvliet/TestableHttpClient
|
/src/Codenizer.HttpClient.Testable/ConfigurationDumpVisitor.cs
| 2.65625
| 3
|
using System.CodeDom.Compiler;
using System.IO;
using System.Linq;
using System.Net.Http;
namespace Codenizer.HttpClient.Testable
{
internal class ConfigurationDumpVisitor : RequestNodeVisitor
{
private readonly StringWriter _writer;
private readonly IndentedTextWriter _indentedWriter;
private bool _hasMultipleQueryParams;
public ConfigurationDumpVisitor()
{
_writer = new StringWriter();
_indentedWriter = new IndentedTextWriter(_writer, " ");
}
public string Output => _writer.ToString();
public override void Header(string key, string value)
{
_indentedWriter.Indent = 4;
_indentedWriter.WriteLine();
_indentedWriter.WriteLine($"{key}: {value}");
}
public override void QueryParameter(string key, string? value)
{
_indentedWriter.Indent = 4;
if (_hasMultipleQueryParams)
{
_indentedWriter.Write("&");
}
else
{
_indentedWriter.Write("?");
}
_indentedWriter.Write($"{key}={value}");
_hasMultipleQueryParams = true;
}
public override void Path(string path)
{
_indentedWriter.Indent = 3;
_indentedWriter.Write(path);
_hasMultipleQueryParams = false;
}
public override void Authority(string authority)
{
_indentedWriter.Indent = 2;
_indentedWriter.WriteLine(authority);
}
public override void Scheme(string scheme)
{
_indentedWriter.Indent = 1;
_indentedWriter.WriteLine($"{scheme}://");
}
public override void Method(HttpMethod method)
{
_indentedWriter.Indent = 0;
_indentedWriter.WriteLine(method.Method);
}
public override void Response(RequestBuilder requestBuilder)
{
_indentedWriter.Indent = 4;
_indentedWriter.WriteLine("Response:");
_indentedWriter.Indent++;
var payload = requestBuilder.Data != null
? $" with {requestBuilder.MediaType} payload"
: "";
_indentedWriter.WriteLine($"HTTP {(int)requestBuilder.StatusCode} {requestBuilder.StatusCode}{payload}");
if (requestBuilder.Headers.Any())
{
foreach (var h in requestBuilder.Headers)
{
_indentedWriter.WriteLine($"{h.Key}: {h.Value}");
}
}
if (requestBuilder.Cookies.Any())
{
foreach (var cookie in requestBuilder.Cookies)
{
_indentedWriter.WriteLine($"Set-Cookie: {cookie}");
}
}
}
}
}
|
5b59e635f65941233d37182497f19624a520f53e
|
C#
|
chcg/js-map-parser
|
/source/JsParser.UI/UI/Theme.cs
| 2.546875
| 3
|
using System.Drawing;
using System.Xml.Linq;
namespace JsParser.UI.UI
{
public class Theme
{
public bool IsPredefined { get; set; }
public string Name { get; set; }
public ColorTable Colors { get; set; }
public XElement SaveToXml()
{
var themeXml = new XElement("theme");
themeXml.SetAttributeValue("Name", this.Name);
themeXml.SetAttributeValue("Predefined", this.IsPredefined);
themeXml.SetAttributeValue("ControlBackground", ColorTranslator.ToHtml(this.Colors.ControlBackground));
themeXml.SetAttributeValue("ControlText", ColorTranslator.ToHtml(this.Colors.ControlText));
themeXml.SetAttributeValue("GridLines", ColorTranslator.ToHtml(this.Colors.GridLines));
themeXml.SetAttributeValue("LineNumbersText", ColorTranslator.ToHtml(this.Colors.LineNumbersText));
themeXml.SetAttributeValue("HighlightBackground", ColorTranslator.ToHtml(this.Colors.HighlightBackground));
themeXml.SetAttributeValue("HighlightInactiveBackground",
ColorTranslator.ToHtml(this.Colors.HighlightInactiveBackground));
themeXml.SetAttributeValue("HighlightInactiveText",
ColorTranslator.ToHtml(this.Colors.HighlightInactiveText));
themeXml.SetAttributeValue("HighlightText", ColorTranslator.ToHtml(this.Colors.HighlightText));
themeXml.SetAttributeValue("MenuBackground", ColorTranslator.ToHtml(this.Colors.MenuBackground));
themeXml.SetAttributeValue("TabText", ColorTranslator.ToHtml(this.Colors.TabText));
themeXml.SetAttributeValue("WindowBackground", ColorTranslator.ToHtml(this.Colors.WindowBackground));
themeXml.SetAttributeValue("WindowText", ColorTranslator.ToHtml(this.Colors.WindowText));
return themeXml;
}
public static Theme LoadFromXml(XElement tx)
{
var t = new Theme();
t.Name = tx.Attribute("Name").Value;
t.IsPredefined = bool.Parse(tx.Attribute("Predefined").Value);
t.Colors = new ColorTable();
t.Colors.ControlBackground = ColorTranslator.FromHtml(tx.Attribute("ControlBackground").Value);
t.Colors.ControlText = ColorTranslator.FromHtml(tx.Attribute("ControlText").Value);
t.Colors.GridLines = ColorTranslator.FromHtml(tx.Attribute("GridLines").Value);
t.Colors.LineNumbersText = ColorTranslator.FromHtml(tx.Attribute("LineNumbersText").Value);
t.Colors.HighlightBackground = ColorTranslator.FromHtml(tx.Attribute("HighlightBackground").Value);
t.Colors.HighlightInactiveBackground =
ColorTranslator.FromHtml(tx.Attribute("HighlightInactiveBackground").Value);
t.Colors.HighlightInactiveText = ColorTranslator.FromHtml(tx.Attribute("HighlightInactiveText").Value);
t.Colors.HighlightText = ColorTranslator.FromHtml(tx.Attribute("HighlightText").Value);
t.Colors.MenuBackground = ColorTranslator.FromHtml(tx.Attribute("MenuBackground").Value);
t.Colors.TabText = ColorTranslator.FromHtml(tx.Attribute("TabText").Value);
t.Colors.WindowBackground = ColorTranslator.FromHtml(tx.Attribute("WindowBackground").Value);
t.Colors.WindowText = ColorTranslator.FromHtml(tx.Attribute("WindowText").Value);
return t;
}
public static Theme GetDefaultBlueTheme()
{
return new Theme()
{
Name = "Blue",
IsPredefined = true,
Colors = new ColorTable()
{
ControlBackground = ColorTranslator.FromHtml("#293955"),
ControlText = ColorTranslator.FromHtml("#000000"),
WindowBackground = ColorTranslator.FromHtml("#ffffff"),
WindowText = ColorTranslator.FromHtml("#000000"),
HighlightBackground = ColorTranslator.FromHtml("#3399ff"),
HighlightInactiveBackground = ColorTranslator.FromHtml("#b4b4b4"),
HighlightText = ColorTranslator.FromHtml("#ffffff"),
HighlightInactiveText = ColorTranslator.FromHtml("#000000"),
GridLines = ColorTranslator.FromHtml("#f0f0f0"),
LineNumbersText = Color.Gray,
TabText = ColorTranslator.FromHtml("#ffffff"),
MenuBackground = ColorTranslator.FromHtml("#e9ecee"),
}
};
}
public static Theme GetDefaultDarkTheme()
{
return Theme.LoadFromXml(XElement.Parse(@"
<theme Name='Dark'
Predefined='true'
ControlBackground='#2d2d30'
ControlText='#f1f1f1'
GridLines='#000000'
LineNumbersText='#777777'
HighlightBackground='#3399ff'
HighlightInactiveBackground='#3f3f46'
HighlightInactiveText='#f1f1f1'
HighlightText='#FFFFFF'
MenuBackground='#1b1b1c'
TabText='#d0d0d0'
WindowBackground='#252526'
WindowText='#f1f1f1' />"));
}
public static Theme GetDefaultLightTheme()
{
return Theme.LoadFromXml(XElement.Parse(@"
<theme Name='Light'
Predefined='true'
ControlBackground='#efeff2'
ControlText='#1e1e1e'
GridLines='#f0f0f0'
LineNumbersText='#777777'
HighlightBackground='#3399ff'
HighlightInactiveBackground='#cccedb'
HighlightInactiveText='#1e1e1e'
HighlightText='#ffffff'
MenuBackground='#e7e8ec'
TabText='#444444'
WindowBackground='#f6f6f6'
WindowText='#1e1e1e' />"));
}
}
}
|
9411d86bfdbedbf5f0a3f1a896d1540889fd3f88
|
C#
|
Albawab/MyWork
|
/WebSocketGameOX/GameOX/Protocol/EventHelper.cs
| 2.890625
| 3
|
// <copyright file="EventHelper.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace HenE.WebSocketExample.Shared.Protocol
{
using System;
using System.Text;
using HenE.Abdul.GameOX;
/// <summary>
/// Helper de events.
/// </summary>
public static class EventHelper
{
/// <summary>
/// terug geven als de spel is gestart.
/// </summary>
/// <param name="game">huidige game.</param>
/// <returns>De message die naar de client gaat als string. De namen van de spelers en de dimension.</returns>
public static string CreateSpelgestartEvent(GameOX game)
{
// wat ga ik terug geven?
// het commando en de lijste met spelers die meedoen, & gescheiden
StringBuilder spelersnamen = new StringBuilder();
foreach (Speler speler in game.Spelers)
{
if (game.FindSpelerByNaam(speler) == speler.Naam)
{
speler.Naam = speler.Naam + 1;
}
break;
}
foreach (var speler in game.Spelers)
{
if (spelersnamen.Length == 0)
{
spelersnamen.AppendFormat("{0}", speler.Naam);
}
else
{
spelersnamen.AppendFormat("&{0}", speler.Naam);
spelersnamen.AppendFormat("&{0}", speler.Dimension);
}
}
return string.Format("{0}{1}", CreateEvent(Events.SpelGestart), spelersnamen.ToString());
}
/// <summary>
/// De event komt naar hier toe als string .
/// Deze method gaat de string omzetten.
/// </summary>
/// <param name="events">De event als string.</param>
/// <returns>De Event.</returns>
public static Events CreateEenEvent(string events)
{
if (Enum.TryParse(events, true, out Events e))
{
if (Enum.IsDefined(typeof(Events), events))
{
return e;
}
}
return Events.NotDefined;
}
/// <summary>
/// Deze Method Created een Wacht Lijst van die speler die open zijn.
/// </summary>
/// <returns>De Event als string.</returns>
public static string CreateWachtenOpEenAndereDeelnemenEvent()
{
return CreateEvent(Events.WachtenOpAndereDeelnemer);
}
/// <summary>
/// Omzetten de even tot string.
/// </summary>
/// <param name="event">De event.</param>
/// <returns>Event als string.</returns>
public static string CreateEvents(Events @event)
{
return CreateEvent(@event);
}
/// <summary>
/// Als er een error is.
/// </summary>
/// <param name="exp">Exception.</param>
/// <returns>Event als string.</returns>
public static string CreateErrorEvent(Exception exp)
{
return string.Format("{0}{1}", CreateEvent(Events.Error), exp.Message);
}
/// <summary>
/// Verdeelt de message die vanuit de speler komt .
/// De eerste deel is de Protocol als string.
/// </summary>
/// <param name="mess">De message.</param>
/// <param name="eventsParams">De rest van de message.</param>
/// <returns>Event.</returns>
public static Events SplitEventAndParamsFromMessage(string mess, out string eventsParams)
{
eventsParams = string.Empty;
// Split de string voor # en na
string[] opgeknipt = mess.Split(new char[] { '#' });
// controleer of er wel een # aanwezig is
if (opgeknipt.Length == 0)
{
throw new ArgumentOutOfRangeException("message bevat geen #.");
}
// wij hebben array met array[0] en array[1]
// als het goorter is dan array[1] dan doe het maar bij array[1]
if (opgeknipt.Length > 1)
{
eventsParams = opgeknipt[1];
}
// probeer dan de eerste om te zetten naar een commandos
Events result = Events.NotDefined;
// Omzetten de string to enum
if (Enum.TryParse(opgeknipt[0], true, out result))
{
if (Enum.IsDefined(typeof(Events), result))
{
return result;
}
}
// niet gevonden, dus info was fout
throw new NotImplementedException();
}
private static string CreateEvent(Events e)
{
switch (e)
{
case Events.SpelGestart:
return "SpelGestart#";
case Events.SpelerGestart:
return "SpelerGestart#";
case Events.WachtenOpAndereDeelnemer:
return "WachtenOpAndereDeelnemer#";
case Events.YourTurn:
return "YourTurn#";
case Events.Winnaar:
return "Winnaar#";
case Events.NieuwRondje:
return "NieuwRondje#";
case Events.StartNieuwRond:
return "StartNieuwRond#";
case Events.IsGewonnen:
return "IsGewonnen#";
case Events.HetIsBezit:
return "HetIsBezit#";
case Events.BordIsVol:
return "BordIsVol#";
case Events.NieuwSpel:
return "NieuwSpel#";
case Events.NiemandGewonnen:
return "NiemandGewonnen#";
case Events.SpelGeannuleerd:
return "SpelGeannuleerd#";
default:
throw new NotImplementedException();
}
}
}
}
|
c42134a5de170443b968261d668352a7a980d315
|
C#
|
oriolrivera/ejercicios-programacion-3
|
/calculadora c saharp/calculadora c saharp/Form1.cs
| 2.78125
| 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;
namespace calculadora_c_saharp
{
public partial class Form1 : Form
{
double dato1;
double dato2;
double result;
string operador;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btn0_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + "0";
}
private void btn1_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + "1";
}
private void btn2_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + "2";
}
private void btn3_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + "3";
}
private void btn4_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + "4";
}
private void btn5_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + "5";
}
private void btn6_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + "6";
}
private void btn7_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + "7";
}
private void btn8_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + "8";
}
private void btn9_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + "9";
}
private void btnpunto_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + ".";
}
private void btnsumar_Click(object sender, EventArgs e)
{
operador = " +";
dato1 = double.Parse(textBox1.Text);
textBox1.Clear();
}
private void btnrestar_Click(object sender, EventArgs e)
{
operador = " -";
dato1 = double.Parse(textBox1.Text);
textBox1.Clear();
}
private void btnmultiplicar_Click(object sender, EventArgs e)
{
operador = " *";
dato1 = double.Parse(textBox1.Text);
textBox1.Clear();
}
private void btndvd_Click(object sender, EventArgs e)
{
operador = " /";
dato1 = double.Parse(textBox1.Text);
textBox1.Clear();
}
private void btnigual_Click(object sender, EventArgs e)
{
dato2 = double.Parse(textBox1.Text);
switch (operador)
{
case " +":
result = dato1 + dato2;
textBox1.Text = result.ToString();
break;
case " -":
result = dato1 - dato2;
textBox1.Text = result.ToString();
break;
case " *":
result = dato1 * dato2;
textBox1.Text = result.ToString();
break;
case " /":
result = dato1 / dato2;
textBox1.Text = result.ToString();
break;
}
}
private void BTNLIMPIAR_Click(object sender, EventArgs e)
{
textBox1.Clear();
}
private void btnraiz_Click(object sender, EventArgs e)
{
operador = " raiz";
dato1 = double.Parse(textBox1.Text);
result = dato1;
textBox1.Text = Math.Sqrt(dato1).ToString();
}
}
}
|
b77dd32988ab4cc3cc027757dad5d9273372d758
|
C#
|
MR-Amoori/Contacts
|
/ContactsConnectionSQL/ContactsConnectionSQL/Services/ContactsRepository.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace ContactsConnectionSQL
{
class ContactsRepository : IContactsRepository
{
private string Connectionstring = "Data Source=.;Initial Catalog=contacts;Integrated Security=true";
/// <summary>
/// ///////////
/// </summary>
/// <returns></returns>
public System.Data.DataTable selectall()
{
string query = "Select * From contacts_tb";
SqlConnection Connection = new SqlConnection(Connectionstring);
SqlDataAdapter Adapter = new SqlDataAdapter(query, Connection);
DataTable Data = new DataTable();
Adapter.Fill(Data);
return Data;
}
/// <summary>
/// ///////////
/// </summary>
/// <param name="_ID"></param>
/// <returns></returns>
public System.Data.DataTable selectrow(int _ID)
{
string query = "Select * From contacts_tb where _ID=" + _ID;
SqlConnection Connection = new SqlConnection(Connectionstring);
SqlDataAdapter Adapter = new SqlDataAdapter(query, Connection);
DataTable Data = new DataTable();
Adapter.Fill(Data);
return Data;
}
/// <summary>
/// //////////////
/// </summary>
/// <param name="name"></param>
/// <param name="family"></param>
/// <param name="numberphone"></param>
/// <param name="email"></param>
/// <param name="age"></param>
/// <param name="addresss"></param>
/// <returns></returns>
public bool insetr(string name, string family, string numberphone, string email, int age, string addresss)
{
SqlConnection connection = new SqlConnection(Connectionstring);
try
{
string query = "Insert Into contacts_tb (name,family,numberphone,email,age,addresss) values (@name,@family,@numberphone,@email,@age,@addresss)";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@name", name);
command.Parameters.AddWithValue("@family", family);
command.Parameters.AddWithValue("@numberphone", numberphone);
command.Parameters.AddWithValue("@email", email);
command.Parameters.AddWithValue("@age", age);
command.Parameters.AddWithValue("@addresss", addresss);
connection.Open();
command.ExecuteNonQuery();
return true;
}
catch
{
return false;
}
finally
{
connection.Close();
}
}
/// <summary>
/// ///////////////
/// </summary>
/// <param name="_ID"></param>
/// <param name="name"></param>
/// <param name="family"></param>
/// <param name="numberphone"></param>
/// <param name="email"></param>
/// <param name="age"></param>
/// <param name="addresss"></param>
/// <returns></returns>
public bool update(int _ID, string name, string family, string numberphone, string email, int age, string addresss)
{
SqlConnection connection = new SqlConnection(Connectionstring);
try
{
string query = "update contacts_tb set name=@name,family=@family,numberphone=@numberphone,email=@email,age=@age,addresss=@addresss where @_ID=_ID";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@name", name);
command.Parameters.AddWithValue("@family", family);
command.Parameters.AddWithValue("@numberphone", numberphone);
command.Parameters.AddWithValue("@email", email);
command.Parameters.AddWithValue("@age", age);
command.Parameters.AddWithValue("@addresss", addresss);
command.Parameters.AddWithValue("@_ID", _ID);
connection.Open();
command.ExecuteNonQuery();
return true;
}
catch
{
return false;
}
finally
{
connection.Close();
}
}
/// <summary>
/// /////////////
/// </summary>
/// <param name="_ID"></param>
/// <returns></returns>
public bool delete(int _ID)
{
SqlConnection connection = new SqlConnection(Connectionstring);
try
{
string query = "delete contacts_tb where _ID= @_ID";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@_ID", _ID);
connection.Open();
command.ExecuteNonQuery();
return true;
}
catch
{
return false;
}
finally
{
connection.Close();
}
}
public DataTable search(string parameter)
{
string query = "Select * From contacts_tb where name like @parameter or family like @parameter";
SqlConnection Connection = new SqlConnection(Connectionstring);
SqlDataAdapter Adapter = new SqlDataAdapter(query, Connection);
Adapter.SelectCommand.Parameters.AddWithValue("@parameter", "%" + parameter + "%");
DataTable Data = new DataTable();
Adapter.Fill(Data);
return Data;
}
public bool ChagePassword(string username, int password)
{
SqlConnection connection = new SqlConnection(Connectionstring);
string query = "update user_tb set username=@username,password=@password";
try
{
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@username", username);
command.Parameters.AddWithValue("@password", password);
connection.Open();
command.ExecuteNonQuery();
return true;
}
catch
{
return false;
}
finally
{
connection.Close();
}
}
}
}
|
7f64cc26340066c788690587fd2f4e6d900e1e0e
|
C#
|
sunc123/PatternLearn
|
/PatternLearn/Factory Method/IDCard.cs
| 3.234375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PatternLearn
{
class IDCard : Product
{
private string owner;
public string Owner { get { return owner; } }
public IDCard(string owner)
{
this.owner = owner;
this.id = NextNumber++;
Console.WriteLine("creat {0}'s IDCard[{1}].", owner, id);
}
public override void Use()
{
Console.WriteLine("used {0}'s IDCard[{1}].", owner, id);
}
}
}
|
4f8f7ae4500ec36f55aed8d4d701f3440cd439df
|
C#
|
ChaXiangMoKe/FastEngine
|
/unity/Assets/FastEngine/Scripts/Core/ResLoader/Res/RunAsync/RunAsync.cs
| 2.609375
| 3
|
using System.Collections.Generic;
namespace FastEngine.Core
{
/// <summary>
/// 资源异步管理洗头
/// </summary>
[MonoSingletonPath("FastEngine/ResLoader/RunAsync")]
public class RunAsync : MonoSingleton<RunAsync>, IRunAsync
{
/// <summary>
/// 同时运行异步最大数
/// </summary>
private const int MAXRunCount = 8;
/// <summary>
/// 当前运行异步数量
/// </summary>
private int _mRunCount;
/// <summary>
/// 异步链表
/// </summary>
/// <typeparam name="IRunAsyncObject"></typeparam>
/// <returns></returns>
private LinkedList<IRunAsyncObject> _mEnumerators = new LinkedList<IRunAsyncObject>();
/// <summary>
/// 添加异步
/// </summary>
/// <param name="enumerator"></param>
public void Push(IRunAsyncObject enumerator)
{
_mEnumerators.AddLast(enumerator);
TryRun();
}
/// <summary>
/// 尝试运行异步
/// </summary>
private void TryRun()
{
if (_mEnumerators.Count == 0) return;
if (_mRunCount >= MAXRunCount) return;
var enumerator = _mEnumerators.First.Value;
_mEnumerators.RemoveFirst();
++_mRunCount;
StartCoroutine(enumerator.AsyncRun(this));
}
/// <summary>
/// 尝试运行下一个异步
/// </summary>
private void TryNextRun()
{
--_mRunCount;
TryRun();
}
public void OnRunAsync()
{
TryNextRun();
}
}
}
|
2a25a86acb3d0964cb034c41b63385b915ed5dba
|
C#
|
HugoMautner/Databas-Uppgift
|
/DatabasUppgift/DatabasUppgift/SqliteDataAccess.cs
| 2.640625
| 3
|
using System;
using System.Configuration;
using System.Data;
using System.Data.SQLite;
using Dapper;
using System.Linq;
using System.Collections.Generic;
namespace DatabasUppgift
{
static class SqliteDataAccess
{
public static void SaveStudent(StudentModel student)
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
cnn.Execute("INSERT INTO students (first_name, last_name, adress, phone_number, e_mail) " +
"VALUES (@first_name, @last_name, @adress, @phone_number, @e_mail)", student);
}
}
public static void SaveGuardian(GuardianModel guardian)
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
cnn.Execute("INSERT INTO guardians (first_name, last_name, adress, phone_number, e_mail) " +
"VALUES (@first_name, @last_name, @adress, @phone_number, @e_mail)", guardian);
}
}
public static void SaveRegistration(StudentModel student)
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
cnn.Execute("INSERT INTO registration (reg_number, student_id, guardian_id) " +
"VALUES (@reg_number, @student_id, @guardian_id)", student);
}
}
public static void SaveTeacher(TeacherModel teacher)
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
cnn.Execute("INSERT INTO teachers (first_name, last_name, adress, phone_number, e_mail) " +
"VALUES (@first_name, @last_name, @adress, @phone_number, @e_mail)", teacher);
}
}
public static void SaveClass(ClassModel c)
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
cnn.Execute("INSERT INTO classes (name, teacher_id) " +
"VALUES (@name, @teacher_id)", c);
}
}
public static void SaveCourse(CourseModel c)
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
cnn.Execute("INSERT INTO courses (name, teacher_id) " +
"VALUES (@name, @teacher_id)", c);
}
}
public static void RemoveStudent(int id)
{
StudentModel sm = GetStudent(id);
RemoveGuardianRegistration(sm);
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
cnn.Execute("DELETE FROM students " +
"WHERE id = '" + id + "'");
}
}
public static void RemoveGuardian(int id)
{
GuardianModel gm = GetGuardian(id);
RemoveGuardianRegistration(gm);
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
cnn.Execute("DELETE FROM guardians " +
"WHERE id = '" + gm.id + "'");
}
}
public static void RemoveClass(string name)
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
cnn.Execute("DELETE FROM classes " +
"WHERE name = '" + name + "'");
}
}
public static void RemoveCourse(string name)
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
cnn.Execute("DELETE FROM courses " +
"WHERE name = '" + name + "'");
}
}
public static void ChangeStudent(StudentModel student)
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
cnn.Execute("UPDATE students " +
"SET first_name = '" + student.first_name + "', last_name = '" + student.last_name + "', adress = '" + student.adress + "', phone_number = '" + student.phone_number + "', e_mail = '" + student.e_mail + "'"
+ "WHERE id = " + student.id);
}
}
public static void ChangeGuardian(GuardianModel guardian)
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
cnn.Execute("UPDATE guardians " +
"SET first_name = '" + guardian.first_name + "', last_name = '" + guardian.last_name + "', adress = '" + guardian.adress + "', phone_number = '" + guardian.phone_number + "', e_mail = '" + guardian.e_mail + "'"
+ "WHERE id = " + guardian.id);
}
}
public static List<StudentModel> LoadStudents()
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
var result = cnn.Query<StudentModel>(
"SELECT * FROM students", new DynamicParameters());
return result.ToList();
}
}
public static List<GuardianModel> LoadGuardians()
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
var result = cnn.Query<GuardianModel>(
"SELECT * FROM guardians", new DynamicParameters());
return result.ToList();
}
}
public static List<ClassModel> LoadClasses()
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
var result = cnn.Query<ClassModel>(
"SELECT * FROM classes", new DynamicParameters());
return result.ToList();
}
}
public static List<CourseModel> LoadCourses()
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
var result = cnn.Query<CourseModel>(
"SELECT * FROM courses", new DynamicParameters());
return result.ToList();
}
}
public static List<TeacherModel> LoadTeachers()
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
var result = cnn.Query<TeacherModel>(
"SELECT * FROM teachers", new DynamicParameters());
return result.ToList();
}
}
public static void SaveGuardianRegistration(GuardianRegistration gr)
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
cnn.Execute("INSERT INTO registrations (student_id, guardian_id) " +
"VALUES (@student_id, @guardian_id)", gr);
}
}
private static void RemoveGuardianRegistration(GuardianModel gm)
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
cnn.Execute("DELETE FROM registrations " +
"WHERE guardian_id = '" + gm.id + "'");
}
}
private static void RemoveGuardianRegistration(StudentModel sm)
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
cnn.Execute("DELETE FROM registrations " +
"WHERE student_id = '" + sm.id + "'");
}
}
public static List<GuardianModel> GetGuardianRegistration(StudentModel sm)
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
var result = cnn.Query<GuardianModel>(
"SELECT guardians.* " +
"FROM guardians " +
"INNER JOIN registrations " +
"ON guardians.id = registrations.guardian_id " +
"WHERE registrations.student_id = '" + sm.id + "'", new DynamicParameters());
return result.ToList();;
}
}
public static List<GuardianModel> LoadGuardans()
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
var result = cnn.Query<GuardianModel>(
"SELECT * FROM guardians", new DynamicParameters());
return result.ToList();
}
}
private static GuardianModel GetGuardian(int id)
{
foreach (GuardianModel gm in LoadGuardians())
{
if (gm.id == id)
{
return gm;
}
}
return null;
}
private static StudentModel GetStudent(int id)
{
foreach (StudentModel sm in LoadStudents())
{
if (sm.id == id)
{
return sm;
}
}
return null;
}
private static string LoadConnectionString(string id = "Default")
{
return ConfigurationManager.ConnectionStrings[id].ConnectionString;
}
}
}
|
e49cfec1d979d4c4bae6f09cb37b19c7e634b559
|
C#
|
sebahomsi/nutricion
|
/Servicio/Objetivo/ObjetivoServicio.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infraestructura.Contexto;
using Servicio.Interface.Objetivo;
namespace Servicio.Objetivo
{
public class ObjetivoServicio : ServicioBase, IObjetivoServicio
{
public async Task Add(ObjetivoDto dto)
{
var objetivo = new Dominio.Entidades.Objetivo()
{
Descripcion = dto.Descripcion,
PacienteId = dto.PacienteId
};
Context.Objetivos.Add(objetivo);
await Context.SaveChangesAsync();
}
public async Task Update(ObjetivoDto dto)
{
var objetivo = Context.Objetivos.FirstOrDefault(x => x.Id == dto.Id);
objetivo.Descripcion = dto.Descripcion;
await Context.SaveChangesAsync();
}
public async Task<ObjetivoDto> GetByPacienteId(long id)
{
var objetivo = await Context.Objetivos.FirstOrDefaultAsync(x => x.PacienteId == id);
if (objetivo == null) return new ObjetivoDto()
{
Descripcion = $"OBJETIVOS DEL TRATAMIENTO\n\t" +
"Mejorar algunos hábitos específicos en pos de una alimentación suficiente, completa, armónica y adecuada. \n\t" +
"Normalizar los valores de IMC. Reducción de peso en forma paulatina y saludable a expensas del tejido graso.\n\t" +
"Aumento de peso de forma paulatina y saludable a expensas de tejido muscular.\n\t" +
"Optimizar composición corporal\n\t" +
"Aumentar ingesta de ácidos grasos poliinsaturados y monoinsaturados(omega 3, 6 y 9); reducir ingesta de ácidos grasos saturados y colesterol.\n\t" +
"Aumentar ingesta de fibra de forma paulatina. \n\t" +
"Disminuir circunferencia de cintura para reducir riesgo cardiometabólico.\n\t" +
"Aumentar niveles de fuerza.\n\t" +
"Mejorar rendimiento físico.",
PacienteId = id,
Id = 0
};
return new ObjetivoDto()
{
Descripcion = objetivo.Descripcion,
Id = objetivo.Id,
PacienteId = objetivo.PacienteId
};
}
}
}
|
ed7ced37893c175925ee0ba6a8c1a05fafcc3a54
|
C#
|
shendongnian/download4
|
/first_version_download2/518168-47840500-162897014-2.cs
| 3.234375
| 3
|
public class Rectangle
{
public int length { get; set; }
public int breadth { get; set; }
public int area()
{
return length * breadth;
}
}
public class Square : Rectangle
{
}
|
131b8da1c228baccf02557f6ff93ba13d7907a3a
|
C#
|
HTD/Woof
|
/Packages/Woof.Console/ConsoleTools/ConsoleTheme.cs
| 2.859375
| 3
|
namespace Woof.ConsoleTools;
/// <summary>
/// Defines console color theme assigning standard console colors to common text elements in hexadecimal format.
/// </summary>
public class ConsoleTheme {
/// <summary>
/// Gets or sets the default text color.
/// </summary>
public string DefaultText { get; set; } = "ccc";
/// <summary>
/// Gets or sets the header text color.
/// </summary>
public string HeaderText { get; set; } = "777";
/// <summary>
/// Gets or sets the bullet symbol color.
/// </summary>
public string BulletSymbol { get; set; } = "ff0";
/// <summary>
/// Gets or sets the bullet text color.
/// </summary>
public string BulletText { get; set; } = "ccc";
/// <summary>
/// Gets or sets the bullet symbol color for <see cref="ConsoleEx.Start(string)"/>.
/// </summary>
public string StartSymbol { get; set; } = "777";
/// <summary>
/// Gets or sets the bullet text color for <see cref="ConsoleEx.Start(string)"/>.
/// </summary>
public string StartText { get; set; } = "ccc";
/// <summary>
/// Gets or sets the color for complete label brackets.
/// </summary>
public string CompleteBrackets { get; set; } = "777";
/// <summary>
/// Gets or sets the color for complete label text with success status.
/// </summary>
public string CompleteLabelSuccess { get; set; } = "0f0";
/// <summary>
/// Gets or sets the color for complete label text with warning status.
/// </summary>
public string CompleteLabelWarning { get; set; } = "ff0";
/// <summary>
/// Gets or sets the color for complete label text with error status.
/// </summary>
public string CompleteLabelFail { get; set; } = "700";
/// <summary>
/// Gets or sets the color for complete message text.
/// </summary>
public string CompleteMessage { get; set; } = "777";
/// <summary>
/// Gets or sets the separator line color.
/// </summary>
public string SeparatorLine { get; set; } = "ccc";
/// <summary>
/// Gets or sets the assembly header title color.
/// </summary>
public string Title { get; set; } = "fff";
/// <summary>
/// Gets or sets the assembly header copyright color.
/// </summary>
public string Copyright { get; set; } = "fff";
/// <summary>
/// Gets or sets the assembly header description color.
/// </summary>
public string Description { get; set; } = "ccc";
/// <summary>
/// Gets or sets the timestamp text color.
/// </summary>
public string TimeStampText { get; set; } = "00f";
/// <summary>
/// Gets or sets the debug message text color.
/// </summary>
public string DebugText { get; set; } = "777";
/// <summary>
/// Gets or set the info label text color.
/// </summary>
public string InfoLabel { get; set; } = "fff";
/// <summary>
/// Gets or sets the warning label text color.
/// </summary>
public string WarningLabel { get; set; } = "770";
/// <summary>
/// Gets or sets the error label color.
/// </summary>
public string ErrorLabel { get; set; } = "700";
/// <summary>
/// Gets or sets the error value color.
/// </summary>
public string ErrorValue { get; set; } = "f00";
/// <summary>
/// Gets or sets the correct value color.
/// </summary>
public string CorrectValue { get; set; } = "0f0";
/// <summary>
/// Gets or sets the color for hexadecimal dump offset.
/// </summary>
public string HexOffset { get; set; } = "777";
/// <summary>
/// Gets or sets the color for hexadecimal dump first separator symbol.
/// </summary>
public string HexS1 { get; set; } = "0ff";
/// <summary>
/// Gets or sets the color for hexadecimal dump data.
/// </summary>
public string HexData { get; set; } = "077";
/// <summary>
/// Gets or sets the color for hexadecimal dump second separator symbol.
/// </summary>
public string HexS2 { get; set; } = "f00";
/// <summary>
/// Gets or sets the color for hexadecimal dump ASCII view.
/// </summary>
public string HexAscii { get; set; } = "777";
}
|
f6c75a7c191e724db2a64d5217f903d7f0c793df
|
C#
|
GhBogdan97/collective-project-backend
|
/collective-project-backend/Controllers/StatisticsController.cs
| 2.59375
| 3
|
using API.Mappers;
using API.ViewModels;
using DatabaseAccess.DTOs;
using DatabaseAccess.Models;
using Microsoft.AspNetCore.Mvc;
using Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace API.Controllers
{
[ApiController]
public class StatisticsController: ControllerBase
{
private readonly StatisticsService _statisticsService;
private readonly InternshipService _internshipService;
private readonly StudentService _studentService;
private readonly CompanyService _companyService;
private readonly RatingService _ratingService;
public StatisticsController(StatisticsService statisticsService,
InternshipService internshipService,
StudentService studentService,
CompanyService companyService,
RatingService ratingService)
{
_statisticsService = statisticsService;
_internshipService = internshipService;
_studentService = studentService;
_companyService= companyService;
_ratingService = ratingService;
}
[HttpGet]
[Route("statistics/evolution")]
public ActionResult<IList<ApplicationsPerYearViewModel>> GetApplicationsPerYear()
{
var userID = User.GetUserId();
if (userID == string.Empty)
return BadRequest("Compania nu a fost recunoscuta");
var applicationsPerYear = new List<ApplicationsPerYearViewModel>();
IList<Internship> internships = null;
try
{
var id = _companyService.GetCompanyIdForUser(userID);
internships = _internshipService.GetInternshipsForCompany(id);
var years = internships.Select(i => i.Start.Year).Distinct().ToList();
foreach (var year in years)
{
int nrApplications = _statisticsService.GetNrApplicationsPerYear(id, year);
ApplicationsPerYearViewModel viewModel = new ApplicationsPerYearViewModel()
{
Year = year,
NumberOfStudents = nrApplications
};
applicationsPerYear.Add(viewModel);
};
return Ok(applicationsPerYear);
}
catch(Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpGet]
[Route("statistics/general")]
public ActionResult<GeneralStatisticsViewModel> GetGeneralStatistics()
{
var generalStatisticsViewModel = new GeneralStatisticsViewModel()
{
NumberOfCompanies = _companyService.CountCompanies(),
NumberOfStudents = _studentService.CountStudents(),
NumberOfInternships = _internshipService.CountInternships()
};
return Ok(generalStatisticsViewModel);
}
[HttpGet]
[Route("statistics/ratings/{companyId}")]
public ActionResult<RatingDTO> GetAverageRatingsCompany(int companyId)
{
RatingDTO ratingDTO = _ratingService.getAverageRatings(companyId);
return Ok(ratingDTO);
}
[HttpGet]
[Route("statistics/piechart/{companyId}")]
public ActionResult<PiechartDTO> GetStatisticsPiechart(int companyId)
{
return Ok(_ratingService.getStatisticsPiechart(companyId));
}
[HttpGet]
[Route("statistics/ratings")]
public ActionResult<RatingDTO> GetAverageRatingsForCurrentCompany()
{
var companyUserId = User.GetUserId();
var companyId= _companyService.GetCompanyIdForUser(companyUserId);
RatingDTO ratingDTO = _ratingService.getAverageRatings(companyId);
return Ok(ratingDTO);
}
[HttpGet]
[Route("statistics/piechart")]
public ActionResult<PiechartDTO> GetStatisticsForCurrentPiechart()
{
var companyUserId = User.GetUserId();
var companyId = _companyService.GetCompanyIdForUser(companyUserId);
return Ok(_ratingService.getStatisticsPiechart(companyId));
}
}
}
|
e712784c0d6ae24950a1d1fafe34dbfa18954d75
|
C#
|
VB6Hobbyst7/SmoothGL
|
/SmoothGL/Graphics/Geometry/VertexElementDouble.cs
| 3.09375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
namespace SmoothGL.Graphics
{
/// <summary>
/// Describes a vertex element as a vector of double precision floating point numbers.
/// </summary>
public class VertexElementDouble : IVertexElement
{
private int _location;
private int _numberOfComponents;
/// <summary>
/// Creates a new vertex element description for a vector of doubles.
/// </summary>
/// <param name="location">Location at which this vertex element is accessible in the vertex shader.</param>
/// <param name="numberOfComponents">Number of components of the described vector in the range between one and four.</param>
public VertexElementDouble(int location, int numberOfComponents)
{
if (numberOfComponents < 1 || numberOfComponents > 4)
throw new ArgumentOutOfRangeException("numberOfComponents", "The number of components must lie between one and four.");
_location = location;
_numberOfComponents = numberOfComponents;
}
public void ApplyDefinition(int strideSize, int offset, int divisor)
{
GL.EnableVertexAttribArray(_location);
GL.VertexAttribLPointer(_location, _numberOfComponents, VertexAttribDoubleType.Double, strideSize, new IntPtr(offset));
GL.VertexAttribDivisor(_location, divisor);
}
public int Size
{
get
{
return _numberOfComponents * 8;
}
}
}
}
|
bbd2240657bdfe513077dee0b23962f37123ff56
|
C#
|
Cpp-dwarf/Unity-Proj
|
/Assets/FluentDialogue/Example/Conversation14.cs
| 2.5625
| 3
|
using UnityEngine;
using Fluent;
/// <summary>
/// This example shows that the conversations can be paused until something happens
/// </summary>
public class Conversation14 : MyFluentDialogue
{
public GameObject blueGuy2;
public GameObject player;
public bool HasVisitedRed { get; set; }
bool cameBackForPrize { get; set; }
public override void OnStart()
{
HasVisitedRed = false;
cameBackForPrize = false;
}
public override FluentNode Create()
{
return
Yell("Stand next to that red guy") *
ContinueWhen(() => HasVisitedRed) *
Yell(blueGuy2, "Well done!") *
Yell(blueGuy2, "Go back for your prize!") *
ContinueWhen(() => cameBackForPrize) *
Yell(player, "Prize please!") *
Yell("It was stolen!") *
Yell(player, ";-(");
}
void OnTriggerEnter(Collider collider)
{
if (HasVisitedRed)
cameBackForPrize = true;
}
}
|
b6e509b98f159767ca3d4cdbe22f55b456c3adee
|
C#
|
pepelefevre/Problems
|
/Island/Island/IslandSolver.cs
| 3.8125
| 4
|
using System;
namespace Island
{
class IslandSolver
{
// Array of 0s and 1s to solve
private int[,] ocean;
// Array of whether the 1 has been visited before
private bool[,] visited;
public IslandSolver(int size)
{
ocean = randomArray(size);
visited = new bool[size, size];
}
int[,] randomArray(int size)
{
// Initialize Random Generator
Random rnd = new Random();
int[,] array = new int[size, size];
for (int i = 0; i < size; ++i)
{
for (int j = 0; j < size; ++j)
{
// Randomly assign 0 or 1 50% chance.
if (rnd.Next(0, 3) == 1)
{
array[i, j] = 1;
}
else
{
array[i, j] = 0;
}
}
}
return array;
}
public int[,] getOcean()
{
return ocean;
}
public int solve()
{
int count = 0;
// Traverse the ocean until we find a 1
for (int i = 0; i < ocean.GetLength(0); ++i)
{
for (int j = 0; j < ocean.GetLength(1); ++j)
{
if (ocean[i,j] == 1 && !visited[i,j])
{
traverseIsland(i, j);
count++;
}
}
}
return count;
}
void traverseIsland(int i, int j)
{
if (canVisit(i, j))
{
visited[i, j] = true;
traverseIsland(i - 1, j - 1);
traverseIsland(i - 1, j);
traverseIsland(i - 1, j + 1);
traverseIsland(i, j - 1);
traverseIsland(i, j + 1);
traverseIsland(i + 1, j + 1);
traverseIsland(i + 1, j);
traverseIsland(i + 1, j - 1);
}
}
bool canVisit(int i, int j)
{
if (i >= ocean.GetLength(0) || i < 0)
{
return false;
}
if (j >= ocean.GetLength(1) || j < 0)
{
return false;
}
if (ocean[i,j] == 0)
{
return false;
}
if (visited[i,j])
{
return false;
}
return true;
}
}
}
|
5e0d057790e6f4771d271d2bafc137c306d0733c
|
C#
|
TameemShahid/CableManagementSystem
|
/CableMangementSystem/GenReport.cs
| 2.71875
| 3
|
using System;
using System.Diagnostics;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.Rendering;
using System.Collections.Generic;
namespace CableMangementSystem
{
static public class GenReport
{
public static void CreateDocumentHistory(string main,string sub,List<string> data)
{
Document document = new Document();
Section sec = document.AddSection();
document.UseCmykColor = true;
DefineStyles(document);
const bool unicode = false;
// creates main and sub heading
Heading(document, main, sub);
// create main table of the customer
CreateTableBilling(document, 8, data);
// render document for pdf
PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(unicode);
pdfRenderer.Document = document;
pdfRenderer.RenderDocument();
// save and start pdf file
const string fileName = "BillingHistory.pdf";
pdfRenderer.PdfDocument.Save(fileName);
Process.Start(fileName);
}
private static void CreateTableBilling(Document doc, int col, List<string> data)
{
Table table = new Table();
table.Borders.Width = 1.00;
float colWidth = 2.00f;
Column column = new Column();
AddColumn(table, column, col, colWidth);
string[] heading = { "HistoryId", "UserId", "Customer Name", "House No", "Payment", "Received By", "Month", "Status" };
Row addRow = table.AddRow();
FillRow(8, addRow, heading);
Queue<string> dataUserStack = new Queue<string>(data);
Row newRow;
Cell newCell;
string newData;
int rowNo = 0;
for (int i = 0; i < data.Count / heading.Length; i++)
{
newRow = table.AddRow();
for (int j = 0; j < data.Count && (dataUserStack.Count != 0); j++)
{
newCell = newRow.Cells[rowNo];
newData = dataUserStack.Dequeue();
newCell.AddParagraph(newData);
rowNo++;
if (rowNo == heading.Length)
rowNo = 0;
if (j == (heading.Length - 1))
break;
}
}
table.SetEdge(0, 0, 0, 0, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 1.5, Colors.Black);
table.Format.Alignment = ParagraphAlignment.Center;
doc.LastSection.Add(table);
}
public static void CreateDocumentInventory(string main, string sub, List<string> data)
{
Document document = new Document();
Section sec = document.AddSection();
document.UseCmykColor = true;
DefineStyles(document);
const bool unicode = false;
// creates main and sub heading
Heading(document, main, sub);
// create main table of the customer
CreateInventoryReport(document, 3, data,sec);
// render document for pdf
PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(unicode);
pdfRenderer.Document = document;
pdfRenderer.RenderDocument();
// save and start pdf file
const string fileName = "MonthlyInventoryReport.pdf";
pdfRenderer.PdfDocument.Save(fileName);
Process.Start(fileName);
}
private static void CreateInventoryReport(Document doc, int col, List<string> data,Section sec)
{
Table table = new Table();
table.Borders.Width = 1.00;
float colWidth = 2.00f;
Column column = new Column();
AddColumn(table, column, col, colWidth);
string[] heading = { "Item Number", "Item Name", "Quantity" };
Row addRow = table.AddRow();
FillRow(3, addRow, heading);
Queue<string> dataUserStack = new Queue<string>(data);
Row newRow;
Cell newCell;
string newData;
int rowNo = 0;
for (int i = 0; i < data.Count / heading.Length; i++)
{
newRow = table.AddRow();
for (int j = 0; j < data.Count && (dataUserStack.Count != 0); j++)
{
newCell = newRow.Cells[rowNo];
newData = dataUserStack.Dequeue();
newCell.AddParagraph(newData);
rowNo++;
if (rowNo == heading.Length)
rowNo = 0;
if (j == (heading.Length - 1))
break;
}
}
var tableW = Unit.FromCentimeter(2);
var leftIndentToCenterTable = (sec.PageSetup.PageWidth.Centimeter -
sec.PageSetup.LeftMargin.Centimeter -
sec.PageSetup.RightMargin.Centimeter -
tableW.Centimeter) / 2;
table.Rows.LeftIndent = Unit.FromCentimeter(leftIndentToCenterTable);
table.SetEdge(0, 0, 0, 0, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 1.5, Colors.Black);
doc.LastSection.Add(table);
}
public static void Heading(Document document, string main, string sub)
{
Paragraph paragraph = document.LastSection.AddParagraph(main, "Heading1");
paragraph.Format.Alignment = ParagraphAlignment.Center;
}
public static void DefineStyles(Document doc)
{
// main heading
Style style = doc.Styles["Normal"];
style = doc.Styles["Heading1"];
style.Font.Name = "Tahoma";
style.Font.Size = 24;
style.Font.Bold = true;
style.Font.Color = Colors.DarkBlue;
style.ParagraphFormat.PageBreakBefore = true;
style.ParagraphFormat.SpaceAfter = 6;
// sub heading
style = doc.Styles["Heading2"];
style.Font.Name = "Tahoma";
style.Font.Size = 14;
style.Font.Bold = true;
style.Font.Color = Colors.DarkBlue;
style.ParagraphFormat.PageBreakBefore = true;
style.ParagraphFormat.SpaceAfter = 6;
}
private static void AddColumn(Table table, Column column, int noOfcol,float colWidth)
{
for (int i = 0; i < noOfcol; i++)
{
column = table.AddColumn(Unit.FromCentimeter(colWidth));
column.Format.Alignment = ParagraphAlignment.Center;
}
}
private static void FillRow(int col, Row addRow, string[] heading)
{
Cell cell;
for (int i = 0; i < col; i++)
{
cell = addRow.Cells[i];
cell.AddParagraph(heading[i]);
}
}
}
}
|
5d27dfcdfe274b76ad13f3c19825fc55a66880ee
|
C#
|
gqy117/YoutubeBatchDownloader
|
/YoutubeBatchDownloader.Service/YoutubeHtmlParser/YoutubeHtmlParser.cs
| 2.53125
| 3
|
namespace YoutubeBatchDownloader.Service
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Practices.Unity;
using AngleSharp.Parser.Html;
using CsQuery;
using YoutubeBatchDownloader.Model;
public abstract class YoutubeHtmlParser
{
#region Properties
protected RegexHelper RegexHelper { get; set; }
protected IGenerator CurrentGenerator { get; set; }
protected HtmlParser HtmlParser { get; set; }
#endregion
#region Init
[InjectionMethod]
public virtual void Init(RegexHelper regexHelper, HtmlParser htmlParser)
{
this.RegexHelper = regexHelper;
this.HtmlParser = htmlParser;
}
#endregion
#region Convert
#region Convert
public virtual string Convert(string youtubeHtmlString)
{
var videoList = this.ConvertVideoList(youtubeHtmlString);
string vbsString = this.CurrentGenerator.Generate(videoList);
return vbsString;
}
public virtual string Convert(string youtubeHtmlString, int startPosition)
{
var videoList = this.ConvertVideoList(youtubeHtmlString);
string vbsString = this.CurrentGenerator.Generate(videoList, startPosition);
return vbsString;
}
#endregion
#endregion
protected IList<Video> ConvertVideoList(string youtubeHtml)
{
var videoList = this.ParseTable(youtubeHtml);
videoList = this.RegexHelper.RemoveInvalidCharacters(videoList);
return videoList;
}
private const string DATATITLE = "data-title";
private const string DATAVIDEO = "data-video-id";
protected abstract Video CreateSingleVideo();
protected IList<Video> ParseTable(string youtubeHtml)
{
IList<Video> listVideo = new List<Video>();
var dom = this.HtmlParser.Parse(youtubeHtml);
var allTrs = dom.QuerySelectorAll("tr");
foreach (var tr in allTrs)
{
var video = this.CreateSingleVideo();
video.Id = tr.Attributes.GetNamedItem(YoutubeHtmlParser.DATAVIDEO).Value;
video.Title = tr.Attributes.GetNamedItem(YoutubeHtmlParser.DATATITLE).Value;
listVideo.Add(video);
}
return listVideo;
}
}
}
|
badb58a25d2e466a9ed876b550b3ad3ea05c3a0e
|
C#
|
Softfire/softfire-monogame-libraries
|
/Softfire.MonoGame.NTWK/Services/Lidgren/LidgrenNetManager.cs
| 2.625
| 3
|
using System.Collections.Generic;
using System.Net;
using Microsoft.Xna.Framework;
using LidgrenNetPeerStatus = Lidgren.Network.NetPeerStatus;
namespace Softfire.MonoGame.NTWK.Services.Lidgren
{
public class LidgrenNetManager<T1, T2> where T1 : LidgrenClient
where T2 : LidgrenServer
{
/// <summary>
/// Clients.
/// </summary>
private Dictionary<string, T1> Clients { get; }
/// <summary>
/// Servers.
/// </summary>
private Dictionary<string, T2> Servers { get; }
/// <summary>
/// Lidgren Network Manager Constructor.
/// </summary>
protected LidgrenNetManager()
{
Clients = new Dictionary<string, T1>();
Servers = new Dictionary<string, T2>();
}
#region Core Server Commands
/// <summary>
/// Add Server.
/// </summary>
/// <param name="identifier">A unique identifier. Used to Get, Start and Shutdown the server. Intaken as a <see cref="string"/>.</param>
/// <param name="applicationIdentifier">Intakes a uniques string to identify the application. Used by clients and servers to connect. Default is Softfire.MonoGame.NTWK.</param>
/// <param name="ipAddress">Intakes an IPAddress that the client will bind to and listen to client responses.</param>
/// <param name="port">Intakes a port number, as an int, to bind to. Default is 16464.</param>
/// <returns>Returns a <see cref="bool"/> indicating whether the Server was added or not.</returns>
public bool AddServer(string identifier, string applicationIdentifier = null, IPAddress ipAddress = null, int port = 16464)
{
var result = false;
if (!Servers.ContainsKey(identifier))
{
Servers.Add(identifier, (T2)new LidgrenServer(applicationIdentifier, ipAddress, port));
result = true;
}
return result;
}
/// <summary>
/// Get Server.
/// </summary>
/// <param name="identifier">Intakes a unique identifier used to find the requested ser of Type T2.</param>
/// <returns>Returns an server of Type T2.</returns>
public T2 GetServer(string identifier)
{
T2 result = null;
if (Servers.ContainsKey(identifier))
{
result = Servers[identifier];
}
return result;
}
/// <summary>
/// Start Server.
/// </summary>
/// <param name="identifier">Intakes a unique identifier used to find the requested ser of Type T2.</param>
/// <returns>Returns a bool indicating whether the server was started successfully.</returns>
public bool StartServer(string identifier)
{
var result = false;
if (Servers.ContainsKey(identifier))
{
if (Servers[identifier].Status == LidgrenNetPeerStatus.NotRunning)
{
Servers[identifier].Start();
result = Servers[identifier].Status == LidgrenNetPeerStatus.Starting ||
Servers[identifier].Status == LidgrenNetPeerStatus.Running;
}
}
return result;
}
/// <summary>
/// Shutdown Server.
/// </summary>
/// <param name="identifier">Intakes a unique identifier used to find the requested ser of Type T2.</param>
/// <param name="shutdownMessage">Intakes a string to be used as the shutdown message that will be sent to the server's clients.</param>
/// <returns>Returns a bool indicating whether the server was shutdown successfully.</returns>
public bool ShutdownServer(string identifier, string shutdownMessage = "Shut down request registered.\nConnections will be terminated and socket(s) closed soon.")
{
var result = false;
if (Servers.ContainsKey(identifier))
{
if (Servers[identifier].Status == LidgrenNetPeerStatus.Running)
{
Servers[identifier].Shutdown(shutdownMessage);
result = Servers[identifier].Status == LidgrenNetPeerStatus.ShutdownRequested ||
Servers[identifier].Status == LidgrenNetPeerStatus.NotRunning;
}
}
return result;
}
/// <summary>
/// Remove Server.
/// </summary>
/// <param name="identifier">Intakes a unique identifier used to find the requested object of Type T2.</param>
/// <returns>Returns a bool indicating whether the object of Type T2 was removed.</returns>
public bool RemoveServer(string identifier)
{
var result = false;
if (Servers.ContainsKey(identifier))
{
if (Servers[identifier].Status == LidgrenNetPeerStatus.NotRunning)
{
result = Servers.Remove(identifier);
}
}
return result;
}
#endregion
#region Core Client Commands
/// <summary>
/// Add Client.
/// </summary>
/// <param name="identifier">A unique identifier. Used to Get, Start and Shutdown the client. Intaken as a <see cref="string"/>.</param>
/// <param name="applicationIdentifier">Intakes a uniques string to identify the application. Used by clients and servers to connect. Default is Softfire.MonoGame.NTWK.</param>
/// <param name="ipAddress">Intakes an IPAddress that the client will bind to and listen to client responses.</param>
/// <param name="port">Intakes a port number, as an int, to bind to. Default is 16462.</param>
/// <returns>Returns a <see cref="bool"/> indicating whether the Client was added or not.</returns>
public bool AddClient(string identifier, string applicationIdentifier = null, IPAddress ipAddress = null, int port = 16462)
{
var result = false;
if (!Clients.ContainsKey(identifier))
{
Clients.Add(identifier, (T1)new LidgrenClient(applicationIdentifier, ipAddress, port));
result = true;
}
return result;
}
/// <summary>
/// Get Client.
/// </summary>
/// <param name="identifier">Intakes a unique identifier used to find the requested ser of Type T1.</param>
/// <returns>Returns an server of Type T1.</returns>
public T1 GetClient(string identifier)
{
T1 result = null;
if (Clients.ContainsKey(identifier))
{
result = Clients[identifier];
}
return result;
}
/// <summary>
/// Start Client.
/// </summary>
/// <param name="identifier">Intakes a unique identifier used to find the requested ser of Type T1.</param>
/// <returns>Returns a bool indicating whether the client was started successfully.</returns>
public bool StartClient(string identifier)
{
var result = false;
if (Clients.ContainsKey(identifier))
{
if (Clients[identifier].Status == LidgrenNetPeerStatus.NotRunning)
{
Clients[identifier].Start();
result = Clients[identifier].Status == LidgrenNetPeerStatus.Starting ||
Clients[identifier].Status == LidgrenNetPeerStatus.Running;
}
}
return result;
}
/// <summary>
/// Shutdown Client.
/// </summary>
/// <param name="identifier">Intakes a unique identifier used to find the requested ser of Type T1.</param>
/// <param name="shutdownMessage">Intakes a string to be used as the shutdown message.</param>
/// <returns>Returns a bool indicating whether the client was shutdown successfully.</returns>
public bool ShutdownClient(string identifier, string shutdownMessage = "Shut down request registered.\nConnections will be terminated and socket(s) closed soon.")
{
var result = false;
if (Clients.ContainsKey(identifier))
{
if (Clients[identifier].Status == LidgrenNetPeerStatus.Running)
{
Clients[identifier].Shutdown(shutdownMessage);
result = Clients[identifier].Status == LidgrenNetPeerStatus.ShutdownRequested ||
Clients[identifier].Status == LidgrenNetPeerStatus.NotRunning;
}
}
return result;
}
/// <summary>
/// Remove Client.
/// </summary>
/// <param name="identifier">Intakes a unique identifier used to find the requested object of Type T1.</param>
/// <returns>Returns a bool indicating whether the object of Type T1 was removed.</returns>
public bool RemoveClient(string identifier)
{
var result = false;
if (Clients.ContainsKey(identifier))
{
if (Clients[identifier].Status == LidgrenNetPeerStatus.NotRunning)
{
result = Clients.Remove(identifier);
}
}
return result;
}
#endregion
/// <summary>
/// Network Manager Update Method.
/// </summary>
/// <param name="gameTime">Intakes MonoGame GameTime.</param>
public virtual void Update(GameTime gameTime)
{
// Update Client
foreach (var client in Clients)
{
if (client.Value.Status == LidgrenNetPeerStatus.Running)
{
client.Value.Update(gameTime);
}
}
// Update Servers
foreach (var server in Servers)
{
if (server.Value.Status == LidgrenNetPeerStatus.Running)
{
server.Value.Update(gameTime);
}
}
}
}
}
|
babfd2f125a5b04d8dbf32d2c22ab0ac8914008e
|
C#
|
dreamplayer-zhang/programingstudy
|
/RootTools_Vision/RemoteProcess/PipeClient.cs
| 2.578125
| 3
|
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
namespace RootTools_Vision
{
class PipeClient
{
public PipeClient(string pipeName)
{
this.pipeName = pipeName;
}
[DllImport("kernel32.dll", SetLastError = true)]
public static extern SafeFileHandle CreateFile(
String pipeName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplate);
public const uint GENERIC_READ = (0x80000000);
public const uint GENERIC_WRITE = (0x40000000);
public const uint OPEN_EXISTING = 3;
public const uint FILE_FLAG_OVERLAPPED = (0x40000000);
public delegate void MessageReceivedHandler(PipeProtocol protocol);
public event MessageReceivedHandler MessageReceived;
void _Dummy()
{
if (MessageReceived != null) MessageReceived(new PipeProtocol());
}
public const int BUFFER_SIZE = 4096;
string pipeName;
private FileStream stream;
private SafeFileHandle handle;
Thread readThread;
bool connected;
public bool Connected
{
get { return this.connected; }
}
public string PipeName
{
get { return this.pipeName; }
set { this.pipeName = value; }
}
/// <summary>
/// Connects to the server
/// </summary>
public void Connect()
{
this.handle =
CreateFile(
@"\\.\pipe\" + this.pipeName,
GENERIC_READ | GENERIC_WRITE,
0,
IntPtr.Zero,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
IntPtr.Zero);
//could not create handle - server probably not running
if (this.handle.IsInvalid)
return;
this.connected = true;
this.stream = new FileStream(this.handle, FileAccess.ReadWrite, BUFFER_SIZE, true);
//start listening for messages
this.readThread = new Thread(new ThreadStart(Read));
this.readThread.Start();
}
public void Send<T>(T obj)
{
byte[] bufferData = Tools.ObjectToByteArray<T>(obj);
byte[] bufferSize = BitConverter.GetBytes(bufferData.Length);
this.stream.Write(bufferSize, 0, sizeof(int));
this.stream.Write(bufferData, 0, bufferData.Length);
this.stream.Flush();
}
public void Send(string msg)
{
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] bufferData = encoder.GetBytes(msg);
byte[] bufferSize = BitConverter.GetBytes(bufferData.Length);
this.stream.Write(bufferSize, 0, sizeof(int));
this.stream.Write(bufferData, 0, bufferData.Length);
this.stream.Flush();
}
/// <summary>
/// Sends a message to the server
/// </summary>
/// <param name="message"></param>
public void SendMessage(string message)
{
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] messageBuffer = encoder.GetBytes(message);
this.stream.Write(messageBuffer, 0, messageBuffer.Length);
this.stream.Flush();
}
private int ConvertBytesToInt(byte[] buffer)
{
byte[] temp = new byte[sizeof(int)];
Buffer.BlockCopy(buffer, 0, temp, 0, sizeof(int));
return (int)BitConverter.ToInt32(temp, 0);
}
public void Read()
{
byte[] bufferType = new byte[sizeof(PIPE_MESSAGE_TYPE)];
bool isExit = false;
int readBytes = 0;
while (isExit == false)
{
readBytes = stream.Read(bufferType, 0, bufferType.Length);
PIPE_MESSAGE_TYPE type = (PIPE_MESSAGE_TYPE)BitConverter.ToInt32(bufferType, 0);
object data = null;
string dataType = "";
switch (type)
{
case PIPE_MESSAGE_TYPE.Message:
case PIPE_MESSAGE_TYPE.Command:
case PIPE_MESSAGE_TYPE.Event:
case PIPE_MESSAGE_TYPE.Data:
{
byte[] bufferDataTypeSize = new byte[sizeof(int)];
readBytes = stream.Read(bufferDataTypeSize, 0, sizeof(int));
int dataTypeSize = BitConverter.ToInt32(bufferDataTypeSize, 0);
byte[] bufferDataType = new byte[dataTypeSize];
readBytes = stream.Read(bufferDataType, 0, dataTypeSize);
dataType = Tools.ByteArrayToObject<string>(bufferDataType);
byte[] bufferDataSize = new byte[sizeof(int)];
readBytes = stream.Read(bufferDataSize, 0, sizeof(int));
int dataSize = BitConverter.ToInt32(bufferDataSize, 0);
byte[] bufferData = new byte[dataSize];
readBytes = stream.Read(bufferData, 0, dataSize);
data = Tools.ByteArrayToObject(bufferData);
}
break;
default:
Debug.WriteLine("No Defined Message");
stream.Flush();
isExit = true;
break;
}
//if (MessageReceived != null)
//MessageReceived(new PipeProtocol(type, dataType, data));
stream.Flush();
}
stream.Close();
this.handle.Close();
}
public void Send(PipeProtocol protocol)
{
byte[] bufferType = BitConverter.GetBytes((int)protocol.msgType);
stream.Write(bufferType, 0, bufferType.Length);
switch (protocol.msgType)
{
case PIPE_MESSAGE_TYPE.Message:
case PIPE_MESSAGE_TYPE.Command:
case PIPE_MESSAGE_TYPE.Event:
case PIPE_MESSAGE_TYPE.Data:
{
byte[] bufferDataType = Tools.ObejctToByteArray(protocol.dataType);
byte[] bufferDataTypeSize = Tools.ObejctToByteArray(bufferDataType.Length);
byte[] bufferData = Tools.ObjectToByteArray(protocol.data);
byte[] bufferDataSize = BitConverter.GetBytes(bufferData.Length);
stream.Write(bufferDataTypeSize, 0, sizeof(int));
stream.Write(bufferDataType, 0, bufferDataType.Length);
stream.Write(bufferDataSize, 0, sizeof(int));
stream.Write(bufferData, 0, bufferData.Length);
}
break;
}
stream.Flush();
}
}
}
|
4f73f84e5a6b4ba2bb16442ec55a00c961e330da
|
C#
|
Vladyslav-lys/Grocery
|
/Grocery.DAL/Grocery.DAL.Repositories/RepositoryFactory.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using Grocery.DAL.Contexts;
using Grocery.DAL.Contract;
using Grocery.BLL.Entities;
namespace Grocery.DAL.Repositories
{
public class RepositoryFactory : IRepositoryFactory
{
readonly Dictionary<Type, object> collection = new Dictionary<Type, object>();
public RepositoryFactory(DBContext context)
{
// Extension point of the factory
this.collection.Add(typeof(IArrivedGoodsRepository), new ArrivedGoodsRepository(context));
this.collection.Add(typeof(ICategoryRepository), new CategoryRepository(context));
this.collection.Add(typeof(IClassRepository), new ClassRepository(context));
this.collection.Add(typeof(IDepartmentRepository), new DepartmentRepository(context));
this.collection.Add(typeof(IProductRepository), new ProductRepository(context));
this.collection.Add(typeof(IProviderRepository), new ProviderRepository(context));
this.collection.Add(typeof(ISaleRepository), new SaleRepository(context));
this.collection.Add(typeof(ISellerRepository), new SellerRepository(context));
this.collection.Add(typeof(ITareChangeRepository), new TareChangeRepository(context));
this.collection.Add(typeof(IUserRepository), new UserRepository(context));
}
public T Create<T>()
{
Type type = typeof(T);
if (!this.collection.ContainsKey(type))
{
throw new MissingMemberException(type.ToString() + "is missing in the collection");
}
return (T)this.collection[type];
}
}
}
|
1ad6dfab925009a49be2e49bea3bebde3240baf8
|
C#
|
Niicksan/SoftwareUniversity
|
/Professional Modules/C# DB Fundamentals/Databases Advanced - Entity Framework/Exercises/01. DB Advanced - Apps Introduction/6. Remove Villain/Remove Villain.cs
| 3.125
| 3
|
using System;
using System.Data.SqlClient;
namespace _6._Remove_Villain
{
class Program
{
static void Main(string[] args)
{
int recivedVillainId = int.Parse(Console.ReadLine());
string connectionString = @"Data Source=(local)\SQLEXPRESS; Initial Catalog = MinionsDB; Integrated Security = true";
SqlConnection connection = new SqlConnection(connectionString);
using (connection)
{
connection.Open();
SqlCommand command = new SqlCommand($"SELECT Id FROM Villains WHERE Id = '{recivedVillainId}'", connection);
int? result = (int)command.ExecuteScalar();
if (result == null)
{
Console.WriteLine("No such villain was found.");
connection.Close();
return;
}
command = new SqlCommand($"SELECT COUNT(*) FROM MinionsVillains WHERE VillainId = '{recivedVillainId}'", connection);
int minionsCount = (int)command.ExecuteScalar();
command = new SqlCommand($"DELETE FROM MinionsVillains WHERE VillainId = '{recivedVillainId}'", connection);
command.ExecuteNonQuery();
command = new SqlCommand($"SELECT Name FROM Villains WHERE Id = '{recivedVillainId}'", connection);
string villainName = (string)command.ExecuteScalar();
command = new SqlCommand($"DELETE FROM Villains WHERE Id = '{recivedVillainId}'", connection);
command.ExecuteNonQuery();
Console.WriteLine($"{villainName} was deleted.");
Console.WriteLine($"{minionsCount} minions were released.");
}
}
}
}
|
ff972441b4f94a8355008a639b66a8c915415077
|
C#
|
Litorasul/TechModule_with_CSharp_at_SoftUni.bg
|
/06.Objects andClasses/06. ObjectsAndClasses/P06.VehicleCatalogue/VehicleCatalogue.cs
| 3.59375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace P06.VehicleCatalogue
{
class VehicleCatalogue
{
static void Main(string[] args)
{
List<string> input = Console.ReadLine().Split().ToList();
List<Vehicle> cars = new List<Vehicle>();
List<Vehicle> trucks = new List<Vehicle>();
List<Vehicle> allVehicles = new List<Vehicle>();
while (input[0] != "End")
{
if (input[0] == "truck")
{
var theTruck = new Vehicle(input[0], input[1], input[2], int.Parse(input[3]));
trucks.Add(theTruck);
allVehicles.Add(theTruck);
}
else if (input[0] == "car")
{
var theCar = new Vehicle(input[0], input[1], input[2], int.Parse(input[3]));
cars.Add(theCar);
allVehicles.Add(theCar);
}
input = Console.ReadLine().Split().ToList();
}
string carToPrint = Console.ReadLine();
while (carToPrint != "Close the Catalogue")
{
Vehicle vehicle = allVehicles.Find(x => x.Model == carToPrint);
Console.WriteLine(vehicle.ToString());
carToPrint = Console.ReadLine();
}
SumAndPrint(trucks, cars);
}
private static void SumAndPrint(List<Vehicle> trucks, List<Vehicle> cars)
{
double sumTrucks = 0.00;
int trucksCount = 0;
for (int i = 0; i < trucks.Count; i++)
{
sumTrucks += trucks[i].Horsepower;
trucksCount++;
}
double sumCars = 0.00;
int carCount = 0;
for (int i = 0; i < cars.Count; i++)
{
sumCars += cars[i].Horsepower;
carCount++;
}
if (carCount > 0)
{
Console.WriteLine($"Cars have average horsepower of: {sumCars / carCount:F2}.");
}
else
{
Console.WriteLine($"Cars have average horsepower of: {0:F2}.");
}
if (trucksCount > 0)
{
Console.WriteLine($"Trucks have average horsepower of: {sumTrucks / trucksCount:F2}.");
}
else
{
Console.WriteLine($"Trucks have average horsepower of: {0:F2}.");
}
}
}
public class Vehicle
{
public string Type;
public string Model;
public string Colour;
public int Horsepower;
public Vehicle()
{
}
public Vehicle(string type, string model, string colour, int horsepower)
{
type = FirstToUpper(type);
Type = type;
Model = model;
Colour = colour;
Horsepower = horsepower;
}
private string FirstToUpper(string type)
{
if (String.IsNullOrEmpty(type))
{
return null;
}
return type.First().ToString().ToUpper() + string.Join("", type.Skip(1));
}
public override string ToString()
{
string toPrint = $"Type: {Type}"
+ Environment.NewLine
+ $"Model: {Model}"
+ Environment.NewLine
+ $"Color: {Colour}"
+ Environment.NewLine
+ $"Horsepower: {Horsepower}";
return toPrint;
}
}
}
|
3112a7a8b0b34cb2bf9392240dc207a2a58d5f68
|
C#
|
kkozmic/PaulTest
|
/PaulBenchmarks/StructureMap.cs
| 2.609375
| 3
|
using PaulBenchmark.PaulModel;
using StructureMap;
namespace PaulBenchmark.PaulBenchmarks
{
public class StructureMap : IBenchmark
{
private readonly Container container;
public StructureMap()
{
container = new Container(e =>
{
e.ForSingletonOf<Game>().Use<Game>();
e.For<Player>().Use<Player>();
e.For<Gun>().Use<Gun>();
e.For<Bullet>().Use<Bullet>();
});
}
public Player ResolvePlayer()
{
return container.GetInstance<Player>();
}
public void Run()
{
var player = ResolvePlayer();
player.Shoot();
}
}
}
|
7b92f1d0a9258ef9480175c48b576b8b14e55c31
|
C#
|
embix/adventofcode
|
/2019/LinqPadQnD/day04_2.linq
| 3.0625
| 3
|
<Query Kind="Program" />
void Main()
{
var cases =
//testcases;
Enumerable.Range(puzzleMin, puzzleMax-puzzleMin+1)
.Select(i=>new TestCase{
Password = i.ToString()
}).ToList();
cases.Last().Dump();
var meetingCount = 0;
foreach(var pw in cases)
{
var isMeetingCriteria = IsMeetingCriteria(pw.Password);
//isMeetingCriteria.Dump($"{pw.Password} expected to meet criteria {pw.IsMeetingCriteria}");
if(isMeetingCriteria){
++meetingCount;
}
}
meetingCount.Dump("that amount of meeting passwords were found");
}
Int32 puzzleMin = 152085;
Int32 puzzleMax = 670283;
Boolean IsMeetingCriteria(String password)
{
// six digit number
if(!Regex.IsMatch(password, @"\d{6}")) return false;
var code = Int32.Parse(password);
// is within range (inclusive?)
if(code<puzzleMin || code>puzzleMax) return false;
// new double rule
if(!ContainsTrueDouble(password)) return false;
//never decreases
if(!IsNeverDecreasing(password)) return false;
return true;
}
Boolean ContainsTrueDouble(String password)
{
var sameChunks = new List<String>();
var i = 0;
var currentLetter = password.Substring(i,1);
var currentString = currentLetter;
while(++i < password.Length)
{
var nextLetter = password.Substring(i,1);
if(nextLetter == currentLetter)
{
// same: add
currentString+=nextLetter;
}
else
{
// different: close
sameChunks.Add(currentString);
currentString = nextLetter;
}
// either way: remember
currentLetter = nextLetter;
}
sameChunks.Add(currentString);
return sameChunks.Any(c=>c.Length==2);
}
// not quite what the spec wants
Boolean HasAdjacentSameButNoTripel(String password)
{
var i = 0;
var currentValue = Int32.Parse(password.Substring(i, 1));
var currentIsDouble = false;
var doubleCount = 0;
while (++i < password.Length)
{
var nextValue = Int32.Parse(password.Substring(i, 1));
if(nextValue == currentValue)
{
if(currentIsDouble){
return false;// tripel found!
}else{
currentIsDouble = true;
++doubleCount;
}
}else{
currentIsDouble = false;
}
currentValue = nextValue;
}
return doubleCount>0;
}
Boolean IsNeverDecreasing(String password)
{
var i = 0;
var currentValue = Int32.Parse(password.Substring(i,1));
while(++i<password.Length)
{
var nextValue = Int32.Parse(password.Substring(i,1));
if(nextValue<currentValue) return false;
currentValue = nextValue;
}
return true;
}
struct TestCase{
public String Password;
public Boolean IsMeetingCriteria;
}
TestCase[] testcases = new TestCase[]{
new TestCase{
Password = "111111",
IsMeetingCriteria = true,
},
new TestCase{
Password = "223450",
IsMeetingCriteria = false,
},
new TestCase{
Password = "123789",
IsMeetingCriteria = false,
}
};
// Define other methods, classes and namespaces here
const String spec = @"--- Day 4: Secure Container ---
You arrive at the Venus fuel depot only to discover it's protected by a password. The Elves had written the password on a sticky note, but someone threw it out.
However, they do remember a few key facts about the password:
It is a six-digit number.
The value is within the range given in your puzzle input.
Two adjacent digits are the same (like 22 in 122345).
Going from left to right, the digits never decrease; they only ever increase or stay the same (like 111123 or 135679).
Other than the range rule, the following are true:
111111 meets these criteria (double 11, never decreases).
223450 does not meet these criteria (decreasing pair of digits 50).
123789 does not meet these criteria (no double).
How many different passwords within the range given in your puzzle input meet these criteria?
Your puzzle input is 152085-670283.";
const String spec2 = @"--- Day 4: Secure Container ---
You arrive at the Venus fuel depot only to discover it's protected by a password. The Elves had written the password on a sticky note, but someone threw it out.
However, they do remember a few key facts about the password:
It is a six-digit number.
The value is within the range given in your puzzle input.
Two adjacent digits are the same (like 22 in 122345).
Going from left to right, the digits never decrease; they only ever increase or stay the same (like 111123 or 135679).
Other than the range rule, the following are true:
111111 meets these criteria (double 11, never decreases).
223450 does not meet these criteria (decreasing pair of digits 50).
123789 does not meet these criteria (no double).
How many different passwords within the range given in your puzzle input meet these criteria?
Your puzzle answer was 1764.
The first half of this puzzle is complete! It provides one gold star: *
--- Part Two ---
An Elf just remembered one more important detail: the two adjacent matching digits are not part of a larger group of matching digits.
Given this additional criterion, but still ignoring the range rule, the following are now true:
112233 meets these criteria because the digits never decrease and all repeated digits are exactly two digits long.
123444 no longer meets the criteria (the repeated 44 is part of a larger group of 444).
111122 meets the criteria (even though 1 is repeated more than twice, it still contains a double 22).
How many different passwords within the range given in your puzzle input meet all of the criteria?
Your puzzle input is still 152085-670283.";
|
85ac4127896d011b6df93abbb3bbd9b38de9f495
|
C#
|
AlexandraDamaschin/Company
|
/Company/DAL/ProductRepository.cs
| 2.578125
| 3
|
using Company.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Company.DAL
{
public class ProductRepository : IProductRepository
{
private SampleDBEntities context;
public ProductRepository(SampleDBEntities context)
{
this.context = context;
}
public void Dispose()
{
context.Dispose();
}
public Product GetProductByID(int id)
{
return context.Products.Find(id);
}
public List<Product> GetProducts()
{
return context.Products.ToList();
}
}
}
|
c44d433d273c500375ab5c176094a0b9826d2a9d
|
C#
|
shendongnian/download4
|
/code9/1610917-45182892-151920009-2.cs
| 2.640625
| 3
|
public class SerialConnection
{
INIFile settings = new INIFile("C:\\Lateco\\settings.ini");
public SerialPort SerialPort { get; set; }
static SerialConnection connection= null;
public event EventHandler WeightReceived;
public static SerialConnection OpenConnection()
{
if(connection == null)
{
connection = new SerialConnection();
string portname, baudrate, parity, databits, stopbits, handshake;
portname = settings.Read("SERIAL PORT PROPERTIES", "PORT_NAME");
baudrate = settings.Read("SERIAL PORT PROPERTIES", "BAUD_RATE");
parity = settings.Read("SERIAL PORT PROPERTIES", "PARITY");
databits = settings.Read("SERIAL PORT PROPERTIES", "DATA_BITS");
stopbits = settings.Read("SERIAL PORT PROPERTIES", "STOP_BITS");
handshake = settings.Read("SERIAL PORT PROPERTIES", "HANDSHAKE");
connection.SerialPort = new SerialPort(); //error here
connection.SerialPort.PortName = portname;
connection.SerialPort.BaudRate = int.Parse(baudrate);
connection.SerialPort.Parity = (Parity)Enum.Parse(typeof(Parity), parity, true);
connection.SerialPort.DataBits = int.Parse(databits);
connection.SerialPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), stopbits, true);
connection.SerialPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), handshake, true);
connection.SerialPort.Open();
connection.SerialPort.ReadTimeout = 200;
connection.SerialPort.DataReceived += new SerialDataReceivedEventHandler(connection.serialPort1_DataReceived);
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
weight = SerialPort.ReadExisting();
weight = weight.Substring(0, 7);
WeightReceived?.Invoke(weight, new EventArgs());
}
catch (TimeoutException) { }
}
return connection;
}
public void CloseConnection()
{
if (SerialPort.IsOpen)
SerialPort.Close();
}
~SerialConnection()
{
if (SerialPort.IsOpen)
SerialPort.Close();
}
}
|
95b5e5187b1e9cd71ce0643813d39673e79a3d4b
|
C#
|
AlAstapov/Equipment
|
/ConsoleApp1/Stock.cs
| 2.90625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
public class Stock
{
public static int SnowBoardCountOnStock;
public static int SkiCountOnStock;
public static void GetSnowBoardsFromStock(int countToTake)
{
if (SnowBoardCountOnStock > countToTake) SnowBoardCountOnStock -= countToTake;
}
public static void GetSkisFromStock(int countToTake)
{
if (SkiCountOnStock > countToTake) SkiCountOnStock -= countToTake;
}
}
}
|
44ac1a0cd362ed0dc587d64d1daa7b7c3c192084
|
C#
|
iKostov86/CSharp
|
/Homeworks/C# - part 1/OperatorsAndExpressions/10. Point, Circle, Rectangle/PointCircleRectangle.cs
| 3.671875
| 4
|
using System;
public class PointCircleRectangle
{
static void Main(string[] args)
{
double x = double.Parse(Console.ReadLine());
double y = double.Parse(Console.ReadLine());
bool inCircle = true;
bool inRectangle = true;
string result = string.Empty;
var circleX = 1;
var circleY = 1;
var circleR = 1.5;
var rectTop = 1;
var rectLeft = -1;
var rectWidth = 6;
var rectHeight = 2;
var distance = Math.Pow((x - circleX), 2) + Math.Pow((y - circleY), 2);
if (distance > circleR * circleR)
{
inCircle = false;
}
if (x < rectLeft || x > (rectLeft + rectWidth) ||
y < (rectTop - rectHeight) || y > rectTop)
{
inRectangle = false;
}
result = (inCircle ? "inside" : "outside") + " circle " +
(inRectangle ? "inside" : "outside") + " rectangle";
Console.WriteLine(result);
}
}
|
28fbb3bf0b2a2a770ccdb6475c2c4be5b7528214
|
C#
|
messyoxd/TrocaArquivo
|
/TrocaArquivo.TupleSpace/Servidor/Servidor.cs
| 2.734375
| 3
|
using System;
using System.Linq;
using System.Threading;
using dotSpace.Objects.Network;
using dotSpace.Objects.Space;
namespace TrocaArquivo.TupleSpace
{
public class TpServidor
{
private readonly string port;
private readonly string ip;
private SpaceRepository repository;
public bool pingCompleted = false;
public RemoteSpace remotespace;
public TpServidor(string ip, string port, SpaceRepository space)
{
this.ip = ip;
this.port = port;
this.repository = space;
// instanciar space
this.remotespace = new RemoteSpace($"tcp://{this.ip}:{this.port}/chat?KEEP");
}
public void StartSpace()
{
this.repository = new SpaceRepository();
this.repository.AddGate($"tcp://{this.ip}:{this.port}?KEEP");
this.repository.AddSpace("TrocaArquivo", new SequentialSpace());
Console.ReadKey();
}
private void checkOnline(string name)
{
// a requisicao para a tupla aguardará até que haja alguma tupla que se encaixe
var tupla = this.remotespace.Get("User", name, "ping", typeof(bool));
pingCompleted = true;
}
private static bool WaitUntil(int numberOfMiliSeconds, Func<bool> condition)
{
int waited = 0;
while (!condition() && waited < numberOfMiliSeconds)
{
Thread.Sleep(100);
waited += 100;
}
return condition();
}
}
}
|
8358dc9c87c9ba8a8fd107b871763d95e45d82a9
|
C#
|
yas-mnkornym/DroneManipulator
|
/DroneManipulator/DroneManipulator.Simulator/ComiketSystem/Settings/SettingsImpl.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ComiketSystem.Cheekichi.Infrastructure.Settings
{
internal class SettingsImpl : CSBaseNotifyPropertyChanged, ICSSettings, IDisposable
{
#region Private Fields
List<Type> knownTypes_ = new List<Type>(); // 既知の型
Dictionary<string, object> settingsData_ = new Dictionary<string, object>(); // 設定データ
Dictionary<string, SettingsImpl> settingsChildren_ = new Dictionary<string, SettingsImpl>(); // 子設定
ISettingsSerializer childSettingsSerializer_ = new DataContractSettingsSerializer(); // 子設定のシリアライザ
#endregion
#region Properties
internal Dictionary<string, object> SettingsData { get { return settingsData_; } }
protected SettingsImpl ParentSettings { get; private set; }
#endregion
#region Constructors
public SettingsImpl(string tag, ICSActionDispatcher dispatcher)
: base(dispatcher)
{
Tag = tag;
}
public SettingsImpl(IEnumerable<Type> knownTypes, ICSActionDispatcher dispatcher = null)
: this(null, knownTypes, dispatcher)
{ }
public SettingsImpl(string tag, IEnumerable<Type> knownTypes, ICSActionDispatcher dispatcher = null)
: this(tag, dispatcher)
{
if (knownTypes != null) {
knownTypes_.AddRange(knownTypes);
}
}
protected SettingsImpl(SettingsImpl parentSettings, string tag, IEnumerable<Type> knownTypes, ICSActionDispatcher dispatcher = null)
: this(tag, knownTypes, dispatcher)
{
if (parentSettings == null) { throw new ArgumentNullException("parentSettings"); }
ParentSettings = parentSettings;
// タグ編集
List<string> tags = new List<string>();
var settings = this;
while(settings != null){
tags.Add(settings.Tag);
settings = settings.ParentSettings;
}
tags.Reverse();
Tag = string.Join("_", tags);
}
#endregion
#region Private Methods
string GetTaggedKey(string key, bool isEmbed = false)
{
string result;
if (Tag == null) {
result = key;
}
else {
result = string.Format("{0}.{1}", Tag, key);
}
if (isEmbed) {
return "__" + result;
}
else {
return result;
}
}
#endregion
#region ICSSettings
public IList<Type> KnownTypes
{
get
{
return knownTypes_;
}
}
public string Tag{get; private set;}
public void Set<T>(string key, T value)
{
var actKey = key;// GetTaggedKey(key);
bool isNew = true;
if (SettingsData.ContainsKey(actKey)) {
var oldValue = SettingsData[actKey];
if (oldValue != null) {
isNew = (!oldValue.Equals(value));
}
else {
isNew = (value != null);
}
}
if (isNew) {
RaisePropertyChanging(key);
SettingsData[actKey] = value;
RaisePropertyChanged(key);
}
}
public T Get<T>(string key, T defaultValue = default(T))
{
var actKey = key; // GetTaggedKey(key);
if (SettingsData.ContainsKey(actKey)) {
return (T)settingsData_[actKey];
}
else {
return defaultValue;
}
}
public bool Exists(string key)
{
var actKey = key;// GetTaggedKey(key);
return SettingsData.ContainsKey(actKey);
}
public void Remove(string key)
{
var actKey = key; // GetTaggedKey(key);
if (SettingsData.ContainsKey(actKey)) {
RaisePropertyChanging(key);
SettingsData.Remove(actKey);
RaisePropertyChanged(key);
}
}
public void Clear()
{
foreach (var key in SettingsData.Keys.ToArray()) {
Remove(key);
}
}
public IEnumerable<string> SettingKeys
{
get
{
return SettingsData.Keys;
}
}
#region Child Settings
public ICSSettings GetChildSettings(string tag, IEnumerable<Type> knownTypes)
{
if (settingsChildren_.ContainsKey(tag)) {
return settingsChildren_[tag];
}
else {
var settings = new SettingsImpl(this, tag, knownTypes, Dispatcher);
// 設定をロード
var setTag = GetTaggedKey(settings.Tag, true);
var setStr = Get<string>(setTag, null);
if (setStr != null) {
using (var ms = new MemoryStream())
using (var writer = new StreamWriter(ms)) {
writer.Write(setStr);
writer.Flush();
ms.Seek(0, SeekOrigin.Begin);
childSettingsSerializer_.Deserialize(ms, settings);
}
}
// 子設定に追加
settings.PropertyChanged += settings_PropertyChanged;
settingsChildren_[settings.Tag] = settings;
return settings;
}
}
void settings_PropertyChanging(object sender, System.ComponentModel.PropertyChangingEventArgs e)
{
var settings = sender as SettingsImpl;
if (settings != null) {
var tag = GetTaggedKey(e.PropertyName);
RaisePropertyChanging(tag);
}
}
void settings_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
var settings = sender as SettingsImpl;
if (settings != null) {
var tag = GetTaggedKey(settings.Tag, true);
string str = null;
using(var ms = new MemoryStream()){
childSettingsSerializer_.Serialize(ms, settings);
ms.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(ms)) {
str = reader.ReadToEnd();
}
}
// 設定保存
Set(tag, str);
}
}
public void RemoveChildSettings(string tag)
{
if (settingsChildren_.ContainsKey(tag)) {
var settings = settingsChildren_[tag];
settingsChildren_[tag] = null;
settings.PropertyChanged -= settings_PropertyChanged;
settings.Dispose();
}
}
public IEnumerable<string> ChildSettingsTags
{
get
{
return settingsChildren_.Keys;
}
}
#endregion // Child Settings
#endregion // ICSSettings
#region IDisposable
bool isDisposed_ = false;
virtual protected void Dispose(bool disposing)
{
if (isDisposed_) { return; }
if (disposing) {
}
isDisposed_ = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
|
2b8f705f0070268c98e968e8a34ed18942a09d02
|
C#
|
samitsuun/15helmi
|
/ConsoleApp1/ConsoleApp1/Program.cs
| 3.140625
| 3
|
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
List<string> rivit = new List<string>();
StreamReader reader = File.OpenText(@"C:\repositories\myfile.txt");
string line = reader.ReadLine();
while (line != null)
{
rivit.Add(line);
Console.WriteLine(line);
line = reader.ReadLine();
}
reader.Close();
//TODO: muokkaa
for (int i = 0; i < rivit.Count; i++)
{
rivit[i]=rivit[i].ToUpper(); //muuttaa kirjaimet isoiksi
}
StreamWriter writer = File.CreateText(@"C:\repositories\myfile.txt");
for (int i = 0; i < rivit.Count; i++)
{
writer.WriteLine(rivit[i]);
}
writer.Close();
}
}
}
|
66cbc3688d79b378f8f6fd4863a56d0f3a22b802
|
C#
|
shendongnian/download4
|
/code6/1069979-27762586-80885830-2.cs
| 3.15625
| 3
|
static void Main(string[] args)
{
//INTEGERS
int max = 5;
Cake[] cakes = new Cake[max];
int[] qty = new int[max];
int[] price = new int[max];
int i;
int qty_search;
int counter = 0, found = 0;
//STRINGS
string search;
string[] cakename = new string[max];
string[] id = new string[max];
//CHAR'S
char opt;
//LOOP
//MENU
do
{
Console.Write("1 - add cake\n2 - display cake\n3 - search cake\n4 - increase qty\n5 - decrease qty\n6 - Update qty\nx - exit\nopt --> ");
opt = Convert.ToChar(Console.ReadLine());
//SWITCH CASES
switch (opt)
{
//ADD CAKE
case '1':
Console.Write("name: ");
cakename[counter] = Console.ReadLine();
cakes[counter] = new Cake();
cakes[counter].cake_Name = cakename[counter];
Console.Write("id: ");
id[counter] = Console.ReadLine();
cakes[counter].id = id[counter];
Console.Write("qty: ");
qty[counter] = Convert.ToInt32(Console.ReadLine());
cakes[counter].qty = qty[counter];
Console.Write("price: ");
price[counter] = Convert.ToInt32(Console.ReadLine());
cakes[counter].price = price[counter];
counter++;
break;
//DISPLAY CAKE
case '2':
Console.WriteLine("List of Cakes");
Console.WriteLine("id -.- Name -.- qty -.- price");
for (i = 0; i < max; i++)
{
Console.WriteLine("{0} {1} {2} {3}", cakes[i].id, cakes[i].cake_Name, cakes[i].qty, cakes[i].price);
}
Console.WriteLine("------------------");
break;
//SEARCH CAKE
case '3':
found = 0;
Console.Write("enter your search cake id: ");
search = Console.ReadLine();
for (i = 0; i < counter; i++)
{
if (string.Equals(id[i], search, StringComparison.OrdinalIgnoreCase))
{
found++;
}
}
Console.Write("found = ");
Console.WriteLine(found);
break;
case '4':
Console.WriteLine("List of Cakes");
for (i = 0; i < counter; i++)
{
Console.WriteLine("{0} {1} {2} {3}", cakes[i].id, cakes[i].cake_Name, cakes[i].qty, cakes[i].price);
}
Console.WriteLine("------------------");
Console.Write("Selected Item ID: ");
qty_search = Convert.ToInt32(Console.ReadLine());
for (i = 0; i < counter; i++)
{
if (qty_search == qty[i])
{
qty[i]++;
}
}
Console.WriteLine("cake qty + 1");
break;
case '5':
Console.WriteLine("List of Cakes");
for (i = 0; i < counter; i++)
{
Console.WriteLine("{0} {1} {2} {3}", cakes[i].id, cakes[i].cake_Name, cakes[i].qty, cakes[i].price);
}
Console.WriteLine("------------------");
Console.Write("Selected Item ID: ");
qty_search = Convert.ToInt32(Console.ReadLine());
for (i = 0; i < counter; i++)
{
if (qty_search == qty[i])
{
qty[i]--;
}
}
Console.WriteLine("cake qty + 1");
break;
case '6':
Console.WriteLine("-- update cake name --");
Console.WriteLine("Cake list");
for (i = 0; i < counter; i++)
{
Console.WriteLine("{0} {1} {2} {3}", cakes[i].id, cakes[i].cake_Name, cakes[i].qty, cakes[i].price);
}
Console.WriteLine("------------------");
Console.Write("Select item ID: ");
search = Console.ReadLine();
for (i = 0; i < counter; i++)
{
if (search == id[i])
{
Console.Write("Enter Name: ");
cakename[i] = Console.ReadLine();
Console.WriteLine("cake updated");
}
}
break;
case 'X':
case 'x':
Console.WriteLine("exit");
break;
default:
Console.WriteLine("Invalid Option");
break;
}
//SWITCH CASE END
} while (opt != 'x' && opt != 'X');
//OUTER MENU LOOP END
//PROGRAM TERMINATE
}
|
3318e864ed18335bc80291336639dd089d7e5a08
|
C#
|
perivar/PresetConverter
|
/PresetConverterProject/CommonUtils/IOUtils.cs
| 3.1875
| 3
|
using System;
using System.IO;
using System.Text;
using System.Linq;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Reflection;
using System.IO.Compression;
namespace CommonUtils
{
/// <summary>
/// Utils for input output (IO).
/// </summary>
public static class IOUtils
{
static readonly Encoding _isoLatin1Encoding = Encoding.GetEncoding("ISO-8859-1");
const string columnSeparator = ",";
#region Get/ Search for Files
/// <summary>
/// Return all files by their extension in ONE Directory (not recursive)
/// </summary>
/// <param name="dir">Directory Path</param>
/// <param name="extensions">extensions, e.g. ".jpg",".exe",".gif"</param>
/// <returns></returns>
/// <example>dInfo.GetFilesByExtensions(".jpg",".exe",".gif");</example>
public static IEnumerable<FileInfo> GetFilesByExtensions(this DirectoryInfo dir, params string[] extensions)
{
if (extensions == null)
throw new ArgumentNullException(nameof(extensions));
IEnumerable<FileInfo> files = dir.EnumerateFiles();
return files.Where(f => extensions.Contains(f.Extension));
}
/// <summary>
/// Get Files using regexp pattern like \.mp3|\.mp4\.wav\.ogg
/// By using SearchOption.AllDirectories, you can make it recursive
/// </summary>
/// <param name="path">Directory Path</param>
/// <param name="searchPatternExpression">Regexp pattern like \.mp3|\.mp4\.wav\.ogg</param>
/// <param name="searchOption">SearchOption like SearchOption.AllDirectories</param>
/// <returns>IEnumerable array of filenames</returns>
/// <example>var files = IOUtils.GetFiles(path, "\\.mp3|\\.mp4\\.wav\\.ogg", SearchOption.AllDirectories);</example>
public static IEnumerable<string> GetFiles(string path, string searchPatternExpression = "", SearchOption searchOption = SearchOption.TopDirectoryOnly)
{
var reSearchPattern = new Regex(searchPatternExpression);
return Directory.EnumerateFiles(path, "*", searchOption).Where(file => reSearchPattern.IsMatch(Path.GetExtension(file).ToLower()));
}
/// <summary>
/// Get Files using array of extensions and executes in parallel
/// By using SearchOption.AllDirectories, you can make it recursive
/// </summary>
/// <param name="path">Directory Path</param>
/// <param name="searchPatterns">Array of extensions like: string[] extensions = { "*.mp3", "*.wav", "*.ogg" };</param>
/// <param name="searchOption">SearchOption like SearchOption.AllDirectories</param>
/// <returns>IEnumerable array of filenames</returns>
/// <example>
/// string[] extensions = { "*.mp3", "*.wma", "*.mp4", "*.wav", "*.ogg" };
/// var files = IOUtils.GetFiles(path, extensions, SearchOption.AllDirectories);
/// </example>
public static IEnumerable<string> GetFiles(string path, string[] searchPatterns, SearchOption searchOption = SearchOption.TopDirectoryOnly)
{
return searchPatterns.AsParallel().SelectMany(searchPattern => Directory.EnumerateFiles(path, searchPattern, searchOption));
}
/// <summary>
/// Get files recursively using a search pattern
/// </summary>
/// <param name="path">Directory Path</param>
/// <param name="searchPattern">Search pattern like: "*.mp3" or "one_specific_file.wav"</param>
/// <returns>IEnumerable array of filenames</returns>
public static IEnumerable<string> GetFilesRecursive(string path, string searchPattern)
{
return Directory.EnumerateFiles(path, searchPattern, SearchOption.AllDirectories);
}
/// <summary>
/// Get files recursively using an array of extensions
/// </summary>
/// <param name="path">Directory Path</param>
/// <param name="extensions">Array of extensions like: string[] extensions = { ".mp3", ".wav", ".ogg" };</param>
/// <returns>IEnumerable array of filenames</returns>
/// <example>
/// string[] extensions = { ".mp3", ".wma", ".mp4", ".wav", ".ogg" };
/// var files = IOUtils.GetFilesRecursive(path, extensions);
/// </example>
public static IEnumerable<string> GetFilesRecursive(string path, string[] extensions)
{
IEnumerable<string> filesAll =
Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories)
.Where(f => extensions.Contains(Path.GetExtension(f).ToLower()));
return filesAll;
}
/// <summary>
/// Get all files recursively
/// </summary>
/// <param name="path">Directory Path</param>
/// <returns>IEnumerable array of filenames</returns>
public static IEnumerable<string> GetFilesRecursive(string path)
{
return Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories);
}
#endregion
/// <summary>
/// Backup a file to a filename.bak or filename.bak_number etc
/// </summary>
/// <param name="fileName">filename to backup</param>
public static void MakeBackupOfFile(string fileName)
{
if (File.Exists(fileName))
{
string destinationBackupFileName = fileName + ".bak";
// make sure to create a new backup if the backup file already exist
int backupFileCount = -1;
do
{
backupFileCount++;
}
while (File.Exists(destinationBackupFileName + (backupFileCount > 0 ? "_" + backupFileCount.ToString() : "")));
destinationBackupFileName += (backupFileCount > 0 ? "_" + (backupFileCount).ToString() : "");
File.Copy(fileName, destinationBackupFileName);
}
}
/// <summary>
/// Get Next Available Filename using passed filepath
/// E.g. _001.ext, 002_ext unt so weiter
/// </summary>
/// <param name="filePath">file path to check</param>
/// <returns>a unique filepath</returns>
public static string NextAvailableFilename(string filePath)
{
// Short-cut if already available
if (!File.Exists(filePath))
return filePath;
// build up filename
var fileInfo = new FileInfo(filePath);
DirectoryInfo folder = fileInfo.Directory;
string folderName = folder.FullName;
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileInfo.Name);
int version = 0;
do
{
version++;
}
while (File.Exists(
string.Format("{0}{1}{2}_{3:000}.h2p", folderName, Path.DirectorySeparatorChar, fileNameWithoutExtension, version)
));
return string.Format("{0}{1}{2}_{3:000}.h2p", folderName, Path.DirectorySeparatorChar, fileNameWithoutExtension, version);
}
/// <summary>
/// Determine whether a path is a file or a directory
/// </summary>
/// <param name="fileOrDirectoryPath">path</param>
/// <returns>true if the path is a directory, false if a file, null if nothing</returns>
public static bool? IsDirectory(string fileOrDirectoryPath)
{
if (Directory.Exists(fileOrDirectoryPath))
{
return true; // is a directory
}
else if (File.Exists(fileOrDirectoryPath))
{
return false; // is a file
}
else
{
return null; // is a nothing
}
}
/// <summary>
/// Create Directory if it doesn't already exist
/// </summary>
/// <param name="filePath">directory path</param>
public static void CreateDirectoryIfNotExist(string filePath)
{
try
{
Directory.CreateDirectory(filePath);
}
catch (Exception)
{
// handle them here
}
}
/// <summary>
/// Log a message to file (e.g. a log file)
/// </summary>
/// <param name="file">filename to use</param>
/// <param name="msg">message to log</param>
public static void LogMessageToFile(FileInfo file, string msg)
{
// Make sure to support Multithreaded write access
using (var fs = new FileStream(file.FullName, FileMode.Append, FileAccess.Write, FileShare.Write))
{
using (var sw = new StreamWriter(fs))
{
string logLine = String.Format(
"{0:G}: {1}", DateTime.Now, msg);
sw.WriteLine(logLine);
}
}
}
/// <summary>
/// Read everything from a file as text (string)
/// </summary>
/// <param name="filePath">file</param>
/// <returns>string</returns>
public static string ReadTextFromFile(string filePath)
{
string text = "";
try
{
if (File.Exists(filePath))
{
text = File.ReadAllText(filePath);
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e);
}
return text;
}
/// <summary>
/// Write text to a file
/// </summary>
/// <param name="filePath">file</param>
/// <param name="text">text to write</param>
/// <returns>true if successful</returns>
public static bool WriteTextToFile(string filePath, string text)
{
try
{
File.WriteAllText(filePath, text);
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e);
return false;
}
return true;
}
/// <summary>
/// Print the passed array to the TextWriter (e.g. Console.out)
/// </summary>
/// <param name="pw">a textwriter, e.g. Console.Out</param>
/// <param name="data">array to output</param>
/// <example>IOUtils.Print(Console.Out, data);</example>
public static void Print(TextWriter pw, double[] data)
{
for (int i = 0; i < data.Length; i++)
{
pw.Write("{0}", data[i].ToString("F4", CultureInfo.InvariantCulture).PadLeft(10) + " ");
pw.Write("\r");
}
pw.WriteLine();
pw.Close();
}
/// <summary>
/// Print the passed array to the TextWriter (e.g. Console.out)
/// </summary>
/// <param name="pw">a textwriter, e.g. Console.Out</param>
/// <param name="data">array to output</param>
/// <example>IOUtils.Print(Console.Out, data);</example>
public static void Print(TextWriter pw, float[] data)
{
for (int i = 0; i < data.Length; i++)
{
pw.Write("{0}", data[i].ToString("F3", CultureInfo.InvariantCulture).PadLeft(10) + " ");
pw.Write("\r");
}
pw.WriteLine();
pw.Close();
}
/// <summary>
/// Return a temporary file name
/// </summary>
/// <param name="extension">extension without the dot e.g. wav or csv</param>
/// <returns>filepath to the temporary file</returns>
public static string GetTempFilePathWithExtension(string extension)
{
var path = Path.GetTempPath();
var fileName = Guid.NewGuid().ToString() + "." + extension;
return Path.Combine(path, fileName);
}
/// <summary>
/// Return the right part of the path after a given base path if found
/// </summary>
/// <param name="path">long path</param>
/// <param name="startAfterPart">base path</param>
/// <returns></returns>
public static string? GetRightPartOfPath(string path, string startAfterPart)
{
int startAfter = path.LastIndexOf(startAfterPart, StringComparison.Ordinal);
if (startAfter == -1)
{
// path path not found
return null;
}
return path.Substring(startAfterPart.Length);
}
/// <summary>
/// Return the full file path without the extension
/// </summary>
/// <param name="fullPath">full path with extension</param>
/// <returns>full path without extension</returns>
public static string GetFullPathWithoutExtension(string fullPath)
{
return Path.Combine(Path.GetDirectoryName(fullPath), Path.GetFileNameWithoutExtension(fullPath));
}
/// <summary>
/// Make sure the file path has a given extension
/// </summary>
/// <param name="fullPath">full path with our without extension</param>
/// <param name="extension">extension in the format .ext e.g. '.png', '.wav'</param>
/// <returns></returns>
public static string EnsureExtension(string fullPath, string extension)
{
if (!fullPath.EndsWith(extension, StringComparison.Ordinal))
{
return fullPath + extension;
}
else
{
return fullPath;
}
}
/// <summary>
/// Remove the unsupported files from the passed file array
/// </summary>
/// <param name="files">all files</param>
/// <param name="supportedExtensions">supported extensions</param>
/// <returns>an array of supported files</returns>
public static string[] FilterOutUnsupportedFiles(string[] files, string[] supportedExtensions)
{
var correctFiles = new List<string>();
foreach (string inputFilePath in files)
{
string fileExtension = Path.GetExtension(inputFilePath);
int pos = Array.IndexOf(supportedExtensions, fileExtension);
if (pos > -1)
{
correctFiles.Add(inputFilePath);
}
}
return correctFiles.ToArray();
}
#region Read and Write CSV files
public delegate object MyParser(int lineCounter, string[] splittedLine, Dictionary<int, string>? lookupDictionary);
public delegate string MyFormatter(object line, int lineCounter, string columnSeparator);
public delegate string MyFormatterHeader(string columnSeparator);
/// <summary>
/// Read a CSV file and use delegate method to parse the lines
/// </summary>
/// <example>
/// public static object CsvDoubleParser(string[] splittedLine)
/// {
/// // only store the second element (the first is a counter)
/// return double.Parse(splittedLine[1]);
/// }
/// var objects = IOUtils.ReadCSV("input.csv", false, CsvDoubleParser);
/// var doubles = objects.Cast<double>().ToArray();
/// </example>
/// <param name="filePath">file path</param>
/// <param name="hasHeader">whether we should skip the first header row</param>
/// <param name="parser">a parser delegate method</param>
/// <param name="columnSeparator">column seperator, default ","</param>
/// <param name="doRemoveEmptyEntries">whether to remove empty entries when parsing lines, default TRUE</param>
/// <returns>a list of objects that can be casted to whatever</returns>
public static List<object> ReadCSV(string filePath, bool hasHeader, MyParser parser, Dictionary<int, string>? lookupDictionary = null, string columnSeparator = columnSeparator, bool doRemoveEmptyEntries = true)
{
int lineCounter = 0;
var list = new List<object>();
// read in the dictionary file in the csv format
foreach (var line in File.ReadLines(filePath, _isoLatin1Encoding))
{
lineCounter++;
// skip header
if (hasHeader && lineCounter == 1) continue;
// ignore blank lines
if (string.IsNullOrEmpty(line))
continue;
// parse
var elements = line.Split(new String[] {
columnSeparator
}, doRemoveEmptyEntries ? StringSplitOptions.RemoveEmptyEntries : StringSplitOptions.None);
list.Add(parser(lineCounter, elements, lookupDictionary));
}
return list;
}
/// <summary>
/// Write a CSV file and and use delegate method to format the lines
/// </summary>
/// <example>
/// public static string CvsComplexFormatter(object line, int lineCounter, string columnSeparator)
/// {
/// var elements = new List<string>();
/// var complex = (CommonUtils.MathLib.FFT.Complex) line;
///
/// elements.Add(String.Format("{0,4}", lineCounter));
/// elements.Add(String.Format("{0,12:N6}", complex.Re));
/// elements.Add(String.Format("{0,12:N6}", complex.Im));
///
/// return string.Join(columnSeparator, elements);
/// }
///
/// Complex[] spectrum = SpectrogramUtils.padded_FFT(ref signal);
/// List<object> lines = spectrum.Cast<object>().ToList();
/// IOUtils.WriteCSV("output.csv", lines, CvsComplexFormatter);
/// </example>
/// <param name="filePath">file path</param>
/// <param name="lines">a list of objects</param>
/// <param name="formatter">a formatter delegate method</param>
/// <param name="columnSeparator">column seperator, default ","</param>
public static void WriteCSV(string filePath, List<object> lines, MyFormatter formatter, MyFormatterHeader? header = null, string columnSeparator = columnSeparator)
{
int lineCounter = 0;
TextWriter pw = new StreamWriter(filePath, false, _isoLatin1Encoding);
if (header != null)
{
pw.WriteLine(header(columnSeparator));
}
// rows and columns
if (lines != null)
{
foreach (var line in lines)
{
lineCounter++;
// write data
var columns = formatter(line, lineCounter, columnSeparator);
pw.Write("{0}\r\n", columns);
}
}
pw.Close();
}
#endregion
/// <summary>
/// Return the path where the executable is running from
/// </summary>
/// <see cref="http://codebuckets.com/2017/10/19/getting-the-root-directory-path-for-net-core-applications/"></see>
/// <see cref="https://www.hanselman.com/blog/how-do-i-find-which-directory-my-net-core-console-application-was-started-in-or-is-running-from"/>
/// <see cref="https://www.softwaredeveloper.blog/executing-assembly-location-in-a-single-file-app"/>
/// <returns>the path where the executable is running from</returns>
public static string GetApplicationExecutionPath()
{
// get the application execution path
// this solution does not work any longer when publishing to an executable (single file app)
// var executableDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
// instead use AppContext.BaseDirectory
var executableDirectory = AppContext.BaseDirectory;
if (string.IsNullOrEmpty(executableDirectory))
{
throw new Exception("Could not find out executable directory!");
}
return executableDirectory;
}
/// <summary>
/// Decompress gzipped byte array
/// </summary>
/// <param name="gzip">gzipped byte array</param>
/// <returns>decompressed bytes</returns>
public static byte[] Decompress(byte[] gzip)
{
// Create a GZIP stream with decompression mode.
// ... Then create a buffer and write into while reading from the GZIP stream.
using (GZipStream stream = new GZipStream(new MemoryStream(gzip),
CompressionMode.Decompress))
{
const int size = 4096;
byte[] buffer = new byte[size];
using (MemoryStream memory = new MemoryStream())
{
int count = 0;
do
{
count = stream.Read(buffer, 0, size);
if (count > 0)
{
memory.Write(buffer, 0, count);
}
}
while (count > 0);
return memory.ToArray();
}
}
}
}
}
|
d57d09bbe9816bd265ec04d15fb819274b3d71c7
|
C#
|
HemlataDhangar/StudentManagement
|
/DataAccess/Concrete/StudentDL/StudentDataLayer.cs
| 2.75
| 3
|
using Common.Model;
using DataAccess.Abstract.IStudentDL;
using Domain;
using Infrastructure.Contract;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
namespace DataAccess.Concrete.StudentDL
{
public class StudentDataLayer : IStudentDataLayer
{
private readonly IBaseRepository<Student> _baseRepository;
private readonly IBaseRepository<StudentModel> _baseRepositoryModel;
public StudentDataLayer(IBaseRepository<Student> baseRepository, IBaseRepository<StudentModel> baseRepositoryModel)
{
_baseRepository = baseRepository;
_baseRepositoryModel = baseRepositoryModel;
}
public int Insert(Student Entity)
{
return _baseRepository.Insert(Entity);
}
public Student GetById(int id) {
return _baseRepository.GetById(id);
}
public IQueryable<Student> FindAll()
{
return _baseRepository.FindAll();
}
public void ExecuteNonQuery(string commandText, CommandType commandType, SqlParameter[] parameters = null)
{
_baseRepository.ExecuteNonQuery(commandText, commandType, parameters);
}
public IQueryable ExcuteSqlQuery(string sqlQuery, CommandType commandType, SqlParameter[] parameters = null)
{
return _baseRepositoryModel.ExcuteSqlQuery(sqlQuery, commandType, parameters);
}
}
}
|
a632d99cc4997ce09f75c55949d9f6797a366fee
|
C#
|
WolfGamesLLC/WolfGamesUnityApps
|
/Marble Motion/Assets/Scripts/OldPlayerController.cs
| 2.578125
| 3
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System;
public class OldPlayerController : MonoBehaviour, IMovementController
{
public BallController ballController;
private Rigidbody rB;
// Run when the enable event is fired
public void OnEnable()
{
ballController = new BallController();
ballController.SetMovementController(this);
}
// Initialize the object
public void Start()
{
rB = GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate()
{
float hMove = Input.GetAxis("Horizontal");
float vMove = Input.GetAxis("Vertical");
ballController.SetSpeed(hMove, vMove);
ballController.Move(hMove, vMove);
}
// OnTriggerEnter is called when the Collider other enters the trigger
public void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("PickUp"))
other.gameObject.SetActive(false);
}
#region IMovementController implementation
public void MoveObject(Vector3 force)
{
rB.AddForce(force);
}
public Vector3 Position()
{
return rB.position;
}
#endregion
}
|
e88f2f2e2ecef8bf3bafc4e7503f5014eacb1bd7
|
C#
|
Dantellevi/Xamarin_develop
|
/Metanit_Lesson/patternMVVM/ContextMenuMVVM/ContextMenuMVVM/ContextMenuMVVM/PhoneViewModel.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
namespace ContextMenuMVVM
{
public class PhoneViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public Phone Phone { get; set; }
public PhonesListViewModel ListViewModel { get; set; }
public PhoneViewModel()
{
Phone = new Phone();
}
public string Title
{
get { return Phone.Title; }
set
{
if (Phone.Title != value)
{
Phone.Title = value;
OnPropertyChanged("Title");
}
}
}
public string Company
{
get { return Phone.Company; }
set
{
if (Phone.Company != value)
{
Phone.Company = value;
OnPropertyChanged("Company");
}
}
}
public int Price
{
get { return Phone.Price; }
set
{
if (Phone.Price != value)
{
Phone.Price = value;
OnPropertyChanged("Price");
}
}
}
protected void OnPropertyChanged(string propName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
}
|
a12f1f55bc5a4b3c24a91dcac842b82071b8e4b7
|
C#
|
BroYee/StudentSoldier
|
/6-25 War - Student Soldier/Assets/InGame/Item/ItemManager.cs
| 2.609375
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemManager : MonoBehaviour {
public List<GameObject> items;
public bool[] itemUsed;
private void Start()
{
StartCoroutine(RegenAmmo(0));
StartCoroutine(RegenFirstAidKit(0));
itemUsed = new bool[items.Capacity];
for (int i = 0; i < items.Capacity; i++)
{
itemUsed[i] = false;
}
}
private void Update()
{
if (itemUsed[0] == true)
{
StartCoroutine(RegenAmmo(10.0f));
itemUsed[0] = false;
}
if (itemUsed[1] == true)
{
StartCoroutine(RegenFirstAidKit(7.0f));
itemUsed[1] = false;
}
}
public IEnumerator RegenAmmo(float time)
{
yield return new WaitForSeconds(time);
GameObject tempAmmo = Instantiate(items[0], new Vector3(-10, 3, 0), Quaternion.identity);
tempAmmo.transform.SetParent(transform);
}
public IEnumerator RegenFirstAidKit(float time)
{
yield return new WaitForSeconds(time);
GameObject tempFirstAidKit = Instantiate(items[1], new Vector3(-4.6f, -3, 0), Quaternion.identity);
tempFirstAidKit.transform.SetParent(transform);
}
}
|
b14d93b753cd8c4355dcf3a0e5b6a7c4ed389ec6
|
C#
|
vicenteMdz/camino-mas-corto-algoritmo-evolutivo
|
/JuegoCaminoMasCorto/Coordenadas.cs
| 3.078125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JuegoCaminoMasCorto
{
class Coordenadas
{
private int coordx = 0; private int coordy = 0;
public String Coordenada
{
get
{
return "(" + coordx + "," + coordy + " )";
}
}//Para devolver la coordenada en String.
public int X
{
get { return this.coordx; }
}//Para el valor de X.
public int Y
{
get { return this.coordy; }
}//Para el valor de Y.
public Coordenadas(int x, int y)
{
this.coordx = x; this.coordy = y;
}//Constructor de la clase Coordenadas.
}//Fin de la clase Coordenadas.
}
|
47c27f659f93c550605560890cb4c7b1f06e05aa
|
C#
|
Dijkstra7/AureaDashboard
|
/Assets/Scripts/Student_Selector_Manager.cs
| 2.765625
| 3
|
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine.UI;
using System.Text.RegularExpressions;
using System.Linq;
using System;
//----------------------------------------------------------
// Generates a student list inside the student selector
// From the file 'Ginzy_Students_List.csv' in 'Resources
//----------------------------------------------------------
public class Student_Selector_Manager : MonoBehaviour
{
public GameObject canvas;
[SerializeField]
private GameObject button;
private List<string> stringList;
private List<string[]> parsedList;
List<string> student_Names = new List<string>();
List<int> student_IDs = new List<int>();
private void Awake() {
//button = canvas.transform.Find("Student_List_Button").gameObject;
}
// Start is called before the first frame update
void Start()
{
stringList = new List<string>();
parsedList = new List<string[]>();
read_Student_File_Android();
initialise_student_List();
}
// Read student names and ids from text file in Resources.
private void read_Student_File_Android() {
TextAsset studnames = Resources.Load("Ginzy_Students_List") as TextAsset;
string[] fLines = Regex.Split( studnames.text, "\n" );
//print(fLines[0]);
// split into jagged array
for( int i=0; i < fLines.Length; i++ ){
string[] student_line = Regex.Split( fLines[i], ";" );
student_Names.Add(student_line[1]);
student_IDs.Add(int.Parse(student_line[0]));
}
}
private void read_Student_File() {
string path = "Assets/Resources/Ginzy_Students_List.csv";
StreamReader inp_stm = new StreamReader(path);
while (!inp_stm.EndOfStream)
{
string inp_ln = inp_stm.ReadLine();
stringList.Add(inp_ln);
}
inp_stm.Close();
parseList();
}
void parseList()
{
for (int i = 0; i < stringList.Count; i++)
{
string[] temp = stringList[i].Split(';');
for (int j = 0; j < temp.Length; j++)
{
temp[j] = temp[j].Trim();
}
parsedList.Add(temp);
}
foreach (var item in parsedList)
{
student_Names.Add(item[1]);
student_IDs.Add(int.Parse(item[0]));
}
}
private void initialise_student_List() {
GameObject newButton;
int count = 0;
foreach(string name in student_Names) {
newButton = Instantiate(button) as GameObject;
newButton.transform.SetParent(canvas.transform, false);
newButton.SetActive(true);
newButton.transform.Find("Text").gameObject.GetComponent<Text>().text = name;
newButton.GetComponent<Student_Data>().ID = student_IDs[count];
newButton.GetComponent<Student_Data>().name = name + ", ID: " + student_IDs[count];
count += 1;
}
}
}
|
2af334cc4764fb642cf6f60adf98750ae1495deb
|
C#
|
tomazk8/SoftCore
|
/SoftCore/Composition/ComposablePart.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Linq;
namespace SoftCore.Composition
{
/// <summary>
/// Represents the part in the IoC container that has at least one export and can have imports.
/// </summary>
public class ComposablePart
{
public ComposablePart(Type partType, IEnumerable<ComposablePartExport> exports,
IEnumerable<ComposablePartImport> imports, LifetimeManager lifetimeManager)
{
this.PartType = partType;
this.Exports = exports;
this.Imports = imports;
this.LifetimeManager = lifetimeManager;
}
public ComposablePart(Type partType)
{
// TODO: although Part itself doesn't know anything about attributes for export, improt and lifetime,
// the attributes are used here only to construct it. It would be wise to move this code out of
// this class.
this.PartType = partType;
Exports = CompositionTools.GetExports(partType);
Imports = CompositionTools.GetImports(partType);
// Create lifetime manager
NotSharedAttribute notSharedAttribute = partType.GetCustomAttribute<NotSharedAttribute>();
LifetimeManager = notSharedAttribute != null
? ((LifetimeManager)new NotSharedLifetimeManager(partType))
: ((LifetimeManager)new SharedLifetimeManager(partType));
}
public ComposablePart(Type partType, LifetimeManager lifetimeManager)
{
// TODO: although Part itself doesn't know anything about attributes for export, improt and lifetime,
// the attributes are used here only to construct it. It would be wise to move this code out of
// this class.
this.PartType = partType;
Exports = CompositionTools.GetExports(partType);
Imports = CompositionTools.GetImports(partType);
this.LifetimeManager = lifetimeManager;
}
public LifetimeManager LifetimeManager { get; private set; }
public Type PartType { get; private set; }
public IEnumerable<ComposablePartExport> Exports { get; private set; }
public IEnumerable<ComposablePartImport> Imports { get; private set; }
}
}
|
55331880c29fe45ad0844fa5045f98a660c08a3e
|
C#
|
sym1945/JYOOK
|
/JYOOK.Infrastructure.Data/Repositories/PackingRepository.cs
| 2.625
| 3
|
using JYOOK.Domain;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace JYOOK.Infrastructure.Data
{
public class PackingRepository : IPackingRepository
{
private const string CONFIG_PATH = @"Configs\Packings.xml";
private readonly XmlSerializer<List<PackingInfo>> _XmlSerializer = new XmlSerializer<List<PackingInfo>>(CONFIG_PATH);
public PackingRepository()
{
}
public async Task<List<PackingInfo>> GetPackingInfos()
{
return await Task.Run(() =>
{
try
{
return _XmlSerializer.LoadXml();
}
catch
{
return new List<PackingInfo>();
}
});
}
public async Task Save(List<PackingInfo> packingInfos)
{
await Task.Run(() =>
{
_XmlSerializer.SaveXml(packingInfos);
});
}
}
}
|
4ca00d4dc2b552e9b8e2b2777d5ccb705d0ffc9e
|
C#
|
wouldyougo/TRx
|
/TRL.Emulation/TradingDataContextExtensionsForEmulation.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TRL.Common.Data;
using TRL.Common.Models;
using TRL.Common.Collections;
namespace TRL.Emulation
{
public static class TradingDataContextExtensionsForEmulation
{
public static Order AddSignalAndItsOrder(this IDataContext context, Signal signal)
{
if (!context.StrategyExists(signal.Strategy))
return null;
if (context.SignalExists(signal))
return context.GetSignalOrder(signal);
context.Get<ObservableHashSet<Signal>>().Add(signal);
Order order = new Order(signal);
order.DeliveryDate = order.DateTime.AddSeconds(1);
context.Get<ObservableHashSet<Order>>().Add(order);
return order;
}
public static bool SignalExists(this IDataContext context, Signal signal)
{
return context.Get<IEnumerable<Signal>>().Any(s => s.Id == signal.Id);
}
public static Order GetSignalOrder(this IDataContext context, Signal signal)
{
return context.Get<IEnumerable<Order>>().SingleOrDefault(o => o.SignalId == signal.Id);
}
public static bool StrategyExists(this IDataContext context, StrategyHeader strategyHeader)
{
return context.Get<IEnumerable<StrategyHeader>>().Any(s => s.Id == strategyHeader.Id);
}
public static Trade AddSignalAndItsOrderAndTrade(this IDataContext context, Signal signal)
{
return context.AddSignalAndItsOrderAndTrade(signal, signal.Price, signal.Amount);
}
public static Trade AddSignalAndItsOrderAndTrade(this IDataContext context, Signal signal, double price)
{
return context.AddSignalAndItsOrderAndTrade(signal, price, signal.Amount);
}
public static Trade AddSignalAndItsOrderAndTrade(this IDataContext context, Signal signal, double price, double amount)
{
Order order = context.AddSignalAndItsOrder(signal);
if (order == null)
return null;
order.FilledAmount += amount;
order.DeliveryDate = order.DateTime.AddSeconds(1);
Trade trade = new Trade(order, order.Portfolio, order.Symbol, price, order.TradeAction == TradeAction.Buy ? amount : -amount, order.DateTime);
context.Get<ObservableHashSet<Trade>>().Add(trade);
return trade;
}
}
}
|
c1871c43f4a0379dec2206d5df3d99700c5838d6
|
C#
|
norisradu/JuniorMind
|
/Field/Field/FieldTests.cs
| 3.28125
| 3
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Field
{
[TestClass]
public class FieldTests
{
[TestMethod]
public void InitialAreaForASimpleScenario()
{
float initialArea = CalculateInitialArea(1, 6);
Assert.AreEqual(2, initialArea);
}
[TestMethod]
public void InitialAreaForASecondScenario()
{
float initialArea = CalculateInitialArea(3, 40);
Assert.AreEqual(5, initialArea);
}
[TestMethod]
public void InitialAreaForTheGivenScenario()
{
float initialArea = CalculateInitialArea(230, 770000);
Assert.AreEqual(770, initialArea);
}
float CalculateInitialArea (int newWidth, int finalArea)
{
double solution1 = 0;
int discriminant = newWidth * newWidth + 4 * finalArea;
if (discriminant > 0)
{
solution1 = (- newWidth + Math.Sqrt(discriminant)) / 2;
return (float)solution1;
}
else return 0;
}
}
}
|
367867fa83ae566fd09dea8c24755052cf77b45e
|
C#
|
balanikas/ExpressQuiz
|
/ExpressQuiz.Core/Utils/DataProvider.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;
using System.Xml.Schema;
using ExpressQuiz.Core.Models;
namespace ExpressQuiz.Core.Utils
{
public class DataProvider
{
private static bool ValidateData(XDocument doc, string schemaUri)
{
var schemas = new XmlSchemaSet();
schemas.Add("", schemaUri);
bool valid = true;
doc.Validate(schemas, (o, e) =>
{
throw new Exception(e.Exception.InnerException.Message);
valid = false;
});
return valid;
}
public static IEnumerable<Quiz> Import(string uri)
{
var xml = XDocument.Load(uri, LoadOptions.PreserveWhitespace);
//TODO: validate against xsd file
char[] charsToTrim = {'\r', ' ', '\n'};
var content = xml.Element("Content");
var quizzes = new List<Quiz>();
foreach (var quiz in content.Element("Quizzes").Elements("Quiz"))
{
var questions = new List<Question>();
foreach (var q in quiz.Elements("Question"))
{
var answers = new List<Answer>();
foreach (var a in q.Elements("Answer"))
{
answers.Add(new Answer
{
Text = a.Element("Text").Value.Trim(charsToTrim),
IsCorrect = a.Descendants("IsCorrect").Any(),
Explanation = a.Element("Explanation").Value.Trim(charsToTrim),
OrderId = int.Parse(a.Element("OrderId").Value.Trim(charsToTrim))
});
}
questions.Add(new Question
{
Answers = answers,
Text = q.Element("Text").Value.Trim(charsToTrim),
OrderId = int.Parse(q.Element("OrderId").Value.Trim(charsToTrim)),
EstimatedTime = int.Parse(q.Element("EstimatedTime").Value.Trim(charsToTrim)),
Points = int.Parse(q.Element("Points").Value.Trim(charsToTrim)),
});
}
quizzes.Add(new Quiz
{
Category = new QuizCategory
{
Name = ((string) quiz.Attribute("category")).Trim(charsToTrim)
},
Name = quiz.Element("Name").Value.Trim(charsToTrim),
Summary = quiz.Element("Summary").Value.Trim(charsToTrim),
Questions = questions,
Created = DateTime.Now,
IsTimeable = quiz.Descendants("IsTimeable").Any(),
CreatedBy = quiz.Element("CreatedBy").Value.Trim(charsToTrim),
Locked = quiz.Descendants("Locked").Any(),
AllowPoints = quiz.Descendants("AllowPoints").Any(),
});
}
return quizzes;
}
public static void Export(List<Quiz> quizzes, string fileName)
{
var doc = new XDocument();
var root = new XElement("Content");
doc.Add(root);
var quizzesEl = new XElement("Quizzes");
root.Add(quizzesEl);
foreach (var quiz in quizzes.ToList())
{
var quizEl = new XElement("Quiz", new XAttribute("category", quiz.Category.Name));
quizEl.Add(new XElement("Name", quiz.Name));
quizEl.Add(new XElement("Summary", quiz.Summary));
quizEl.Add(new XElement("CreatedBy", quiz.CreatedBy));
if (quiz.IsTimeable)
{
quizEl.Add(new XElement("IsTimeable"));
}
if (quiz.Locked)
{
quizEl.Add(new XElement("Locked"));
}
if (quiz.AllowPoints)
{
quizEl.Add(new XElement("AllowPoints"));
}
foreach (var q in quiz.Questions.ToList())
{
var qEl = new XElement("Question");
qEl.Add(new XElement("OrderId", q.OrderId));
qEl.Add(new XElement("Text", q.Text));
qEl.Add(new XElement("EstimatedTime", q.EstimatedTime));
qEl.Add(new XElement("Points", q.Points));
foreach (var a in q.Answers.ToList())
{
var aEl = new XElement("Answer");
aEl.Add(new XElement("OrderId", a.OrderId));
aEl.Add(new XElement("Text", a.Text));
aEl.Add(new XElement("Explanation", a.Explanation));
if (a.IsCorrect)
{
aEl.Add(new XElement("IsCorrect"));
}
qEl.Add(aEl);
}
quizEl.Add(qEl);
}
quizzesEl.Add(quizEl);
}
doc.Save(fileName);
}
public static string MapPath(string seedFile)
{
var absolutePath = new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath;
var directoryName = Path.GetDirectoryName(absolutePath);
var path = Path.Combine(directoryName, ".." + seedFile.TrimStart('~').Replace('/', '\\'));
return path;
}
}
}
|
85533876c03d7bf1779403f5baf930b1dbaa9470
|
C#
|
AndreyMav/OpenTradingFrameworkNet
|
/OTFNCore/Market/Timeframe.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OTFN.Core.Market
{
public class Timeframe
{
private int minutes;
public int Minutes
{
get
{
return minutes;
}
}
private Timeframe(int minutes)
{
this.minutes = minutes;
timeframeByMinutes.Add(minutes, this);
}
private static Dictionary<int, Timeframe> timeframeByMinutes = new Dictionary<int, Timeframe>();
public static Timeframe GetFromMinutes(int minutes)
{
Timeframe tf = null;
if (!timeframeByMinutes.TryGetValue(minutes, out tf))
{
tf = new Timeframe(minutes);
}
return tf;
}
public static Timeframe M1 = new Timeframe(1);
public static Timeframe M5 = new Timeframe(5);
public static Timeframe M15 = new Timeframe(15);
public static Timeframe M30 = new Timeframe(30);
public static Timeframe H1 = new Timeframe(60);
public static Timeframe H4 = new Timeframe(INMUNITES_H4);
public static Timeframe D1 = new Timeframe(INMUNITES_D1);
public static Timeframe W1 = new Timeframe(INMUNITES_W1);
public static Timeframe MN1 = new Timeframe(INMUNITES_MN1);
public const int INMUNITES_H4 = 240;
public const int INMUNITES_D1 = 1440;
public const int INMUNITES_W1 = 10080;
public const int INMUNITES_MN1 = 43200;
}
}
|
cfd8cd3c08d5ba4451e18edf24093f76981f8837
|
C#
|
FabricioZAGA/programacion-entornos-visuales-issc
|
/A6 - GEOMETRÍA/A6 - GEOMETRÍA/Program.cs
| 3.203125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace A6___GEOMETRÍA
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("¿Prismas (1) o Pirámides (2)");
int res = Int32.Parse(Console.ReadLine());
while (res != 1 && res != 2)
{
Console.WriteLine("¿Prismas (1) o Pirámides (2)");
res = Int32.Parse(Console.ReadLine());
}
if (res == 1) //Prismas
{
Prisma prisma = new Prisma();
Console.WriteLine("Nombre Figura");
prisma.Nombre = Console.ReadLine();
Console.WriteLine("NumLados");
prisma.NumLados = Int32.Parse(Console.ReadLine());
Console.WriteLine("Longitud del Lado");
prisma.LongLado = Double.Parse(Console.ReadLine());
Console.WriteLine("Longitud del Radio");
prisma.Radio = Double.Parse(Console.ReadLine());
Console.WriteLine("Altura");
prisma.Altura = Double.Parse(Console.ReadLine());
Console.WriteLine("Area " + prisma.Nombre + ": " + prisma.GetArea());
Console.WriteLine("Perimetro " + prisma.Nombre + ": " + prisma.GetPerimetro());
Console.WriteLine("Volumen " + prisma.Nombre + ": " + prisma.GetVolumen());
Console.WriteLine("Area de Prisma " + prisma.Nombre + ": " + prisma.GetAreaPrisma());
Console.ReadKey();
}
else if(res == 2) //Piramides
{
Piramide piramide = new Piramide();
Console.WriteLine("Nombre Figura");
piramide.Nombre = Console.ReadLine();
Console.WriteLine("NumLados");
piramide.NumLados = Int32.Parse(Console.ReadLine());
Console.WriteLine("Longitud del Lado");
piramide.LongLado = Double.Parse(Console.ReadLine());
Console.WriteLine("Longitud del Radio");
piramide.Radio = Double.Parse(Console.ReadLine());
Console.WriteLine("Altura");
piramide.Altura = Double.Parse(Console.ReadLine());
Console.WriteLine("Area " + piramide.Nombre + ": " + piramide.GetArea());
Console.WriteLine("Perimetro " + piramide.Nombre + ": " + piramide.GetPerimetro());
Console.WriteLine("Volumen " + piramide.Nombre + ": " + piramide.GetVolumen());
Console.WriteLine("Area de Piramide " + piramide.Nombre + ": "+ piramide.GetAreaPiramide());
Console.ReadKey();
}
}
}
}
|
d132a540def85ead73cb54be41d98e0bb4bafa79
|
C#
|
Tuka96/ASP-DOT-NET
|
/class demo/AmazonOnline/DAL/CatalogDBManger.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using Catalog;
using System.Runtime.InteropServices;
namespace DAL
{
public static class CatalogDBManger
{
//CRUD Operations against database
//read
public static IEnumerable<Product> GetAllProducts()
{
//Invoke backend data into .NET application
// needed database connectivity
// you need to use
// 1. ADO.NET Object Model ( JDBC) (Activex Data Object or
// 2. Entity Framework (Hibernate)
// 1.connect to database
// query against database using SQL
// get resultset from Query Processing
// Create List of Products from resultset
//return list of Products
List<Product> allProducts = new List<Product>();
IDbConnection con = new SqlConnection();
con.ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\C - DAC Assignment\ASP.NET\ASP - DOT - NET\class demo\AmazonOnline\TesterApp\ECommerce.mdf;Integrated Security=True";
IDbCommand cmd = new SqlCommand();
string query = "SELECT * FROM flowers";
cmd.Connection = con;
cmd.CommandText = query;
IDataReader reader = null;
try
{
con.Open();
reader=cmd.ExecuteReader();
while (reader.Read())
{
int id = int.Parse(reader["ProductID"].ToString());
string title = reader["title"].ToString();
string description = reader["description"].ToString();
int unitPrice =int.Parse(reader["price"].ToString());
int quantity=int.Parse(reader["quantity"].ToString());
Product theProduct = new Product
{
ID = id,
Title = title,
Description = description,
UnitPrice = unitPrice,
Quantity = quantity
};
allProducts.Add(theProduct);
}
reader.Close();
}
catch (SqlException exp)
{
string message = exp.Message;
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
return allProducts;
}
//create
public static bool Insert(Product theProduct)
{
bool status = false;
// logic to insertion
return status;
}
//update
public static bool Update(Product theProduct)
{
bool status = false;
// logic to updation
return status;
}
//delte
public static bool Delete(int productID)
{
bool status = false;
// logic to removal
return status;
}
}
}
|
2bb32d4893dc099a53a9050584f38fcdc72de1f7
|
C#
|
cdoyle02/TacoParser
|
/LoggingKata/Program.cs
| 3.203125
| 3
|
using System;
using System.Linq;
using System.IO;
using GeoCoordinatePortable;
namespace LoggingKata
{
class Program
{
static readonly ILog logger = new TacoLogger();
const string csvPath = "TacoBell-US-AL.csv";
static void Main(string[] args)
{
logger.LogInfo("Log initialized");
var lines = File.ReadAllLines(csvPath);
logger.LogInfo($"Lines: {lines[0]}");
if(lines.Length == 0)
{
logger.LogError("There are 0 lines.", null);
}
if(lines.Length == 1)
{
logger.LogWarning("There is only 1 line.");
}
var parser = new TacoParser();
var locations = lines.Select(parser.Parse).ToArray();
ITrackable tb1 = new TacoBell();
ITrackable tb2 = new TacoBell();
double distance1 = 0.00;
for(int i = 0; i < locations.Length; i++)
{
var locA = locations[i];
var corA = locA.Location;
GeoCoordinate loc1 = new GeoCoordinate(corA.Latitude, corA.Longitude);
for(int j = locations.Length - 1; j >= 1; j--)
{
var locB = locations[j];
var corB = locB.Location;
GeoCoordinate loc2 = new GeoCoordinate(corB.Latitude, corB.Longitude);
double distance = loc2.GetDistanceTo(loc1);
if(distance1 < distance)
{
distance1 = distance;
tb1 = locA;
tb2 = locB;
}
}
}
Console.WriteLine($"The distance between {tb1.Name} and {tb2.Name} is {distance1}");
}
}
}
|
321a2e6296c87cb95d2df3a5df168ee6fbb5674b
|
C#
|
efletche/PetClass
|
/PetClassTest/Program.cs
| 3.125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PetClassTest
{
class Program
{
static void Main(string[] args)
{
List<PetClass> PetList = new List<PetClass>();
PetList.Add(new PetCat("Mittens","Cream"));
PetList.Add(new CoolCat("Garfield"));
PetList.Add(new PetDog("Bowser"));
foreach(var pet in PetList)
{
pet.Speak();
if(pet.petType == "cat")
{
Console.WriteLine("Jon loves his best friend {0}", pet.name);
Console.WriteLine("and {0}", ((PetCat)pet).furColor);
}
}
Console.WriteLine("Hello World");
//.ReadLine();
}
}
}
|
fae0d14ac811d6a52bc6e8609cc199613053e611
|
C#
|
WhoStoleMyToast/StockBuddy
|
/ZackRankFinder/SymbolFetcher.cs
| 2.953125
| 3
|
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
namespace ZackRankFinder
{
public class SymbolFetcher : ISymbolFetcher
{
private ILogger _logger;
public SymbolFetcher(ILogger<SymbolFetcher> logger)
{
_logger = logger;
}
public async Task<List<string>> GetSymbols()
{
var symbols = new List<string>();
try
{
// Other
string otherListed = string.Empty;
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://ftp.nasdaqtrader.com/SymbolDirectory/otherlisted.txt");
request.Method = WebRequestMethods.Ftp.DownloadFile;
using (Stream stream = request.GetResponse().GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
otherListed = await reader.ReadToEndAsync();
}
otherListed = otherListed.Replace("ACT Symbol|Security Name|Exchange|CQS Symbol|ETF|Round Lot Size|Test Issue|NASDAQ Symbol\r\n", "");
// Nasdaq
string nasdaqListed = string.Empty;
FtpWebRequest request2 =
(FtpWebRequest)WebRequest.Create("ftp://ftp.nasdaqtrader.com/SymbolDirectory/nasdaqlisted.txt");
request2.Method = WebRequestMethods.Ftp.DownloadFile;
using (Stream stream = request2.GetResponse().GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
nasdaqListed = await reader.ReadToEndAsync();
}
nasdaqListed = nasdaqListed.Replace("Symbol|Security Name|Market Category|Test Issue|Financial Status|Round Lot Size\r\n", "");
// Combine
var stocksStr = (nasdaqListed + otherListed);
var stocks = stocksStr.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var stock in stocks)
{
symbols.Add(stock.Split(new char[] { '|' })[0]);
}
}
catch (Exception ex)
{
_logger.LogDebug(ex, "GetSymbols --> {0}");
}
return symbols;
}
}
}
|
23772fea416304f80d58d6ceb6b0ca7e189a324c
|
C#
|
doublnt/dotnetcore
|
/EntityFrameworkCore/EFWebDemo/DataBaseContext/BooksContext.cs
| 2.609375
| 3
|
using System;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using EFWebDemo.Model;
namespace EFWebDemo.DataBaseContext
{
public class BooksContext : DbContext
{
public BooksContext(DbContextOptions<BooksContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuiler)
{
modelBuiler.Entity<Book>()
.HasKey(p => p.Name);
}
public DbSet<Book> Books { get; set; }
}
}
|
62597a4c30f6b9110537e8d9e0d42e6a54bb4aad
|
C#
|
atanasd357/Introducing-to-Programming-With-CSharp-Book
|
/13.Strings/CensorForbiddenWords/Program.cs
| 3.375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
//Task 11
namespace CensorForbiddenWords
{
class Program
{
static void Main(string[] args)
{
string text = "Microsoft announced its next generation C# compiler today. " +
"It uses advanced parser and special optimizer for the Microsoft CLR.";
Console.WriteLine(text);
string words = "C#,CLR,Microsoft";
Console.WriteLine("\nForbidden words is: " + words);
char[] splitChars = { ' ', ',' };
string[] forbiddenWords = words.Split(splitChars);
for (int i = 0; i < forbiddenWords.Length; i++)
{
int wordIndex = text.IndexOf(forbiddenWords[i].Trim());
while (wordIndex != -1)
{
string replacement = new String('*', forbiddenWords[i].Length);
text = text.Replace(text, Regex.Replace(text, forbiddenWords[i], replacement));
wordIndex = text.IndexOf(forbiddenWords[i].Trim(),
wordIndex + forbiddenWords[i].Trim().Length);
}
}
Console.WriteLine("\n" + text + "\n");
}
}
}
|
d436030428db40ea25e627980c8ddc29ccfd9707
|
C#
|
MirellaU/Complec-project
|
/Project/Complex.cs
| 3.578125
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project
{
class Complex
{
public double Real { get; set; }
public double Imaginary { get; set; }
public Complex(double real, double imaginary)
{
this.Real = real;
this.Imaginary = imaginary;
}
static public Complex Addition(Complex a, Complex b)
{
double c_real = a.Real + b.Real;
double c_imag = a.Imaginary + b.Imaginary;
Complex c = new Complex(c_real, c_imag);
return c;
}
static public Complex Subtraction(Complex a, Complex b)
{
double c_real = a.Real - b.Real;
double c_imag = a.Imaginary - b.Imaginary;
Complex c = new Complex(c_real, c_imag);
return c;
}
static public Complex Multiplication(Complex a, Complex b)
{
double c_real = a.Real*b.Real-a.Imaginary*b.Imaginary;
double c_imag = a.Imaginary * b.Real + a.Real * b.Imaginary;
Complex c = new Complex(c_real, c_imag);
return c;
}
static public Complex Division(Complex a, Complex b)
{
double c_imag = (a.Imaginary * b.Real - a.Real * b.Imaginary)/(Math.Pow(b.Real,2)+ Math.Pow(b.Imaginary,2));
double c_real = a.Real * b.Real + a.Imaginary * b.Imaginary+c_imag/ (Math.Pow(b.Real, 2) + Math.Pow(b.Imaginary, 2));
Complex c = new Complex(c_real, c_imag);
return c;
}
}
}
|
461adfd7a4b425ec2c921a568dd1809f57f71a37
|
C#
|
coderhardly/BasicPracticeByCsharp
|
/Singleton/Program.cs
| 3.28125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Singleton
{
class Program
{
static void Main(string[] args)
{
SingeltonDemo s1 = SingeltonDemo.GetInstance();
SingeltonDemo s2 = SingeltonDemo.GetInstance();
if (s1 == s2)
{
Console.WriteLine("equal");
}
object obj1 = null;
object obj2 = null;
Thread thread1 = new Thread(() =>
{
obj1 = SingeltonDemo.GetInstance1();
});
thread1.Start();
Thread thread2 = new Thread(() =>
{
obj2= SingeltonDemo.GetInstance1();
});
thread2.Start();
thread1.Join();
thread2.Join();
if (obj2 != null && obj1 != null && obj2 == obj1)
{
Console.WriteLine("equal2");
}
Console.Read();
}
}
}
|
f8ebccd8321bc6ea703b009ef52e9e4cd30e2872
|
C#
|
aL3891/FinBotFramework
|
/FinBotFramework/Program.cs
| 2.59375
| 3
|
using System;
using System.IO;
using System.Linq;
using Tulip;
namespace FinBotNet
{
class Program
{
public static string ToProp(string input) => string.Join("", input.Replace("%", "").Split(' ').Select(n => Cap(n)));
public static string Cap(string input) => input[0].ToString().ToUpper() + input.Substring(1);
static void Main(string[] args)
{
GenerateTulipIndicators()
}
private static void GenerateTulipIndicators()
{
foreach (var item in Indicators.IndicatorsDefinition)
{
var fi = new FileInfo($@"..\..\..\Tulip\{item.Key.ToUpper()}.cs");
var props = string.Join(Environment.NewLine, item.Value.Outputs.Concat(item.Value.Options).Select(p => $" public decimal {ToProp(p)} {{ get; set; }}"));
File.WriteAllText(fi.FullName, $@"using Microsoft.EntityFrameworkCore;
using System;
using FinBotNet;
using System.Threading.Tasks;
using Tulip;
using System.Linq;
namespace FinBotNet.Tulip
{{
/// <summary>
/// {item.Value.FullName}
/// </summary>
[Keyless]
public class {item.Key.ToUpper()}
{{
public Stock Stock {{ get; set; }}
public string StockId {{ get; set; }}
public DateTime Date {{ get; set; }}
public TimeSpan TimeSpan {{ get; set; }}
{props}
public async Task Calculate(BotContext context)
{{
var indicator = Indicators.IndicatorsDefinition[""{item.Key}""];
var count = indicator.Start(new decimal[] {{{string.Join(", ", item.Value.Options.Select(p => ToProp(p)))}}});
var inputLength = (int){(item.Value.Options.Contains("period") ? "Period" : "1")} + count;
var price = await context.StockPrice
.Where(s => s.StockId == StockId)
.Where(s => s.Date < Date)
.Where(s => s.TimeSpan == TimeSpan)
.OrderByDescending(s => s.Date)
.Take(inputLength)
.ToArrayAsync();
if (price.Length - count < 1)
return;
decimal[][] input = price.Select(c => new decimal[] {{ {string.Join(", ", item.Value.Inputs.Select(p => "c." + ToProp(p.Replace("real", "close"))))} }}).ToArray();
decimal[][] output = new decimal[price.Length - count][];
for (int i = 0; i < output.Length; i++)
{{
output[i] = new decimal[{item.Value.Outputs.Length}];
}}
indicator.Run(input, new decimal[] {{{string.Join(", ", item.Value.Options.Select(p => ToProp(p)))}}}, output);
{ string.Join(Environment.NewLine, item.Value.Outputs.Select((o, i) => ToProp(o) + " = output[0][" + i + "];"))}
}}
}}
}}
");
}
}
}
}
|
16567dfcc16ad28a5f05e509530bdc186f151a3f
|
C#
|
mangostools/ScriptEditor
|
/ScriptEditor/FormMaskCalculator.cs
| 2.9375
| 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;
namespace ScriptEditor
{
public partial class FormMaskCalculator : Form
{
public uint ReturnValue { get; set; } // we return the mask in this
public FormMaskCalculator(uint phasemask)
{
InitializeComponent();
ReturnValue = phasemask;
}
private void FormMaskCalculator_Load(object sender, EventArgs e)
{
UpdatePhasesList();
}
private void UpdatePhasesList()
{
if (ReturnValue == 0)
{
txtPhasesList.Text = "No phases are excluded.";
return;
}
txtPhasesList.Text = "";
for (int i = 0; i < 32; i++)
{
uint current = (uint)Math.Pow(2, i);
if ((ReturnValue & current) != 0)
txtPhasesList.Text += "Phase " + i + ": 0x" + current.ToString("x8") + "\r\n";
}
txtPhasesList.Text += "\r\n-----------------\r\nTotal mask value: " + ReturnValue.ToString();
}
private void btnPhaseAdd_Click(object sender, EventArgs e)
{
uint phase = 0;
if ((txtPhase.Text.Length == 0) || (!uint.TryParse(txtPhase.Text, out phase)))
return;
uint mask = (uint)Math.Pow(2, phase);
if ((ReturnValue & mask) != 0)
return;
else
ReturnValue |= mask;
UpdatePhasesList();
}
private void btnPhaseRemove_Click(object sender, EventArgs e)
{
uint phase = 0;
if ((txtPhase.Text.Length == 0) || (!uint.TryParse(txtPhase.Text, out phase)))
return;
uint mask = (uint)Math.Pow(2, phase);
if ((ReturnValue & mask) != 0)
ReturnValue -= mask;
else
return;
UpdatePhasesList();
}
}
}
|
03f89da0738118a1842a22f298dae71d0c26f160
|
C#
|
CloudHolic/VST.Net-Synthesizer
|
/Syntage.Framework/Parameters/IntegerParameter.cs
| 3.015625
| 3
|
using System;
using System.Globalization;
using Syntage.Framework.Tools;
namespace Syntage.Framework.Parameters
{
public class IntegerParameter : Parameter<int>
{
public IntegerParameter(string name, string label, string shortLabel, int min, int max,
int step, bool canBeAutomated = true) :
base(name, label, shortLabel, min, max, step, canBeAutomated)
{
}
public override int FromReal(double value)
{
return (int)Math.Round(DSPFunctions.Lerp(Min, Max, value), MidpointRounding.AwayFromZero);
}
public override double ToReal(int value)
{
return (value - Min) / (Max - Min);
}
public override int FromStringToValue(string s)
{
return (int)Math.Round(DSPFunctions.Clamp(int.Parse(s, CultureInfo.InvariantCulture), Min, Max), MidpointRounding.AwayFromZero);
}
public override string FromValueToString(int value)
{
return value.ToString();
}
}
}
|
e7d9d643cffc5ab531aa299979aa2de703c68085
|
C#
|
mastertnt/cga-parser
|
/CGACompute/Extrude.cs
| 3.140625
| 3
|
using System;
using CGAParser;
using SharpDX;
namespace CGACompute
{
/// <summary>
/// Extrude algorithm.
/// </summary>
public class Extrude : IAlgorithm<Polygon, Geometry>
{
/// <summary>
/// Distance of extrusion.
/// </summary>
public float Distance
{
get;
private set;
}
/// <summary>
/// Extrusion type.
/// </summary>
public ExtrusionType ExtrusionType
{
get;
private set;
}
/// <summary>
/// Initializes the extrude algorithm.
/// </summary>
/// <param name="pDistance">The distance to applies.</param>
/// <param name="pExtrusionType">The type of extrusion.</param>
public Extrude(float pDistance, ExtrusionType pExtrusionType = ExtrusionType.World_Up)
{
this.Distance = pDistance;
this.ExtrusionType = pExtrusionType;
}
public Shape Compute(Shape pSource)
{
return this.Compute(pSource as Polygon);
}
/// <summary>
/// This method computes the geometry based on the incoming polygon.
/// </summary>
/// <param name="pSource">The source polygon.</param>
/// <returns>The computed geometry.</returns>
public Geometry Compute(Polygon pSource)
{
Geometry lResult = new Geometry();
switch (this.ExtrusionType)
{
case ExtrusionType.World_Up:
{
// First clone the polygon and add it to the geometry.
Polygon lBase = (Polygon)pSource.Clone();
Polygon lTop = new Polygon();
foreach (Vector3 lVertex in lBase.Vertices)
{
lTop.Vertices.Add(new Vector3(lVertex.X, lVertex.Y + this.Distance, lVertex.Z));
}
lTop.Normal = lBase.Normal;
lResult.Polygons.Add(lBase);
lResult.Polygons.Add(lTop);
// Now, create all other polygons.
for (int lIndex = 0; lIndex < lBase.Vertices.Count; lIndex++)
{
int lNext = (lIndex + 1) % (lBase.Vertices.Count - 1);
Polygon lSide = new Polygon();
lSide.Vertices.Add(new Vector3(lBase.Vertices[lIndex].X, lBase.Vertices[lIndex].Y, lBase.Vertices[lIndex].Z));
lSide.Vertices.Add(new Vector3(lBase.Vertices[lNext].X, lBase.Vertices[lNext].Y, lBase.Vertices[lNext].Z));
lSide.Vertices.Add(new Vector3(lTop.Vertices[lNext].X, lTop.Vertices[lNext].Y, lTop.Vertices[lNext].Z));
lSide.Vertices.Add(new Vector3(lTop.Vertices[lIndex].X, lTop.Vertices[lIndex].Y, lTop.Vertices[lIndex].Z));
lResult.Polygons.Add(lSide);
}
lTop.Normal = lBase.Normal;
}
break;
case ExtrusionType.Face_Normal:
{
throw new NotSupportedException();
}
case ExtrusionType.Vertex_Normal:
{
throw new NotSupportedException();
}
case ExtrusionType.WorldUp_FlatTop:
{
throw new NotSupportedException();
}
}
return lResult;
}
}
}
|
81e8d1a28d7bd464eb530203313f877aa59dda94
|
C#
|
tectronics/revenge-of-the-titans
|
/Project/Assets/Scripts/Skills/Dispel.cs
| 2.546875
| 3
|
using System.Collections.Generic;
namespace Assets.Scripts.Skills
{
public class Dispel : Skill
{
public Dispel()
{
TypesTarget = TypesTarget.OneFriend;
Name = "Очищение";
Description = "Снимает все негативные эффекты.";
IsOnlyAliveTarget = true;
}
public override void UseSkill(Character initiator, List<Character> targets)
{
foreach (Character target in targets)
target.TimingSkills.RemoveAll(skill => skill.IsBadEffect);
}
}
}
|
b1063d61151f6abdd10cb72fb02242169904f367
|
C#
|
RuzmanovDev/Telerik-Academy-Season-2016-2017
|
/Modul-II/01.High-Quality-Code/04.Design-Patterns/DIi.NET_SourceCode/HelloDI/HelloDIUnitTest/SecureMessageWriterTest.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
using Moq;
using Ploeh.Samples.HelloDI.CommandLine;
using System.Security.Principal;
using System.Threading;
namespace Ploeh.Samples.HelloDI.UnitTest
{
public class SecureMessageWriterTest : IDisposable
{
private readonly IPrincipal originalPrincipal;
public SecureMessageWriterTest()
{
this.originalPrincipal = Thread.CurrentPrincipal;
}
[Fact]
public void SutIsMessageWriter()
{
// Fixture setup
var dummyMessageWriter = new Mock<IMessageWriter>().Object;
// Exercise system
var sut = new SecureMessageWriter(dummyMessageWriter);
// Verify outcome
Assert.IsAssignableFrom<IMessageWriter>(sut);
// Teardown
}
[Fact]
public void InitializeWithNullWriterThrows()
{
// Fixture setup
// Exercise system and verify outcome
Assert.Throws<ArgumentNullException>(() =>
new SecureMessageWriter(null));
// Teardown
}
[Fact]
public void WriteInvokesDecoratedWriterWhenPrincipalIsAuthenticated()
{
// Fixture setup
var principalStub = new Mock<IPrincipal>();
principalStub.SetupGet(p => p.Identity.IsAuthenticated).Returns(true);
Thread.CurrentPrincipal = principalStub.Object;
var writerMock = new Mock<IMessageWriter>();
var sut = new SecureMessageWriter(writerMock.Object);
// Exercise system
var message = "Whatever";
sut.Write(message);
// Verify outcome
writerMock.Verify(w => w.Write(message));
// Teardown
}
[Fact]
public void WriteDoesNotInvokeWriterWhenPrincipalIsNotAuthenticated()
{
// Fixture setup
var principalStub = new Mock<IPrincipal>();
principalStub.SetupGet(p => p.Identity.IsAuthenticated).Returns(false);
Thread.CurrentPrincipal = principalStub.Object;
var writerMock = new Mock<IMessageWriter>();
var sut = new SecureMessageWriter(writerMock.Object);
// Exercise system
sut.Write("Anonymous value");
// Verify outcome
writerMock.Verify(w => w.Write(It.IsAny<string>()), Times.Never());
// Teardown
}
#region IDisposable Members
public void Dispose()
{
Thread.CurrentPrincipal = this.originalPrincipal;
}
#endregion
}
}
|
b3088b436f2037d2313da679dea8c908cb3ee290
|
C#
|
stargarner/StarGarner
|
/StarGarner/Model/GiftHistory.cs
| 2.6875
| 3
|
using Newtonsoft.Json.Linq;
using StarGarner.Util;
using System;
using System.Collections.Generic;
namespace StarGarner.Model {
public class GiftHistory {
static readonly Log log = new Log( "GiftHistory" );
private class Item : IComparable<Item> {
public readonly Int64 time;
public readonly Int32 count;
public Item(Int64 time, Int32 count) {
this.time = time;
this.count = count;
}
public JObject encodeJson()
=> new JObject {
{ Config.KEY_TIME, time.ToString() },
{ Config.KEY_COUNT, count }
};
public static Item? decodeJson(JObject item) {
try {
var time = item.Value<String?>( Config.KEY_TIME ) ?? throw new Exception( "missing time" );
var count = item.Value<Int32?>( Config.KEY_COUNT ) ?? throw new Exception( "missing count" );
return new Item( Int64.Parse(time),count);
} catch (Exception ex) {
log.e( ex, "History.decodeJson failed." );
return null;
}
}
public Int32 CompareTo(Item other) => time.CompareTo( other.time );
public override String ToString() => $"{time.formatTime()} {count}";
}
private readonly List<Item> list = new List<Item>();
private readonly String itemName;
public GiftHistory(String itemName) => this.itemName = itemName;
public Int32 count() => list.Count;
// 取得履歴をStatusCollectionに追加する
public void addCountTo(StatusCollection sc, Boolean hasExceed) {
var countStr = hasExceed ? "X" : list.Count.ToString();
sc.addRun( $"取得履歴 {countStr}" );
}
// 取得履歴をStatusCollectionに追加する
public void addTo(StatusCollection sc) {
if (list.Count > 0) {
sc.add( String.Join( ", ", list ), fontSize: Config.giftHistoryFontSize );
}
}
// 取得履歴をログに出力する
public void dump(String caption) {
foreach (var h in list) {
log.d( $"{caption} {itemName} {h}" );
}
}
// JSONデータにエンコード
public JArray encodeJson() {
var dst = new JArray();
foreach (var item in list) {
dst.Add( item.encodeJson() );
}
return dst;
}
// JSONデータをデコードして内容を取り込む
public void load(JArray src) {
foreach (JObject item in src) {
var h = Item.decodeJson( item );
if (h != null)
list.Add( h );
}
list.Sort();
trim( UnixTime.now );
}
// 内容をクリア
public void clear() => list.Clear();
// trim old unnecessary entry.
private Item? trim(Int64 now, Boolean add = false) {
Item? lastStart = null;
lock (list) {
// count==1の要素を調べる
for (var i = list.Count - 1; i >= 0; --i) {
var h = list[ i ];
if (h.count == 1) {
lastStart = h;
break;
}
}
if (lastStart == null || lastStart.time < now - UnixTime.hour1 * 1L - 1000L) {
// count==1の要素がないか、古すぎるなら履歴を初期化する
if (list.Count > 0) {
log.d( "History.trim: history initialize!" );
list.Clear();
lastStart = null;
}
} else {
var removeCount = 0;
// lastStartより古い要素は要らないので削除する
for (var i = list.Count - 1; i >= 0; --i) {
if (list[ i ].time < lastStart.time) {
list.RemoveAt( i );
++removeCount;
}
}
if (removeCount > 0) {
log.d( $"History.trim: history remove {removeCount}" );
}
}
if (add) {
var newCount = 1 + ( list.lastOrNull()?.count ?? 0 );
list.Add( new Item( now, newCount > 10 ? 1 : newCount ) );
}
}
return lastStart;
}
// 履歴を追加
public void increment(Int64 now) => trim( now, true );
// 解除予測が変化したらログ出力する
private Int64? lastExpectedReset = null;
// 解除予測時刻を調べる
// 副作用として古い取得履歴を削除する
// count() を呼び出す前に必ずこのメソッドを呼び出す必要がある
internal Int64 expectedReset(Int64 now) {
// count==1の要素を調べる
var lastStart = trim( now );
var newValue = lastStart != null ? lastStart.time + UnixTime.hour1 : 0L;
// 解除予測が変化したらログ出力する
if (lastExpectedReset != null && lastExpectedReset != newValue) {
if (newValue == 0L) {
log.d( $"{itemName} 解除予測がリセットされました。" );
} else {
log.d( $"{itemName} 解除予測が変わりました。{newValue.formatTime( showMillisecond: true )} 残り{( newValue - now ).formatDuration()}" );
}
}
lastExpectedReset = newValue;
return newValue;
}
}
}
|
7d5936833c28f98397676b8eec2af39612a31f5f
|
C#
|
luizdequeiroz/cursos-cast-group
|
/app/Controllers/CategoriaController.cs
| 2.78125
| 3
|
using domain.Entities;
using domain.Enums;
using Microsoft.AspNetCore.Mvc;
using service;
using System.Threading.Tasks;
namespace app.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class CategoriaController : ControllerBase
{
private readonly ICategoriaService categoriaService;
public CategoriaController(ICategoriaService categoriaService)
{
this.categoriaService = categoriaService;
}
[HttpPost]
public async Task<IActionResult> CreateAsync(Categoria categoria)
{
var categoriaCreated = await categoriaService.SetNewAsync(categoria);
if (categoriaCreated.code != Code.SUCCESS)
return BadRequest(categoriaCreated);
return Created("", categoriaCreated.result);
}
[HttpGet]
public async Task<IActionResult> ReadAllAsync()
{
var categorias = await categoriaService.GetAllAsync();
if (categorias.code == Code.UNLISTED_ITEMS)
return BadRequest(new { categorias.code, message = "Não foi possível realizar a busca das categorias." });
if (categorias.code == Code.ITENS_NOT_FOUND)
return NotFound(new { categorias.code, message = "Não existem categorias cadastradas." });
return Ok(categorias.result);
}
[HttpGet("{id}")]
public async Task<IActionResult> ReadByIdAsync(int id)
{
var categoria = await categoriaService.GetByIdAsync(id);
if (categoria.code == Code.ITEM_DOES_NOT_EXIST)
return NotFound(new { categoria.code, message = "Nenhuma categoria encontrada." });
return Ok(categoria.result);
}
[HttpPut("{id}")]
public async Task<IActionResult> UpdateAsync(int id, Categoria categoria)
{
categoria.Id = id;
var categoriaUpdated = await categoriaService.AlterAsync(categoria);
if (categoriaUpdated.code == Code.ITEM_DOES_NOT_EXIST)
return BadRequest(new { categoriaUpdated.code, message = "Não foi possível realizar a atualização da categoria, pois ela não existe." });
return Ok(categoriaUpdated.result);
}
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteAsync(int id)
{
var result = await categoriaService.DeleteAsync(id);
if (result.code == Code.ITEM_NOT_DELETED)
return BadRequest(new { result.code, message = "Não foi possível deletar a categoria." });
return Ok("Categoria deletada com sucesso.");
}
}
}
|
1c24a607ac2acf7e9abe5a2279b6bbb96aafde8a
|
C#
|
AllanO-Cell/Luma-Game-Test-
|
/Luma Test Game/Assets/Scripts/Player/GunControls.cs
| 2.765625
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GunControls : MonoBehaviour
{
Character_Movement movement;
PlayerStats m_playerStats;
public GameObject bulletPrefab;
public Transform bulletSpawn;
public float bulletSpeed = 30;
float shootRateTimeStamp;
private void Awake()
{
movement = FindObjectOfType<Character_Movement>();
m_playerStats = FindObjectOfType<PlayerStats>();
}
/// <summary>
/// Checks if the player is running. if it is then the player will fire. if not the player will not fire
/// </summary>
private void Update()
{
if (movement.isRunning)
{
FireGun();
}
else
return;
}
/// <summary>
/// We instantiate bullets here based on our players attack speed.
/// Instantiate was used rather than object pooling due to time and amount of code to be written
/// </summary>
private void FireGun()
{
if (Time.time > shootRateTimeStamp)
{
GameObject bullet = Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation);
bullet.GetComponent<Rigidbody>().AddForce(bulletSpawn.forward * bulletSpeed);
shootRateTimeStamp = Time.time + m_playerStats.playerAttackSpeed;
}
}
}
|
d3abf4f2407980ef39948c877e4432151090c23d
|
C#
|
voodoo123x/TuxBlox
|
/Tuxblox/Model/Entities/NodeStatusEntity.cs
| 2.515625
| 3
|
namespace Tuxblox.Model.Entities
{
public class NodeStatusEntity : BaseEntity
{
private string _Status;
private int _BlockHeight;
private int _Headers;
private int _Connections;
/// <summary>
/// Gets and sets the Status property.
/// </summary>
public string Status
{
get { return _Status; }
set { SetValue(ref _Status, value); }
}
/// <summary>
/// Gets and sets the BlockHeight property.
/// </summary>
public int BlockHeight
{
get { return _BlockHeight; }
set { SetValue(ref _BlockHeight, value); }
}
/// <summary>
/// Gets and sets the Headers property.
/// </summary>
public int Headers
{
get { return _Headers; }
set { SetValue(ref _Headers, value); }
}
/// <summary>
/// Gets and sets the Connections property.
/// </summary>
public int Connections
{
get { return _Connections; }
set { SetValue(ref _Connections, value); }
}
}
}
|
21912fb62181ca595569d80acd09b6be1bf740b6
|
C#
|
eelmartin/Ingen-eria-y-servicios-industriales
|
/Capa.BL/Helpers/PdfHandler.cs
| 2.65625
| 3
|
using Capa.DATOS.Templates;
using iText.Forms;
using iText.Kernel.Pdf;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Capa.BL.Helpers
{
public class PdfHandler
{
public static bool CrearPDF(IPdfTemplate template, string pathSalida)
{
return LlenarForm(template.GetForm(), template.GetTemplate(), pathSalida);
}
private static bool LlenarForm(Dictionary<string, string> data, string pathEntrada, string pathSalida)
{
try
{
using (PdfDocument p = new PdfDocument(new PdfReader(pathEntrada), new PdfWriter(pathSalida)))
{
PdfAcroForm form = PdfAcroForm.GetAcroForm(p, true);
foreach (string key in data.Keys)
{
data.TryGetValue(key, out string value);
var field = form.GetField(key);
field.SetValue(value);
}
form.FlattenFields();
}
return true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return false;
}
}
}
}
|
7093b1dc36c288b516ea66b24cbdae9c31a27d4d
|
C#
|
EsaGit2022/IsisStandAlone
|
/EF_Model/Uitbreiding/KlantUitbreiding.cs
| 2.90625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Windows;
namespace EF_Model
{
partial class Klant : IDataErrorInfo
{
public bool CanSave
{
get
{
foreach (string property in ValidatedProperties)
{
if (GetValidationError(property) != null) // there is an error
return false;
}
return true;
}
}
#region Data Validation
static readonly string[] ValidatedProperties =
{
"Naam",
"Voornaam",
"Id",
"Straat",
"Nummer",
"Gemeente",
"Postcode",
"Telefoon",
"Gsm",
"Email",
"AndereNaam",
"Betalingswijze",
"Gebruikersnummer",
"TypeNaam",
"TypePlaats"
};
public string GetValidationError(string propertyName)
{
string result = null;
var validationResults = new List<ValidationResult>();
Validator.TryValidateProperty(
GetType().GetProperty(propertyName).GetValue(this),
new ValidationContext(this)
{
MemberName = propertyName
}, validationResults);
if(validationResults.Count > 0)
result = validationResults.First().ErrorMessage;
else
switch (propertyName)
{
case "Id":
{
if (InvalidId == true)
result = "Klantnummer is al in gebruik!";
break;
}
case "Telefoon":
{
if (!String.IsNullOrEmpty(Telefoon) && (!Telefoon.All(char.IsDigit) || Telefoon.Length != 9))
{
result = "Geen geldig telefoonnummer!";
}
break;
}
case "Gsm":
{
if (String.IsNullOrEmpty(Gsm))
{
if (String.IsNullOrEmpty(Telefoon))
result = "U dient ofwel een telefoon of gsm in te vullen!";
}
else if (!Gsm.All(char.IsDigit) || Gsm.Length != 10)
{
result = "Geen geldig gsmnummer!";
}
break;
}
case "Gebruikersnummer":
{
if (Betalingswijze == "Elektronisch")
{
if (String.IsNullOrWhiteSpace(Gebruikersnummer))
result = "U hebt gekozen voor Elektronisch betalen dan is een Gebruikersnummer verplicht";
else if (Gebruikersnummer.Length != 13 || Gebruikersnummer[3] != ' ')
result = "Niet geldig! Structuur = 123 123456789";
}
break;
}
}
return result;
}
#endregion
#region Interface Implementation
public string Error => "";
public string this[string columnName] => GetValidationError(columnName);
#endregion
//Is used to check if our ID is unique!
[NotMapped]
public bool InvalidId { get; set; }
//Convert 'Actief' number into text
public string ActiefString
{
get
{
switch (Actief)
{
case 0:
return "Gedeactiveerd";
case 1:
return "Actief";
case 2:
return "Slapend inactief";
}
return "";
}
}
public override string ToString()
{
return Naam + " " + Voornaam + "\t\t" + Id;
}
}
}
|
f0b27143eae3e9dd346dac55050de4bc18065ce8
|
C#
|
mivak/CSharp
|
/ExamPreparation/CoffeeMachine/ConsoleApplication1/CoffeeMachine.cs
| 3.78125
| 4
|
namespace CoffeeMachine
{
using System;
using System.Globalization;
using System.Threading;
public class CoffeeMachine
{
public static void Main()
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CurrentCulture;
int tray1 = int.Parse(Console.ReadLine());
int tray2 = int.Parse(Console.ReadLine());
int tray3 = int.Parse(Console.ReadLine());
int tray4 = int.Parse(Console.ReadLine());
int tray5 = int.Parse(Console.ReadLine());
decimal amount = decimal.Parse(Console.ReadLine());
decimal price = decimal.Parse(Console.ReadLine());
decimal machineSum = (decimal)((tray1 * 0.05) + (tray2 * 0.1) + (tray3 * 0.2) + (tray4 * 0.5) + tray5);
if (price > amount)
{
Console.WriteLine("More {0:F2}", price - amount);
}
else if (machineSum > amount - price)
{
Console.WriteLine("Yes {0:F2}", machineSum + price - amount);
}
else
{
Console.WriteLine("No {0:F2}", amount - price - machineSum);
}
}
}
}
|
56be89c7cc7fe9955bfa0f32024dc573d0a5fd10
|
C#
|
RGIvan/Altair1718-VS
|
/2ª Evaluación/wd3_GestionAlumnosFP_En2capas/LNegocioyADatos/Entidades/Grupo.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LNegocioyADatos.Entidades
{
public class Grupo
{
//Campos
int idgrupo;
string alias;
string nombre;
//Constructor
public Grupo(int idgrupo, string alias, string nombre)
{
this.idgrupo = idgrupo;
this.alias = alias;
this.nombre = nombre;
}
public Grupo(DataSet1.GruposRow regGrupo)
{
this.idgrupo = regGrupo.idGrupo;
this.alias = regGrupo.alias;
this.nombre = regGrupo.nombre;
}
//Propiedades
public int Idgrupo
{
set { idgrupo = value; }
get { return idgrupo; }
}
public string Alias
{
set { alias = value; }
get { return alias; }
}
public string Nombre
{
set { nombre = value; }
get { return nombre; }
}
}
}
|
ff4be7d9c46b7559a648b345eb871f41c546fced
|
C#
|
RoxanneIheanacho/Programming-in-C-
|
/Shape_Calculator/Shape.cs
| 3.6875
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace examination_2
{
//https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/abstract will only be base class
public abstract class Shape
{
/**The abstract keyword enables you to create classes and class members that
are incomplete and must be implemented in a derived class.An abstract class cannot be instantiated. The purpose of an abstract class
is to provide a common definition of a base class that multiple derived classes can share
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/abstract-and-sealed-classes-and-class-members*/
private ShapeType shapeType;
protected Shape(ShapeType shapeType)
{
/**skapar privat ShapeType some är shapetype "The protected keyword
is a member access modifier. A protected member is accessible within
its class and by derived class instances. Using protected means you can have functionality in a
class that's available to derived classes, but not to classes that
just instantiate the object"
https://stackoverflow.com/questions/3626690/protected-keyword-c-sharp*/
ShapeType = shapeType;
}
public ShapeType ShapeType
{
get
{
/**returns shapeType enumerable*/
return shapeType;
}
private set
{
/*privat setter, shapeType värde*/
this.shapeType = value;
}
}
public bool Is3D
{
get
{
/**om ShapeType är Cupid, Cylinder, Sphere, då är is3D till boolean true**/
switch (ShapeType)
{
case ShapeType.Cuboid:
return true;
case ShapeType.Cylinder:
return true;
case ShapeType.Sphere:
return true;
default:
return false;
}
}
}
public abstract override string ToString();
//https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-override-the-tostring-method
//this is what "G" would present if not for "R", is the override ToString of values
/**When you create a custom class or struct, you should override the
ToString method in order to provide information about your type to client code.*/
}
}
|
d709d6b5b215f843765b9fb24f1d7e2f3bd3edd9
|
C#
|
trovao1990/Alura-CSharp.Net
|
/CaixaEletronico/Form1.cs
| 2.640625
| 3
|
using System;
using System.Windows.Forms;
namespace CaixaEletronico
{
public partial class Form1 : Form
{
Conta[] contas;
Conta contaSelecionada;
Conta contaDestino;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
contas = new Conta[2];
contas[0] = new Conta();
contas[1] = new Conta();
Cliente c1 = new Cliente("Vinicius");
Cliente c2 = new Cliente("Ranay");
contas[0].Numero = 1;
contas[0].Titular= c1;
contas[0].Deposita(3000.0);
contas[1].Numero = 2;
contas[1].Titular = c2;
contas[1].Deposita(3020.0);
foreach (Conta c in contas)
{
comboOrigem.Items.Add(c.Numero);
}
foreach (Conta c in contas)
{
comboDestino.Items.Add(c.Numero);
}
}
private void btnDeposito_Click(object sender, EventArgs e)
{
string textoValorDeposito = textoValor.Text;
double valorDeposito = Convert.ToDouble(textoValorDeposito);
contaSelecionada = this.BuscaContaSelecionada();
contaSelecionada.Deposita(valorDeposito);
this.MostraConta();
}
private void btnSaque_Click(object sender, EventArgs e)
{
string textoValorSaque = textoValor.Text;
double valorSaque = Convert.ToDouble(textoValorSaque);
contaSelecionada = this.BuscaContaSelecionada();
contaSelecionada.Saca(valorSaque);
this.MostraConta();
}
private Conta BuscaContaSelecionada()
{
int indiceSelecionado = comboOrigem.SelectedIndex;
return this.contas[indiceSelecionado];
}
private void MostraConta()
{
textoTitular.Text = contaSelecionada.Titular.Nome;
textoNumero.Text = Convert.ToString(contaSelecionada.Numero);
textoSaldo.Text = Convert.ToString(contaSelecionada.Saldo);
}
private void button1_Click(object sender, EventArgs e)
{
contas[0].Deposita(10);
contas[1].Deposita(100);
/*for (int i = 0; i < contas.Length; i++)
{
MessageBox.Show("O saldo da conta "+ "é " + contas[i].Saldo);
}
foreach (Conta conta in contas)
{
MessageBox.Show("O saldo da conta " + "é " + conta.Saldo);
} */
}
private void btnTotalizador_Click(object sender, EventArgs e)
{
/* TotalizadorDeContas t = new TotalizadorDeContas();
Conta c1 = new Conta();
c1.Deposita(10.0);
t.Adiciona(c1);
Conta c2 = new Conta();
c2.Deposita(120.0);
t.Adiciona(c2);
ContaPoupanca cp1 = new ContaPoupanca();
cp1.Deposita(100.0);
t.Adiciona(cp1);
MessageBox.Show("Total de Contas: " + t.Total); */
}
private void comboContas_SelectedIndexChanged(object sender, EventArgs e)
{
contaSelecionada = this.BuscaContaSelecionada();
textoTitular.Text = contaSelecionada.Titular.Nome;
textoNumero.Text = Convert.ToString(contaSelecionada.Numero);
textoSaldo.Text = Convert.ToString(contaSelecionada.Saldo);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void btnTransferencia_Click(object sender, EventArgs e)
{
contaSelecionada = this.BuscaContaSelecionada();
int indiceContaDestino = comboDestino.SelectedIndex;
Conta contaDestino = this.contas[indiceContaDestino];
string textoTransferencia = textoValor.Text;
double valorTransferencia = Convert.ToDouble(textoTransferencia);
contaSelecionada.Transfere(valorTransferencia, contaDestino);
this.MostraConta();
}
}
}
|
a3e1b8e9ebf84e77a4e61f5b6cc47b1314e3efa4
|
C#
|
warawicht/office-point-bot2
|
/OfficePointBot/Dialogs/KnockKnockDialog.cs
| 2.546875
| 3
|
using Microsoft.Bot.Builder.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
namespace OfficePointBot.Dialogs
{
public class KnockKnockDialog
{
public static readonly IDialog<string> Dialog = Chain
.PostToChain()
.Select(m => m.Text)
.Switch
(
Chain.Case
(
new Regex("^tell me a knock knock joke"),
(context, text) =>
Chain.Return("Knock, knock.")
.PostToUser()
.WaitToBot()
.Select(ignoreUser => "Interrupting Cow")
.PostToUser()
.Do(async (ctx, res) =>
{
await Task.Delay(2000);
})
.Select(ignoreUser => "MOOOOO!")
),
Chain.Default<string, IDialog<string>>(
(context, text) =>
Chain.Return("Say 'tell me a knock knock joke'")
)
)
.Unwrap().PostToUser();
}
}
|
16dd3a536ce18d67574be2fd7bee246eba90c71b
|
C#
|
skclusive/Skclusive.Mobx.StateTree
|
/src/StateTree/Type/TypeExtensions.cs
| 2.84375
| 3
|
using System;
using System.Linq;
namespace Skclusive.Mobx.StateTree
{
public static class TypeExtensions
{
public static bool IsSimpleType(
this object target)
{
return target == null || target.GetType().IsSimpleType();
}
/// <summary>
/// Determine whether a type is simple (String, Decimal, DateTime, etc)
/// or complex (i.e. custom class with public properties and methods).
/// </summary>
/// <see cref="http://stackoverflow.com/questions/2442534/how-to-test-if-type-is-primitive"/>
public static bool IsSimpleType(
this Type type)
{
return
type.IsValueType ||
type.IsPrimitive ||
new Type[]
{
typeof(String),
typeof(Decimal),
typeof(DateTime),
typeof(DateTimeOffset),
typeof(TimeSpan),
typeof(Guid)
}.Contains(type) ||
Convert.GetTypeCode(type) != TypeCode.Object;
}
public static INode CreateNode<S, T>(this IType<S, T> type, ObjectNode parent, string subpath,
IEnvironment environment, object initialValue)
{
return (type as IType).CreateNode<S, T>(parent, subpath, environment, initialValue);
}
public static INode CreateNode<S, T>(this IType type, ObjectNode parent, string subpath,
IEnvironment environment, object initialValue)
{
return type.CreateNode<S, T>(parent, subpath, environment, initialValue, (child, node) => child);
}
public static INode CreateNode<S, T>(this IType<S, T> type, ObjectNode parent, string subpath,
IEnvironment environment, object initialValue, Func<object, IStateTreeNode, object> createNewInstance, Action<INode, object, IStateTreeNode> finalizeNewInstance = null)
{
return (type as IType).CreateNode<S, T>(parent, subpath, environment, initialValue, createNewInstance, finalizeNewInstance);
}
public static INode CreateNode<S, T>(this IType type, ObjectNode parent, string subpath, IEnvironment environment,
object initialValue, Func<object, IStateTreeNode, object> createNewInstance, Action<INode, object, IStateTreeNode> finalizeNewInstance = null)
{
if (initialValue.IsStateTreeNode())
{
var targetNode = initialValue.GetStateTreeNode();
if (!targetNode.IsRoot)
{
throw new Exception($"Cannot add an object to a state tree if it is already part of the same or another state tree. Tried to assign an object to '{parent?.Path ?? ""}/{subpath}', but it lives already at '{targetNode.Path}'");
}
targetNode.SetParent(parent, subpath);
return targetNode;
}
if (type.ShouldAttachNode)
{
return new ObjectNode
(
type,
parent,
subpath,
environment,
initialValue,
createNewInstance,
finalizeNewInstance
);
}
return new ScalarNode
(
type,
parent,
subpath,
environment,
initialValue,
createNewInstance,
finalizeNewInstance
);
}
}
}
|
2ac92ba58b2011cd4caa75b9b6d7c3cf5e3e8e4c
|
C#
|
michaelmcmullin/csMatrix
|
/csMatrix.Tests/MatrixRowColumnOperationTests.cs
| 2.984375
| 3
|
using System;
using Xunit;
namespace csMatrix.Tests
{
public class MatrixRowColumnOperationTests
{
[Theory]
[InlineData(1, 2)]
[InlineData(2, 1)]
[InlineData(5, 2)]
public void MatrixGetEnumerator(int rows, int columns)
{
Matrix m = new Matrix(rows, columns);
int size = 0;
foreach (double element in m)
{
size++;
}
Assert.Equal(m.Size, size);
}
[Fact]
public void MatrixSwapRowsFirstSecond()
{
Matrix m1 = new Matrix(new double[,] { { 1.0, 2.0, 3.0 }, { 4.0, 5.0, 6.0 }, { 7.0, 8.0, 9.0 } });
Matrix m2 = new Matrix(m1);
Matrix expected = new Matrix(new double[,] { { 4.0, 5.0, 6.0 }, { 1.0, 2.0, 3.0 }, { 7.0, 8.0, 9.0 } });
m1.SwapRows(0, 1);
Matrix test = Matrix.SwapRows(m2, 0, 1);
Assert.Equal(expected, m1);
Assert.Equal(expected, test);
Assert.NotEqual(m2, test); // Ensures m2 wasn't mutated.
}
[Fact]
public void MatrixSwapRowsLastSecondLast()
{
Matrix m1 = new Matrix(new double[,] { { 1.0, 2.0, 3.0 }, { 4.0, 5.0, 6.0 }, { 7.0, 8.0, 9.0 } });
Matrix m2 = new Matrix(m1);
Matrix expected = new Matrix(new double[,] { { 1.0, 2.0, 3.0 }, { 7.0, 8.0, 9.0 }, { 4.0, 5.0, 6.0 } });
m1.SwapRows(1, 2);
Matrix test = Matrix.SwapRows(m2, 1, 2);
Assert.Equal(expected, m1);
Assert.Equal(expected, test);
Assert.NotEqual(m2, test); // Ensures m2 wasn't mutated.
}
[Fact]
public void MatrixSwapRowsOutOfRange()
{
Matrix m = new Matrix(new double[,] { { 1.0, 2.0, 3.0 }, { 4.0, 5.0, 6.0 }, { 7.0, 8.0, 9.0 } });
Assert.Throws<IndexOutOfRangeException>(() => m.SwapRows(m.Rows, 0));
Assert.Throws<IndexOutOfRangeException>(() => Matrix.SwapRows(m, m.Rows, 0));
}
[Fact]
public void MatrixSwapColumnsFirstSecond()
{
Matrix m1 = new Matrix(new double[,] { { 1.0, 2.0, 3.0 }, { 4.0, 5.0, 6.0 }, { 7.0, 8.0, 9.0 } });
Matrix m2 = new Matrix(m1);
Matrix expected = new Matrix(new double[,] { { 2.0, 1.0, 3.0 }, { 5.0, 4.0, 6.0 }, { 8.0, 7.0, 9.0 } });
m1.SwapColumns(0, 1);
Matrix test = Matrix.SwapColumns(m2, 0, 1);
Assert.Equal(expected, m1);
Assert.Equal(expected, test);
Assert.NotEqual(m2, test); // Ensures m2 wasn't mutated.
}
[Fact]
public void MatrixSwapColumnsLastSecondLast()
{
Matrix m1 = new Matrix(new double[,] { { 1.0, 2.0, 3.0 }, { 4.0, 5.0, 6.0 }, { 7.0, 8.0, 9.0 } });
Matrix m2 = new Matrix(m1);
Matrix expected = new Matrix(new double[,] { { 1.0, 3.0, 2.0 }, { 4.0, 6.0, 5.0 }, { 7.0, 9.0, 8.0 } });
m1.SwapColumns(m1.Columns - 1, m1.Columns - 2);
Matrix test = Matrix.SwapColumns(m2, m2.Columns - 1, m2.Columns - 2);
Assert.Equal(expected, m1);
Assert.Equal(expected, test);
Assert.NotEqual(m2, test); // Ensures m2 wasn't mutated.
}
[Fact]
public void MatrixSwapColumnsOutOfRange()
{
Matrix m = new Matrix(new double[,] { { 1.0, 2.0, 3.0 }, { 4.0, 5.0, 6.0 }, { 7.0, 8.0, 9.0 } });
Assert.Throws<IndexOutOfRangeException>(() => m.SwapColumns(m.Columns, 0));
Assert.Throws<IndexOutOfRangeException>(() => Matrix.SwapColumns(m, m.Columns, 0));
}
[Fact]
public void MatrixAddRowsOneAtStart()
{
Matrix m1 = Setup.GetTestMatrix1();
Matrix m2 = Matrix.AddRows(Setup.GetTestMatrix1(), 0, 1, 2.0);
m1.AddRows(0, 1, 2.0);
Matrix expected = new Matrix(new double[,] { { 2.0, 2.0, 2.0 }, { 1.0, 2.0, 3.0 }, { 4.0, 5.0, 6.0 } });
Assert.True(expected == m1);
Assert.True(expected == m2);
}
[Fact]
public void MatrixAddRowsOneAtEnd()
{
Matrix m1 = Setup.GetTestMatrix1();
Matrix m2 = Matrix.AddRows(Setup.GetTestMatrix1(), m1.Rows, 1, 2.0);
m1.AddRows(m1.Rows, 1, 2.0);
Matrix expected = new Matrix(new double[,] { { 1.0, 2.0, 3.0 }, { 4.0, 5.0, 6.0 }, { 2.0, 2.0, 2.0 } });
Assert.True(expected == m1);
Assert.True(expected == m2);
}
[Fact]
public void MatrixAddRowsTwoInCentre()
{
Matrix m1 = Setup.GetTestMatrix1();
Matrix m2 = Matrix.AddRows(Setup.GetTestMatrix1(), 1, 2, 2.0);
m1.AddRows(1, 2, 2.0);
Matrix expected = new Matrix(new double[,] { { 1.0, 2.0, 3.0 }, { 2.0, 2.0, 2.0 }, { 2.0, 2.0, 2.0 }, { 4.0, 5.0, 6.0 } });
Assert.True(expected == m1);
Assert.True(expected == m2);
}
[Fact]
public void MatrixAddRowsZeroRows()
{
Matrix m1 = Setup.GetTestMatrix1();
Matrix m2 = Matrix.AddRows(Setup.GetTestMatrix1(), 1, 0, 2.0);
m1.AddRows(1, 0, 2.0);
Matrix expected = Setup.GetTestMatrix1();
Assert.True(expected == m1);
Assert.True(expected == m2);
}
[Theory]
[InlineData(3)]
[InlineData(-1)]
public void MatrixAddRowsOutOfRange(int startRow)
{
Matrix m = Setup.GetTestMatrix1();
Assert.Throws<IndexOutOfRangeException>(() => m.AddRows(startRow, 1, 0));
Assert.Throws<IndexOutOfRangeException>(() => Matrix.AddRows(Setup.GetTestMatrix1(), startRow, 1, 0));
}
[Fact]
public void MatrixAddColumnsOneAtStart()
{
Matrix m1 = Setup.GetTestMatrix1();
Matrix m2 = Matrix.AddColumns(Setup.GetTestMatrix1(), 0, 1, 2.0);
m1.AddColumns(0, 1, 2.0);
Matrix expected = new Matrix(new double[,] { { 2.0, 1.0, 2.0, 3.0 }, { 2.0, 4.0, 5.0, 6.0 } });
Assert.True(expected == m1);
Assert.True(expected == m2);
}
[Fact]
public void MatrixAddColumnsOneAtEnd()
{
Matrix m1 = Setup.GetTestMatrix1();
Matrix m2 = Matrix.AddColumns(Setup.GetTestMatrix1(), m1.Columns, 1, 2.0);
m1.AddColumns(m1.Columns, 1, 2.0);
Matrix expected = new Matrix(new double[,] { { 1.0, 2.0, 3.0, 2.0 }, { 4.0, 5.0, 6.0, 2.0 } });
Assert.True(expected == m1);
Assert.True(expected == m2);
}
[Fact]
public void MatrixAddColumnsTwoInCentre()
{
Matrix m1 = Setup.GetTestMatrix1();
Matrix m2 = Matrix.AddColumns(Setup.GetTestMatrix1(), 1, 2, 2.0);
m1.AddColumns(1, 2, 2.0);
Matrix expected = new Matrix(new double[,] { { 1.0, 2.0, 2.0, 2.0, 3.0 }, { 4.0, 2.0, 2.0, 5.0, 6.0 } });
Assert.True(expected == m1);
Assert.True(expected == m2);
}
[Fact]
public void MatrixAddColumnsZeroColumns()
{
Matrix m1 = Setup.GetTestMatrix1();
Matrix m2 = Matrix.AddColumns(Setup.GetTestMatrix1(), 1, 0, 2.0);
m1.AddColumns(1, 0, 2.0);
Matrix expected = Setup.GetTestMatrix1();
Assert.True(expected == m1);
Assert.True(expected == m2);
}
[Theory]
[InlineData(4)]
[InlineData(-1)]
public void MatrixAddColumnsOutOfRange(int startColumn)
{
Matrix m = Setup.GetTestMatrix1();
Assert.Throws<IndexOutOfRangeException>(() => m.AddColumns(startColumn, 1, 0));
Assert.Throws<IndexOutOfRangeException>(() => Matrix.AddColumns(Setup.GetTestMatrix1(), startColumn, 1, 0));
}
[Fact]
public void MatrixExtractRowsFirstRow()
{
Matrix m1 = Setup.GetTestMatrix1();
Matrix m2 = Matrix.ExtractRows(Setup.GetTestMatrix1(), 0, 1);
m1.ExtractRows(0, 1);
Matrix expected = new Matrix(new double[,] { { 1.0, 2.0, 3.0 } });
Assert.True(expected == m1);
Assert.True(expected == m2);
}
[Fact]
public void MatrixExtractRowsLastRow()
{
Matrix m1 = Setup.GetTestMatrix1();
Matrix m2 = Matrix.ExtractRows(Setup.GetTestMatrix1(), m1.Rows - 1, 1);
m1.ExtractRows(m1.Rows - 1, 1);
Matrix expected = new Matrix(new double[,] { { 4.0, 5.0, 6.0 } });
Assert.True(expected == m1);
Assert.True(expected == m2);
}
[Fact]
public void MatrixExtractRowsTwoRows()
{
Matrix m1 = Setup.GetTestMatrix3();
Matrix m2 = Matrix.ExtractRows(Setup.GetTestMatrix3(), 1, 2);
m1.ExtractRows(1, 2);
Matrix expected = new Matrix(new double[,] { { 3.0, 4.0 }, { 5.0, 6.0 } });
Assert.True(expected == m1);
Assert.True(expected == m2);
}
[Theory]
[InlineData(5, 1)]
[InlineData(0, 5)]
[InlineData(-1, 1)]
public void MatrixExtractRowsOutOfRange(int startRow, int count)
{
Matrix m = Setup.GetTestMatrix1();
Assert.Throws<IndexOutOfRangeException>(() => m.ExtractRows(startRow, count));
Assert.Throws<IndexOutOfRangeException>(() => Matrix.ExtractRows(Setup.GetTestMatrix1(), startRow, count));
}
[Fact]
public void MatrixExtractRowsZeroRows()
{
Matrix m = Setup.GetTestMatrix1();
Assert.Throws<InvalidMatrixDimensionsException>(() => m.ExtractRows(0, 0));
Assert.Throws<InvalidMatrixDimensionsException>(() => Matrix.ExtractRows(Setup.GetTestMatrix1(), 0, 0));
}
[Fact]
public void MatrixExtractColumnsFirstColumn()
{
Matrix m1 = Setup.GetTestMatrix1();
Matrix m2 = Matrix.ExtractColumns(Setup.GetTestMatrix1(), 0, 1);
m1.ExtractColumns(0, 1);
Matrix expected = new Matrix(new double[,] { { 1.0 }, { 4.0 } });
Assert.True(expected == m1);
Assert.True(expected == m2);
}
[Fact]
public void MatrixExtractColumnsLastColumn()
{
Matrix m1 = Setup.GetTestMatrix1();
Matrix m2 = Matrix.ExtractColumns(Setup.GetTestMatrix1(), m1.Columns - 1, 1);
m1.ExtractColumns(m1.Columns - 1, 1);
Matrix expected = new Matrix(new double[,] { { 3.0 }, { 6.0 } });
Assert.True(expected == m1);
Assert.True(expected == m2);
}
[Fact]
public void MatrixExtractColumnsTwoColumns()
{
Matrix m1 = Setup.GetTestMatrix1();
Matrix m2 = Matrix.ExtractColumns(Setup.GetTestMatrix1(), 1, 2);
m1.ExtractColumns(1, 2);
Matrix expected = new Matrix(new double[,] { { 2.0, 3.0 }, { 5.0, 6.0 } });
Assert.True(expected == m1);
Assert.True(expected == m2);
}
[Theory]
[InlineData(5, 1)]
[InlineData(0, 5)]
[InlineData(-1, 1)]
public void MatrixExtractColumnsOutOfRange(int startColumn, int count)
{
Matrix m = Setup.GetTestMatrix1();
Assert.Throws<IndexOutOfRangeException>(() => m.ExtractColumns(startColumn, count));
Assert.Throws<IndexOutOfRangeException>(() => Matrix.ExtractColumns(Setup.GetTestMatrix1(), startColumn, count));
}
[Fact]
public void MatrixExtractColumnsZeroColumns()
{
Matrix m = Setup.GetTestMatrix1();
Assert.Throws<InvalidMatrixDimensionsException>(() => m.ExtractColumns(0, 0));
Assert.Throws<InvalidMatrixDimensionsException>(() => Matrix.ExtractColumns(Setup.GetTestMatrix1(), 0, 0));
}
[Fact]
public void MatrixRemoveRowsOneAtStart()
{
Matrix m1 = Setup.GetTestMatrix1();
Matrix m2 = Matrix.RemoveRows(Setup.GetTestMatrix1(), 0, 1);
m1.RemoveRows(0, 1);
Matrix expected = new Matrix(new double[,] { { 4.0, 5.0, 6.0 } });
Assert.True(expected == m1);
Assert.True(expected == m2);
}
[Fact]
public void MatrixRemoveRowsOneAtEnd()
{
Matrix m1 = Setup.GetTestMatrix1();
Matrix m2 = Matrix.RemoveRows(Setup.GetTestMatrix1(), m1.Rows - 1, 1);
m1.RemoveRows(m1.Rows - 1, 1);
Matrix expected = new Matrix(new double[,] { { 1.0, 2.0, 3.0 } });
Assert.True(expected == m1);
Assert.True(expected == m2);
}
[Fact]
public void MatrixRemoveRowsTwoInCentre()
{
Matrix m1 = Setup.GetTestMatrix3();
Matrix m2 = Matrix.RemoveRows(Setup.GetTestMatrix3(), 1, 2);
m1.RemoveRows(1, 2);
Matrix expected = new Matrix(new double[,] { { 1.0, 2.0 } });
Assert.True(expected == m1);
Assert.True(expected == m2);
}
[Fact]
public void MatrixRemoveRowsZeroRows()
{
Matrix m1 = Setup.GetTestMatrix1();
Matrix m2 = Matrix.RemoveRows(Setup.GetTestMatrix1(), 1, 0);
m1.RemoveRows(1, 0);
Matrix expected = Setup.GetTestMatrix1();
Assert.True(expected == m1);
Assert.True(expected == m2);
}
[Theory]
[InlineData(3)]
[InlineData(-1)]
public void MatrixRemoveRowsOutOfRange(int startRow)
{
Matrix m = Setup.GetTestMatrix1();
Assert.Throws<IndexOutOfRangeException>(() => m.RemoveRows(startRow, 1));
Assert.Throws<IndexOutOfRangeException>(() => Matrix.RemoveRows(Setup.GetTestMatrix1(), startRow, 1));
}
[Fact]
public void MatrixRemoveColumnsOneAtStart()
{
Matrix m1 = Setup.GetTestMatrix1();
Matrix m2 = Matrix.RemoveColumns(Setup.GetTestMatrix1(), 0, 1);
m1.RemoveColumns(0, 1);
Matrix expected = new Matrix(new double[,] { { 2.0, 3.0 }, { 5.0, 6.0 } });
Assert.True(expected == m1);
Assert.True(expected == m2);
}
[Fact]
public void MatrixRemoveColumnsOneAtEnd()
{
Matrix m1 = Setup.GetTestMatrix1();
Matrix m2 = Matrix.RemoveColumns(Setup.GetTestMatrix1(), m1.Columns - 1, 1);
m1.RemoveColumns(m1.Columns - 1, 1);
Matrix expected = new Matrix(new double[,] { { 1.0, 2.0 }, { 4.0, 5.0 } });
Assert.True(expected == m1);
Assert.True(expected == m2);
}
[Fact]
public void MatrixRemoveColumnsTwoInCentre()
{
Matrix m1 = Setup.GetTestMatrix1();
Matrix m2 = Matrix.RemoveColumns(Setup.GetTestMatrix1(), 1, 2);
m1.RemoveColumns(1, 2);
Matrix expected = new Matrix(new double[,] { { 1.0 }, { 4.0 } });
Assert.True(expected == m1);
Assert.True(expected == m2);
}
[Fact]
public void MatrixRemoveColumnsZeroColumns()
{
Matrix m1 = Setup.GetTestMatrix1();
Matrix m2 = Matrix.RemoveColumns(Setup.GetTestMatrix1(), 1, 0);
m1.RemoveColumns(1, 0);
Matrix expected = Setup.GetTestMatrix1();
Assert.True(expected == m1);
Assert.True(expected == m2);
}
[Theory]
[InlineData(4)]
[InlineData(-1)]
public void MatrixRemoveColumnsOutOfRange(int startColumn)
{
Matrix m = Setup.GetTestMatrix1();
Assert.Throws<IndexOutOfRangeException>(() => m.RemoveColumns(startColumn, 1));
Assert.Throws<IndexOutOfRangeException>(() => Matrix.RemoveColumns(Setup.GetTestMatrix1(), startColumn, 1));
}
}
}
|
2e304a262eadcd88c41657d262d8b2957bc43972
|
C#
|
nurike/Qiwi
|
/Program.cs
| 3.0625
| 3
|
using Qiwi.Classes;
using System;
namespace Qiwi
{
public class Program
{
static void Main(string[] args)
{
MyQueue queue = new MyQueue();
Console.WriteLine("Введите список номер тел.:");
string input = Console.ReadLine();
Console.WriteLine("Сколько номеров вывести на экран?");
string inputtwo = Console.ReadLine();
try
{
queue.enqueue(input.Split(' '));
queue.getResult(Int32.Parse(inputtwo));
}
catch (NullReferenceException ex)
{
Console.WriteLine("{0}, {1}",ex.StackTrace, ex.Message);
}
Console.ReadKey();
}
}
}
|
3d41a17b018ce3f1006a15e2572be08f77ac4737
|
C#
|
Tsoy-tech/it-nordic-school
|
/CourseProject_v.2/Reminder.Storage/Reminder.Storage.WebApi.Client/ReminderStorageWebApiClient.cs
| 2.640625
| 3
|
using Reminder.Storage.Core;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Reminder.Storage.WebApi.Core;
using System.Linq;
using System.Text;
namespace Reminder.Storage.WebApi.Client
{
public class ReminderStorageWebApiClient : IReminderStorage
{
private readonly HttpClient _httpClient;
//https://localhost:44354/api/reminders
private readonly string _baseWebApiUrl;
public ReminderStorageWebApiClient(string baseWebApiUrl)
{
if (baseWebApiUrl == null)
throw new ArgumentException(nameof(baseWebApiUrl));
_baseWebApiUrl = baseWebApiUrl.TrimEnd('/') + '/';
_httpClient = new HttpClient();
}
public Guid Add(ReminderItemRestricted reminderItemRestricted)
{
HttpResponseMessage response = CallWebApi(HttpMethod.Post, string.Empty,
new ReminderItemAddModel(reminderItemRestricted));
//Check Response status codes
if (response.StatusCode != HttpStatusCode.Created)
throw CreateException(response);
string path = response.Headers.Location.LocalPath;
int lastIndexOfSlash = path.LastIndexOf('/');
if (lastIndexOfSlash > -1)
{
return Guid.Parse(path.Substring(lastIndexOfSlash + 1));
}
throw CreateException(response);
}
public ReminderItem Get(Guid id)
{
HttpResponseMessage response = CallWebApi(HttpMethod.Get, id.ToString());
if (response.StatusCode == HttpStatusCode.NotFound)
return null;
if (response.StatusCode != HttpStatusCode.OK)
throw CreateException(response);
// Read response Body
var content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
// Parse response Model
ReminderItemGetModel model = JsonConvert.DeserializeObject<ReminderItemGetModel>(content);
if (model == null)
throw new Exception("Body cannot be parsed as List<ReminderItemGetModel>");
//Return the Result
return model.ToReminderItem();
}
public List<ReminderItem> GetList(IEnumerable<ReminderItemStatus> statuses, int count = -1, int startPosition = 0)
{
string relativeUrl = string.Empty;
var statusList = statuses.ToList();
if(statusList.Count > 0)
{
relativeUrl += '?';
foreach(var status in statusList)
{
relativeUrl += "status=" + status + '&';
}
}
HttpResponseMessage response = CallWebApi(HttpMethod.Get, relativeUrl);
if (response.StatusCode != HttpStatusCode.OK) //проверить статус код
throw CreateException(response);
var content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
List<ReminderItemGetModel> list = JsonConvert.DeserializeObject <List<ReminderItemGetModel>>(content);
if (list == null)
throw new Exception("Body cannot be parsed as List<ReminderItemGetModel>");
return list.Select(m => m.ToReminderItem()).ToList();
}
public void Update(ReminderItem reminderItem)
{
HttpResponseMessage response = CallWebApi(HttpMethod.Put, reminderItem.Id.ToString(),
new ReminderItemUpdateModel(reminderItem));
//Check Response status codes
if (response.StatusCode != HttpStatusCode.NoContent)
throw CreateException(response);
}
private Exception CreateException(HttpResponseMessage response)
{
return new Exception($"Status code: {response.StatusCode}\n" +
$"Content:\n{response.Content.ReadAsStringAsync().GetAwaiter().GetResult()}");
}
private HttpResponseMessage CallWebApi(HttpMethod httpMethod, string relativeUrl, object model = null)
{
//Prepare Request
var request = new HttpRequestMessage(httpMethod, _baseWebApiUrl + relativeUrl);
//Add Headers
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
if(model != null)
{
string content = JsonConvert.SerializeObject(model);
request.Content = new StringContent(
content,
Encoding.UTF8,
"application/Json");
}
return _httpClient.SendAsync(request).GetAwaiter().GetResult();
}
}
}
|
4d27d1915cf5baf89b4b0eeb8217913d2fbc966f
|
C#
|
kylegalbraith/aws-email-service
|
/src/Processors/SendEmail.Lambda/Function.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
using Amazon.SQS;
using Amazon.S3;
using SQS.Adapater;
using S3.Adapter;
using EmailMessage.Repository;
using SES.Adapter;
using Amazon.SimpleEmail;
using SES.Adapter.Config;
using SendEmail.MessageDelivery;
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace SendEmail.Lambda
{
public class Function
{
/// <summary>
/// A simple function that takes a string and does a ToUpper
/// </summary>
/// <param name="input"></param>
/// <param name="context"></param>
/// <returns></returns>
public async Task FunctionHandler(string input, ILambdaContext context)
{
IAmazonSQS sqsClient = new AmazonSQSClient();
ISqsAdapter sqsAdapter = new SqsAdapter(sqsClient, "");
IAmazonS3 s3Client = new AmazonS3Client();
IS3Adapter s3Adapter = new S3Adapter(s3Client);
IEmailMessageRepository emailMessageRepository = new EmailMessageRepository(sqsAdapter, s3Adapter);
IAmazonSimpleEmailService sesClient = new AmazonSimpleEmailServiceClient();
IEmailDeliveryConfig emailConfig = new EmailDeliveryConfig()
{
FromAddress = ""
};
ISESAdapter sesAdapter = new SESAdapter(sesClient, emailConfig);
IEmailMessageDelivery messageDelivery = new EmailMessageDelivery(sesAdapter);
IEmailQueueProcessor emailProcessor = new EmailQueueProcessor(emailMessageRepository, messageDelivery);
var emptyProcesses = 0;
while(emptyProcesses <= 3 && context.RemainingTime > TimeSpan.FromSeconds(30))
{
var count = await emailProcessor.ProcessEmailMessages();
if (count == 0)
emptyProcesses++;
}
}
}
}
|
23ea15341b7a3f7f8d0347075e9c862e6ae5546d
|
C#
|
jakakordez/roks-adventures
|
/Roks adventures/Drawable.cs
| 3.421875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Roks_adventures
{
class Drawable
{
public string[] Lines;
public int x, y, width;
public Action<int, int, string, bool> Print;
public Drawable(string[] lines, Action<int, int, string, bool> printer)
{
Lines = lines;
width = lines[0].Length;
Print = printer;
}
public void Draw()
{
for (int i = 0; i < Lines.Length; i++)
{
Print(x, y - i, Lines[i], false);
}
}
public void Delete()
{
for (int i = 0; i < Lines.Length; i++)
{
Print(x, y-i, new String(' ', width), false);
}
}
public void Clear()
{
for (int i = 0; i < Lines.Length; i++)
{
Print(x - 2, y-i, " ", false);
Print(x + width, y - i, " ", false);
}
}
}
}
|
4f6412f562dee7812a72e9403e9ba6c120e691b4
|
C#
|
DesislavaPlam/GiftSuggester
|
/GiftSuggester/GiftSuggester/GiftSuggester.Shared/ViewModels/EventsViewModel.cs
| 2.59375
| 3
|
namespace GiftSuggester.ViewModels
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GiftSuggester.Data;
using GiftSuggester.Data.UnitOfWork;
using GiftSuggester.Models;
public class EventsViewModel : ViewModelBase
{
private IAppData data;
private ICommand refreshCommand;
private ICommand addDataCommand;
private ObservableCollection<EventViewModel> events;
public EventsViewModel()
{
this.data = new AppData(new AppDbConnection());
this.LoadEvents();
}
public IEnumerable<EventViewModel> Events
{
get
{
if (this.events == null)
{
this.Events = new ObservableCollection<EventViewModel>();
}
return this.events;
}
set
{
if (this.events == null)
{
this.events = new ObservableCollection<EventViewModel>();
}
this.events.Clear();
foreach (var item in value)
{
this.events.Add(item);
}
}
}
public ICommand Refresh
{
get
{
if (this.refreshCommand == null)
{
this.refreshCommand = new RelayCommand(this.PerformRefresh);
}
return this.refreshCommand;
}
}
public ICommand AddData
{
get
{
if (this.addDataCommand == null)
{
this.addDataCommand = new RelayCommand(this.PerformAddData);
}
return this.addDataCommand;
}
}
public async Task LoadEvents()
{
var events = (await this.data.Events.All())
.AsQueryable()
//.Where(ev => ev.Date > DateTime.Now)
.OrderBy(ev => ev.Date)
.Select(EventViewModel.FromEvent)
.AsEnumerable();
this.Events = events;
}
private void AddEvents()
{
List<Event> events = new List<Event>()
{
new Event
{
Type = EventType.Christmass,
Date = DateTime.Now.AddDays(31),
FriendId = 2
},
new Event
{
Type = EventType.BirthDay,
Date = DateTime.Now.AddHours(2),
FriendId = 1
},
new Event
{
Type = EventType.NameDay,
Date = DateTime.Now.AddDays(3),
FriendId = 1
}
};
this.data.Events.Add(events[0]);
this.data.Events.Add(events[1]);
this.data.Events.Add(events[2]);
}
private void PerformRefresh()
{
this.LoadEvents();
}
private void PerformAddData()
{
this.AddEvents();
}
}
}
|
4c05e9a3fbc1273971b67d48a796326ca53de15c
|
C#
|
jazd/Business
|
/CSharp/Core.Test/TestBalance.cs
| 2.859375
| 3
|
using System;
using NUnit.Framework;
namespace Business.Core.Test
{
[TestFixture]
public class TestBalance
{
[Test]
public void Value() {
var record = new Balance() {
RightSide = true,
Debit = 10,
Credit = 4
};
Assert.AreEqual(6, record.Value);
record.Credit = null;
Assert.AreEqual(10, record.Value);
record = new Balance() {
RightSide = false,
Debit = 40,
Credit = 100
};
Assert.AreEqual(60, record.Value);
record.Debit = null;
Assert.AreEqual(100, record.Value);
record.Credit = null;
Assert.AreEqual(0, record.Value);
}
[Test]
// Get Value by account type from BookBalance result
public void AccountTypeValue() {
System.Collections.Generic.List<Balance> records = new System.Collections.Generic.List<Balance>();
// BookBalance('Sale Jane Doe', 1000) results
records.Add(new Balance() {
Book = 20,
Entry = 1,
Account = 100,
Name = "Cash",
RightSide = false,
Type = "Asset",
Debit = 15050,
Credit = 10300
});
records.Add(new Balance() {
Book = 20,
Entry = 1,
Account = 102,
Name = "Sales",
RightSide = true,
Type = "Income",
Debit = null,
Credit = 3300
});
records.Add(new Balance() {
Book = 20,
Entry = 1,
Account = 200,
Name = "Commissions Payable",
RightSide = true,
Type = "Liability",
Debit = null,
Credit = 750
});
Assert.AreEqual(4750, Balance.AccountTypeValue(records, "Asset"));
Assert.AreEqual(3300, Balance.AccountTypeValue(records, "Income"));
Assert.AreEqual(750, Balance.AccountTypeValue(records, "Liability"));
}
[Test]
// Get Value Sum by account types
public void AccountTypeValues() {
System.Collections.Generic.List<Balance> records = new System.Collections.Generic.List<Balance>();
records.Add(new Balance() {
Book = 20,
Entry = 1,
Account = 200,
Name = "Commissions Payable",
RightSide = true,
Type = "Liability",
Debit = null,
Credit = 700
});
records.Add(new Balance() {
Book = 20,
Entry = 1,
Account = 200,
Name = "Taxes Payable",
RightSide = true,
Type = "Liability",
Debit = null,
Credit = 50
});
Assert.AreEqual(750, Balance.AccountTypeValue(records, "Liability"));
}
}
}
|
172ad401faf8119bae4fd149c6de3a563ed30a96
|
C#
|
Barleysack/CSharpbasics
|
/C#basics/Day5/Short_test_01/Short_test_01/Program.cs
| 3.515625
| 4
|
using System;
namespace Short_test_01
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("값을 입력하세요 : ");
int input = Convert.ToInt32(Console.ReadLine());
Console.WriteLine($"입력된 값은 {input} 입니다");
Console.WriteLine("값을 입력하세요 : ");
//직점 실행창 및 호출 스택 확인.
}
catch (Exception ex)
{
Console.WriteLine($"예외발생:{ex.StackTrace}");
throw;
}
{
}
int ival = 10;
Console.WriteLine($"값은 {ival} 입니다");
for (int i = 2; i < 10; i++)
{
for (int j = 1; j < 10; j++)
{
Console.WriteLine($"{i}*{j}={i*j}");
}
}
}
}
}
|
0b1b3f9689979acda0c9f7b809eac78ca64bfb6e
|
C#
|
zhulinyin/UserManagementSystemUWP
|
/UserManagementSystem/UserManagementSystem/ViewModels/EmployeeViewModel.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using UserManagementSystem.Models;
using Windows.Data.Json;
namespace UserManagementSystem.ViewModels
{
class EmployeeViewModel
{
private static EmployeeViewModel uniqueInstance;
public static EmployeeViewModel getInstance()
{
if (uniqueInstance == null)
uniqueInstance = new EmployeeViewModel();
return uniqueInstance;
}
private ObservableCollection<Employee> employees = new ObservableCollection<Employee>();
public ObservableCollection<Employee> Employees { get { return employees; } }
public Employee SelectedItem;
public EmployeeViewModel()
{
SelectedItem = null;
ResolveJson();
}
static private async Task<string> GetEmployeesAsync()
{
string str = null;
HttpResponseMessage response = await App.client.GetAsync("/GetEmployee");
if (response.IsSuccessStatusCode)
{
str = await response.Content.ReadAsStringAsync();
}
return str;
}
private async void ResolveJson()
{
Employees.Clear();
string str = await GetEmployeesAsync();
if (str == null) return;
JsonArray jsonArray = JsonArray.Parse(str);
for(uint i = 0; i < jsonArray.Count; i++)
{
string eid = jsonArray.GetObjectAt(i).GetNamedValue("eid").ToString().TrimStart('\"').TrimEnd('\"');
string ename = jsonArray.GetObjectAt(i).GetNamedValue("ename").ToString().TrimStart('\"').TrimEnd('\"');
string dname = jsonArray.GetObjectAt(i).GetNamedValue("dname").ToString().TrimStart('\"').TrimEnd('\"');
string ebirth = jsonArray.GetObjectAt(i).GetNamedValue("ebirth").ToString().TrimStart('\"').TrimEnd('\"').Substring(0,10);
string status = jsonArray.GetObjectAt(i).GetNamedValue("name").ToString().TrimStart('\"').TrimEnd('\"');
string esex = jsonArray.GetObjectAt(i).GetNamedValue("esex").ToString().TrimStart('\"').TrimEnd('\"');
string ehometown = jsonArray.GetObjectAt(i).GetNamedValue("ehometown").ToString().TrimStart('\"').TrimEnd('\"');
string ebody = jsonArray.GetObjectAt(i).GetNamedValue("ebody").ToString().TrimStart('\"').TrimEnd('\"');
Employees.Add(new Employee(eid, ename, dname, ebirth, status, esex, ehometown, ebody));
}
}
public async Task<bool> CreateItem(string name, string birth, string sex, string hometown, string body,
string department)
{
var content = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"name",name },
{"birth",birth },
{"sex",sex },
{"hometown",hometown },
{"body",body },
{"department",department }
});
var response = await App.client.PostAsync("/newEmployee", content);
var resdata = await response.Content.ReadAsStringAsync();
if (resdata.Equals("true"))
{
ResolveJson();
return true;
}
else return false;
}
public async Task<bool> UpdateItem(string id, string name, string birth, string hometown, string body)
{
var content = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"eid",id },
{"name",name },
{"birth",birth },
{"hometown",hometown },
{"body",body }
});
var response = await App.client.PutAsync("/updateEmployee", content);
var resdata = await response.Content.ReadAsStringAsync();
if (resdata.Equals("true"))
{
ResolveJson();
return true;
}
else return false;
}
}
}
|
ff5477b338ea3f95309d9cee95e95cfe95707540
|
C#
|
KJfe/Labb3
|
/View/GeneralForm.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ValumeFigyre;
namespace View
{
public partial class GeneralForm : Form, IAddObjectDelegate
{
private IValumeFigyre _figyre;
public GeneralForm()
{
InitializeComponent();
}
/// <summary>
/// добавление фигур
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void AddFigyre_Click(object sender, EventArgs e)
{
AddObject AddFigure = new AddObject();
AddFigure.Delegate=this;
AddFigure.FormClosed += (obj, arg) =>
{
if (_figyre != null)
{
Grid.Rows.Add(_figyre.TypeFigyre, _figyre.Valume);
_figyre = null;
}
};
AddFigure.ShowDialog();
}
/// <summary>
/// удаление строки в таблице
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RemoveFigyre_Click(object sender, EventArgs e)
{
if (Grid.CurrentRow != null)
{
try
{
Grid.Rows.Remove(Grid.CurrentRow);
}
catch (System.InvalidOperationException) { }
}
}
/// <summary>
/// передача делегата
/// </summary>
/// <param name="figure"></param>
public void DidFinish(IValumeFigyre figure)
{
_figyre = figure;
}
/// <summary>
/// создание в таблице делсяти случайных фигур и объемов к ним
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Random_Click(object sender, EventArgs e)
{
#if DEBUG
Random random = new Random();
double randomValue;
int maxRandom;
int maxGridSize;
maxRandom = 10;
maxGridSize = 10;
for (int i = 0; i < maxGridSize; i++)
{
switch (random.Next(0, 3))
{
case 0:
{
Box BoxVolume = new Box(height: random.NextDouble() + random.Next(0, maxRandom),
width: random.NextDouble() + random.Next(0, maxRandom),
deep: random.NextDouble() + random.Next(0, maxRandom));
Grid.Rows.Add("Parallepiped", BoxVolume.Valume);
break;
}
case 1:
{
Sphear SphearVolume = new Sphear(radius: random.NextDouble() + random.Next(0, maxRandom));
Grid.Rows.Add("Sphear", SphearVolume.Valume);
break;
}
case 2:
{
Pyramid PyramidVolume = new Pyramid(area: random.NextDouble() + random.Next(0, maxRandom),
height: random.NextDouble() + random.Next(0, maxRandom));
randomValue = Grid.Rows.Add("Pyramid", PyramidVolume.Valume);
break;
}
default:
break;
}
}
#endif
}
/// <summary>
/// сохранить данные таблицы
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Save_Click(object sender, EventArgs e)
{
try
{
DataSet ds = new DataSet(); // создаем пока что пустой кэш данных
DataTable dt = new DataTable(); // создаем пока что пустую таблицу данных
dt.TableName = "Figures"; // название таблицы
dt.Columns.Add("Figure"); // название колонок
dt.Columns.Add("Volume");
ds.Tables.Add(dt); //в ds создается таблица, с названием и колонками, созданными выше
foreach (DataGridViewRow r in Grid.Rows) // пока в Grid есть строки
{
DataRow row = ds.Tables["Figures"].NewRow(); // создаем новую строку в таблице, занесенной в ds
row["Figure"] = r.Cells[0].Value; //в столбец этой строки заносим данные из первого столбца dataGridView1
row["Volume"] = r.Cells[1].Value; // то же самое со вторыми столбцами
ds.Tables["Figures"].Rows.Add(row); //добавление всей этой строки в таблицу ds.
}
saveDialog.ShowDialog();
ds.WriteXml(saveDialog.FileName);
MessageBox.Show("Vol file successfully saved.", "Complete");
}
catch
{
MessageBox.Show("Unable to save file Vol", "Error");
}
}
/// <summary>
/// открыть сохранения
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Open_Click(object sender, EventArgs e)
{
openDialog.ShowDialog();
if ((File.Exists(openDialog.FileName)) && (openDialog.FileName.Length !=0)) // если существует данный файл
{
DataSet ds = new DataSet(); // создаем новый пустой кэш данных
ds.ReadXml(openDialog.FileName); // записываем в него XML-данные из файла
foreach (DataRow item in ds.Tables["Figures"].Rows)
{
int n = Grid.Rows.Add(); // добавляем новую сроку в dataGridView1
Grid.Rows[n].Cells[0].Value = item["Figure"]; // заносим в первый столбец созданной строки данные из первого столбца таблицы ds.
Grid.Rows[n].Cells[1].Value = item["Volume"]; // то же самое со вторым столбцом
}
}
}
/// <summary>
/// очистить таблицу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Clear_Click(object sender, EventArgs e)
{
if (Grid.Rows.Count > 0)
{
Grid.Rows.Clear();
}
else
{
MessageBox.Show("Table is empty", "Error");
}
}
}
}
|
9f3f1c34491c1bd0987cd5c539b611818269d7e2
|
C#
|
blakeohare/pyweek22
|
/mapeditor/TileStore.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MapEditor
{
public static class TileStore
{
private static string[] tiles = null;
private static Dictionary<string, Tile> idsToTiles = new Dictionary<string, Tile>();
private static Dictionary<string, string> idsToPaths = new Dictionary<string, string>();
private static void Init()
{
if (tiles != null) return;
string gitRoot = Util.GetGitRoot();
string manifestPath = System.IO.Path.Combine(gitRoot, "source", "images", "tiles", "manifest.txt");
foreach (string line in System.IO.File.ReadAllLines(manifestPath))
{
string trimmedLine = line.Trim();
if (trimmedLine.Length > 0 && trimmedLine[0] != '#')
{
string[] parts = trimmedLine.Split('\t');
string id = parts[0];
string flags = parts[1];
string imagePath = parts[2].Split(',')[0];
Tile tile = new Tile(id, imagePath, System.IO.Path.Combine(gitRoot, "source", "images", "tiles", (imagePath + ".png").Replace('/', '\\')));
idsToTiles[id] = tile;
idsToPaths[id] = imagePath;
}
}
List<string> ids = new List<string>(idsToTiles.Keys);
TileStore.tiles = ids.OrderBy(id => idsToPaths[id]).ToArray();
}
public static List<Tile> GetTiles()
{
Init();
List<Tile> tiles = new List<Tile>(TileStore.tiles.Select<string, Tile>(tileId => idsToTiles[tileId]));
return tiles;
}
public static Tile GetTile(string id)
{
if (id == null || id.Length == 0) return null;
return idsToTiles[id];
}
}
}
|
c0ca26ca1aceead82e0fffb71452a328d54ab546
|
C#
|
Marin-Tsanov/2.-C-Sharp-Advanced
|
/5. Numeral Systems/4. Hexadecimal to decimal/Program.cs
| 3.609375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Numerics;
namespace _4.Hexadecimal_to_decimal
{
class Program
{
static void Main()
{
string number = Console.ReadLine();
Console.WriteLine(empty(number));
}
static string empty(string empty)
{
BigInteger sum = 0;
for (int i = empty.Length -1; i >=0; i--)
{
if (char.IsDigit(empty[i]))
{
sum += ((empty[i]-'0')*(BigInteger)(Math.Pow(16, (empty.Length - 1 - i))));
}
else
{
sum+= ((empty[i] - 'A'+10) * (BigInteger)(Math.Pow(16, (empty.Length - 1 - i))));
}
}
return empty=sum.ToString();
}
}
}
|
f9df4d085fb95cc4fb378ffaeaf278b02e9f405c
|
C#
|
ivandrofly/DoFactorydotNetDesignPattern
|
/Abstract Factory/Structural codes/AbstractProductA.cs
| 2.578125
| 3
|
/// <summary>
/// Creates an instance of several families of classes.
///
/// Provide an interface for creating families of related or
/// dependent objects without specifying their concrete classes.
///
/// Frequence of use: 5 high.
/// </summary>
namespace DoFactory.GangOfFour.Abstract.Structural
{
/// <summary>
/// The 'AbstractProductA' abstract class
/// </summary>
abstract class AbstractProductA
{
}
}
|
2ffa54f86947fc9f367494fe5b7123d06d028a70
|
C#
|
Makzz90/VKClient_re
|
/VKClient.Common/framework/DelegateCommand.cs
| 2.75
| 3
|
using System;
using System.Windows.Input;
namespace VKClient.Common.Framework
{
public class DelegateCommand : ICommand
{
private Func<object, bool> canExecute;
private Action<object> executeAction;
public event EventHandler CanExecuteChanged;
public DelegateCommand(Action<object> executeAction)
: this(executeAction, null)
{
}
public DelegateCommand(Action<object> executeAction, Func<object, bool> canExecute)
{
if (executeAction == null)
throw new ArgumentNullException("executeAction");
this.executeAction = executeAction;
this.canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
bool flag = true;
Func<object, bool> canExecute = this.canExecute;
if (canExecute != null)
flag = canExecute(parameter);
return flag;
}
public void RaiseCanExecuteChanged()
{
// ISSUE: reference to a compiler-generated field
EventHandler canExecuteChanged = this.CanExecuteChanged;
if (canExecuteChanged == null)
return;
canExecuteChanged(this, new EventArgs());
}
public void Execute(object parameter)
{
this.executeAction(parameter);
}
}
}
|
1543d60747182daf7eb45fa1810c8389a2ab8485
|
C#
|
sebastianOrtiz/Concurrente2
|
/PacmanServidor/PACMANv3/PACMANv3/pkgModelo/DatosJugador.cs
| 3.125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
namespace PACMANv3.pkgModelo {
/// <summary>
/// Clase que representa un jugador
/// </summary>
public class DatosJugador {
private string nombre;
private string fecha;
private int puntaje;
private String dificultad;
/// <summary>
/// Constructor vacio que sirve para crear el objeto cuando recontruido desde el archivo JSON
/// </summary>
public DatosJugador() {
}
/// <summary>
/// Contructor de la clase DatosJugador que recive nombre del jugador y dificultad de juego
/// </summary>
/// <param name="nombre">Nombre del jugador</param>
/// <param name="dificultad">Dificultad de Juego</param>
public DatosJugador(string nombre, String dificultad) {
this.nombre = nombre;
this.dificultad = dificultad;
this.puntaje = 0;
}
/// <summary>
/// Metodo ToString de la clase DatosJugador
/// </summary>
/// <returns>Retorna una representacion en forma de cadena de texto de la clase</returns>
public override string ToString() {
return nombre + " " + dificultad + " " + puntaje + " " + fecha;
}
/// <summary>
/// Aumenta el puntaje del jugador
/// </summary>
/// <param name="puntos">Numero de puntos a aumentar</param>
/// <returns>Retorna el numero de puntos actual del jugador</returns>
public int aumentarPuntaje(int puntos) {
puntaje = puntaje + puntos;
return puntaje;
}
/// <summary>
/// Accesor y mutador de el atributo Dificultad
/// </summary>
public String Dificultad {
get { return dificultad; }
set { dificultad = value; }
}
/// <summary>
/// Accesor y mutador de el atributo Fecha
/// </summary>
public string Fecha {
get { return fecha; }
set { fecha = value; }
}
/// <summary>
/// Accesor y mutador de el atributo Puntaje
/// </summary>
public int Puntaje {
get { return puntaje; }
set { puntaje = value; }
}
/// <summary>
/// Accesor y mutador de el atributo Nombre
/// </summary>
public string Nombre {
get { return nombre; }
set { nombre = value; }
}
}
}
|
ef512eb57f70c8391aa5e84a1f905bde19ad23b0
|
C#
|
KrzysztofKowalski/scalex
|
/src/DrawingSurface/GDIDrawingSurface.cs
| 2.890625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using Webprofusion.Scalex.Util;
namespace Webprofusion.Scalex.Rendering
{
public class GDIDrawingSurface : IGenericDrawingSurface
{
private Graphics canvas;
private Brush ForegroundBrush = Brushes.Black;
private Brush MutedForegroundBrush = Brushes.DarkGray;
private Brush SubtleBrush = Brushes.LightGray;
private Brush BackgroundBrush = Brushes.White;
private Brush AccentBrush = new System.Drawing.SolidBrush((Color)new System.Drawing.ColorConverter().ConvertFrom("#FF312121"));
public string DefaultFontName = "Arial";
public GDIDrawingSurface(Graphics g)
{
canvas = g;
}
#region IGenericDrawingSurface Members
public void DrawString(double x, double y, string text)
{
DrawString(x, y, text, ColorPreset.Foreground);
}
public void DrawString(double x, double y, string text, ColorPreset color)
{
DrawString(x, y, text, 9, color);
}
public void DrawStringCentered(double y, string text, double canvasWidth, double fontSize)
{
double x = (canvasWidth / 2) - ((text.Length * fontSize) / 2);
DrawString(x, y, text, fontSize);
}
public void DrawString(double x, double y, string text, double size)
{
DrawString(x, y, text, size, ColorPreset.Foreground);
}
public void DrawString(double x, double y, string text, double fontSize, ColorPreset color)
{
Font f = new Font(DefaultFontName, (float)fontSize, GraphicsUnit.Pixel);
canvas.DrawString(text, f, GetPresetBrush(color), (float)x, (float)y);
}
public void DrawLine(double x1, double y1, double x2, double y2, double strokeThickness, ColorPreset color)
{
Pen p = new Pen(GetPresetBrush(color), (float)strokeThickness);
canvas.DrawLine(p, (float)x1, (float)y1, (float)x2, (float)y2);
}
public void DrawArc(double x, double y, double width, bool isArcDown)
{
canvas.DrawArc(Pens.Black, (float)x, (float)y, (float)width, 10, 30, 30);
}
public void Clear()
{
}
public void FillRectangle(double x, double y, double w, double h, ColorPreset FillColor, ColorPreset BorderColor)
{
System.Drawing.RectangleF rect = new RectangleF((float)x, (float)y, (float)w, (float)h);
canvas.FillRectangle(GetPresetBrush(FillColor), rect);
canvas.DrawRectangle(new Pen(GetPresetBrush(BorderColor)), rect.X, rect.Y, rect.Width, rect.Height);
}
public void FillEllipse(double x, double y, double w, double h, ColorPreset FillColor, ColorPreset BorderColor)
{
System.Drawing.RectangleF rect = new RectangleF((float)x, (float)y, (float)w, (float)h);
canvas.FillEllipse(GetPresetBrush(FillColor), rect);
canvas.DrawEllipse(new Pen(GetPresetBrush(BorderColor)), rect);
}
public void FillEllipse(double x, double y, double w, double h, ColorValue FillColor, ColorValue BorderColor)
{
System.Drawing.RectangleF rect = new RectangleF((float)x, (float)y, (float)w, (float)h);
Brush fillBrush = new System.Drawing.SolidBrush(Color.CadetBlue);
Pen strokePen = new System.Drawing.Pen(Color.Aquamarine);
canvas.FillEllipse(fillBrush, rect);
canvas.DrawEllipse(strokePen, rect);
}
private Brush GetPresetBrush(ColorPreset c)
{
switch (c)
{
case ColorPreset.Foreground:
return ForegroundBrush;
case ColorPreset.ForegroundText:
return BackgroundBrush;
case ColorPreset.MutedForeground:
return MutedForegroundBrush;
case ColorPreset.Subtle:
return SubtleBrush;
case ColorPreset.Accent:
return AccentBrush;
default:
return ForegroundBrush;
}
}
public void FillEllipse(double x1, double y1, double w, double h, ColorPreset FillColor, ColorValue BorderColor)
{
throw new NotImplementedException();
}
#endregion IGenericDrawingSurface Members
}
}
|
6490e507cc71b37752d63ca41c54a51152391653
|
C#
|
Nikolay-712/CSharp-OOP
|
/Exercises/Polymorphism-Exercise/03.WildFarm/Birds/Owl.cs
| 3.484375
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace _03.WildFarm
{
public class Owl : Bird
{
private static double OwlFoodModificator = 0.25;
public Owl(string name, double weight, double wingSize)
: base(name, weight, wingSize)
{
}
public override string ProducieSound()
{
return "Hoot Hoot";
}
public override void CheckFoodType(Food food)
{
var typeFood = food.GetType().Name;
if (typeFood != "Meat")
{
throw new ArgumentException($"{this.GetType().Name} does not eat {typeFood}!");
}
base.CheckFoodType(food);
IncreaseAnimalWeight(food);
}
private void IncreaseAnimalWeight(Food food)
{
this.Weight = this.Weight + food.Quantity * OwlFoodModificator;
}
public override string ToString()
{
return base.ToString();
}
}
}
|
a0be681655aa1009788ffa4f5b53fd96f9e0fc30
|
C#
|
rix1/mgdev-life-of-pi
|
/Assets/Scripts/g_NoteGenerator.cs
| 2.71875
| 3
|
using UnityEngine;
using System.Collections;
using Rhythmify;
public class g_NoteGenerator : _AbstractRhythmObject {
public GameObject green;
public GameObject red;
public GameObject yellow;
private Vector3 spawnLoc1 = new Vector3(-1.8f ,4f,0f);
private Vector3 spawnLoc2 = new Vector3(0.0f ,4f,0f);
private Vector3 spawnLoc3 = new Vector3(1.8f ,4f,0f);
private int random = 0;
private Quaternion rotation = Quaternion.Euler(0,0,0);
override protected void rhythmUpdate(int i){
Debug.Log("BEAT: " + i + " : " + Random.Range(1,4));
random = Random.Range(1,4);
drawNote(random);
}
void drawNote(int i){
switch (i)
{
case 1:
Instantiate(green, spawnLoc1, rotation);
break;
case 2:
Instantiate(yellow, spawnLoc2, rotation);
break;
case 3:
Instantiate(red, spawnLoc3, rotation);
break;
default:
break;
}
}
}
|
e2df4b63d1de1640505e5ff1db2123270e98eb17
|
C#
|
qq550723504/DesignPatterns
|
/BehavioralPatterns/MediatorPattern/Program.cs
| 2.515625
| 3
|
using System;
namespace MediatorPattern
{
class Program
{
static void Main(string[] args)
{
var robert = new User("Robert");
var john = new User("John");
robert.SendMessage("Hi! John!");
john.SendMessage("Hello! Robert!");
Console.ReadKey();
}
}
}
|
09cfe38707e990a8f85d9ea6863fa91ff608f1a5
|
C#
|
Whathecode/NET-Standard-Library-Extension
|
/src/Whathecode.System/IO/Extensions.DirectoryInfo.cs
| 3.15625
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace Whathecode.System.IO
{
public static partial class Extensions
{
/// <summary>
/// Returns an enumerable collection of file information that matches a regular expression.
/// </summary>
/// <param name = "directory">The directory to search in.</param>
/// <param name = "searchOption">Specifies whether to search in all subdirectories as well.</param>
/// <param name = "regexPattern">The regular expression which is used to see whether a file matches.</param>
/// <param name = "regexOptions">Options for the regular expression.</param>
public static IEnumerable<FileInfo> EnumerateFiles(
this DirectoryInfo directory,
SearchOption searchOption,
string regexPattern,
RegexOptions regexOptions = RegexOptions.None )
{
return directory.EnumerateFiles( "*", searchOption ).Where( file => Regex.IsMatch( file.FullName, regexPattern, regexOptions ) );
}
/// <summary>
/// Returns the first common subdirectory if any, null otherwise.
/// </summary>
/// <param name = "source">The source for this extension method.</param>
/// <param name = "directory">The directory to check for a common subdirectory.</param>
/// <returns>The first common subdirectory if any, null otherwise.</returns>
public static DirectoryInfo GetCommonParentDirectory( this DirectoryInfo source, DirectoryInfo directory )
{
Func<DirectoryInfo, Stack<DirectoryInfo>> getParentDirs = d =>
{
Stack<DirectoryInfo> sourceParents = new Stack<DirectoryInfo>();
while ( d.Parent != null )
{
sourceParents.Push( d );
d = d.Parent;
}
sourceParents.Push( d );
return sourceParents;
};
Stack<DirectoryInfo> parents1 = getParentDirs( source );
Stack<DirectoryInfo> parents2 = getParentDirs( directory );
DirectoryInfo lastMatching = null;
while ( parents1.Count > 0 && parents2.Count > 0 )
{
DirectoryInfo p1 = parents1.Pop();
DirectoryInfo p2 = parents2.Pop();
if ( p1.FullName == p2.FullName )
{
lastMatching = p1;
}
else
{
break;
}
}
return lastMatching;
}
}
}
|
e22ebe2b48a50c449a7e300dc9c50ac3ccf2d322
|
C#
|
AzureCloudMonk/introducing-dapr
|
/Chapter 9/ImageProcessing/ObjectRecognition/DataStructures/ModelResult.cs
| 3.09375
| 3
|
namespace ObjectRecognition.DataStructures
{
public class ModelResult
{
/// <summary>
/// x1, y1, x2, y2 coordinates.
/// </summary>
public float[] BBox { get; }
/// <summary>
/// The category of the bounding box.
/// </summary>
public string Label { get; }
/// <summary>
/// Confidence level.
/// </summary>
public float Confidence { get; }
public ModelResult(float[] bbox, string label, float confidence)
{
BBox = bbox;
Label = label;
Confidence = confidence;
}
}
}
|
d63225f16544a41b7568e6096f2c901661d140f7
|
C#
|
MartinArvidsson/1dv402-ma223ku-Recept_p-_fil
|
/FiledRecipes/FiledRecipes/Views/RecipeView.cs
| 2.890625
| 3
|
using FiledRecipes.Domain;
using FiledRecipes.App.Mvp;
using FiledRecipes.Properties;
using System;
using System.Collections.Generic;
using System.Linq;
namespace FiledRecipes.Views
{
/// <summary>
///
/// </summary>
public class RecipeView : ViewBase, IRecipeView // Publik klass som heter RecipeView, ärver ifrån Viewbase och Interfacet IRecipeView
{
private const string ingredienser = "Ingredienser";
private const string instruktioner = "Instruktioner";
public void Show(IRecipe recipe) //Visar 1 recept
{
Header = recipe.Name; // Header blir receptets namn
ShowHeaderPanel(); // Visar headern
Console.WriteLine("");
Console.WriteLine("============");
Console.WriteLine(ingredienser);//Skriv ut ingredienserna
Console.WriteLine("============");
foreach(IIngredient ingredient in recipe.Ingredients) // För varje ingrediens i recipie.Ingredients
{
Console.WriteLine(ingredient); // Skriv ut ingrediensen
}
int instructionPart = 1; // Sätter variablen instructionPart till 1
Console.WriteLine("");
Console.WriteLine("==============");
Console.WriteLine(instruktioner); // Skriver ut instruktionerna
Console.WriteLine("=============="); // Skriver ut instruktionerna
foreach(string instruction in recipe.Instructions) // För varje string /rad i recipe.Instruktions
{
Console.WriteLine("{0}.\n {1}", instructionPart,instruction); //Skriv ut instructionPart, sedan instruktionen
instructionPart++; // Plussa på med 1
}
}
public void Show(IEnumerable<IRecipe> recipes) // Visar alla recept.
{
foreach(IRecipe recipe in recipes) // För varje recept i recept
{
Show(recipe); // Visa recept ( Gör rad 15 till 31)
ContinueOnKeyPressed(); // Gå vidare på tangenttryck till nästa recept
}
}
}
}
|
79febd70bb396f1eddd80c985f441c22feffb501
|
C#
|
Danailnd/Principles-of-Programing
|
/Ch 2 Calculating Area for Circle, Rectangle or Square/Program.cs
| 4.1875
| 4
|
using System;
namespace Ch_2_Calculating_Area_for_Circle__Rectangle_or_Square
{
class Program
{
static void Main(string[] args)
{
bool repeat = false;
do
{
Console.WriteLine("Hello. Please choose one of the following shapes to calculate the area of: ");
Console.Write("rectangle, triangle or circle: ");
string shape = Console.ReadLine();
if (shape == "rectangle")
{
Console.WriteLine("Please Input Length ");
double length = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please Input Width ");
double width = Convert.ToDouble(Console.ReadLine());
double Area = width * length;
double Perimeter = 2 * (width + length);
Console.WriteLine("The area of your " + shape + " is: " + Area);
Console.WriteLine("The perimeter of your " + shape + " is: " + Perimeter);
}
else if (shape == "triangle")
{ bool check = false;
while (!check)
{
Console.WriteLine("Please input the first side ");
double side1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please input the second side ");
double side2 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please input the third side ");
double side3 = Convert.ToDouble(Console.ReadLine());
if (side1 + side2 > side3 && side1 + side3 > side2 && side2 + side3 > side1)
{
double Perimeter = side1 + side2 + side3;
double Area = Math.Sqrt(Perimeter / 2 * (Perimeter / 2 - side1) * (Perimeter / 2 - side2) * (Perimeter / 2 - side3));
// sqrt (p (p − a)(p − b)(p − c)) -> Heron's Formula where p is perimeter/2
Console.WriteLine("The area of your " + shape + " is: " + Area);
Console.WriteLine("The perimeter of your " + shape + " is: " + Perimeter);
check = true;
}
else
{
Console.WriteLine("No triangle can exist with the given sides. ");
Console.WriteLine("Please try again. (The sum of two sides of a triangle is always bigger than the third side) ");
}
}
}
else if (shape == "circle")
{
Console.WriteLine("Please input radius ");
double radius = Convert.ToDouble(Console.ReadLine());
double Area = Math.Pow(radius, 2) * Math.PI;
double Perimeter = 2 * radius * Math.PI;
Console.WriteLine("The area of your " + shape + " is: " + Area);
Console.WriteLine("The circumference of your " + shape + " is: " + Perimeter);
}
else
{
Console.WriteLine("Please type one of the three shapes listed above. (Note that the program is case-sensitive) ");
repeat = true;
}
} while (repeat);
Console.ReadLine();
}
}
}
|
66e411381328a16154ddcc721ce7ab14496790b3
|
C#
|
jasarvn/howdengroup
|
/insuranceMonitoringSystem/insuranceMonitoringSystem/Helpers/Dbhelper.cs
| 2.640625
| 3
|
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using insuranceMonitoringSystem.Constants;
using Microsoft.EntityFrameworkCore;
namespace insuranceMonitoringSystem.Helpers
{
public class Dbhelper
{
protected static string cs = Constants.Constants.connString;
public static DataTable GetDbData(string sql)
{
DataTable rm = new DataTable();
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
using (SqlDataAdapter adpter = new SqlDataAdapter(sql, conn))
{
adpter.Fill(rm);
}
conn.Close();
}
return rm;
}
public static void processData(string sql)
{
DataTable rm = new DataTable();
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
using (SqlDataAdapter adpter = new SqlDataAdapter())
{
adpter.InsertCommand = new SqlCommand(sql, conn);
adpter.InsertCommand.ExecuteNonQuery();
//adpter.Fill(rm);
}
conn.Close();
}
}
}
}
|