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
|
|---|---|---|---|---|---|---|
2faa6952d93bf7df2c75e4941662a34d71d6d5b3
|
C#
|
studentazz/CodeJamProject
|
/CodeJam/Problems/Problem1.cs
| 2.703125
| 3
|
using System;
namespace CodeJam.Problems
{
public class Problem1 : IProblem
{
public bool IsSoved(string output)
{
if (output == null) return false;
output = output.Trim(new char[] { '\r', '\n', ' ' });
throw new NotImplementedException();
}
public string Id => "Problem1Id";
public string Input => "";
}
}
|
8b49fd396307e78536b876df36c6d847c8c5c67c
|
C#
|
Clackgot/RIAA
|
/RIAA.4/Form1.cs
| 2.515625
| 3
|
using System;
using System.Windows.Forms;
namespace RIAA._4
{
public partial class Form1 : Form
{
private Panel inputs;
private Panel labels;
private NumericUpDown inputA;
private NumericUpDown inputB;
private NumericUpDown inputEps;
private NumericUpDown inputN;
public Form1()
{
InitializeComponent();
inputs = panelInputs;
labels = panelLabels;
}
private void Clear()
{
inputs.Controls.Clear();
labels.Controls.Clear();
}
/// <summary>
/// Метод Симпсона
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void radioButtonSimpsonMethod_CheckedChanged(object sender, EventArgs e)
{
Clear();
labels.Controls.Add(new Label()
{
AutoSize = true,
Location = new System.Drawing.Point(0, 2),
Size = new System.Drawing.Size(46, 17),
Text = "Левая граница интегрирования",
TextAlign = System.Drawing.ContentAlignment.MiddleLeft
});
labels.Controls.Add(new Label()
{
AutoSize = true,
Location = new System.Drawing.Point(0, 29),
Size = new System.Drawing.Size(46, 17),
Text = "Правая граница интегрирования",
TextAlign = System.Drawing.ContentAlignment.MiddleLeft
});
labels.Controls.Add(new Label()
{
AutoSize = true,
Location = new System.Drawing.Point(0, 56),
Size = new System.Drawing.Size(46, 17),
Text = "Точность эпсилон",
TextAlign = System.Drawing.ContentAlignment.MiddleLeft
});
inputA = new NumericUpDown()
{
DecimalPlaces = 3,
Increment = new decimal(new int[] {
0,
0,
0,
0 }),
Location = new System.Drawing.Point(3, -1),
Maximum = new decimal(new int[] {
147483648,
0,
0,
0 }),
Minimum = new decimal(new int[] {
147483648,
0,
0,
-2147483648 }),
Size = new System.Drawing.Size(120, 22),
Value = 1
};
inputB = new NumericUpDown()
{
DecimalPlaces = 3,
Increment = new decimal(new int[] {
0,
0,
0,
0}),
Location = new System.Drawing.Point(3, 26),
Maximum = new decimal(new int[] {
147483648,
0,
0,
0}),
Minimum = new decimal(new int[] {
147483648,
0,
0,
-2147483648}),
Size = new System.Drawing.Size(120, 22),
Value = 2
};
inputEps = new NumericUpDown()
{
DecimalPlaces = 3,
Increment = new decimal(new int[] {
0,
0,
0,
0}),
Location = new System.Drawing.Point(3, 53),
Maximum = new decimal(new int[] {
147483648,
0,
0,
0}),
Minimum = new decimal(new int[] {
147483648,
0,
0,
-2147483648}),
Size = new System.Drawing.Size(120, 22),
Value = 1
};
inputs.Controls.Add(inputA);
inputs.Controls.Add(inputB);
inputs.Controls.Add(inputEps);
}
/// <summary>
/// Метод трапеций
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void radioButtonTrapezoidMethod_CheckedChanged(object sender, EventArgs e)
{
Clear();
labels.Controls.Add(new Label()
{
AutoSize = true,
Location = new System.Drawing.Point(0, 2),
Size = new System.Drawing.Size(46, 17),
Text = "Левая граница интегрирования",
TextAlign = System.Drawing.ContentAlignment.MiddleLeft
});
labels.Controls.Add(new Label()
{
AutoSize = true,
Location = new System.Drawing.Point(0, 29),
Size = new System.Drawing.Size(46, 17),
Text = "Правая граница интегрирования",
TextAlign = System.Drawing.ContentAlignment.MiddleLeft
});
labels.Controls.Add(new Label()
{
AutoSize = true,
Location = new System.Drawing.Point(0, 56),
Size = new System.Drawing.Size(46, 17),
Text = "Число отрезков",
TextAlign = System.Drawing.ContentAlignment.MiddleLeft
});
inputA = new NumericUpDown()
{
DecimalPlaces = 3,
Increment = new decimal(new int[] {
0,
0,
0,
0}),
Location = new System.Drawing.Point(3, -1),
Maximum = new decimal(new int[] {
147483648,
0,
0,
0}),
Minimum = new decimal(new int[] {
147483648,
0,
0,
-2147483648}),
Size = new System.Drawing.Size(120, 22),
Value = 1
};
inputB = new NumericUpDown()
{
DecimalPlaces = 3,
Increment = new decimal(new int[] {
0,
0,
0,
0}),
Location = new System.Drawing.Point(3, 26),
Maximum = new decimal(new int[] {
147483648,
0,
0,
0}),
Minimum = new decimal(new int[] {
147483648,
0,
0,
-2147483648}),
Size = new System.Drawing.Size(120, 22),
Value = 2
};
inputN = new NumericUpDown()
{
DecimalPlaces = 0,
Increment = new decimal(new int[] {
0,
0,
0,
0}),
Location = new System.Drawing.Point(3, 53),
Maximum = new decimal(new int[] {
147483648,
0,
0,
0}),
Minimum = new decimal(new int[] {
147483648,
0,
0,
-2147483648}),
Size = new System.Drawing.Size(120, 22),
Value = 5
};
inputs.Controls.Add(inputA);
inputs.Controls.Add(inputB);
inputs.Controls.Add(inputN);
}
/// <summary>
/// Метод средних треугольников
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void radioButtonMiddleRectangleMethod_CheckedChanged(object sender, EventArgs e)
{
Clear();
labels.Controls.Add(new Label()
{
AutoSize = true,
Location = new System.Drawing.Point(0, 2),
Size = new System.Drawing.Size(46, 17),
Text = "Левая граница интегрирования",
TextAlign = System.Drawing.ContentAlignment.MiddleLeft
});
labels.Controls.Add(new Label()
{
AutoSize = true,
Location = new System.Drawing.Point(0, 29),
Size = new System.Drawing.Size(46, 17),
Text = "Правая граница интегрирования",
TextAlign = System.Drawing.ContentAlignment.MiddleLeft
});
labels.Controls.Add(new Label()
{
AutoSize = true,
Location = new System.Drawing.Point(0, 56),
Size = new System.Drawing.Size(46, 17),
Text = "Число отрезков",
TextAlign = System.Drawing.ContentAlignment.MiddleLeft
});
labels.Controls.Add(new Label()
{
AutoSize = true,
Location = new System.Drawing.Point(0, 83),
Size = new System.Drawing.Size(46, 17),
Text = "Точность эпсилон",
TextAlign = System.Drawing.ContentAlignment.MiddleLeft
});
inputA = new NumericUpDown()
{
DecimalPlaces = 3,
Increment = new decimal(new int[] {
0,
0,
0,
0}),
Location = new System.Drawing.Point(3, -1),
Maximum = new decimal(new int[] {
147483648,
0,
0,
0}),
Minimum = new decimal(new int[] {
147483648,
0,
0,
-2147483648}),
Size = new System.Drawing.Size(120, 22),
Value = 1
};
inputB = new NumericUpDown()
{
DecimalPlaces = 3,
Increment = new decimal(new int[] {
0,
0,
0,
0}),
Location = new System.Drawing.Point(3, 26),
Maximum = new decimal(new int[] {
147483648,
0,
0,
0}),
Minimum = new decimal(new int[] {
147483648,
0,
0,
-2147483648}),
Size = new System.Drawing.Size(120, 22),
Value = 2
};
inputN = new NumericUpDown()
{
DecimalPlaces = 0,
Increment = new decimal(new int[] {
0,
0,
0,
0}),
Location = new System.Drawing.Point(3, 53),
Maximum = new decimal(new int[] {
147483648,
0,
0,
0}),
Minimum = new decimal(new int[] {
147483648,
0,
0,
-2147483648}),
Size = new System.Drawing.Size(120, 22),
Value = 10
};
inputEps = new NumericUpDown()
{
DecimalPlaces = 3,
Increment = new decimal(new int[] {
0,
0,
0,
0}),
Location = new System.Drawing.Point(3, 80),
Maximum = new decimal(new int[] {
147483648,
0,
0,
0}),
Minimum = new decimal(new int[] {
147483648,
0,
0,
-2147483648}),
Size = new System.Drawing.Size(120, 22),
Value = (decimal)(0.004)
};
inputs.Controls.Add(inputA);
inputs.Controls.Add(inputB);
inputs.Controls.Add(inputN);
inputs.Controls.Add(inputEps);
}
/// <summary>
/// Метод левых треугольников
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void radioButtonLeftRectangleMethod_CheckedChanged(object sender, EventArgs e)
{
Clear();
labels.Controls.Add(new Label()
{
AutoSize = true,
Location = new System.Drawing.Point(0, 2),
Size = new System.Drawing.Size(46, 17),
Text = "Левая граница интегрирования",
TextAlign = System.Drawing.ContentAlignment.MiddleLeft
});
labels.Controls.Add(new Label()
{
AutoSize = true,
Location = new System.Drawing.Point(0, 29),
Size = new System.Drawing.Size(46, 17),
Text = "Правая граница интегрирования",
TextAlign = System.Drawing.ContentAlignment.MiddleLeft
});
labels.Controls.Add(new Label()
{
AutoSize = true,
Location = new System.Drawing.Point(0, 56),
Size = new System.Drawing.Size(46, 17),
Text = "Точность эпсилон",
TextAlign = System.Drawing.ContentAlignment.MiddleLeft
});
inputA = new NumericUpDown()
{
DecimalPlaces = 3,
Increment = new decimal(new int[] {
0,
0,
0,
0}),
Location = new System.Drawing.Point(3, -1),
Maximum = new decimal(new int[] {
147483648,
0,
0,
0}),
Minimum = new decimal(new int[] {
147483648,
0,
0,
-2147483648}),
Size = new System.Drawing.Size(120, 22),
Value = 1
};
inputB = new NumericUpDown()
{
DecimalPlaces = 3,
Increment = new decimal(new int[] {
0,
0,
0,
0}),
Location = new System.Drawing.Point(3, 26),
Maximum = new decimal(new int[] {
147483648,
0,
0,
0}),
Minimum = new decimal(new int[] {
147483648,
0,
0,
-2147483648}),
Size = new System.Drawing.Size(120, 22),
Value = 2
};
inputEps = new NumericUpDown()
{
DecimalPlaces = 3,
Increment = new decimal(new int[] {
0,
0,
0,
0}),
Location = new System.Drawing.Point(3, 53),
Maximum = new decimal(new int[] {
147483648,
0,
0,
0}),
Minimum = new decimal(new int[] {
147483648,
0,
0,
-2147483648}),
Size = new System.Drawing.Size(120, 22),
Value = (decimal)(0.004)
};
inputs.Controls.Add(inputA);
inputs.Controls.Add(inputB);
inputs.Controls.Add(inputEps);
}
/// <summary>
/// Метод правых треугольников
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void radioButtonRightRectangleMethod_CheckedChanged(object sender, EventArgs e)
{
Clear();
labels.Controls.Add(new Label()
{
AutoSize = true,
Location = new System.Drawing.Point(0, 2),
Size = new System.Drawing.Size(46, 17),
Text = "Левая граница интегрирования",
TextAlign = System.Drawing.ContentAlignment.MiddleLeft
});
labels.Controls.Add(new Label()
{
AutoSize = true,
Location = new System.Drawing.Point(0, 29),
Size = new System.Drawing.Size(46, 17),
Text = "Правая граница интегрирования",
TextAlign = System.Drawing.ContentAlignment.MiddleLeft
});
labels.Controls.Add(new Label()
{
AutoSize = true,
Location = new System.Drawing.Point(0, 56),
Size = new System.Drawing.Size(46, 17),
Text = "Точность эпсилон",
TextAlign = System.Drawing.ContentAlignment.MiddleLeft
});
inputA = new NumericUpDown()
{
DecimalPlaces = 3,
Increment = new decimal(new int[] {
0,
0,
0,
0}),
Location = new System.Drawing.Point(3, -1),
Maximum = new decimal(new int[] {
147483648,
0,
0,
0}),
Minimum = new decimal(new int[] {
147483648,
0,
0,
-2147483648}),
Size = new System.Drawing.Size(120, 22),
Value = 1
};
inputB = new NumericUpDown()
{
DecimalPlaces = 3,
Increment = new decimal(new int[] {
0,
0,
0,
0}),
Location = new System.Drawing.Point(3, 26),
Maximum = new decimal(new int[] {
147483648,
0,
0,
0}),
Minimum = new decimal(new int[] {
147483648,
0,
0,
-2147483648}),
Size = new System.Drawing.Size(120, 22),
Value = 2
};
inputEps = new NumericUpDown()
{
DecimalPlaces = 3,
Increment = new decimal(new int[] {
0,
0,
0,
0 }),
Location = new System.Drawing.Point(3, 53),
Maximum = new decimal(new int[] {
147483648,
0,
0,
0 }),
Minimum = new decimal(new int[] {
147483648,
0,
0,
-2147483648 }),
Size = new System.Drawing.Size(120, 22),
Value = (decimal)(0.004)
};
inputs.Controls.Add(inputA);
inputs.Controls.Add(inputB);
inputs.Controls.Add(inputEps);
}
private void button1_Click(object sender, EventArgs e)
{
if(radioButtonSimpsonMethod.Checked == true)
{
labelAnswer.Text = Lib.SimpsonMethod((double)inputA.Value, (double)inputB.Value, (double)inputEps.Value).ToString();
}
else if(radioButtonTrapezoidMethod.Checked == true)
{
labelAnswer.Text = Lib.TrapezoidMethod((double)inputA.Value, (double)inputB.Value, (int)inputN.Value).ToString();
}
else if (radioButtonLeftRectangleMethod.Checked == true)
{
labelAnswer.Text = Lib.LeftRectangleMethod((double)inputA.Value, (double)inputB.Value, (double)inputEps.Value).ToString();
}
else if (radioButtonRightRectangleMethod.Checked == true)
{
labelAnswer.Text = Lib.RightRectangleMethod((double)inputA.Value, (double)inputB.Value, (double)inputEps.Value).ToString();
}
else if (radioButtonMiddleRectangleMethod.Checked == true)
{
labelAnswer.Text = Lib.MiddleRectangleMethod((double)inputA.Value, (double)inputB.Value, (double)inputEps.Value, (int)inputN.Value).ToString();
}
}
}
}
|
552943408a63133a42f24d6617e6e6f0c8301cf0
|
C#
|
sephirothwzc/Sephiroth.Common
|
/StringExten/SIC_Exten.cs
| 2.671875
| 3
|
namespace Sephiroth.Infrastructure.Common
{
using System;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Security;
/// <summary>
/// 通用字符串扩展
/// </summary>
public static class SIC_Exten
{
/// <summary>
/// 编码
/// </summary>
/// <param name="str"></param>
/// <param name="toType"></param>
/// <returns></returns>
public static string EnCode(this string str, CodeType toType = CodeType.MD5)
{
string str2 = str;
switch (toType)
{
case CodeType.MD5:
return GetSwcMD5(str);
//return FormsAuthentication.HashPasswordForStoringInConfigFile(str, "md5");
case CodeType.SHA1:
return GetSwcSH1(str);
//return FormsAuthentication.HashPasswordForStoringInConfigFile(str, "SHA1");
}
return str2;
}
private static string GetSwcSH1(string value)
{
SHA1 algorithm = SHA1.Create();
byte[] data = algorithm.ComputeHash(Encoding.UTF8.GetBytes(value));
string sh1 = "";
for (int i = 0; i < data.Length; i++)
{
sh1 += data[i].ToString("x2").ToUpperInvariant();
}
return sh1;
}
private static string GetSwcMD5(string value)
{
MD5 algorithm = MD5.Create();
byte[] data = algorithm.ComputeHash(Encoding.UTF8.GetBytes(value));
string sh1 = "";
for (int i = 0; i < data.Length; i++)
{
sh1 += data[i].ToString("x2").ToUpperInvariant();
}
return sh1;
}
/// <summary>
/// 加密
/// </summary>
/// <param name="str">字符串</param>
/// <param name="key">密钥</param>
/// <param name="toType">类型</param>
/// <returns></returns>
public static string EnCode(this string str, string key, CodeType toType = CodeType.MD5)
{
string str2 = str;
switch (toType)
{
case CodeType.MD5:
return GetSwcMD5(key + str);
//return FormsAuthentication.HashPasswordForStoringInConfigFile(key + str, "md5");
case CodeType.SHA1:
return GetSwcSH1(key + str);
//return FormsAuthentication.HashPasswordForStoringInConfigFile(key + str, "SHA1");
}
return str2;
}
//public static string GetParam(string str)
//{
// if (HttpContext.Current.Request.QueryString[str] != null)
// {
// return HttpContext.Current.Request.QueryString[str].Replace("script", "<i>script<i>");
// }
// if (HttpContext.Current.Request.Form[str] != null)
// {
// return HttpContext.Current.Request.Form[str].Replace("script", "<i>script<i>");
// }
// return "";
//}
/// <summary>
///
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool NotEmpty(this string str)
{
return !string.IsNullOrWhiteSpace(str);
}
/// <summary>
///
/// </summary>
/// <param name="str"></param>
/// <param name="def"></param>
/// <returns></returns>
public static double ToDouble(this string str, double def)
{
double num;
if (double.TryParse(str, out num))
{
return num;
}
return def;
}
/// <summary>
/// TryParse
/// </summary>
/// <param name="str"></param>
/// <param name="def">转换失败默认int参数</param>
/// <returns></returns>
public static int ToInt(this string str, int def = 0)
{
int num;
if (int.TryParse(str, out num))
{
return num;
}
return def;
}
/// <summary>
///
/// </summary>
/// <param name="dt"></param>
/// <param name="beginTime"></param>
/// <returns></returns>
public static long ToTimeMs(this DateTime dt, DateTime beginTime)
{
long ticks = dt.Ticks - beginTime.Ticks;
TimeSpan span = new TimeSpan(ticks);
return (long)span.TotalMilliseconds;
}
/// <summary>
///
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
public static string Week(string date)
{
string str = DateTime.Parse(date).DayOfWeek.ToString();
string str3 = str;
if (str3 == null)
{
return str;
}
if (!(str3 == "Monday"))
{
if (str3 != "Tuesday")
{
if (str3 == "Wednesday")
{
return "星期三";
}
if (str3 == "Friday")
{
return "星期五";
}
if (str3 == "Saturday")
{
return "星期六";
}
if (str3 != "Sunday")
{
return str;
}
return "星期日";
}
}
else
{
return "星期一";
}
return "星期二";
}
/// <summary>
/// 编码格式
/// </summary>
public enum CodeType
{
/// <summary>
///
/// </summary>
DES = 3,
/// <summary>
///
/// </summary>
MD5 = 1,
/// <summary>
///
/// </summary>
SHA1 = 2
}
/// <summary>
/// 获取中文字符串的首字母
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string GetChineseSpell(this string str)
{
int len = str.Length;
string myStr = "";
for (int i = 0; i < len; i++)
{
myStr += str.Substring(i, 1).getSpell();
}
return myStr;
}
/// <summary>
/// 获取单个中文的首字母
/// </summary>
/// <param name="cnChar"></param>
/// <returns></returns>
private static string getSpell(this string cnChar)
{
byte[] arrCN = Encoding.Default.GetBytes(cnChar);
if (arrCN.Length > 1)
{
int area = (short)arrCN[0];
int pos = (short)arrCN[1];
int code = (area << 8) + pos;
int[] areacode = { 45217, 45253, 45761, 46318, 46826, 47010, 47297, 47614, 48119, 48119, 49062, 49324, 49896, 50371, 50614, 50622, 50906, 51387, 51446, 52218, 52698, 52698, 52698, 52980, 53689, 54481 };
for (int i = 0; i < 26; i++)
{
int max = 55290;
if (i != 25)
{
max = areacode[i + 1];
}
if (areacode[i] <= code && code < max)
{
return Encoding.Default.GetString(new byte[] { (byte)(97 + i) });
}
}
return "*";
}
else return cnChar;
}
/// <summary>
/// 给一个字符串进行MD5加密
/// </summary>
/// <param name="strText">待加密字符串</param>
/// <returns>加密后的字符串</returns>
public static string MD5Encrypt(this string strText)
{
byte[] data = Encoding.GetEncoding("GB2312").GetBytes(strText);
MD5 md5 = new MD5CryptoServiceProvider();
byte[] OutBytes = md5.ComputeHash(data);
string OutString = "";
for (int i = 0; i < OutBytes.Length; i++)
{
OutString += OutBytes[i].ToString("x2");
}
// return OutString.ToUpper();
return OutString.ToLower();
//MD5 md5 = new MD5CryptoServiceProvider();
//byte[] result = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(strText));
//return System.Text.Encoding.Default.GetString(result);
}
}
}
|
cde7ac7b82c8c6141718373d11f9c1f18367d762
|
C#
|
Pathoschild/smapi-mod-dump
|
/source/Family Planning/FamilyPlanning/ContentPackData.cs
| 2.90625
| 3
|
/*************************************************
**
** You're viewing a file in the SMAPI mod dump, which contains a copy of every open-source SMAPI mod
** for queries and analysis.
**
** This is *not* the original file, and not necessarily the latest version.
** Source repository: https://github.com/loe2run/FamilyPlanningMod
**
*************************************************/
using System;
using System.Collections.Generic;
namespace FamilyPlanning
{
/*
* I'm expanding from a ChildSpriteData Content Pack to a generic ContentPackData.
* This will support child sprites and will also support dialogue for your spouse.
* Details on these are below.
*/
class ContentPackData
{
/* ChildSpriteID:
* -> The ChildSpriteID data structure contains the data required to pair children with their sprites.
* -> The first string, the key, is the name of the child.
* -> The second string, the value, is a pair of file names. First is the baby sprites, second is the toddler sprites.
*/
public Dictionary<string, Tuple<string, string>> ChildSpriteID { get; set; }
/* BirthSpouseDialogue:
* -> The BirthSpouseDialogue data structure contains dialogue information for the CustomBirthingEvent.
* -> The first string, the key, is the name of the spouse you'd like it to effect. (This matches the displayName value.)
* -> The second string, the value, is pair of values.
* The first is the number of children where the dialogue should trigger, second is the new dialogue.
* The second value, the dialogue, supports the use of {0} to represent the baby name and {1} to represent the player name.
*/
public Dictionary<string, List<Tuple<int, string>>> SpouseDialogue { get; set; }
public ContentPackData()
{
ChildSpriteID = new Dictionary<string, Tuple<string, string>>();
SpouseDialogue = new Dictionary<string, List<Tuple<int, string>>>();
}
}
}
|
fc6d47dfd713fd85bfe190d23996b60117b2524d
|
C#
|
dvenkat508/OTMC
|
/OTMC/Classes/ServerConnection.cs
| 2.96875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace OTMC.Classes
{
class ServerConnection
{
public static readonly Socket ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public const int PORT = 975;
public static bool ConnectToServer()
{
int count = 0;
while (!ClientSocket.Connected && count<=1)
{
try
{
count++;
// Change IPAddress.Loopback to a remote IP to connect to a remote host.
ClientSocket.Connect("192.168.0.50", PORT);
}
catch (SocketException)
{
}
}
if(count>2)
{
return false;
}
else
{
return true;
}
}
}
}
|
8393cb1179c7079ac72900c9a80e64d1f7b42045
|
C#
|
MoacirSilva/googleBooks
|
/BooksRepo.cs
| 2.734375
| 3
|
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace googleBooksApp
{
public class BooksRepo
{
public static async Task<Books> GetBookssAsync()
{
HttpClient client = new HttpClient();
try
{
string url = "https://www.googleapis.com/books/v1/volumes?q=z_JRBQAAQBAJ";
var response = await client.GetStringAsync(url);
var produtos = JsonConvert.DeserializeObject <Books>(response);
return produtos;
}
catch (Exception ex)
{
throw ex;
}
}
}
}
|
fdaa77e5288a72e4685b5fcf11bc7b3c6391af1b
|
C#
|
oldmonitor/NetDataStructure
|
/DataStructureProblems.Test/BacktrackingProblems/FindAllPossibleSubsetsTest.cs
| 2.796875
| 3
|
using DataStructureProblems.BacktrackingProblems;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataStructureProblems.Test.BacktrackingProblems
{
[TestClass]
public class FindAllPossibleSubsetsTest
{
[TestMethod]
public void TestListWithJustOneItem()
{
FindAllPossibleSubsets c = new FindAllPossibleSubsets();
List<List<string>> result = c.HandleFindAllPossibleSubsets(new List<string>() { "a" });
Assert.AreEqual(1, result.Count);
Assert.AreEqual("a", result[0][0]);
}
[TestMethod]
public void TestListWithJustTwoItem()
{
FindAllPossibleSubsets c = new FindAllPossibleSubsets();
List<List<string>> result = c.HandleFindAllPossibleSubsets(new List<string>() { "a", "b", "c" });
Assert.AreEqual(7, result.Count);
}
}
}
|
a38142b4c9be4efefb41683c3da4080bc477a21f
|
C#
|
ascensivetechnologies/Line-Of-Credit-Management-Platform
|
/AMP/z_RiskClasses/RiskDocumentCollection.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AMP.Models;
using AMP.Services;
using AMP.ViewModels;
namespace AMP.RiskClasses
{
public class RiskDocumentCollection
{
private IEnumerable<RiskDocument> _riskDocuments;
private IDocumentService _documentService;
public RiskDocumentCollection(IEnumerable<RiskDocument> riskDocuments, IDocumentService documentService)
{
_riskDocuments = riskDocuments;
_documentService = documentService;
}
public IEnumerable<RiskDocument> AllRiskDocuments()
{
return _riskDocuments;
}
public bool HasRiskDocuments()
{
if (_riskDocuments != null && _riskDocuments.Any())
{
return true;
}
else
{
return false;
}
}
//Do something that maps the Risk Documents into a View Model.
public List<RiskDocumentVM> CreateRiskDocumentsVM()
{
List<RiskDocumentVM> riskDocumentsVm = new List<RiskDocumentVM>();
foreach (RiskDocument document in _riskDocuments)
{
RiskDocumentVM documentVm = new RiskDocumentVM
{
ProjectID = document.ProjectID,
DocumentID = document.DocumentID,
Description = document.Description,
DocumentLink = _documentService.ReturnDocumentUrl(document.DocumentID, document.DocSource),
LastUpdate = document.LastUpdate,
RiskRegisterID = document.RiskRegisterID,
UserID = document.UserID
};
riskDocumentsVm.Add(documentVm);
}
return riskDocumentsVm;
}
}
}
|
50b8a67ec9700b82da6ea88baf880053c601466f
|
C#
|
fgranados1693/Coworkspaces
|
/ProyectoFinal/DataAccess/Crud/DocumentoCrudFactory.cs
| 3.09375
| 3
|
using DataAccess.Dao;
using DataAccess.Mapper;
using Entities_POJO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess.Crud
{
public class DocumentoCrudFactory : CrudFactory
{
DocumentoMapper mapper;
public DocumentoCrudFactory() : base()
{
mapper = new DocumentoMapper();
dao = SqlDao.GetInstance();
}
/// <summary>
/// Metodo para registrar el documento en la base de datos
/// </summary>
/// <param name="entity">Instancia del documento con la informacion recibida</param>
public override void Create(BaseEntity entity)
{
var documento = (Documento)entity;
var sqlOperation = mapper.GetCreateStatement(documento);
dao.ExecuteProcedure(sqlOperation);
}
/// <summary>
/// Metodo para buscar un documento por su id en la base de datos
/// </summary>
/// <param name="entity">Instancia de documento con el id del documento que se quiere buscar</param>
/// <returns></returns>
public override T Retrieve<T>(BaseEntity entity)
{
var sqlOperation = mapper.GetRetriveStatement(entity);
var lstResult = dao.ExecuteQueryProcedure(sqlOperation);
var dic = new Dictionary<string, object>();
if (lstResult.Count > 0)
{
dic = lstResult[0];
var objs = mapper.BuildObject(dic);
return (T)Convert.ChangeType(objs, typeof(T));
}
return default(T);
}
/// <summary>
/// Metodo para listar todos los documentos registrados en la base de datos
/// </summary>
/// <returns>Lista de todos los documentos registrados en la base de datos</returns>
public override List<T> RetrieveAll<T>()
{
var lstDocumentos = new List<T>();
var lstResult = dao.ExecuteQueryProcedure(mapper.GetRetriveAllStatement());
var dic = new Dictionary<string, object>();
if (lstResult.Count > 0)
{
var objs = mapper.BuildObjects(lstResult);
foreach (var c in objs)
{
lstDocumentos.Add((T)Convert.ChangeType(c, typeof(T)));
}
}
return lstDocumentos;
}
/// <summary>
/// Metodo para actualizar un documento en la base de datos
/// </summary>
/// <param name="entity">Instancia de documento con el id del documento que se quiere actualizar</param>
public override void Update(BaseEntity entity)
{
var documento = (Documento)entity;
dao.ExecuteProcedure(mapper.GetUpdateStatement(documento));
}
/// <summary>
/// Metodo para eliminar un documento de la base de datos
/// </summary>
/// <param name="entity">Instancia de documento con el id del documento que se quiere eliminar</param>
public override void Delete(BaseEntity entity)
{
var documento = (Documento)entity;
dao.ExecuteProcedure(mapper.GetDeleteStatement(documento));
}
}
}
|
e1a7ed9226087a2aba767b4958c5d1829c838bd0
|
C#
|
Xin-Shiyu/NDictPlus
|
/NDictPlus/Compatibility/VersionedDictionary.cs
| 3
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;
using System.Xml;
using System.Globalization;
namespace NDictPlus.Compatibility
{
// used for migrating from the old ndict
public class VersionedDictionary : IDictionary<string, string>
{
private enum OperationType
{
Add,
Set,
Del,
}
private class Operation
{
public readonly OperationType Type;
public readonly string Key;
public readonly string Value;
public Operation(OperationType type, string key, string value = null)
{
Type = type;
Key = key;
Value = value;
}
}
private readonly Dictionary<string, string> cache =
new Dictionary<string, string>();
private readonly List<Operation> operations =
new List<Operation>();
public VersionedDictionary(string path)
{
var dir = new DirectoryInfo(path);
if (!dir.Exists) dir.Create();
var files = dir
.GetFiles("*.opg", SearchOption.TopDirectoryOnly)
.OrderBy(file =>
DateTime.ParseExact(
Path.GetFileNameWithoutExtension(file.Name),
"yyyyMMddHHmmssffff",
CultureInfo.InvariantCulture));
foreach (FileInfo file in files)
{
XmlDocument xml = new XmlDocument();
xml.Load(file.FullName);
XmlNode root = xml.SelectSingleNode("group");
foreach (XmlElement node in root.ChildNodes)
{
switch (node.Name)
{
case "add":
cache.Add(node.GetAttribute("key"), node.GetAttribute("val"));
break;
case "set":
cache[node.GetAttribute("key")] = node.GetAttribute("val");
break;
case "del":
cache.Remove(node.GetAttribute("key"));
break;
}
}
}
}
public ICollection<string> Keys => cache.Keys;
public ICollection<string> Values => cache.Values;
public int Count => cache.Count;
public bool IsReadOnly => false;
public string this[string key]
{
get => cache[key];
set
{
cache[key] = value;
operations.Add(new Operation(OperationType.Set, key, value));
}
}
public void Add(string key, string value)
{
cache.Add(key, value);
operations.Add(new Operation(OperationType.Add, key, value));
}
public bool ContainsKey(string key)
{
return cache.ContainsKey(key);
}
public bool Remove(string key)
{
if (cache.Remove(key))
{
operations.Add(new Operation(OperationType.Del, key));
return true;
}
return false;
}
public bool TryGetValue(string key, out string value)
{
return cache.TryGetValue(key, out value);
}
public void Add(KeyValuePair<string, string> item)
{
cache.Add(item.Key, item.Value);
operations.Add(new Operation(OperationType.Set, item.Key, item.Value));
}
public void Clear()
{
foreach (var key in cache.Keys) operations.Add(new Operation(OperationType.Del, key));
cache.Clear();
}
public bool Contains(KeyValuePair<string, string> item)
{
return ((ICollection<KeyValuePair<string, string>>)cache).Contains(item);
}
public void CopyTo(KeyValuePair<string, string>[] array, int arrayIndex)
{
((ICollection<KeyValuePair<string, string>>)cache).CopyTo(array, arrayIndex);
}
public bool Remove(KeyValuePair<string, string> item)
{
if(((ICollection<KeyValuePair<string, string>>)cache).Remove(item))
{
operations.Add(new Operation(OperationType.Del, item.Key));
return true;
}
return false;
}
public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
{
return cache.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return cache.GetEnumerator();
}
}
}
|
da1a6e5530d97ad4516f1dc539cde924366b1519
|
C#
|
guillermocorrea/ds-algos
|
/tests/ProblemsTests/DataStructures/Heap/MaxHeapTests.cs
| 3.15625
| 3
|
using Problems.DataStructures.Heap;
using Xunit;
namespace ProblemsTests.DataStructures.Heap
{
public class MaxHeapTests
{
[Fact]
public void CanInsertMinHeap()
{
// Given
var minHeap = new Heap<int>(int.MinValue, int.MaxValue, HeapType.MinHeap);
// When
minHeap.Insert(50);
minHeap.Insert(45);
minHeap.Insert(25);
minHeap.Insert(10);
minHeap.Insert(15);
minHeap.Insert(40);
minHeap.Insert(35);
minHeap.Insert(20);
minHeap.Insert(75);
// Then
var min = minHeap.Remove();
Assert.Equal(10, min);
}
[Fact]
public void CanInsertMaxHeap()
{
// Given
var maxHeap = new Heap<int>(int.MinValue, int.MaxValue, HeapType.MaxHeap);
// When
maxHeap.Insert(50);
maxHeap.Insert(45);
maxHeap.Insert(25);
maxHeap.Insert(10);
maxHeap.Insert(15);
maxHeap.Insert(40);
maxHeap.Insert(35);
maxHeap.Insert(20);
maxHeap.Insert(75);
// Then
var max = maxHeap.Remove();
Assert.Equal(75, max);
}
}
}
|
842e81081d445364f9f24d58494108e3bbbb34a2
|
C#
|
Xyaneon/Xyaneon.Bioinformatics.FASTA
|
/Xyaneon.Bioinformatics.FASTA.Test/Identifiers/ThirdPartyEMBLIdentifierTest.cs
| 2.703125
| 3
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using Xyaneon.Bioinformatics.FASTA.Identifiers;
namespace Xyaneon.Bioinformatics.FASTA.Test.Identifiers
{
[TestClass]
public class ThirdPartyEMBLIdentifierTest
{
private const string Code = "tpe";
private const string Accession = "accession";
private const string Name = "name";
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Constructor_ShouldRejectNullAccessionNumber()
{
_ = new ThirdPartyEMBLIdentifier(null, Name);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Constructor_ShouldRejectEmptyAccessionNumber()
{
_ = new ThirdPartyEMBLIdentifier("", Name);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Constructor_ShouldRejectWhitespaceAccessionNumber()
{
_ = new ThirdPartyEMBLIdentifier(" ", Name);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Constructor_ShouldRejectNullName()
{
_ = new ThirdPartyEMBLIdentifier(Accession, null);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Constructor_ShouldRejectEmptyName()
{
_ = new ThirdPartyEMBLIdentifier(Accession, "");
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Constructor_ShouldRejectWhitespaceName()
{
_ = new ThirdPartyEMBLIdentifier(Accession, " ");
}
[TestMethod]
public void Code_ShouldReturnCorrectValue()
{
Identifier identifier = new ThirdPartyEMBLIdentifier(Accession, Name);
Assert.AreEqual(Code, identifier.Code);
}
[TestMethod]
public void ToString_ShouldFormatCorrectly()
{
Identifier identifier = new ThirdPartyEMBLIdentifier(Accession, Name);
Assert.AreEqual($"{Code}|{Accession}|{Name}", identifier.ToString());
}
}
}
|
a10bf84bde1bc68a1440101d90bf307a78a6e6a0
|
C#
|
AdamBallinger/Fragmentum
|
/Assets/Scripts/Objects/BatBoss/GateController.cs
| 2.546875
| 3
|
using System.Collections;
using UnityEngine;
namespace Assets.Scripts.Objects.BatBoss
{
public class GateController : MonoBehaviour
{
public float moveSpeed = 1.0f;
public float closeDistance = 1.0f;
private bool isClosed;
private Vector3 openPos = Vector3.zero;
private bool runtime;
private Transform _transform;
private void Start()
{
_transform = transform;
runtime = true;
openPos = _transform.position;
}
public void CloseGate()
{
if (isClosed)
{
return;
}
isClosed = true;
StartCoroutine(Close());
}
private IEnumerator Close()
{
var pos = _transform.position;
var closePos = pos - Vector3.down * closeDistance;
while (true)
{
pos = Vector3.MoveTowards(pos, closePos, moveSpeed * Time.deltaTime);
_transform.position = pos;
if(pos == closePos)
{
yield break;
}
yield return null;
}
}
private void OnDrawGizmos()
{
var bottom = transform.position + Vector3.down * GetComponent<BoxCollider>().bounds.size.y / 2;
var closePos = (runtime ? openPos : transform.position) - Vector3.down * closeDistance;
closePos.y -= GetComponent<BoxCollider>().bounds.size.y / 2;
Gizmos.color = Color.green;
Gizmos.DrawLine(bottom, closePos);
}
}
}
|
e74b080a057c476a95c8cc2cbcac83a11aa26f23
|
C#
|
Andi11449/mathnet-numerics
|
/src/Numerics/LinearAlgebra/Matrix.Indexing.cs
| 3.125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MathNet.Numerics.LinearAlgebra
{
public abstract partial class Matrix<T>
{
public Vector<T> this[int row, Indexer columns]
{
get {
columns.Init(ColumnCount);
var target = Vector<T>.Build.Dense(columns.Count);
for (var i = 0; i < columns.Count; i++)
{
target[i] = this[row, columns[i]];
}
return target;
}
set
{
columns.Init(ColumnCount);
if (value.Count != 1 && value.Count != columns.Count)
{
throw new ArgumentOutOfRangeException("The number of elements must match the number of indexed columns");
}
if (value.Count == 1)
{
var v = value[0];
foreach (var column in columns)
{
this[row, column] = v;
}
}
else
{
for (var i = 0; i < columns.Count; i++)
{
this[row, columns[i]] = value[i];
}
}
}
}
public Vector<T> this[Indexer rows, int column]
{
get
{
rows.Init(RowCount);
var target = Vector<T>.Build.Dense(rows.Count);
for (var i = 0; i < rows.Count; i++)
{
target[i] = this[rows[i], column];
}
return target;
}
set
{
rows.Init(RowCount);
if (value.Count != 1 && value.Count != rows.Count)
{
throw new ArgumentOutOfRangeException("The number of elements must match the number of indexed rows");
}
if (value.Count == 1)
{
var v = value[0];
foreach (var row in rows)
{
this[row, column] = v;
}
}
else
{
for (var i = 0; i < rows.Count; i++)
{
this[rows[i], column] = value[i];
}
}
}
}
public Matrix<T> this[Indexer rows, Indexer columns]
{
get
{
rows.Init(RowCount);
columns.Init(ColumnCount);
var target = Build.Dense(rows.Count, columns.Count);
for (var col = 0; col < columns.Count; col++)
{
for (var row = 0; row < rows.Count; row++)
{
target[row, col] = this[rows[row], columns[col]];
}
}
return target;
}
set
{
rows.Init(RowCount);
columns.Init(ColumnCount);
if (value.ColumnCount != 1 && value.ColumnCount != columns.Count)
{
throw new ArgumentOutOfRangeException("The number of elements must match the number of indexed columns");
}
if (value.RowCount != 1 && value.RowCount != rows.Count)
{
throw new ArgumentOutOfRangeException("The number of elements must match the number of indexed rows");
}
if (value.RowCount == 1 && value.ColumnCount == 1)
{
var v = value[0, 0];
foreach (var row in rows)
{
foreach (var column in columns)
{
this[row, column] = v;
}
}
}
else
{
for (var ci = 0; ci < columns.Count; ci++)
{
for (var ri = 0; ri < rows.Count; ri++)
{
this[rows[ri], columns[ci]] = value[ri, ci];
}
}
}
}
}
}
}
|
3bd1a66067634aa57187abf5b44057bd156bfd20
|
C#
|
discord-net/Discord.Net
|
/docs/guides/entities/samples/safety-cast-pass.cs
| 3.296875
| 3
|
private void MyFunction(IMessage message)
{
// Here we do the reverse as in the previous examples, and let it continue the code below if it IS an IUserMessage
if (message is not IUserMessage userMessage)
return;
// Because we do the above check inline (don't give the statement a body),
// the code will still declare `userMessage` as available outside of the above statement.
Console.WriteLine(userMessage.Author);
}
|
f3e73ea758b020950eb4bc04301d6cb34632a032
|
C#
|
Khantastic96/Hemorrhage
|
/Hemorrhage/Assets/Project/Scripts/Game/ForceReceiver.cs
| 2.6875
| 3
|
/**
* Created DD/MM/2020
* By: Sharek Khan
* Last Modified DD/MM/2020
* By: Sharek Khan
*
* Contributors: Sharek Khan
*/
using UnityEngine;
/*
* ForceReceiver applies a kickback force to a GameObject containing the CharacterController Component
* Code based on Zenva Studios -COMPLETE COURSE Create a Unity FPS Game in 3 hours - https://www.youtube.com/watch?v=UtlAqRyZrUw
*/
public class ForceReceiver : MonoBehaviour
{
public float deceleration = 5;
public float mass = 3;
private Vector3 intensity;
private CharacterController character;
// Start is called before the first frame update
void Start()
{
intensity = Vector3.zero;
character = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
// Condition checks if magnitude of the forces intensity is below a float value
if(intensity.magnitude > 0.2f)
{
// Translates the character in a specific vector with the force intensity
character.Move(intensity * Time.deltaTime);
}
intensity = Vector3.Lerp(intensity, Vector3.zero, deceleration * Time.deltaTime);
}
// AddForce receives a vector and force amount and defines the intensity relative to mass
public void AddForce(Vector3 direction, float force)
{
intensity += direction.normalized * force / mass;
}
}
|
858f67605d137da66bf1399ce47b836ea8bcc265
|
C#
|
dotnet/efcore
|
/src/EFCore/Diagnostics/LoggerCategory.cs
| 2.5625
| 3
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace Microsoft.EntityFrameworkCore.Diagnostics;
/// <summary>
/// Generic helper class used to implement the <see cref="Name" /> property.
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-diagnostics">Logging, events, and diagnostics</see> for more information and examples.
/// </remarks>
/// <typeparam name="T">The logger category type.</typeparam>
public abstract class LoggerCategory<T>
{
/// <summary>
/// The logger category name, for use with <see cref="ILoggerProvider" />, etc.
/// </summary>
/// <returns>The category name.</returns>
public static string Name { get; } = ToName(typeof(T));
/// <summary>
/// The logger category name.
/// </summary>
/// <returns>The logger category name.</returns>
public override string ToString()
=> Name;
/// <summary>
/// The logger category name.
/// </summary>
/// <param name="loggerCategory">The category.</param>
public static implicit operator string(LoggerCategory<T> loggerCategory)
=> loggerCategory.ToString();
private static string ToName(Type loggerCategoryType)
{
const string outerClassName = "." + nameof(DbLoggerCategory);
var name = loggerCategoryType.FullName!.Replace('+', '.');
var index = name.IndexOf(outerClassName, StringComparison.Ordinal);
if (index >= 0)
{
name = name[..index] + name[(index + outerClassName.Length)..];
}
return name;
}
}
|
428736cf35c11e6b893998fff49f492eaa382b19
|
C#
|
NickOosterhuis/FriendshipBenchCleanBack
|
/WebApi/Seeders/UserRoleSeeder.cs
| 2.609375
| 3
|
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApi.Seeders
{
public class UserRoleSeeder
{
private readonly RoleManager<IdentityRole> _roleManager;
public UserRoleSeeder(RoleManager<IdentityRole> roleManager)
{
this._roleManager = roleManager;
}
public async void SeedRoles()
{
var adminRoleBool = _roleManager.RoleExistsAsync("admin").Result;
var clientRoleBool = _roleManager.RoleExistsAsync("client").Result;
var healthWorkerRoleBool = _roleManager.RoleExistsAsync("healthworker").Result;
if(!adminRoleBool)
await _roleManager.CreateAsync(new IdentityRole("admin"));
if(!healthWorkerRoleBool)
await _roleManager.CreateAsync(new IdentityRole("healthworker"));
if(!clientRoleBool)
await _roleManager.CreateAsync(new IdentityRole("client"));
}
}
}
|
d56a267a3e06cc7564a493725f0cb275b6a37018
|
C#
|
naik899/ReadTextFromImage
|
/ReadFromImage/Helpers/ImageParser.cs
| 3.0625
| 3
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tesseract;
namespace ReadFromImage.Helpers
{
public class ImageParser
{
internal static string GetTextFromImage(Bitmap imgsource)
{
try
{
var ocrtext = string.Empty;
var tessdataPath = string.Empty; // this should contain the tess data in the folder tessdata
var engine = new TesseractEngine(tessdataPath, "eng");
using (var img = PixConverter.ToPix(imgsource))
{
using (var page = engine.Process(img))
{
ocrtext = page.GetText();
}
}
return ocrtext;
}
catch (Exception ex)
{
Console.WriteLine("Exception at GetTextFromImage: " + ex.ToString());
return ex.ToString();
}
}
}
}
|
a5a537aeebfea9a4d0ceea626bccc8b5b7d81984
|
C#
|
zzattack/munia
|
/MUNIA-win/SVG#/External/ExCSS/Model/TextBlocks/StringBlock.cs
| 3.21875
| 3
|
namespace ExCSS.Model.TextBlocks
{
internal class StringBlock : Block
{
StringBlock(GrammarSegment type)
{
GrammarSegment = type;
}
internal static StringBlock Plain(string data, bool bad = false)
{
return new StringBlock(GrammarSegment.String) { Value = data, IsBad = bad };
}
internal static StringBlock Url(string data, bool bad = false)
{
return new StringBlock(GrammarSegment.Url) { Value = data, IsBad = bad };
}
internal string Value { get; private set; }
internal bool IsBad { get; private set; }
public override string ToString()
{
if (GrammarSegment == GrammarSegment.Url)
{
return "url(" + Value + ")";
}
return "'" + Value + "'";
}
}
}
|
54f177ba48d9fb62402b5fe54d0f7b67280daa25
|
C#
|
Gustice/Public-Status-Indicator
|
/PublicStatusIndicator/Webserver/RequestParser.cs
| 3.078125
| 3
|
using System;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
namespace PublicStatusIndicator.Webserver
{
internal static class RequestParser
{
/// <summary>
/// Tries to get the (Basic) authorisation credentials out of the given request string
/// </summary>
/// <param name="requestString">the request string wich contains the basic auth info </param>
/// <returns><see cref="NetworkCredential"/></returns>
public static NetworkCredential GetCredentials(string requestString)
{
if (string.IsNullOrWhiteSpace(requestString))
throw new ArgumentException(nameof(requestString));
var authRegex = new Regex(@"\b(Basic).[^\s]+");
var user = authRegex.Match(requestString);
var encodedUsernamePassword = user.Value.Substring("Basic ".Length).Trim();
var encoding = Encoding.GetEncoding("iso-8859-1");
var usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));
if (string.IsNullOrEmpty(usernamePassword))
throw new Exception("Auth Error");
if (!usernamePassword.Contains(":"))
throw new Exception("Auth Error");
return new NetworkCredential()
{
UserName = usernamePassword.Split(':')[0],
Password= usernamePassword.Split(':')[1]
};
}
}
}
|
ae7c6347affb3e605a76ca630f3d23a3043f921f
|
C#
|
userv/programming-fundamentals
|
/exercises/ObjectsAndSimpleClasses-MoreExercises/4.Websites/Websites.cs
| 3.5
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _4.Websites
{
class Websites
{
public class Website
{
public string Host { get; set; }
public string Domain { get; set; }
public List<string> Queries = new List<string>();
}
public static Website AddWebsite(string websiteData)
{
string[] tokens = websiteData.Split(new char[] { ' ', '|', ',' }, StringSplitOptions.RemoveEmptyEntries).ToArray();
string host = tokens[0];
string domain = tokens[1];
List<string> queries = tokens.Skip(2).ToList();
Website website = new Website
{
Host = host,
Domain = domain,
Queries = queries
};
return website;
}
static void Main(string[] args)
{
List<Website> websites = new List<Website>();
string inputLine = Console.ReadLine();
while (inputLine != "end")
{
websites.Add(AddWebsite(inputLine));
inputLine = Console.ReadLine();
}
foreach (var website in websites)
{
if (website.Queries.Count < 1)
{
Console.WriteLine($"https://www.{website.Host}.{website.Domain}");
}
else
{
Console.Write($"https://www.{website.Host}.{website.Domain}/query?=");
for (int i = 0; i < website.Queries.Count; i++)
{
if (i == 0)
{
Console.Write($"[{website.Queries[i]}]");
}
else
{
Console.Write($"&[{website.Queries[i]}]");
}
}
Console.WriteLine();
}
}
}
}
}
|
f34a6ea3695ce37ae4b77cfd4d4da601b31e6945
|
C#
|
ArturTrainee/programing.term4
|
/Lab3/Exercise8And9/RegistrationForm.cs
| 2.90625
| 3
|
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Lab3.Exercise8And9
{
public partial class RegistrationForm : Form
{
public RegistrationForm()
{
InitializeComponent();
}
private void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
var lb1 = new Label();
lb1.Location = new Point(6, 74);
lb1.Size = new Size(32, 23);
lb1.Name = "labelll";
lb1.TabIndex = 2;
lb1.Text = "PIN2";
groupBox1.Controls.Add(lb1);
var txt = new TextBox();
txt.Location = new Point(64, 74);
txt.Size = new Size(140, 22);
txt.Name = "textboxx";
txt.TabIndex = 1;
txt.Text = "";
txt.KeyPress += TextBox2_KeyPress;
groupBox1.Controls.Add(txt);
}
else
{
int lcv = groupBox1.Controls.Count;
while (lcv > 4)
{
groupBox1.Controls.RemoveAt(lcv - 1);
lcv--;
}
}
}
private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar))
{
e.Handled = true;
MessageBox.Show("Поле Name не може містити цифри");
errorProvider1.SetError(textBox1, "Must be letter");
}
}
private void TextBox2_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar))
{
e.Handled = true;
MessageBox.Show("Поле PIN може містити лише цифри");
errorProvider1.SetError(textBox2, "Must be digit");
}
}
private void TextBox2_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
if (string.IsNullOrEmpty(textBox2.Text))
{
e.Cancel = false;
}
else
{
try
{
double.Parse(textBox2.Text);
e.Cancel = false;
}
catch
{
e.Cancel = true;
MessageBox.Show("Поле PIN не може містити букви");
}
}
}
}
}
|
7761523f0eb806c7c7c244ac8dbd0e172cd12e90
|
C#
|
glcherepanov/rp
|
/ds-3/JobLogger/RedisDbContext.cs
| 2.984375
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.Extensions.Configuration;
using StackExchange.Redis;
namespace JobLogger
{
class RedisDbContext
{
public static string GetDesription(string id)
{
string currentDirectoryPath = Directory.GetCurrentDirectory();
string jsonPath = Directory.GetParent(currentDirectoryPath) + "/config/config.json";
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(jsonPath, optional: false)
.Build();
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect($"localhost:{config.GetValue<int>("RedisPort")}");
IDatabase db = redis.GetDatabase();
string description = db.StringGet(id);
return description;
}
}
}
|
3b417c9e4c98534c0a6b15d784a69b0824c576ac
|
C#
|
tolgasavass/yazilimGelistirmeKampi
|
/myDictionary/myDictionary/myList.cs
| 3.21875
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace myDictionary
{
class myList<Tip>
{
Tip[] array;
Tip[] tempArray;
public myList()
{
array = new Tip[0];
}
public void Add(Tip item, string v)
{
tempArray = array;
array = new Tip[array.Length + 1];
for (int i = 0; i < tempArray.Length; i++)
{
array[i] = tempArray[i];
}
array[array.Length - 1] = item;
}
public int Sayac
{
get { return array.Length; }
}
}
}
|
1651c9421745cf6321fc38b9ec43a3ffe61e768e
|
C#
|
ikedatatsuya0802/Ongaku_Game
|
/Shooting_Game/Assets/Script/SingletonMonoBehaviour.cs
| 3.046875
| 3
|
using System.Collections;
using UnityEngine;
/// <summary>
/// MonoBehaviourのシングルトン対応クラス
/// </summary>
public class SingletonMonoBehaviour<T> : MonoBehaviour where T : SingletonMonoBehaviour<T>
{
protected static T instance;
/// <summary>
///インスタンスのゲッター
/// </summary>
/// <returns>クラスインスタンス</returns>
public static T Instance
{
get{
if(instance == null)
{
instance = (T)FindObjectOfType(typeof(T));
if( instance == null)
{
//基本的にここは通らないはず
Debug.LogWarning(typeof(T)+"は存在しません");
}
}
return instance;
}
}
protected void Awake()
{
CheckInstance();
}
/// <summary>
/// インスタンスが存在するか確認し、存在しない場合は自身のインスタンスを使用する
/// 存在してる場合は自身のオブジェクトを破棄する
/// </summary>
/// <returns>自身を使用する場合true</returns>
protected bool CheckInstance()
{
if( instance == null)
{
instance = (T)this;
return true;
}else if (Instance == this)
{
return true;
}
Destroy(this);
return false;
}
}
|
52ebfdcce195098a8e5d9364b2bc3c6a9d33f916
|
C#
|
anotherlab/thedoctors-deprecated
|
/Doctors/Doctors.iPhone/DetailViewController.cs
| 2.515625
| 3
|
using System;
using System.Drawing;
using System.Collections.Generic;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using Doctors.Models;
namespace Doctors.iPhone
{
public partial class DetailViewController : UIViewController
{
DoctorActor detailItem;
private UILabel ActorLabel, Actor, IncarnationLabel, Incarnation, StartDateLabel, StartDate, AgeLabel, Age;
public DetailViewController(IntPtr handle)
: base(handle)
{
float dy = 20f;
float dyy = 24f;
float y = 260f;
var labelsize = 12f;
var textside = 18f;
Title = "DetailsTitle".t();
ActorLabel = MakeLabel("Actor".t(), y, labelsize);
y += dy;
Actor = MakeLabel("Actor".t(), y, textside);
y += dyy;
IncarnationLabel = MakeLabel("Incarnation".t(), y, labelsize);
y += dy;
Incarnation = MakeLabel("Actor".t(), y, textside);
y += dyy;
StartDateLabel = MakeLabel("StartDate".t(), y, labelsize);
y += dy;
StartDate = MakeLabel("Actor".t(), y, textside);
y += dyy;
AgeLabel = MakeLabel("AgeAtStart".t(), y, labelsize);
y += dy;
Age = MakeLabel("Actor".t(), y, textside);
}
public void SetDetailItem(DoctorActor newDetailItem)
{
if (detailItem != newDetailItem)
{
detailItem = newDetailItem;
// Update the view
ConfigureView();
}
}
private UILabel MakeLabel(string Caption, float y, float size)
{
var label = new UILabel()
{
Text = Caption,
Font = UIFont.FromName("TrebuchetMS", size),
Frame = new RectangleF(10, y, 250, 25)
};
View.Add(label);
return label;
}
void ConfigureView()
{
// Update the user interface for the detail item
if (IsViewLoaded && (detailItem != null))
{
photo.Image = UIImage.FromBundle("images/" + detailItem.ImageUrl);
Actor.Text = detailItem.Actor;
Incarnation.Text = detailItem.Incarnation;
StartDate.Text = detailItem.StartDate.ToShortDateString ();
Age.Text = detailItem.Age.ToString ();
}
}
public override void DidReceiveMemoryWarning()
{
// Releases the view if it doesn't have a superview.
base.DidReceiveMemoryWarning();
// Release any cached data, images, etc that aren't in use.
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
// Perform any additional setup after loading the view, typically from a nib.
ConfigureView();
}
}
}
|
73dca3f3b2949ac3aceecb1086ad8558f0c8f369
|
C#
|
zleao/MvvmCross-Extensions
|
/Libraries/MvxExtensions/Extensions/AssemblyExtensions.cs
| 3.0625
| 3
|
using System.Reflection;
namespace MvxExtensions.Extensions
{
/// <summary>
/// Extensions for Assembly type
/// </summary>
public static class AssemblyExtensions
{
/// <summary>
/// Gets the name of the assembly.
/// Deals with null source
/// </summary>
/// <param name="source">The source.</param>
/// <returns></returns>
public static AssemblyName SafeGetName(this Assembly source)
{
if (source == null)
return null;
return new AssemblyName(source.FullName);
}
}
}
|
a690780487e69372b84ad56ff4f8ba576f14ab26
|
C#
|
AlexandRLV/SomeUniversityWork
|
/AdoNetApp1/AdoNetApp1/EditCategoryForm.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AdoNetApp1.Models;
namespace AdoNetApp1
{
public partial class EditCategoryForm : Form
{
// Категория, с которой работаем
private Category category;
public EditCategoryForm(FormType type, Category c)
{
// Сохраняем полученную категорию
this.category = c;
InitializeComponent();
label6.Text = "";
if (category == null)
{
category = new Category();
}
// Записываем значения полей
if (type == FormType.Update)
{
textBox1.Text = c.Name;
button1.Text = "Применить";
this.Text = "Изменить";
}
if (type == FormType.Create)
{
button1.Text = "Добавить";
this.Text = "Добавить";
}
}
// Сохранение изменений
private void button1_Click(object sender, EventArgs e)
{
// Флаг для проверки корректности полей
bool flag = true;
// Проверка названия
if (String.IsNullOrWhiteSpace(textBox1.Text))
{
label6.Text = "Некорректное название";
flag = false;
}
else if (textBox1.Text.Length > 50)
{
label6.Text = "Максимум 50 символов";
flag = false;
}
else
{
label6.Text = "";
}
// Если все поля корректны, сохраняем изменения
if (flag)
{
category.Name = textBox1.Text;
this.Close();
}
}
}
}
|
716d3ec5147f518b68bc6b7fc0179ab27c675d77
|
C#
|
jimolle/MVCDesignmonster
|
/MVCDesignmonster.Test/BusinessObjectsTests/EmployerRepositoryTests.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MVCDesignmonster.BusinessObjects.Models;
using MVCDesignmonster.BusinessObjects.Repository;
using MVCDesignmonster.Test.Fakes;
namespace MVCDesignmonster.Test.BusinessObjectsTests
{
[TestClass]
public class EmployerRepositoryTests
{
private IEmployerRepository _repo;
public EmployerRepositoryTests()
{
//_repo = new EmployerRepository(new ProfileDbContext());
_repo = new FakeEmployerRepository();
}
[TestMethod]
public void GetPublicEmployers()
{
// Arrange
var educ = _repo.GetPublicEmployers();
// Act
int count = 1;
// Assert
Assert.AreEqual(count, educ.Count());
}
[TestMethod]
public void UpdateEmployer()
{
// Arrange
var emp = _repo.GetAllEmployersEvenPrivate().SingleOrDefault(n => n.EmployerId == 2);
// Act
emp.Name = "UPDATED";
emp.StartDate = DateTime.Parse("3000-01-01");
emp.EndDate = DateTime.Parse("3001-01-01");
emp.Public = false;
_repo.UpdateEmployer(emp);
_repo.Save();
// Assert
Assert.AreEqual(emp.Name, _repo.GetAllEmployersEvenPrivate().SingleOrDefault(n => n.EmployerId == 2).Name);
}
[TestMethod]
public void CreateEmployer()
{
// Arrange
// Act
var emp = new Employer()
{
Name = "NewEmployer",
StartDate = DateTime.Parse("2013-01-01"),
EndDate = DateTime.Parse("2013-06-01"),
Public = true
};
_repo.CreateEmployer(emp);
_repo.Save();
// Assert
Assert.AreEqual(emp.Name, _repo.GetAllEmployersEvenPrivate().SingleOrDefault(n => n.Name == "NewEmployer").Name);
}
[TestMethod]
public void DeleteEmployer()
{
// Arrange
// Act
_repo.DeleteEmployer(1);
_repo.Save();
// Assert
Assert.IsNull(_repo.GetAllEmployersEvenPrivate().SingleOrDefault(n => n.EmployerId == 1));
}
}
}
|
d4f14ff67f17fe73d2834d687d0183ff9cb6cdf2
|
C#
|
zhangmeng1226/Mohawk_Battleship
|
/Bots CSharp/DaveBot_1_4_5/HuntingMap.cs
| 2.65625
| 3
|
using MBC.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MBC.Controllers.DaveBot_1_4_5 {
class HuntingMap : ProbabilityMap {
protected const bool RESET_HUNTING_ON_SINK = true; // Wipes hunting mode memory when a ship is sunk, if false,
protected const bool REDUCE_PROBABILITY_ON_SINK = false; // Treats sinks as a miss and reduces hunting probability as such
public HuntingMap(int size, int[] shipLengths, CellStateMap cellStateMap)
: base(size, shipLengths, cellStateMap) {
this.weighted = 50;
}
public void shipSunk(Coordinates coords) {
if (RESET_HUNTING_ON_SINK) {
//should not exist, probability reducing should be better
this.reset();
}
// Pointless if hunting was just reset
if (REDUCE_PROBABILITY_ON_SINK) {
this.removeHuntingProbability(coords);
}
}
public void addHuntingProbability(Coordinates coords) {
List<List<Coordinates>> coordsLists;
int maxLength;
coordsLists = ShotHelper.getSurrounding(coords, shipLengths.Max() - 1);
foreach (List<Coordinates> coordList in coordsLists) {
maxLength = howManyFree(coordList) + 1; // how many sequential spaces are available in these coordinates
addProbabilitiy(coords, coordList, maxLength);
}
}
public void removeHuntingProbability(Coordinates coords) {
List<List<Coordinates>> coordsLists;
int maxLength;
coordsLists = ShotHelper.getSurrounding(coords, shipLengths.Max() - 1);
foreach (List<Coordinates> coordList in coordsLists) {
maxLength = howManyFree(coordList) + 1;
removeProbabilitiy(coordList, maxLength);
}
}
}
}
|
28a9c32eeb99d962b612a483d80c72dc12823181
|
C#
|
quanliang2000/eventbus
|
/examples/InMemoryUnitTest/SimplePublisherTests.cs
| 2.5625
| 3
|
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tingle.EventBus;
using Tingle.EventBus.Transports.InMemory;
using Xunit;
namespace InMemoryUnitTest
{
public class SimplePublisherTests
{
// This unit test applies when you have an implementation that does not call the event publisher directly
[Theory]
[InlineData(1)]
[InlineData(6)]
public async Task EventIsPublishedOnBysAsync(int orderNumber)
{
var services = new ServiceCollection()
.AddLogging()
.AddSingleton<IHostEnvironment, FakeHostEnvironment>()
.AddEventBus(builder => builder.AddInMemoryTransport().AddInMemoryTestHarness())
.AddSingleton<RandomOrderProcessor>();
var provider = services.BuildServiceProvider();
var harness = provider.GetRequiredService<InMemoryTestHarness>();
await harness.StartAsync();
try
{
var orderProcessor = provider.GetRequiredService<RandomOrderProcessor>();
await orderProcessor.ProcessAsync(orderNumber);
// expect publish for event order numbers
if ((orderNumber % 2) == 0)
{
// Ensure no failures
Assert.False(harness.Failed().Any());
// Ensure only one was published
var context = Assert.Single(harness.Published<OrderProcessedEvent>());
var evt = context.Event;
Assert.Equal(2021 + orderNumber, evt.Year);
}
else
{
// Ensure no failures
Assert.False(harness.Failed().Any());
// Ensure nothing was published
Assert.False(harness.Published().Any());
}
}
finally
{
await harness.StopAsync();
}
}
class OrderProcessedEvent : SimpleConsumer.SampleEvent { }
class RandomOrderProcessor
{
private readonly IEventPublisher publisher;
public RandomOrderProcessor(IEventPublisher publisher)
{
this.publisher = publisher ?? throw new ArgumentNullException(nameof(publisher));
}
public async Task ProcessAsync(int orderNumber)
{
// only publish if the order number is even (can be any other condition)
if ((orderNumber % 2) == 0)
{
await publisher.PublishAsync(new OrderProcessedEvent
{
Make = "TESLA",
Model = "Roadster 2.0",
Registration = "1234567890",
VIN = "5YJ3E1EA5KF328931",
Year = 2021 + orderNumber,
});
}
}
}
}
}
|
a3e5bbfd5fb2b377d839413b995a7a5f698f6eb4
|
C#
|
bytting/gammalab
|
/GammaGUI/FormGammaGUI_ShowText.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GammaGUI
{
public partial class FormGammaGUI_ShowText : Form
{
private bool mUseDefaultPrinter = false;
public FormGammaGUI_ShowText(bool useDefaultPrinter)
{
InitializeComponent();
mUseDefaultPrinter = useDefaultPrinter;
}
public void setContent(string content)
{
textBoxContent.Text = content.Replace((char)0, ' ');
textBoxContent.SelectionStart = 0;
textBoxContent.SelectionLength = 0;
}
private void buttonClose_Click(object sender, EventArgs e)
{
Close();
}
private void buttonPrint_Click(object sender, EventArgs e)
{
try
{
PrintDialog pd = new PrintDialog();
pd.PrinterSettings = new PrinterSettings();
MultipadPrintDocument printDoc = new MultipadPrintDocument();
if (mUseDefaultPrinter)
{
if (!pd.PrinterSettings.IsValid)
if (pd.ShowDialog() != DialogResult.OK)
return;
}
else
{
if (pd.ShowDialog() != DialogResult.OK)
return;
}
printDoc.PrinterSettings = pd.PrinterSettings;
printDoc.Font = textBoxContent.Font;
printDoc.Text = textBoxContent.Text;
printDoc.Print();
}
catch (Exception ex)
{
MessageBox.Show("Printing failed. Make sure a printer is online and available", "Message");
}
}
private void buttonFind_Click(object sender, EventArgs e)
{
FormGammaGUI_Find form = new FormGammaGUI_Find();
if (form.ShowDialog() != System.Windows.Forms.DialogResult.OK)
return;
try
{
int pos, startPos;
Point x = textBoxContent.GetPositionFromCharIndex(textBoxContent.SelectionStart);
pos = textBoxContent.GetCharIndexFromPosition(x);
startPos = textBoxContent.Text.IndexOf(form.Token, pos, StringComparison.OrdinalIgnoreCase);
if (!(startPos > 0))
{
MessageBox.Show("Search text: '" + form.Token + "' could not be found", "Text Not Found", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
return;
}
else
{
textBoxContent.Select(startPos, form.Token.Length);
textBoxContent.ScrollToCaret();
textBoxContent.Focus();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Search Error");
}
}
}
}
|
6bf51d3b0a9f48388893aa15cffe40d9d0b7a0ac
|
C#
|
Herdubreid/Celin.AIS.Data
|
/src/Literal.cs
| 2.53125
| 3
|
using Pidgin;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using static Pidgin.Parser;
namespace Celin.AIS.Data
{
public class Literal
{
public static readonly Regex VARIABLE = new Regex(@"^%VARIABLE:(\w+)(?>\[(\d+)\])?:%");
static readonly Parser<char, int> Index =
Try(DecimalNum.Between(Char('['), Char(']')));
static readonly Parser<char, string> VariableName =
Try(Char('@'))
.Then(LetterOrDigit
.ManyString(), (h, t) => t);
static readonly Parser<char, string> Variable =
Map((name, index) => $"%VARIABLE:{name}{(index.HasValue ? $"[{index.Value}]" : string.Empty)}:%", VariableName, Index.Optional());
static readonly Parser<char, string> Plain =
Try(LetterOrDigit)
.Then(LetterOrDigit
.ManyString(), (h, t) => h + t);
public static readonly Parser<char, string> Quoted =
AnyCharExcept('"')
.ManyString()
.Between(Char('"'));
public static Parser<char, string> Parser
=> Plain
.Or(Variable)
.Or(Quoted)
.Labelled("Literal");
public static Parser<char, IEnumerable<string>> Array
=> Parser
.SeparatedAtLeastOnce(Char(','))
.Labelled("Literal Array");
}
}
|
d7edbad8877ba9535b3f7fa8e737fc5069230b95
|
C#
|
shendongnian/download4
|
/code5/937870-23602620-64906815-2.cs
| 2.5625
| 3
|
private async void ResponseCallback(IAsyncResult asyncres)
{
try
{
HttpWebRequest wreq = (HttpWebRequest)asyncres.AsyncState;
HttpWebResponse wres = (HttpWebResponse)wreq.EndGetResponse(asyncres);
StreamReader sr = new StreamReader(wres.GetResponseStream());
string result = await sr.ReadToEndAsync();
//HTML View
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
HTML.Text = result;
});
//Readable
string read;
read = Regex.Replace(result, "<script.*?</script>", "", RegexOptions.Singleline | RegexOptions.IgnoreCase);
read = Regex.Replace(read, "<style.*?</style>", "", RegexOptions.Singleline | RegexOptions.IgnoreCase);
read = Regex.Replace(read, "</?[a-z][a-z0-9]*[^<>]*>", "");
read = Regex.Replace(read, "<!--(.|\\s)*?-->", "");
read = Regex.Replace(read, "<!(.|\\s)*?>", "");
read = Regex.Replace(read, "[\t\r\n]", " ");
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
readable.Text = read;
});
}
catch (WebException ex)
{
//MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK);
}
}
|
b56d1e5b361c03fd7993d055ee3c7bfa8554ca0b
|
C#
|
synara/perceptron
|
/Perceptron/Perceptron/Perceptron.cs
| 3.421875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Perceptron
{
public class Perceptron
{
private static double[] inputs;
private static double classe;
public static int ativador(double saida)
{
if (saida >= 0)
return 1;
else
return -1;
}
public static double perceptron(double[] entradas, double[] pesos)
{
double saida = 0.0;
int i = 0;
foreach (var p in pesos)
{
for (i = i; i < entradas.Length; i++)
{
saida += p * entradas[i];
i += 1;
break;
}
}
return ativador(saida);
}
public static double[] calcularPeso(double[] inputs, double[] pesos, double aprendizagem, double erro)
{
int j = 0;
for (int i = 0; i < pesos.Length; i++)
{
for (j = j; j < inputs.Length; j++)
{
pesos[i] = pesos[i] + aprendizagem * erro * inputs[j];
j = j + 1;
break;
}
}
return pesos;
}
public static void treinar(List<double[]> entradas, double aprendizagem, double[] pesos, int bias = 1)
{
bool verificar = false;
foreach (var item in entradas)
{
separarDados(item, bias);
int controle = 1;
double erro = 0.0d;
while (true)
{
var p = perceptron(inputs, pesos);
erro = classe - p;
if (erro == 0)
{
Console.WriteLine($"({item[0] + "," + item[1] + ", " + item[2]}) correto na interação número {controle}.");
controle += 1;
break;
}
else
{
verificar = true;
pesos = calcularPeso(inputs, pesos, aprendizagem, erro);
Console.WriteLine($"({item[0] + "," + item[1] + ", " + item[2]}) incorreto na interação número {controle}.");
controle += 1;
}
}
}
if (verificar)
{
treinar(entradas, aprendizagem, pesos);
Console.WriteLine("Pesos finais: (" + pesos[0] + "," + pesos[1] + ", " + pesos[2] + ")");
}
}
private static void separarDados(double[] item, int bias)
{
inputs = new double[] { item[0], item[1], bias };
classe = Convert.ToInt32(item[2]);
}
}
}
|
f3296761b44223bd95e5c1df57fcbb7b10f955d0
|
C#
|
b1712/UAVLandingSYS_Ship
|
/ShipImplementation/TestBusinessLayer/TestShipMotion.cs
| 2.796875
| 3
|
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Assets.BusinessLayer;
using System.Reflection;
//using Assets.PresentationLayer;
namespace TestBusinessLayer
{
[TestClass]
public class TestShipMotion
{
/// <summary>
/// This test method uses reflection to invoke the private method calculateRelativeSpeed() and
/// check the private field relativeSpeed is within expected limits.
///
/// Setup A_1
/// For SS6 in head on waves at max speed the relative speed should be between 20.0 and 24.1 m/s.
///
/// </summary>
[TestMethod]
public void TestCalculateRelativeSpeed_Setup1()
{
ShipMotion target = new ShipMotion(SeaState.SeaState6, WaveDirection.Zero_Degrees, ShipSpeed.Full);
//typeof(ShipMotion).GetMethod("calculateRelativeValues",
// BindingFlags.NonPublic | BindingFlags.Instance).Invoke(target, null);
float actual = (float)typeof(ShipMotion).GetField("relativeSpeed",
BindingFlags.NonPublic | BindingFlags.Instance).GetValue(target);
float expectedLow = 20.0f;
float expectedHigh = 24.1f;
Assert.IsTrue(actual >= expectedLow);
Assert.IsTrue(actual <= expectedHigh);
}
/// <summary>
/// This test method uses reflection to invoke the private method calculateRelativeSpeed() and
/// check the private field relativeSpeed is within expected limits.
/// Setup A_2
/// For SS3 in 45 degree waves at half speed the relative speed should be between 9.6 and 11.4 m/s.
///
/// </summary>
[TestMethod]
public void TestCalculateRelativeSpeed_Setup2()
{
ShipMotion target = new ShipMotion(SeaState.SeaState3, WaveDirection.FortyFive_Degrees, ShipSpeed.Half);
typeof(ShipMotion).GetMethod("calculateRelativeValues",
BindingFlags.NonPublic | BindingFlags.Instance).Invoke(target, null);
float actual = (float)typeof(ShipMotion).GetField("relativeSpeed",
BindingFlags.NonPublic | BindingFlags.Instance).GetValue(target);
float expectedLow = 9.6f;
float expectedHigh = 11.4f;
Assert.IsTrue(actual >= expectedLow);
Assert.IsTrue(actual <= expectedHigh);
}
/// <summary>
/// This test method uses reflection to invoke the private method calculateRelativeSpeed() and
/// check the private field relativeSpeed is within expected limits.
/// Setup A_3
/// For SS0 in no waves at zero speed the relative speed should be between 0 m/s.
///
/// </summary>
[TestMethod]
public void TestCalculateRelativeSpeed_Setup3()
{
ShipMotion target = new ShipMotion(SeaState.SeaState0, WaveDirection.Zero_Degrees, ShipSpeed.Stop);
typeof(ShipMotion).GetMethod("calculateRelativeValues",
BindingFlags.NonPublic | BindingFlags.Instance).Invoke(target, null);
float actual = (float)typeof(ShipMotion).GetField("relativeSpeed",
BindingFlags.NonPublic | BindingFlags.Instance).GetValue(target);
float expected = 0.0f;
Assert.AreEqual(expected, actual);
}
/// <summary>
/// This test method uses reflection to invoke the private method populateHeaveArray() and
/// check the private collection heaveArray is within expected limits.
/// Setup B_1
/// For SS6 in head on waves at max speed the maximum wave amplitude should be less than 6.0 m.
///
/// </summary>
[TestMethod]
public void TestPopulateHeaveArray_S_S_6()
{
ShipMotion target = new ShipMotion(SeaState.SeaState6, WaveDirection.Zero_Degrees, ShipSpeed.Full);
float actualMax = float.MinValue;
float actualMin = float.MaxValue;
typeof(ShipMotion).GetMethod("populateHeaveArray",
BindingFlags.NonPublic | BindingFlags.Instance).Invoke(target, null);
IList<float> heaveArray = typeof(ShipMotion).GetField("heaveArray",
BindingFlags.NonPublic | BindingFlags.Instance).GetValue(target) as IList<float>;
foreach (float value in heaveArray)
{
if (value > actualMax)
{
actualMax = value;
}
if (value < actualMin)
{
actualMin = value;
}
}
// As the wave is sinusoidal the max and min values are an equal distance from 0 in the positive and
// negative directions.
float expectedMax = 6.0f;
float expectedMin = -6.0f;
Assert.IsTrue(expectedMax >= actualMax);
Assert.IsTrue(expectedMin <= actualMin);
}
/// <summary>
/// This test method uses reflection to invoke the private method populateHeaveArray() and
/// check the private collection heaveArray is within expected limits.
/// Setup B_2
/// For SS3 in head on waves at max speed the maximum wave amplitude should be less than 1.25 m.
///
/// </summary>
[TestMethod]
public void TestPopulateHeaveArray_S_S_3()
{
ShipMotion target = new ShipMotion(SeaState.SeaState3, WaveDirection.Zero_Degrees, ShipSpeed.Full);
float actualMax = float.MinValue;
float actualMin = float.MaxValue;
typeof(ShipMotion).GetMethod("populateHeaveArray",
BindingFlags.NonPublic | BindingFlags.Instance).Invoke(target, null);
IList<float> heaveArray = typeof(ShipMotion).GetField("heaveArray",
BindingFlags.NonPublic | BindingFlags.Instance).GetValue(target) as IList<float>;
foreach (float value in heaveArray)
{
if (value > actualMax)
{
actualMax = value;
}
if (value < actualMin)
{
actualMin = value;
}
}
// As the wave is sinusoidal the max and min values are an equal distance from 0 in the positive and
// negative directions.
float expectedMax = 1.25f;
float expectedMin = -1.25f;
Assert.IsTrue(expectedMax >= actualMax);
Assert.IsTrue(expectedMin <= actualMin);
}
/// <summary>
/// This test method uses reflection to invoke the private method populateHeaveArray() and
/// check the private collection heaveArray is within expected limits.
/// Setup B_3
/// For SS0 in head on waves at max speed there are no waves so the amplitude is 0.
///
/// </summary>
[TestMethod]
public void TestPopulateHeaveArray_S_S_0()
{
ShipMotion target = new ShipMotion(SeaState.SeaState0, WaveDirection.Zero_Degrees, ShipSpeed.Full);
float actualMax = float.MinValue;
float actualMin = float.MaxValue;
typeof(ShipMotion).GetMethod("populateHeaveArray",
BindingFlags.NonPublic | BindingFlags.Instance).Invoke(target, null);
IList<float> heaveArray = typeof(ShipMotion).GetField("heaveArray",
BindingFlags.NonPublic | BindingFlags.Instance).GetValue(target) as IList<float>;
foreach (float value in heaveArray)
{
if (value > actualMax)
{
actualMax = value;
}
if (value < actualMin)
{
actualMin = value;
}
}
// As the wave is sinusoidal the max and min values are an equal distance from 0 in the positive and
// negative directions.
float expectedMax = 0.0f;
float expectedMin = 0.0f;
Assert.AreEqual(expectedMax, actualMax);
Assert.AreEqual(expectedMin, actualMin);
}
/// <summary>
/// This test method uses reflection to invoke the private method populatePitchArray() and
/// check the private collection heaveArray is within expected limits.
/// Setup C_1
/// For SS6 in head on waves at max speed, the maximum pitch angle is +/- 3.0 degrees.
///
/// </summary>
[TestMethod]
public void TestPopulatePitchArray_S_S_6()
{
ShipMotion target = new ShipMotion(SeaState.SeaState6, WaveDirection.Zero_Degrees, ShipSpeed.Full);
float actualMax = float.MinValue;
float actualMin = float.MaxValue;
// There is a dependence on data generated from the populateHeaveArray so it must
// be invoked first.
typeof(ShipMotion).GetMethod("populateHeaveArray",
BindingFlags.NonPublic | BindingFlags.Instance).Invoke(target, null);
typeof(ShipMotion).GetMethod("populatePitchArray",
BindingFlags.NonPublic | BindingFlags.Instance).Invoke(target, null);
IList<float> pitchArray = typeof(ShipMotion).GetField("pitchArray",
BindingFlags.NonPublic | BindingFlags.Instance).GetValue(target) as IList<float>;
foreach (float value in pitchArray)
{
if (value > actualMax)
{
actualMax = value;
}
if (value < actualMin)
{
actualMin = value;
}
}
// As the wave is sinusoidal the max and min values are an equal distance from 0 in the positive and
// negative directions.
float expectedMax = 3.0f;
float expectedMin = -3.0f;
Assert.IsTrue(expectedMax >= actualMax);
Assert.IsTrue(expectedMin <= actualMin);
}
/// <summary>
/// This test method uses reflection to invoke the private method populatePitchArray() and
/// check the private collection heaveArray is within expected limits.
/// Setup C_2
/// For SS3 in head on waves at max speed, the maximum pitch angle is +/- 0.53 degrees.
///
/// </summary>
[TestMethod]
public void TestPopulatePitchArray_S_S_3()
{
ShipMotion target = new ShipMotion(SeaState.SeaState3, WaveDirection.Zero_Degrees, ShipSpeed.Full);
float actualMax = float.MinValue;
float actualMin = float.MaxValue;
// There is a dependence on data generated from the populateHeaveArray so it must
// be invoked first.
typeof(ShipMotion).GetMethod("populateHeaveArray",
BindingFlags.NonPublic | BindingFlags.Instance).Invoke(target, null);
typeof(ShipMotion).GetMethod("populatePitchArray",
BindingFlags.NonPublic | BindingFlags.Instance).Invoke(target, null);
IList<float> pitchArray = typeof(ShipMotion).GetField("pitchArray",
BindingFlags.NonPublic | BindingFlags.Instance).GetValue(target) as IList<float>;
foreach (float value in pitchArray)
{
if (value > actualMax)
{
actualMax = value;
}
if (value < actualMin)
{
actualMin = value;
}
}
// As the wave is sinusoidal the max and min values are an equal distance from 0 in the positive and
// negative directions.
float expectedMax = 0.53f;
float expectedMin = -0.53f;
Assert.IsTrue(expectedMax >= actualMax);
Assert.IsTrue(expectedMin <= actualMin);
}
/// <summary>
/// This test method uses reflection to invoke the private method populatePitchArray() and
/// check the private collection heaveArray is within expected limits.
/// Setup C_3
/// For SS0 in to 90 degree waves at max speed, there are no waves so the pitch angle is 0.
///
/// </summary>
[TestMethod]
public void TestPopulatePitchArray_S_S_0()
{
ShipMotion target = new ShipMotion(SeaState.SeaState0, WaveDirection.Ninety_Degrees, ShipSpeed.Full);
float actualMax = float.MinValue;
float actualMin = float.MaxValue;
typeof(ShipMotion).GetMethod("populatePitchArray",
BindingFlags.NonPublic | BindingFlags.Instance).Invoke(target, null);
IList<float> pitchArray = typeof(ShipMotion).GetField("pitchArray",
BindingFlags.NonPublic | BindingFlags.Instance).GetValue(target) as IList<float>;
foreach (float value in pitchArray)
{
if (value > actualMax)
{
actualMax = value;
}
if (value < actualMin)
{
actualMin = value;
}
}
// As the wave is sinusoidal the max and min values are an equal distance from 0 in the positive and
// negative directions.
float expectedMax = 0.0f;
float expectedMin = 0.0f;
Assert.AreEqual(expectedMax, actualMax);
Assert.AreEqual(expectedMin, actualMin);
}
/// <summary>
/// This test method uses reflection to invoke the private method populateRollArray() and
/// check the private collection heaveArray is within expected limits.
/// Setup D_1
/// For SS6 in 90 degree waves at max speed, the maximum roll angle is +/- 16.0 degrees.
///
/// </summary>
[TestMethod]
public void TestPopulateRollArray_S_S_6()
{
ShipMotion target = new ShipMotion(SeaState.SeaState6, WaveDirection.Ninety_Degrees, ShipSpeed.Full);
float actualMax = float.MinValue;
float actualMin = float.MaxValue;
// There is a dependence on data generated from the populateHeaveArray so it must
// be invoked first.
typeof(ShipMotion).GetMethod("populateHeaveArray",
BindingFlags.NonPublic | BindingFlags.Instance).Invoke(target, null);
typeof(ShipMotion).GetMethod("populateRollArray",
BindingFlags.NonPublic | BindingFlags.Instance).Invoke(target, null);
IList<float> rollArray = typeof(ShipMotion).GetField("rollArray",
BindingFlags.NonPublic | BindingFlags.Instance).GetValue(target) as IList<float>;
foreach (float value in rollArray)
{
if (value > actualMax)
{
actualMax = value;
}
if (value < actualMin)
{
actualMin = value;
}
}
// As the wave is sinusoidal the max and min values are an equal distance from 0 in the positive and
// negative directions.
float expectedMax = 16.0f;
float expectedMin = -16.0f;
Assert.IsTrue(expectedMax >= actualMax);
Assert.IsTrue(expectedMin <= actualMin);
}
/// <summary>
/// This test method uses reflection to invoke the private method populateRollArray() and
/// check the private collection heaveArray is within expected limits.
/// Setup D_2
/// For SS3 in 90 degree waves at max speed, the maximum roll angle is +/- 8.0 degrees.
///
/// </summary>
[TestMethod]
public void TestPopulateRollArray_S_S_3()
{
ShipMotion target = new ShipMotion(SeaState.SeaState3, WaveDirection.Ninety_Degrees, ShipSpeed.Full);
float actualMax = float.MinValue;
float actualMin = float.MaxValue;
// There is a dependence on data generated from the populateHeaveArray so it must
// be invoked first.
typeof(ShipMotion).GetMethod("populateHeaveArray",
BindingFlags.NonPublic | BindingFlags.Instance).Invoke(target, null);
typeof(ShipMotion).GetMethod("populateRollArray",
BindingFlags.NonPublic | BindingFlags.Instance).Invoke(target, null);
IList<float> rollArray = typeof(ShipMotion).GetField("rollArray",
BindingFlags.NonPublic | BindingFlags.Instance).GetValue(target) as IList<float>;
foreach (float value in rollArray)
{
if (value > actualMax)
{
actualMax = value;
}
if (value < actualMin)
{
actualMin = value;
}
}
// As the wave is sinusoidal the max and min values are an equal distance from 0 in the positive and
// negative directions.
float expectedMax = 8.0f;
float expectedMin = -8.0f;
Assert.IsTrue(expectedMax >= actualMax);
Assert.IsTrue(expectedMin <= actualMin);
}
/// <summary>
/// This test method uses reflection to invoke the private method populateRollArray() and
/// check the private collection heaveArray is within expected limits.
/// Setup D_3
/// For SS0 in 90 degree waves at max speed, there are no waves so the roll angle is 0.
///
/// </summary>
[TestMethod]
public void TestPopulateRollArray_S_S_0()
{
ShipMotion target = new ShipMotion(SeaState.SeaState0, WaveDirection.Ninety_Degrees, ShipSpeed.Full);
float actualMax = float.MinValue;
float actualMin = float.MaxValue;
// There is a dependence on data generated from the populateHeaveArray so it must
// be invoked first.
typeof(ShipMotion).GetMethod("populateHeaveArray",
BindingFlags.NonPublic | BindingFlags.Instance).Invoke(target, null);
typeof(ShipMotion).GetMethod("populateRollArray",
BindingFlags.NonPublic | BindingFlags.Instance).Invoke(target, null);
IList<float> rollArray = typeof(ShipMotion).GetField("rollArray",
BindingFlags.NonPublic | BindingFlags.Instance).GetValue(target) as IList<float>;
foreach (float value in rollArray)
{
if (value > actualMax)
{
actualMax = value;
}
if (value < actualMin)
{
actualMin = value;
}
}
// As the wave is sinusoidal the max and min values are an equal distance from 0 in the positive and
// negative directions.
float expectedMax = 0.0f;
float expectedMin = 0.0f;
Assert.AreEqual(expectedMax, actualMax);
Assert.AreEqual(expectedMin, actualMin);
}
}
}
|
d6fd055feeea766c09922c1b618d93f2575baf19
|
C#
|
frogsbreath-games/deckbuilder
|
/src/Deckbuilder.Core/Builders/Cards.cs
| 2.640625
| 3
|
using System.Collections.Generic;
using Deckbuilder.Core.Enums;
using Deckbuilder.Core.Models;
using Deckbuilder.Core.Models.CardTypes;
namespace Deckbuilder.Core.Builders
{
public static class Cards
{
public static SpellCard Spell(
int id,
string name,
int price,
CardAction? effect = null,
IEnumerable<Ability>? abilities = null,
FactionCode? faction = null,
IEnumerable<KeywordCode>? keywords = null)
{
return new SpellCard(
id,
name,
name.Replace(' ', '_').ToLower(),
price,
effect,
abilities,
faction: faction,
keywords: keywords);
}
public static HeroCard Hero(
int id,
string name,
FactionCode faction,
CardAction? effect = null,
IEnumerable<Ability>? abilities = null)
{
return new HeroCard(
id,
name,
name.Replace(' ', '_').ToLower(),
faction,
effect,
abilities);
}
public static MonsterCard Monster(
int id,
string name,
int power,
CardAction bounty,
IEnumerable<KeywordCode>? keywords = null)
{
return new MonsterCard(
id,
name,
name.Replace(' ', '_').ToLower(),
power,
bounty,
keywords);
}
}
}
|
09881c5b9cd4c4194dea22edc1f5df4ccb325d74
|
C#
|
umittal/MunimJi
|
/trunk/packages/src/envers/Query/Criteria/AuditRelatedId.cs
| 2.578125
| 3
|
using NHibernate.Envers.Query.Property;
namespace NHibernate.Envers.Query.Criteria
{
public class AuditRelatedId
{
private readonly IPropertyNameGetter _propertyNameGetter;
public AuditRelatedId(IPropertyNameGetter propertyNameGetter)
{
_propertyNameGetter = propertyNameGetter;
}
public IAuditCriterion Eq(object id)
{
return new RelatedAuditExpression(_propertyNameGetter, id, true);
}
public IAuditCriterion Ne(object id)
{
return new RelatedAuditExpression(_propertyNameGetter, id, false);
}
}
}
|
400b246c76ae2e022fb096448b297168f557445d
|
C#
|
samuel-clemens/WSN
|
/Zad2/ViewModels/ViewModel.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zad2.Common;
using Zad2.Models;
namespace Zad2.ViewModels
{
/// <summary>
/// Klasa ze wszystkimi zmiennymi do bindingowania w GUI
/// </summary>
public class ViewModel : ObservableObject
{
#region fields
private SquareList _canvasList = new SquareList();
private List<SquareList> _imageList = SampleManager.Instance.Samples;
private bool _isTaught = false;
private bool _canReduceNoise = false;
private bool _areChangesUnsaved = false;
private string _filename = "[bez nazwy]";
private int _sampleId = 0;
private int _sampleCount = 0;
#endregion
#region properties
public SquareList CanvasSquareList
{
get { return _canvasList; }
set {
_canvasList = value;
NotifyPropertyChanged("CanvasSquareList");
}
}
public SquareList ImageSquareList
{
get {
if (_sampleCount > 0 && _sampleId - 1 >= 0 && _sampleId - 1 < _sampleCount)
return _imageList[_sampleId-1];
return null;
}
set {
_imageList[_sampleId-1] = value;
}
}
public bool IsTaught { get { return _isTaught; } set { _isTaught = value; NotifyPropertyChanged("IsTaught"); } }
public bool CanReduceNoise { get { return _canReduceNoise; } set { _canReduceNoise = value; NotifyPropertyChanged("CanReduceNoise"); } }
public bool AreChangesUnsaved { get { return _areChangesUnsaved; } set { _areChangesUnsaved = value; NotifyPropertyChanged("AreChangesUnsaved"); } }
public string FileName { get { return _filename; } set { _filename = value; NotifyPropertyChanged("FileName"); } }
public int SampleId { get { return _sampleId; } set { _sampleId = value;
NotifyPropertyChanged("SampleId");
NotifyPropertyChanged("ImageSquareList");
} }
public int SampleCount { get { return _sampleCount; } set { _sampleCount = value; NotifyPropertyChanged("SampleCount"); } }
public int ParentWidth { get { return Globals.ParentWidth; } }
public int ParentHeight { get { return Globals.ParentHeight; } }
#endregion
public void LoadNewImageSquareList()
{
NotifyPropertyChanged("ImageSquareList");
SampleCount = _imageList.Count();
SampleId = 1;
AreChangesUnsaved = false;
}
public void RemoveActualItemFromCollection()
{
if (SampleCount > 0)
{
_imageList.Remove(ImageSquareList);
/*
ta konstrukcja jest po to żeby jak się pokazuje np. "1/2" (że zdjęcie 1 z 2)
to żeby po usunięciu jakiegoś się odpowiednie cyferki pokazywały
nie jestem dumna z tej konstrukcji, ale zdobywam cenne doświadczenie
i nastęnym razem zaprojektuję program jakoś tak by był ładniej niż to...
*/
if (SampleId == 1 && SampleCount == 1)
SampleId = SampleCount = 0;
else
{
SampleCount--;
if (SampleId > 1)
SampleId--;
else
NotifyPropertyChanged("ImageSquareList");
}
}
}
public void LoadImageToCanvas()
{
for (int i = 0; i < ImageSquareList.Count(); ++i)
{
if (ImageSquareList[i].IsFilled)
CanvasSquareList[i].IsFilled = true;
else
CanvasSquareList[i].IsFilled = false;
}
}
}
}
|
3328ce7b1240ed9b75c35eb481d9a522b13101e6
|
C#
|
AshbyGeek/Thermostat
|
/Thermostat/HardwareVirtualization/VirtualHardwareViewModel.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Thermostat.HardwareVirtualization
{
public class VirtualHardwareViewModel
{
public VirtualSystem System { get; }
public VirtualClock Clock { get; }
public VirtualHardwareViewModel(VirtualSystem system, VirtualClock clock)
{
System = system;
Clock = clock;
}
public double OutdoorTemp
{
get => System.CurrentSensorValues.OutdoorTemp;
set => System.CurrentSensorValues.OutdoorTemp = value;
}
public VirtualHardwareViewModel()
{
Clock = new VirtualClock();
System = new VirtualSystem(Clock);
}
}
}
|
62dff066c047b8be200371d93d6829119bf94da6
|
C#
|
ypablo/StudentsDiary-C-sharp
|
/AddEditStudent.cs
| 2.953125
| 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;
namespace StudentsDiary
{
public partial class AddEditStudent : Form
{
private string _filePath = System.IO.Path.Combine(Environment.CurrentDirectory, "students3.txt");
private int _studentID;
private Student _student;
private FileHelper<List<Student>> _fileHelper = new FileHelper<List<Student>>(Program.FilePath);
public AddEditStudent(int id = 0)
{
InitializeComponent();
_studentID = id;
GetStudentData();
tbName.Select();
}
private void GetStudentData()
{
if (_studentID != 0)
{
Text = "Edit student's info";
var students = _fileHelper.DeserializeFromFile();
_student = students.FirstOrDefault(x => x.Id == _studentID);
if (_student == null)
throw new Exception("Brak uzytkownika o podanym Id.");
FillTextBoxes();
}
}
private void FillTextBoxes()
{
tbId.Text = _student.Id.ToString();
tbName.Text = _student.FirstName;
tbSurename.Text = _student.SureName;
tbMath.Text = _student.Math;
tbPhysics.Text = _student.Physics;
tbTechnology.Text = _student.Technology;
tbEnglishLang.Text = _student.EnglishLang;
tbFrenchLang.Text = _student.FrenchLang;
rtbComments.Text = _student.Comments;
}
private void btnCancel_Click(object sender, EventArgs e)
{
Close();
}
private void btnConfirm_Click(object sender, EventArgs e)
{
var students = _fileHelper.DeserializeFromFile();
if(_studentID != 0)
{
students.RemoveAll(x => x.Id == _studentID);
}
else
{
AssignIdToNewStudent(students);
}
var student = new Student
{
Id = _studentID,
FirstName = tbName.Text,
SureName = tbSurename.Text,
Comments = rtbComments.Text,
Math = tbMath.Text,
Technology = tbTechnology.Text,
EnglishLang = tbEnglishLang.Text,
Physics = tbPhysics.Text,
FrenchLang = tbFrenchLang.Text
};
students.Add(student);
_fileHelper.SerializeToFile(students);
Close();
}
private void AssignIdToNewStudent(List<Student> students)
{
var studentWithHighestId = students.OrderByDescending(x => x.Id).FirstOrDefault();
if (studentWithHighestId == null)
{
_studentID = 1;
}
else
{
_studentID = studentWithHighestId.Id + 1;
}
}
}
}
|
7671ef44735efcfa5c397be7e104f8260d9a55c0
|
C#
|
DerekLiang/microphone-volume-controller
|
/VolumeControl/Settings.cs
| 2.515625
| 3
|
using System.ComponentModel;
using System.Configuration;
using System.Windows.Media;
namespace VolumeControl
{
public class Settings : ApplicationSettingsBase
{
[UserScopedSetting()]
[DefaultSettingValue("")]
public int DefaultVolume
{
get
{
if (this["DefaultVolume"] is string)
{
var returnVal = 50;
int.TryParse((string) this["DefaultVolume"], out returnVal);
return returnVal;
}
return ((int)this["DefaultVolume"]);
}
set
{
this["DefaultVolume"] = value;
}
}
}
}
|
586589dcc917d7150bc69a32808e8512255945cd
|
C#
|
wangjialei001/Storage
|
/WeiCloudStorageAPI/Model/RequestBackStatuEnum.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WeiCloudStorageAPI.Model
{
public class Enumeration : IComparable
{
private readonly int _value;
private readonly string _displayName;
public int Value
{
get { return _value; }
}
public int CompareTo(object other)
{
return Value.CompareTo(((Enumeration)other).Value);
}
protected Enumeration()
{
}
public string DisplayName
{
get { return _displayName; }
}
protected Enumeration(int value, string displayName)
{
_value = value;
_displayName = displayName;
}
}
public class RequestBackStatuEnum : Enumeration
{
private RequestBackStatuEnum(int value, string displayName) : base(value, displayName)
{
}
/// <summary>
/// 成功执行
/// </summary>
public static readonly RequestBackStatuEnum success = new RequestBackStatuEnum(200, nameof(success).ToLowerInvariant());
/// <summary>
/// 不存在指定对象
/// </summary>
public static readonly RequestBackStatuEnum notexist = new RequestBackStatuEnum(2001, nameof(notexist).ToLowerInvariant());
/// <summary>
/// 存在指定对象
/// </summary>
public static readonly RequestBackStatuEnum exist = new RequestBackStatuEnum(2002, nameof(exist).ToLowerInvariant());
/// <summary>
/// 存在指定条件的数据集
/// </summary>
public static readonly RequestBackStatuEnum hasdata = new RequestBackStatuEnum(2003, nameof(hasdata).ToLowerInvariant());
/// <summary>
/// 不存在指定条件的数据集
/// </summary>
public static readonly RequestBackStatuEnum nodata = new RequestBackStatuEnum(2004, nameof(nodata).ToLowerInvariant());
/// <summary>
/// 服务端错误
/// </summary>
public static readonly RequestBackStatuEnum fail = new RequestBackStatuEnum(2005, nameof(fail).ToLowerInvariant());
/// <summary>
/// 请求失败
/// </summary>
public static readonly RequestBackStatuEnum badrequest = new RequestBackStatuEnum(2006, nameof(badrequest).ToLowerInvariant());
/// <summary>
/// 未找到指定接口
/// </summary>
public static readonly RequestBackStatuEnum notfound = new RequestBackStatuEnum(2007, nameof(notfound).ToLowerInvariant());
/// <summary>
/// 网络连接失败
/// </summary>
public static readonly RequestBackStatuEnum loselink = new RequestBackStatuEnum(2008, nameof(loselink).ToLowerInvariant());
/// <summary>
/// 没有权限
/// </summary>
public static readonly RequestBackStatuEnum unauthorized = new RequestBackStatuEnum(401, nameof(unauthorized).ToLowerInvariant());
public static IEnumerable<RequestBackStatuEnum> List() =>
new[] { success, badrequest, notfound, loselink };
}
}
|
e98fbeb031381d80a485b016a518f0903741021c
|
C#
|
dukedhx/File-and-text-sharing-host
|
/ConsoleApplication1/WindowsFormsApplication1/SettingIO.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
namespace WindowsFormsApplication1
{
static class SettingIO
{
static readonly public String pathname = "path", addrname = "addr", smtp ="smtp",pop3="pop3";
static readonly public String[] names = new String []{ pathname, addrname, smtp, pop3 };
static private String name;
static public Boolean checkDB()
{
try
{
if (!File.Exists(Constants.dbfilename))
File.WriteAllBytes(Constants.dbfilename,WindowsFormsApplication1.Properties.Resources.Database1);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
return true;
}
static public String Name { get { if(String.IsNullOrEmpty(name))name=System.AppDomain.CurrentDomain.FriendlyName.Split(Constants.dot)[0] + ".ini"; return name;} }
static public Dictionary<String,String> load()
{
try
{
if (File.Exists(Name))
{
Dictionary<String, String> dict = new Dictionary<String, String>();
using(StreamReader sr = new StreamReader(Name)){
String line;
var namelist = new List<String>(names);
while (!String.IsNullOrEmpty((line = sr.ReadLine()))&& namelist.Count>0)
{
String[] parts=line.Split(Constants.equal);
if (parts.Length > 1)
{
String vname = parts[0]; int id;
if ((id=namelist.IndexOf(vname)) > -1)
{
if (dict.ContainsKey(vname)) dict[vname] = parts[1];
else dict.Add(vname,parts[1]);
namelist.RemoveAt(id);
}
}
}
}
return dict;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return null;
}
static public void save(String name, String value)
{
try
{
Dictionary<String, String> dict = load();
if (dict.ContainsKey(name)) dict[name] = value;
else dict.Add(name,value);
save(dict);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
static public void save(Dictionary<String, String> dict)
{
try
{
if(Util.validateIE(dict)&&!String.IsNullOrEmpty(name))
File.WriteAllText(name,String.Join("\n",dict.Select(x=>x.Key+Constants.equal+x.Value).ToArray()));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
|
59487a83f9306882aa2915047539f297a6b67212
|
C#
|
AndreyAkinshin/perfolizer
|
/src/Perfolizer/Perfolizer/Mathematics/Sequences/ArithmeticProgressionSequence.cs
| 2.796875
| 3
|
namespace Perfolizer.Mathematics.Sequences;
public class ArithmeticProgressionSequence : ISequence
{
private readonly double start, step;
public ArithmeticProgressionSequence(double start, double step)
{
this.start = start;
this.step = step;
}
public double Value(int index) => start + index * step;
}
|
cb4aac1192bbed6fd61ffc15080a294925ce38c6
|
C#
|
ADolodarenko/ExcelImageReader
|
/ExcelImageReader/Model/ImageLocators.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExcelImageReader.Model
{
public class ImageLocators
{
private String url;
private String name;
private String extension;
public ImageLocators(String url, String name, String extension)
{
this.url = url;
this.name = name;
this.extension = extension;
}
public String GetUrl()
{
return url;
}
public String GetName()
{
return name;
}
public String GetExtension()
{
return extension;
}
}
}
|
43e713e0568ca4762bb3bd432e4bc851647db1b2
|
C#
|
Ryocham-prog/AtCoderCSharp
|
/ABC/166/AtCoder/Abc/QuestionB.cs
| 3.28125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AtCoder.Abc
{
// https://atcoder.jp/contests/abc166/tasks/abc166_b
class QuestionB
{
public static void Main(string[] args)
{
using (var sw = new System.IO.StreamWriter(Console.OpenStandardOutput()))
{
Console.SetOut(sw);
// N:すぬけ君の数, K:お菓子の種類の入力
var inputArray = Console.ReadLine().Split(' ').Select(i => int.Parse(i)).ToArray();
if (inputArray.Length != 2)
{
Console.Error.WriteLine("入力値を確認してください。(入力形式:\"N K\")");
return;
}
var n = inputArray[0];
var k = inputArray[1];
var snackInfo = Enumerable.Range(1, k)
.Select((x, index) =>
{
// d: dnのお菓子を持っている人数
var d = int.Parse(Console.ReadLine());
// A:お菓子を持っている人
var aStr= Console.ReadLine();
var a = (d == 1) ? new int[1] { int.Parse(aStr) } : aStr.Split(' ').Select(i => int.Parse(i));
return new { d, a };
}).ToArray();
var trickCount = Enumerable.Range(1, n)
.Select(check => {
var treatCount = snackInfo.Where(x => x.a.Contains(check)).Count();
return treatCount;
})
.Where(x => x == 0)
.Count();
Console.WriteLine(trickCount.ToString());
Console.Out.Flush();
}
}
}
}
|
a5339fee673c51ea38d09f597ddddaae3be8378a
|
C#
|
dotnet/dotnet-api-docs
|
/snippets/csharp/System.Windows.Forms/InputLanguage/FromCulture/source.cs
| 2.921875
| 3
|
using System;
using System.Data;
using System.ComponentModel;
using System.Windows.Forms;
public class Form1: Form
{
protected TextBox textBox1;
// <Snippet1>
public void SetNewCurrentLanguage() {
// Gets the default, and current languages.
InputLanguage myDefaultLanguage = InputLanguage.DefaultInputLanguage;
InputLanguage myCurrentLanguage = InputLanguage.CurrentInputLanguage;
textBox1.Text = "Current input language is: " +
myCurrentLanguage.Culture.EnglishName + '\n';
textBox1.Text += "Default input language is: " +
myDefaultLanguage.Culture.EnglishName + '\n';
//Print the new current input language.
InputLanguage myCurrentLanguage2 = InputLanguage.CurrentInputLanguage;
textBox1.Text += "New current input language is: " +
myCurrentLanguage2.Culture.EnglishName;
}
// </Snippet1>
}
|
6b72d7a8806686309b2bb742b8e448ba968fc6bf
|
C#
|
eeguia21/MicroMasterCSharpExercises
|
/Dynamic Programming/PlacingParentheses/PlacingParentheses/Program.cs
| 3.609375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PlacingParentheses
{
class Program
{
static void Main(string[] args)
{
int[] numbers = new int[6] {5, 8, 7, 4, 8, 9};
char[] ops = new char[5] {'-', '+', '*', '-', '+'};
int maxValue = 0;
PlacingParenthesesDP objPP = new PlacingParenthesesDP();
maxValue = objPP.ComputeParenthesis(numbers, ops);
Console.WriteLine(maxValue);
Console.ReadLine();
}
}
public class PlacingParenthesesDP
{
public int ComputeParenthesis(int [] numbers, char [] ops)
{
int[,] Max = new int[numbers.Length, numbers.Length];
int[,] Min = new int[numbers.Length, numbers.Length];
int j = 0;
int[] res = new int[2];
for (int i = 0; i < numbers.Length; i ++)
{
Min[i, i] = numbers[i];
Max[i, i] = numbers[i];
}
for (int s = 0; s < numbers.Length - 1; s++)
{
for (int i = 0; i < numbers.Length - s - 1; i++)
{
j = i + s + 1;
res = ComputeMinMax(i, j, Max, Min, ops);
Min[i, j] = res[0];
Max[i, j] = res[1];
}
}
return Max[0, numbers.Length - 1];
}
public int[] ComputeMinMax(int i, int j, int [,] Max, int [,] Min, char [] ops)
{
int min = 10000;
int max = -10000;
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int[] result = new int[2];
for (int z = i; z < j; z++)
{
if (ops[z] == '+')
{
a = Max[i, z] + Max[z + 1, j];
b = Max[i, z] + Min[z + 1, j];
c = Min[i, z] + Max[z + 1, j];
d = Min[i, z] + Min[z + 1, j];
}
else if (ops[z] == '-')
{
a = Max[i, z] - Max[z + 1, j];
b = Max[i, z] - Min[z + 1, j];
c = Min[i, z] - Max[z + 1, j];
d = Min[i, z] - Min[z + 1, j];
}
else if (ops[z] == '*')
{
a = Max[i, z] * Max[z + 1, j];
b = Max[i, z] * Min[z + 1, j];
c = Min[i, z] * Max[z + 1, j];
d = Min[i, z] * Min[z + 1, j];
}
min = Math.Min(min, Math.Min(a, (Math.Min(b, Math.Min(c, d)))));
max = Math.Max(max, Math.Max(a, (Math.Max(b, Math.Max(c, d)))));
}
result[0] = min;
result[1] = max;
return result;
}
}
}
|
1ddf0ac1228ee06bd1e25e06ba6fab6bb5e74835
|
C#
|
hwiewie/LeetCode
|
/202.cs
| 3.6875
| 4
|
using System;
using System.Text;
namespace HN
{
class happynumber
{
static bool ifhappynum(string str)
{
int[] looktable = new int[] { 0, 1, 4, 9, 16, 25, 36, 49 , 64, 81 };
int[] result = new int[50];
int count=0;
while(true)
{
char[] tempnum = str.ToCharArray();
int numb=0;
for(int i =0;i<str.Length;i++)
{
numb += looktable[Convert.ToInt32(tempnum[i])];
}
result[count]=numb;
for(int j=0;j<count;j++)
{
if(result[j]==numb)
return false;
}
count++;
if(numb==1)
return true;
str = numb.ToString();
}
}
public static void main(string[] args)
{
Console.WriteLine("請輸入一個數,程式會判斷是否為Happy number:");
string numstr = Console.ReadLine();
if(ifhappynum(numstr))
Console.WriteLine("此數為快樂數");
else
Console.WriteLine("此數不是快樂數");
}
}
}
|
d47070a8d91369ea096a6d299d576e0d91694ff1
|
C#
|
EvansYe/bookingTest
|
/Server/BookingPlatform.Core/MyEnum/EnumPeriod.cs
| 3.03125
| 3
|
using System.ComponentModel;
namespace BookingPlatform.Common.MyEnum
{
public enum EnumPeriod
{
Morning = 1,
Nooning = 2,
Afternoon = 3,
Night = 4,
Other = 0,
}
public static class EnumPeriod_Class
{
public static string EnumPeriod_GetExplainByEnum(EnumPeriod ep)
{
switch (ep)
{
case EnumPeriod.Morning: return "上午";
case EnumPeriod.Nooning: return "中午";
case EnumPeriod.Afternoon: return "下午";
case EnumPeriod.Night: return "夜间";
default: return "其他";
}
}
public static int EnumPeriod_GetExplainByTime(string t)
{
switch (t)
{
case "上午": return 1;
case "中午": return 2;
case "下午": return 3;
case "夜间": return 4;
default: return 0;
}
}
public static string EnumPeriod_GetExplainByInt(int i)
{
switch (i)
{
case 1: return "上午";
case 2: return "中午";
case 3: return "下午";
case 4: return "夜间";
default: return "其他";
}
}
public static EnumPeriod EnumPeriod_GetEnum(string e)
{
switch (e)
{
case "上午": return EnumPeriod.Morning;
case "中午": return EnumPeriod.Nooning;
case "下午": return EnumPeriod.Afternoon;
case "夜间": return EnumPeriod.Night;
default: return EnumPeriod.Other;
}
}
/// <summary>
/// 科室检查时间
/// </summary>
public static class EnumTimeInterval_Class
{
public static string EnumTimeInterval_GetEnum(string TimeInterval)
{
switch (TimeInterval)
{
case "0": return "0分钟";
case "1": return "15分钟";
case "2": return "30分钟";
case "3": return "45分钟";
default: return "60分钟";
}
}
public static int EnumTimeInterval_GetIntByDBInt(int timeInterval)
{
switch (timeInterval)
{
case 0: return 0;
case 1: return 15;
case 2: return 30;
case 3: return 45;
case 4: return 60;
default: return 0;
}
}
}
public static class EnumCheckqueueType_Class
{
public static string EnumCheckqueueType_GetEnum(string TimeInterval)
{
switch (TimeInterval)
{
case "0": return "0分钟";
case "1": return "15分钟";
case "2": return "30分钟";
case "3": return "45分钟";
default: return "60分钟";
}
}
}
public enum EnumExamInterval
{
[Description("不设置")]
None = 1,
[Description("启用检查科室间隔")]
ExamClinicInterval = 2,
[Description("启用检查队列间隔")]
ExamQueueInterval = 3
}
public static class EnumExamInterval_Class
{
public static EnumExamInterval EnumExamInterval_GetEnumByInt(int code)
{
switch (code)
{
case 1: return EnumExamInterval.None;
case 2: return EnumExamInterval.ExamClinicInterval;
case 3: return EnumExamInterval.ExamQueueInterval;
default: return EnumExamInterval.None;
}
}
public static string EnumExamInterval_GetStringByEnum(EnumExamInterval eg)
{
switch (eg)
{
case EnumExamInterval.None: return "不设置";
case EnumExamInterval.ExamClinicInterval: return "启用检查科室间隔";
case EnumExamInterval.ExamQueueInterval: return "启用检查队列间隔";
default: return "不设置";
}
}
public static int EnumExamInterval_GetIntByEnum(EnumExamInterval eg)
{
switch (eg)
{
case EnumExamInterval.None: return 1;
case EnumExamInterval.ExamClinicInterval: return 2;
case EnumExamInterval.ExamQueueInterval: return 3;
default: return 1;
}
}
}
}
}
|
d70fc768f6dbd97b1edfdcd3bc4a9c9865f78039
|
C#
|
dimitarpopov7/SoftUni
|
/SoftUni C# OOP Basic/1. Defining Classes Exercises/3. Opinion Poll/3. Opinion Poll/Program.cs
| 3.515625
| 4
|
namespace _3.Opinion_Poll
{
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
int n = int.Parse(Console.ReadLine());
var listPeople = new List<Person>();
for (int i = 0; i < n; i++)
{
var currentPerson = Console.ReadLine().Split().ToList();
var person = new Person(currentPerson[0], int.Parse(currentPerson[1]));
listPeople.Add(person);
}
foreach (var guy in listPeople.Where(x => x.Age > 30).OrderBy(x => x.Name))
{
Console.WriteLine($"{guy.Name} - {guy.Age}");
}
}
}
}
|
978504cb396016b7a59273ee29df0611c4551387
|
C#
|
MatheusRod0296/EClothing
|
/EClothing.Infra/SharedContext/RepositoryGeneric.cs
| 2.859375
| 3
|
using System.Collections.Generic;
using System.Linq;
using EClothing.Domain.SharedContext.Repository;
using Microsoft.EntityFrameworkCore;
namespace EClothing.Infra.SharedContext
{
public class RepositoryGeneric<TEntity, TKey> : IRepositoryGeneric<TEntity, TKey> where TEntity : class
{
private EClothingContext _context;
public RepositoryGeneric(EClothingContext eClothing)
{
_context = eClothing;
}
public List<TEntity> Get()
{
return _context.Set<TEntity>().ToList();
}
public TEntity GetById(TKey id)
{
return _context.Set<TEntity>().Find(id);
}
public void Insert(TEntity model)
{
_context.Set<TEntity>().Add(model);
_context.SaveChanges();
}
public void Update(TEntity model)
{
_context.Set<TEntity>().Attach(model);
_context.Entry(model).State = EntityState.Modified;
_context.SaveChanges();
}
public void Delete(TEntity model)
{
_context.Set<TEntity>().Attach(model);
_context.Entry(model).State = EntityState.Deleted;
_context.SaveChanges();
}
public void DeleteById(TKey id)
{
var model = GetById(id);
Delete(model);
}
}
}
|
4810464568e9d7a5f777e265c5faa1e06c9dfdd4
|
C#
|
gdanielch9/DesignPatterns
|
/Command/MathLib.cs
| 3.203125
| 3
|
using System;
namespace Command
{
public class MathLib
{
protected int _value = 0;
public int Value
{
get { return _value; }
}
public void Add(int argument)
{
_value += argument;
}
public void Substract(int argument)
{
_value -= argument;
}
public void Multiply(int argument)
{
_value *= argument;
}
public void Divide(int argument)
{
_value /= argument;
}
}
}
|
851344d7a00904c3162094345fc2b398db81fc5b
|
C#
|
DylanJDCornish/VotingSystem
|
/constituencyvotingsystem/Report.cs
| 2.890625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConstituencyVotingSystem
{
public class Report
{
public string RepType { get; set; }
public List<ConstituencyDataMeasure> TotalVotesDataMeasure { get; set; }
public Report(String repType)
{
this.RepType = repType;
this.TotalVotesDataMeasure = new List<ConstituencyDataMeasure>();
}
public override String ToString()
{
String votes = String.Format("\tVotes: ");
foreach (var m in TotalVotesDataMeasure)
{
votes += String.Format("\n\t\t{0}", m.ToString());
}
return String.Format("Constituency Report {0}:\n{1}", RepType, votes);
}
}
}
|
75085befa628299602adfc984943fa8949d50e52
|
C#
|
gitprojectjockey/CompleteMvcCodeFirstProject
|
/ContosoWebUI/Controllers/HomeController.cs
| 2.65625
| 3
|
using ContosoWebUI.DAL;
using ContosoWebUI.ViewModels;
using System.Linq;
using System.Web.Mvc;
namespace ContosoWebUI.Controllers
{
public class HomeController : Controller
{
private SchoolContext db = new SchoolContext();
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
//IQueryable<EnrollmentDateGroup> data = from student in db.Students
// group student by student.EnrollmentDate into dateGroup
// select new EnrollmentDateGroup()
// {
// EnrollmentDate = dateGroup.Key,
// StudentCount = dateGroup.Count()
// };
//I used lamda expression instead
IQueryable<EnrollmentDateGroup> data = db.Students
.GroupBy(s => s.EnrollmentDate)
.Select(s => new EnrollmentDateGroup()
{
EnrollmentDate = s.Key,
StudentCount = s.Count()
});
return View(data.ToList());
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
//Don't forget to dispose
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}
|
590fa07d70bcc05e619a7ca7b3bfab2867586394
|
C#
|
joemorin73/EmpyrionServerManager
|
/SharedCode/Extensions.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EmpyrionModApi.ExtensionMethods
{
public static class Extensions
{
public static bool AreTheSame( this Eleon.Modding.ItemStack[] lhs, Eleon.Modding.ItemStack[] rhs )
{
if(lhs == null)
{
return (rhs == null);
}
else if (rhs == null)
{
return false;
}
if (lhs.Length != rhs.Length)
{
return false;
}
for(int i = 0; i < lhs.Length; ++i)
{
if((lhs[i].id != rhs[i].id) || (lhs[i].count != rhs[i].count))
{
return false;
}
}
return true;
}
public static System.Numerics.Vector3 ToVector3(this Eleon.Modding.PVector3 vector)
{
return new System.Numerics.Vector3(vector.x, vector.y, vector.z);
}
public static Eleon.Modding.PVector3 ToPVector3(this System.Numerics.Vector3 vector)
{
return new Eleon.Modding.PVector3(vector.X, vector.Y, vector.Z);
}
static public bool GreaterOrEqual(this System.Numerics.Vector3 lhs, System.Numerics.Vector3 rhs)
{
return ((lhs.X >= rhs.X) && (lhs.Y >= rhs.Y) && (lhs.Z >= rhs.Z));
}
static public bool LessOrEqual(this System.Numerics.Vector3 lhs, System.Numerics.Vector3 rhs)
{
return ((lhs.X <= rhs.X) && (lhs.Y <= rhs.Y) && (lhs.Z <= rhs.Z));
}
// Only format if args are actually passed in to prevent a string passed in from a config using {0} and crashing us.
static public string SafeFormat(this string format, params object[] args)
{
return (args.Length > 0) ? string.Format(format, args) : format;
}
}
}
|
94a59ee10bfebeb7d93c11d0ba4748063f99e3bf
|
C#
|
radtek/ZilLion.Core.TaskManager
|
/ZilLion.Core.TaskManager/ZilLion.Core.Unities/UnitiesMethods/Admin/AdminRun.cs
| 2.859375
| 3
|
using System;
using System.Diagnostics;
using System.Security.Principal;
namespace ZilLion.Core.Unities.UnitiesMethods.Admin
{
public class AdminRun
{
/// <summary>
/// 以管理员方式运行程序
/// </summary>
public static void Run()
{
/**
* 当前用户是管理员的时候,直接启动应用程序
* 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
*/
//获得当前登录的Windows用户标示
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
//判断当前登录用户是否为管理员
//如果不是管理员,则以管理员方式运行
if (principal.IsInRole(WindowsBuiltInRole.Administrator)) return;
//创建启动对象
var startInfo = new ProcessStartInfo
{
UseShellExecute = true,
WorkingDirectory = Environment.CurrentDirectory,
FileName = Process.GetCurrentProcess().MainModule.FileName,
Verb = "runas"
};
//设置启动动作,确保以管理员身份运行
Process.Start(startInfo);
Environment.Exit(0);
}
}
}
|
abe171164655156e4d1c1b5f6f2e4afc27426d3f
|
C#
|
kuite/CodeTask
|
/JetShop.RentalCars.Domain.Tests/CarRentsTests/CarRentPassTests.cs
| 2.5625
| 3
|
using System;
using AutoFixture;
using JetShop.RentalCars.Domain.CarRents;
using JetShop.RentalCars.Domain.Cars;
using Xunit;
namespace JetShop.RentalCars.Domain.Tests.CarRentsTests
{
public class CarRentPassTests
{
[Theory]
[InlineData(CarType.Compact, 2, 1.5, 1.4, 50, 3)]
[InlineData(CarType.Minivan, 2, 1.5, 1.4, 50, 110.1)]
[InlineData(CarType.Premium, 2, 1.5, 1.4, 50, 73.6)]
[InlineData(CarType.Compact, 8, 1.5, 1.4, 40, 12)]
[InlineData(CarType.Minivan, 8, 1.5, 1.4, 40, 104.4)]
[InlineData(CarType.Premium, 8, 1.5, 1.4, 40, 70.4)]
public void CalculateTotalPrice_WhenValidInput_ReturnsCorrectPrice(
CarType carType,
int durationDays,
double baseDayRental,
double kilometerPrice,
int mileage,
double expectedPrice)
{
// Arrange
var fixture = new Fixture();
var rentStartOn = DateTime.Now;
var rentEndOn = rentStartOn.AddDays(durationDays);
var startMileage = 1;
var endMileage = startMileage + mileage;
var carRent = fixture.Build<CarRent>()
.With(x => x.CarStartMileage, startMileage)
.With(x => x.CarEndMileage, endMileage)
.With(x => x.RentStartOn, rentStartOn)
.With(x => x.RentEndOn, rentEndOn)
.With(x => x.CarType, carType)
.Create();
// Act
var price = carRent.CalculateTotalPrice(baseDayRental, kilometerPrice);
// Assert
Assert.Equal(expectedPrice, price);
}
}
}
|
ab8708f9b185c58b357ebac57ec9affc41b06fe4
|
C#
|
engeziellithon/SerieWeb-Api
|
/Udemy.Api/Dtos/UserForRegisterDto.cs
| 2.5625
| 3
|
using System.ComponentModel.DataAnnotations;
namespace Udemy.Api.Dtos
{
public class UserForRegisterDto
{
[Required]
[StringLength(30, MinimumLength = 2 , ErrorMessage = "The username need be between 2 and 30 characters")]
public string Username { get; set; }
[Required]
[StringLength(8, MinimumLength = 4, ErrorMessage = "The password need be between 4 and 8 characters")]
public string Password { get; set; }
}
}
|
6170183097c31c73f66998215063125945345090
|
C#
|
yzzzh/SCUT
|
/DB.cs
| 2.78125
| 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 SCUT
{
class DB : IDisposable
{
private SqlConnection sqlConnection;
public DB()
{
sqlConnection = new SqlConnection(@"server=DESKTOP-3UIQV75;database=SCUT;Trusted_Connection=SSPI;");
sqlConnection.Open();
}
public DataTable getBySql(string sql)
{
SqlDataAdapter adapter = new SqlDataAdapter(new SqlCommand(sql, sqlConnection));
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
return dataTable;
}
public void setBySql(string sql)
{
new SqlCommand(sql, sqlConnection).ExecuteNonQuery();
}
public void Dispose()
{
sqlConnection.Close();
}
}
}
|
2536a83d2ad2c541ea2567e913e91f7efc773219
|
C#
|
ehotinger/leetcode
|
/easy/balanced-binary-tree.cs
| 3.75
| 4
|
// https://leetcode.com/problems/balanced-binary-tree/submissions/
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public bool IsBalanced(TreeNode root) {
if(root == null) return true;
var left = GetDepth(root.left);
var right = GetDepth(root.right);
if(Math.Abs(left-right) > 1) {
return false;
}
return IsBalanced(root.left) && IsBalanced(root.right);
}
public int GetDepth(TreeNode root) {
if(root == null) return 0;
var left = GetDepth(root.left);
var right = GetDepth(root.right);
return Math.Max(left, right) + 1;
}
}
|
6b80ccca50cbf322af2299c368f76f4b96253ac7
|
C#
|
MorneJooste/ArkSavegameToolkitNet
|
/ArkSavegameToolkitNet/Data/ExtraDataFoliageHandler.cs
| 2.53125
| 3
|
using ArkSavegameToolkitNet.Exceptions;
using ArkSavegameToolkitNet.Structs;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArkSavegameToolkitNet.Data
{
public class ExtraDataFoliageHandler : IExtraDataHandler
{
private static ILog _logger = LogManager.GetLogger(typeof(ExtraDataFoliageHandler));
public bool CanHandle(GameObject obj, long length)
{
return obj.ClassName.Token.Equals("InstancedFoliageActor");
}
public IExtraData Read(GameObject obj, ArkArchive archive, long length)
{
var shouldBeZero = archive.GetInt();
if (shouldBeZero != 0) _logger.Warn($"Expected int after properties to be 0 but found {shouldBeZero} at {archive.Position - 4:X}");
var structMapCount = archive.GetInt();
IList<IDictionary<string, StructPropertyList>> structMapList = new List<IDictionary<string, StructPropertyList>>(structMapCount);
try
{
for (int structMapIndex = 0; structMapIndex < structMapCount; structMapIndex++)
{
var structCount = archive.GetInt();
IDictionary<string, StructPropertyList> structMap = new Dictionary<string, StructPropertyList>();
for (int structIndex = 0; structIndex < structCount; structIndex++)
{
var structName = archive.GetString();
StructPropertyList properties = new StructPropertyList(archive, null);
var shouldBeZero2 = archive.GetInt();
if (shouldBeZero2 != 0) _logger.Warn($"Expected int after properties to be 0 but found {shouldBeZero2} at {archive.Position - 4:X}");
structMap[structName] = properties;
}
structMapList.Add(structMap);
}
}
catch (UnreadablePropertyException)
{
// Just stop reading and attach collected structs
}
ExtraDataFoliage extraDataFoliage = new ExtraDataFoliage();
extraDataFoliage.StructMapList = structMapList;
return extraDataFoliage;
}
}
}
|
e2a1162f448a0916cf4973bb82e0123ec0e875c4
|
C#
|
raihanthecooldude/Webtech
|
/PHP/Ticket Printer/Ticket Printer/TicketPrinter.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace Ticket_Printer
{
public partial class TicketPrinter : Form
{
public TicketPrinter()
{
InitializeComponent();
this.PreviewLabel.Visible = false;
this.PreviewBtn.Visible = false;
}
private int quantity = 0;
OpenFileDialog img = new OpenFileDialog();
private void BrowseClicked(object sender, EventArgs e)
{
img.Filter = "Choose Image(*.jpg;*.png;*.gif)|*.jpg;*.png;*.gif";
if (img.ShowDialog() == DialogResult.OK)
{
//ImagePictureBox.Image = Image.FromFile(img.FileName);
ImagePictureBox.Image = System.Drawing.Image.FromFile(img.FileName);
}
}
private void CreatePDFClicked(object sender, EventArgs e)
{
try
{
FileStream fs = new FileStream(@"C:\Users\Asus\Desktop\Ticket" + ".pdf", FileMode.Create, FileAccess.Write, FileShare.None);
Document doc = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.GetInstance(doc, fs);
doc.Open();
//BaseFont bft = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
//Font ft = new Font(bft, 12);
Paragraph p = new Paragraph("\n\n");
//doc.Add(p);
//string url = "C:/Users/Asus/Downloads/atlanta-skyline-by-colton-hd-wallpaper.jpg";
string url = img.FileName;
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(url);
//doc.Add(image);
quantity = Convert.ToInt32(QuantityTextBox.Text);
for (int i = 0; i < quantity; i++)
{
doc.Add(image);
doc.Add(p);
}
doc.Close();
MessageBox.Show("PDF has been generated.", "Done");
}
catch
{
MessageBox.Show("There is an error.", "Error");
}
}
private void PreviewClicked(object sender, EventArgs e)
{
}
}
}
|
27c406a29283da8a4fd9bb02f839cedc21369690
|
C#
|
Zapperi/CodeSnippets
|
/Uneksimo/UIController.cs
| 2.65625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/**
* Author: Henri Leppänen
* <summary>
* Handles UI related events and delegates.
* </summary>
*/
public class UIController : MonoBehaviour {
public static UIController Instance;
#region EVENTS
public delegate void UIEventHandler();
public delegate void UIEventHandlerWorld(WorldManager.WorldID world);
public delegate void SelectStickerEventHandler(int id);
/// <summary>
/// This event is raised when Drag has started on Dragpoint (Stickerbook).
/// </summary>
public event UIEventHandler StickerbookDragStarted;
/// <summary>
/// This event is raised when Settings panel is set to visible.
/// </summary>
public event UIEventHandler ShowSettings;
/// <summary>
/// This event is raised when Settings panel is set to hidden.
/// </summary>
public event UIEventHandler HideSettings;
/// <summary>
/// This event is raised when Settings visibility state is changed.
/// </summary>
public event UIEventHandler ToggleSettings;
/// <summary>
/// This event is raised when Sticker Book is set to visible.
/// </summary>
public event UIEventHandler ShowStickerBook;
/// <summary>
/// This event is raised when Sticker Book is set to hidden.
/// </summary>
public event UIEventHandler HideStickerBook;
/// <summary>
/// This event is raised when World Selection Buttons are set to visible.
/// </summary>
public event UIEventHandler ShowWorldButtons;
/// <summary>
/// This event is raised when World Selection Buttons are set to hidden.
/// </summary>
public event UIEventHandler HideWorldButtons;
/// <summary>
/// This event is raised when visibility state of World Selection Buttons is changed.
/// </summary>
public event UIEventHandler ToggleWorldButtons;
/// <summary>
/// This event is raised when World Selection Main Button has changed. World enum as parameter.
/// </summary>
public event UIEventHandlerWorld UpdateMainWorldButtonEvent;
/// <summary>
/// This event is raised when UI buttons are set to hidden.
/// </summary>
public event UIEventHandler HideUIButtons;
/// <summary>
/// This event is raised when UI buttons are set to visible.
/// </summary>
public event UIEventHandler ShowUIButtons;
/// <summary>
/// This event is raised when a Placed Sticker is selected. Instance ID (int) as parameter.
/// </summary>
public event SelectStickerEventHandler SelectSticker;
#endregion
/// <summary>
/// Is UI currently hidden or not.
/// </summary>
public bool isUIHidden;
private void Awake()
{
if(Instance == null)
{
Instance = this;
}
else
{
Destroy(this);
}
}
private void Start()
{
if(GameController.Instance != null)
{
GameController.Instance.WorldActivated += ShowUI;
WorldManager.Instance.WorldSelected += HideUI;
GameController.Instance.GameControllerReady += HideUI;
}
}
#region EVENT DELEGATES
/// <summary>
/// Raises SelectSticker event with given sticker instance ID.
/// </summary>
/// <param name="id">Instance ID of the Sticker.</param>
public void OnSelectSticker(int id)
{
if(SelectSticker != null)
{
SelectSticker(id);
}
}
/// <summary>
/// Raises ShowSettings event.
/// </summary>
public void OnShowSettings()
{
if (ShowSettings != null)
{
ShowSettings();
}
}
/// <summary>
/// Raises StickerbookDragStarted event.
/// </summary>
public void OnStickerbookDragStarted()
{
if (StickerbookDragStarted != null)
{
StickerbookDragStarted();
}
}
/// <summary>
/// Raises HideSettings event.
/// </summary>
public void OnHideSettings()
{
if (HideSettings != null)
{
HideSettings();
}
}
/// <summary>
/// Raises ShowStickerBook event.
/// </summary>
public void OnShowStickerBook()
{
if (ShowStickerBook != null)
{
ShowStickerBook();
}
}
/// <summary>
/// Raises HideStickerBook event.
/// </summary>
public void OnHideStickerBook()
{
if (HideStickerBook != null)
{
HideStickerBook();
}
}
/// <summary>
/// Raises ShowWorldButtons event.
/// </summary>
public void OnShowWorldButtons()
{
if (ShowWorldButtons != null)
{
ShowWorldButtons();
}
}
/// <summary>
/// Raises HideWorldButtons event.
/// </summary>
public void OnHideWorldButtons()
{
if (HideWorldButtons != null)
{
HideWorldButtons();
}
}
/// <summary>
/// Raises ToggleWorldButtons event.
/// </summary>
public void OnToggleWorldButtons()
{
if (ToggleWorldButtons != null)
{
ToggleWorldButtons();
}
}
/// <summary>
/// Raises ToggleSettings event.
/// </summary>
public void OnToggleSettings()
{
if (ToggleSettings != null)
{
ToggleSettings();
}
}
#endregion
/// <summary>
/// Updates currently active world button with given world.
/// </summary>
/// <param name="world">New world that is active.</param>
public void UpdateMainWorldButton(WorldManager.WorldID world)
{
if (UpdateMainWorldButtonEvent != null) {
UpdateMainWorldButtonEvent(world);
}
}
/// <summary>
/// Hides World Selection Buttons and StickerBook Drag object.
/// </summary>
public void HideUI()
{
if(HideUIButtons != null)
{
isUIHidden = true;
HideUIButtons();
}
}
/// <summary>
/// Shows World Selection Buttons and StickerBook Drag object.
/// </summary>
public void ShowUI()
{
if (ShowUIButtons != null)
{
isUIHidden = false;
ShowUIButtons();
}
}
}
|
d47fb4fdc344afc15c5e54f88fea9056c6326646
|
C#
|
Winvision/Sandboxable
|
/src/Hyak.Common/RetryHandler.cs
| 2.625
| 3
|
using Sandboxable.Hyak.Common.Properties;
using Sandboxable.Hyak.Common.TransientFaultHandling;
using System;
using System.Globalization;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Sandboxable.Hyak.Common
{
/// <summary>
/// Http retry handler.
/// </summary>
public class RetryHandler : DelegatingHandler
{
private readonly TimeSpan DefaultMinBackoff = new TimeSpan(0, 0, 1);
private readonly TimeSpan DefaultMaxBackoff = new TimeSpan(0, 0, 10);
private readonly TimeSpan DefaultBackoffDelta = new TimeSpan(0, 0, 10);
/// <summary>
/// Gets or sets retry policy.
/// </summary>
public RetryPolicy RetryPolicy
{
get;
set;
}
/// <summary>
/// Initializes a new instance of the <see cref="T:Hyak.Common.RetryHandler" /> class. Sets
/// default retry policty base on Exponential Backoff.
/// </summary>
public RetryHandler()
{
var exponentialBackoff = new ExponentialBackoff(3, this.DefaultMinBackoff, this.DefaultMaxBackoff, this.DefaultBackoffDelta);
this.RetryPolicy = new RetryPolicy<DefaultHttpErrorDetectionStrategy>(exponentialBackoff);
}
/// <summary>
/// Initializes a new instance of the <see cref="T:Hyak.Common.RetryHandler" /> class. Sets
/// the default retry policty base on Exponential Backoff.
/// </summary>
/// <param name="innerHandler">Inner http handler.</param>
public RetryHandler(DelegatingHandler innerHandler) : base(innerHandler)
{
var exponentialBackoff = new ExponentialBackoff(3, this.DefaultMinBackoff, this.DefaultMaxBackoff, this.DefaultBackoffDelta);
this.RetryPolicy = new RetryPolicy<DefaultHttpErrorDetectionStrategy>(exponentialBackoff);
}
/// <summary>
/// Initializes a new instance of the <see cref="T:Hyak.Common.RetryHandler" /> class.
/// </summary>
/// <param name="retryPolicy">Retry policy to use.</param>
/// <param name="innerHandler">Inner http handler.</param>
public RetryHandler(RetryPolicy retryPolicy, DelegatingHandler innerHandler) : base(innerHandler)
{
if (retryPolicy == null)
{
throw new ArgumentNullException(nameof(retryPolicy));
}
this.RetryPolicy = retryPolicy;
}
/// <summary>
/// Sends an HTTP request to the inner handler to send to the server as an asynchronous
/// operation. Retries request if needed based on Retry Policy.
/// </summary>
/// <param name="request">The HTTP request message to send to the server.</param>
/// <param name="cancellationToken">A cancellation token to cancel operation.</param>
/// <returns>Returns System.Threading.Tasks.Task<TResult>. The
/// task object representing the asynchronous operation.</returns>
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
this.RetryPolicy.Retrying += (sender, args) =>
{
if (this.Retrying == null)
{
return;
}
this.Retrying(sender, args);
};
HttpResponseMessage responseMessage = null;
try
{
await this.RetryPolicy.ExecuteAsync(async () =>
{
responseMessage = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
if (!responseMessage.IsSuccessStatusCode)
{
throw new HttpRequestExceptionWithStatus(string.Format(CultureInfo.InvariantCulture, Resources.ResponseStatusCodeError, responseMessage.StatusCode, responseMessage.StatusCode))
{
StatusCode = responseMessage.StatusCode
};
}
return responseMessage;
}, cancellationToken).ConfigureAwait(false);
return responseMessage;
}
catch
{
if (responseMessage != null)
{
return responseMessage;
}
throw;
}
}
/// <summary>
/// An instance of a callback delegate that will be invoked whenever a retry condition is encountered.
/// </summary>
public event EventHandler<RetryingEventArgs> Retrying;
}
}
|
f633d50730871f9b95deb3bf4d65d77e95340887
|
C#
|
SeregaFreeman/TeststackCalculator
|
/Calculator/CalculatorTest.cs
| 2.578125
| 3
|
using NUnit.Framework;
using Calculator.utils;
using Calculator.windows;
using TestStack.White;
using System.Threading;
namespace Calculator
{
[TestFixture]
public class CalculatorTest
{
private Application _app;
[SetUp]
public void StartApp()
{
LoggerUtil.InitLogger();
LoggerUtil.Log.Info("Test started");
ProcessesUtil.CloseAllProcessesByName(Settings.Default.processName);
_app = App.GetInstance().GetApplication();
LoggerUtil.Log.Info("Precondition completed");
}
[Test]
public void UiTest()
{
MainWindow mainWindow = new MainWindow(_app);
mainWindow.SelectMode("Standard");
mainWindow.EnterNumber(12);
Thread.Sleep(1000);
mainWindow.AddNumber(999);
Thread.Sleep(1000);
mainWindow.RememberResult();
mainWindow.EnterNumber(19);
mainWindow.PressAdd();
Thread.Sleep(1000);
mainWindow.GetNumberFromMemory();
mainWindow.PressEquals();
Assert.True("1030".Equals(mainWindow.GetResult()));
}
[TearDown]
public void Cleanup()
{
_app.Kill();
LoggerUtil.Log.Info("Test finished\n");
}
}
}
|
e6492395c4b67e6192232533764e7eb52f2bc768
|
C#
|
M-Kersten/space-invaders
|
/innerspace-invaders/Assets/Scripts/Tools/CustomMaths.cs
| 3.390625
| 3
|
namespace Invaders.Tools
{
public static class CustomMaths
{
public static int CalculateFibonacci(int n)
{
if (n < 1)
{
UnityEngine.Debug.LogError($"number to get fibonacci for is {n}, this is lower than 1 and cannot be used in calculation");
return 0;
}
int fibNumber = n + 1;
int[] fibonacci = new int[fibNumber + 1];
fibonacci[0] = 0;
fibonacci[1] = 1;
for (int i = 2; i <= fibNumber; i++)
{
fibonacci[i] = fibonacci[i - 2] + fibonacci[i - 1];
}
return fibonacci[fibNumber];
}
}
}
|
2ff08b0ba61782d0fe897802851c64fc616cb345
|
C#
|
zsolti111/CFGlib
|
/CFGlib/CFGlib/CFGNode.cs
| 2.6875
| 3
|
using CFGlib;
using dnlib.DotNet.Emit;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Xml.Serialization;
namespace CFGlib
{
public class CFGNode
{
public int Id
{
get; set;
}
public Instruction Footer
{
get; set;
}
public Instruction Header
{
get; set;
}
public ControlFlowBlockType Type
{
get; set;
}
public uint ILOffset
{
get; set;
}
public enum NodeShape
{
Ellipse,
Rectangle
}
public enum NodeBorder
{
Single,
Double
}
public enum NodeColor
{
White,
Green,
Orange,
Red,
Indigo,
Blue,
None
}
[Browsable(false)]
[ReadOnly(true)]
public NodeColor Color
{
get; set;
}
[Category("Node details")]
[DisplayName("Generated test code")]
[Description("The generated source code if it is a leaf node and a test was generated (e.g., not a duplicate).")]
[ReadOnly(true)]
[XmlAttribute("gtc")]
public string GenerateTestCode
{
get; set;
}
[Category("Node details")]
[DisplayName("Node status")]
[Description("Status of the node indicating whether there are remaining uncovered branches starting from this node.")]
[ReadOnly(true)]
[XmlAttribute("status")]
public string Status
{
get; set;
}
[Category("Node details")]
[DisplayName("Execution runs")]
[Description("The list of executions that this node was involved in.")]
[ReadOnly(true)]
[XmlAttribute("runs")]
public string Runs
{
get; set;
}
[Category("Node details")]
[DisplayName("Method name")]
[Description("Fully qualified name of the method that contains this node.")]
[ReadOnly(true)]
[XmlAttribute("method")]
public string MethodName
{
get; set;
}
[Category("Node appearance")]
[DisplayName("Shape (solver calls)")]
[Description("Shape of the node determines if the node triggered a constraint solver call. If yes, the shape is an ellipse, otherwise it is a rectangle.")]
[ReadOnly(true)]
public NodeShape Shape
{
get; set;
}
[Category("Node details")]
[DisplayName("Path condition")]
[Description("Full form of the path condition that contains all constraints from the start.")]
[ReadOnly(true)]
[XmlAttribute("pc")]
public string PathCondition
{
get; set;
}
[Category("Node details")]
[DisplayName("Incremental path condition")]
[Description("Incremental form of the path condition, compared to its parent node.")]
[ReadOnly(true)]
[XmlAttribute("ipc")]
public string IncrementalPathCondition
{
get; set;
}
[Category("Node details")]
[DisplayName("Source code mapping")]
[Description("Aprroximation of the place in the source code.")]
[ReadOnly(true)]
[XmlAttribute("scm")]
public string SourceCodeMappingString
{
get; set;
}
[Category("Node appearance")]
[DisplayName("Border (source mapping)")]
[Description("Border of the node determines if the node has exact source code location mapping. If yes, the border is doubled, otherwise the border is single.")]
[ReadOnly(true)]
public NodeBorder Border
{
get; set;
}
private Stack<NodeColor> originalColors = new Stack<NodeColor>();
public bool IsSelected
{
get; set;
}
public void Deselect ()
{
IsSelected = false;
RevertToOriginalColor();
}
public void RevertToOriginalColor ()
{
NodeColor o;
if (originalColors.Count == 1)
o = originalColors.Peek();
else
o = originalColors.Pop();
if (o != Color)
{
Color = o;
}
}
public bool IsCollapsed
{
get; set;
}
public HashSet<CFGNode> CollapsedSubtreeNodes
{
get; private set;
}
public HashSet<CFGEdge> CollapsedSubtreeEdges
{
get; private set;
}
public CFGNode ( int id, Instruction footer, Instruction header, ControlFlowBlockType type, uint iLOffset, bool solverCall )
{
Id = id;
Footer = footer;
Header = header;
Type = type;
ILOffset = iLOffset;
Shape = ( solverCall ) ? NodeShape.Ellipse : NodeShape.Rectangle;
}
public CFGNode ( int id, bool solverCall )
{
Id = id;
Shape = ( solverCall ) ? NodeShape.Ellipse : NodeShape.Rectangle;
}
public override string ToString ()
{
return Id.ToString();
}
public static CFGNode Factory ( string id )
{
return new CFGNode(int.Parse(id), false);
}
public void Select ()
{
IsSelected = true;
NodeColor o = originalColors.Peek();
//else o = originalColors.Pop();
if (o != NodeColor.Blue)
{
originalColors.Push(Color);
Color = NodeColor.Blue;
}
}
public void Collapse ()
{
NodeColor o;
if (originalColors.Count == 1)
o = originalColors.Peek();
else
o = originalColors.Pop();
if (o != NodeColor.Indigo)
{
originalColors.Push(Color);
Color = NodeColor.Indigo;
}
}
public void Expand ()
{
if (IsSelected)
{
originalColors.Pop();
}
RevertToOriginalColor();
}
}
}
|
a4b2a05f6cc548bd8333269a591d3d1435165a30
|
C#
|
surfsky/AppPlat4
|
/Utils/App.UtilsTests/Serialization/JsonHelperTests.cs
| 2.546875
| 3
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using App.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace App.Utils.Tests
{
[TestClass()]
public class JsonHelperTests
{
[TestMethod()]
public void ParseJsonTest()
{
Person p = new Person("Kevin");
var txt = p.ToJson();
var o = txt.ParseJson<Person>();
Assert.AreEqual(p.Name, o.Name);
txt = "blabla";
o = txt.ParseJson<Person>(true, null);
Assert.AreEqual(o, null);
}
}
}
|
051ba45aab970ebcf7b05b9ac50ac646ff799820
|
C#
|
cjlpowers/Inaugura
|
/Inaugura.RealLeads/LevelCollection.cs
| 3.328125
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
namespace Inaugura.RealLeads
{
/// <summary>
/// A collection of levels
/// </summary>
public class LevelCollection : System.Collections.CollectionBase, Inaugura.Xml.IXmlable
{
#region Variables
#endregion
#region Accessors
/// <summary>
/// Returns the level at the specified zero based index
/// </summary>
/// <param name="index">The zero based index into the collection</param>
/// <returns>The level at the specified index</returns>
public Level this[int index]
{
get
{
return this.List[index] as Level;
}
}
/// <summary>
/// Returns the level with a specific ID
/// </summary>
/// <param name="id">The ID of the level</param>
/// <returns>The level with the specified ID</returns>
[Obsolete()]
public Level this[string id]
{
get
{
Guid guid = new Guid(id);
return this[guid];
}
}
/// <summary>
/// Returns the level with a specific ID
/// </summary>
/// <param name="id">The ID of the level</param>
/// <returns>The level with the specified ID</returns>
public Level this[Guid id]
{
get
{
foreach (Level level in this)
{
if (level.ID == id)
return level;
}
return null;
}
}
#endregion
#region IXmlable Members
/// <summary>
/// The xml representation of the the instance
/// </summary>
public XmlNode Xml
{
get
{
XmlNode node = Inaugura.Xml.Helper.NewNodeDocument("Levels");
this.PopulateNode(node);
return node;
}
}
#endregion
#region Method
/// <summary>
/// Constructor
/// </summary>
/// <param name="node">The xml node which represents the instance</param>
public LevelCollection(XmlNode node)
{
this.PopulateInstance(node);
}
/// <summary>
/// Constructor
/// </summary>
public LevelCollection()
{
}
/// <summary>
/// Adds a level to the collection
/// </summary>
/// <param name="level">The level to add</param>
public void Add(Level level)
{
this.List.Add(level);
}
/// <summary>
/// Removes a level from the collection
/// </summary>
/// <param name="level">The level to remove</param>
public void Remove(Level level)
{
this.List.Remove(level);
}
/// <summary>
/// Determins wheather the collection contains a level
/// </summary>
/// <param name="level">The level</param>
/// <returns>True if the collection contains the level, false otherwise</returns>
public bool Contains(Level level)
{
return this.List.Contains(level);
}
/// <summary>
/// Gets a level which contains a specific room
/// </summary>
/// <param name="roomID">The id of the room</param>
/// <returns>The level containing the room, otherwise null</returns>
public Level GetLevelByRoom(Guid roomID)
{
foreach (Level level in this)
{
if (level.Rooms[roomID] != null)
return level;
}
return null;
}
/// <summary>
/// Moves a level up in the list
/// </summary>
/// <param name="levelID">The ID of the level</param>
public void MoveUp(string levelID)
{
Level r = this[levelID];
if (r != null)
this.MoveUp(r);
}
/// <summary>
/// Moves a level up in the list
/// </summary>
/// <param name="level">The level to move</param>
public void MoveUp(Level level)
{
if (level == null)
return;
lock (this.List)
{
if (this.List.Contains(level))
{
int index = this.List.IndexOf(level);
if (index != 0)
{
index--;
this.List.Remove(level);
this.List.Insert(index, level);
}
}
}
}
/// <summary>
/// Moves a level down in the list
/// </summary>
/// <param name="levelID">The level ID</param>
public void MoveDown(string levelID)
{
Level r = this[levelID];
if (r != null)
this.MoveDown(r);
}
/// <summary>
/// Moves a room down in the list
/// </summary>
/// <param name="level">The level to move</param>
public void MoveDown(Level level)
{
if (level == null)
return;
lock (this.List)
{
if (this.List.Contains(level))
{
int index = this.List.IndexOf(level);
if (index != this.List.Count - 1)
{
index++;
this.List.Remove(level);
this.List.Insert(index, level);
}
}
}
}
/// <summary>
/// Determins the index of a specific level in the list
/// </summary>
/// <param name="level">The level</param>
/// <returns>The index</returns>
public int IndexOf(Level level)
{
lock (this.List)
{
return this.List.IndexOf(level);
}
}
/// <summary>
/// Populates a xml node with the objects data
/// </summary>
/// <param name="node">The node to populate</param>
public virtual void PopulateNode(XmlNode node)
{
foreach (Level level in this)
{
XmlNode levelNode = node.OwnerDocument.CreateElement("Level");
level.PopulateNode(levelNode);
node.AppendChild(levelNode);
}
}
/// <summary>
/// Populates the instance with the specifed xml data
/// </summary>
/// <param name="node">The xml node</param>
public virtual void PopulateInstance(XmlNode node)
{
XmlNodeList nodes = node.SelectNodes("Level");
foreach (XmlNode levelNode in nodes)
{
Level level = new Level(levelNode);
this.Add(level);
}
}
#endregion
}
}
|
c11080d342757e95ea7979e5c6e0d3f2022ca0e8
|
C#
|
MargaritaKolosok/CSharp
|
/Starter/Lesson_9/Task_1-1/Task_1-1/Program.cs
| 3.875
| 4
|
using System;
namespace Task_1_1
{
class Program
{
// Create First Array with set by User arrLength, and random values
static int[] CreateArray(int[] array, int arrLength)
{
for (int i=0; i<array.Length; i++)
{
array[i] = arrLength * (i+1) + 2*i;
}
return array;
}
// Check max, min, avarage, Sum of elements of the array
static void ArrayAnalysis(int[] array, out int max, out int min, out int avarage, out int SumEl)
{
max = 0;
min = array[1];
avarage = 0;
int Sum = 0;
for (int i=0; i<array.Length; i++)
{
if (array[i] > max)
{
max = array[i];
}
if (array[i] < min)
{
min = array[i];
}
Sum += array[i];
}
SumEl = Sum;
avarage = Sum / array.Length;
}
// Check number of even numbers in the array
static int EvenNum(int[] array, out int evenNum)
{
evenNum = 0;
for (int i=0; i<array.Length; i++)
{
if (IsEven(array[i]))
{
evenNum++;
}
}
return evenNum;
}
// Check is array elements value Even
static bool IsEven(int Num)
{
bool result = false;
if (Num % 2 != 0)
{
result = true;
}
else
{
result = false;
}
return result;
}
// Create new Even array with length equal to its even elements. Save even elements of the array to even array
static void CreateEvenArray(int[] array, ref int evenNum, out int[] myEvenArray)
{
int[] evenArray = new int[evenNum];
int j = 0;
for (int i=0; i<array.Length; i++)
{
if (IsEven(array[i]))
{
evenArray[j] = array[i];
j++;
}
}
myEvenArray = evenArray;
}
static void Main(string[] args)
{
Console.WriteLine("Enter number of array elements:");
// User enters Number of Array elements
int arrLength = Convert.ToInt32(Console.ReadLine());
// Create myArray
int[] myArray = new int [arrLength];
myArray = CreateArray(myArray, arrLength);
// Check min, max, avarage, Sum numbers in the array
ArrayAnalysis(myArray, out int maxValue, out int minValue, out int avarageValue, out int SumValue);
// Show Array that was Created
for (int i=0; i<myArray.Length; i++)
{
Console.WriteLine("Array element {0}", myArray[i]);
}
// Array Analysis result
Console.WriteLine("Array MAX element {0}, Array MIN element {1}, Array AVARAGE {2}, Sum of elements {3}", maxValue, minValue, avarageValue, SumValue);
Console.WriteLine("Even numbers in array {0}", EvenNum(myArray, out int evenNumbers));
CreateEvenArray(myArray, ref evenNumbers, out int[] myEvenArray);
for (int i = 0; i < myEvenArray.Length; i++)
{
Console.WriteLine("Array EVEN element {0}", myEvenArray[i]);
}
Console.ReadKey();
}
}
}
|
bf941c801c3e4ce9b53345c993ee2023365961fe
|
C#
|
GrupoAura/Developer
|
/Inventario/Vistas/Clientes/listClientes.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;
namespace inventory.Vistas.Clientes
{
class listClientes : Panel
{
public SqlConnection conection;
public Panel list()
{
InitializeComponent();
try
{
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT * FROM usuarios", conection);
conection.Open();
System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows == true)
{
while (reader.Read())
{
MessageBox.Show(String.Format("{0}", reader["usuario"]) + " " + String.Format("{0}", reader["usuario"]));
}
reader.Close();
}
else
{
//RETORNO = false;
//ERROR = "El Usuario o Contraseña son incorrectas.";
}
}
catch (Exception err)
{
MessageBox.Show("Hola - " + err.Message);
//ERROR = "La Conexion con el servidor fallo.\n"
/* + "Posibles Causas:\n "
+ "\t1. Su computadora no tiene conexion a la red.\n"
+ "\t2. El servidor no esta accesible.\n"
+ "Por favor intente mas tarde. Si el problema persiste pongase en contacto con el administrador del sistema.";*/
//RETORNO = false;
}
finally
{
//conection.Close();
}
return this;
}
private void InitializeComponent()
{
this.SuspendLayout();
this.ResumeLayout(false);
}
}
}
|
ef7ccd93f309a3140a76c82ea4c1ab03345a01a6
|
C#
|
jknopp/RedisCacheLib
|
/CacheStack/CacheTrigger.cs
| 2.515625
| 3
|
namespace CacheStack
{
public interface ICacheTrigger
{
/// <summary>
/// Key to store cache keys for items watching updates to any item
/// </summary>
string CacheKeyForAnyItem { get; }
/// <summary>
/// Key to store cache keys for an individual item
/// </summary>
string CacheKeyForIndividualItem { get; }
}
public class CacheTrigger : ICacheTrigger
{
public string CacheKeyForAnyItem { get; set; }
public string CacheKeyForIndividualItem { get; set; }
}
}
|
85ddfbe8d9ac85a9a320f2477b0109dad7c3b5e2
|
C#
|
michelgrootjans/qwars
|
/src/QWars.NHibernate.Tests/GangCrudTests.cs
| 2.71875
| 3
|
using System.Linq;
using NUnit.Framework;
using QWars.NHibernate.Entities;
namespace QWars.NHibernate.Tests
{
[TestFixture]
public class GangCrudTests : DataAccessTest
{
private object gangId;
private object bossId;
private const string gangName = "Los Techies";
protected override void PrepareData()
{
var boss = new Player("boss");
var gang = boss.CreateGang(gangName, "yeah");
session.Save(boss);
gangId = session.GetIdentifier(gang);
bossId = session.GetIdentifier(boss);
}
[Test]
public void should_be_able_to_get_gang_from_db()
{
var gang = session.Get<Gang>(gangId);
Assert.AreEqual(gangName, gang.Name);
}
[Test]
public void gang_boss_should_be_player()
{
var player = session.Get<Player>(bossId);
var gang = session.Get<Gang>(gangId);
Assert.AreSame(player, gang.Boss);
}
[Test]
public void added_member_should_be_persisted()
{
var gang = session.Get<Gang>(gangId);
var member = new Player("member");
session.Save(member);
member.Join(gang);
FlushAndClear();
gang = session.Get<Gang>(gangId);
Assert.AreEqual(1, gang.Members.Count());
}
[Test]
public void added_task_should_be_persisted()
{
var gang = session.Get<Gang>(gangId);
gang.CreateTask("do it", 1, 2, 3);
FlushAndClear();
gang = session.Get<Gang>(gangId);
Assert.AreEqual(1, gang.Tasks.Count());
}
}
}
|
1849e96d2ec12e8740cfeab53407d051723856e1
|
C#
|
KashaTeplaya/CalkulVADANDR
|
/CALKULATOR/CALKULATOR.tests/TwoArgumentsOperations/DivTest.cs
| 2.671875
| 3
|
using System;
using CALKULATOR.TwoArgumentsOperations;
using NUnit.Framework;
namespace CALKULATOR.tests.TwoArgumentsOperations
{
[TestFixture]
public class DivTest
{
[Test]
public void CalculateTest()
{
ITwoArgumentsCalculator calculator = new Div();
double result = calculator.Calculate(10, 5);
Assert.AreEqual(2, result);
}
[Test]
public void ErrorTest()
{
var calculator = new Div();
Assert.Throws<Exception>(() => calculator.Calculate(-5, 0));
}
}
}
|
2e64558a180c2f5c5e25ef08428dfc841849a4d3
|
C#
|
CodeMasterZeroOne/Event-Driven-Programming
|
/Exercise 02/Submision414/SimpleGenericLoginSystem/SimpleGenericLoginSystem/RegisterForm.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SimpleGenericLoginSystem
{
public partial class RegisterForm : Form
{
private Form callingForm;
private HelpForm helpForm;
private User user;
/// <summary>
/// Public method for initialization of the values.
/// </summary>
/// <param name="callingForm"></param>
public RegisterForm(Form callingForm)
{
this.callingForm = callingForm;
this.user = new User();
InitializeComponent();
}
private void RegisterForm_Load(object sender, EventArgs e)
{
comboBoxInputRole.SelectedIndex = 0;
}
private void buttonCancelRegistration_Click(object sender, EventArgs e)
{
this.Close();
callingForm.Show();
}
private void buttonRegisterUser_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(textBoxInputFirstName.Text) ||
String.IsNullOrEmpty(textBoxInputLastName.Text) ||
String.IsNullOrEmpty(textBoxInputUserID.Text) ||
String.IsNullOrEmpty(textBoxInputPassword.Text) ||
String.IsNullOrEmpty(textBoxInputEmail.Text))
{
string message = "Fields required are:\nFirst Name:\nLast Name:\nUser ID:\nPassword:\nEmail:\n";
string caption = "New User";
MessageBoxButtons buttons = MessageBoxButtons.OK;
MessageBox.Show(message, caption, buttons, MessageBoxIcon.Exclamation);
}
else
{
string message = "New user registered successfully.";
string caption = "New User";
MessageBoxButtons buttons = MessageBoxButtons.OK;
MessageBox.Show(message, caption, buttons, MessageBoxIcon.Asterisk);
callingForm.Show();
}
}
private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
helpForm = new HelpForm();
helpForm.Show();
}
private void comboBoxInputRole_SelectedIndexChanged(object sender, EventArgs e)
{
user.setUsersRole(comboBoxInputRole.SelectedIndex);
labelUserPrivilages.Text = "User privilages: " +
"\nView Account Information: " + user.ViewAccountInformation +
" View Account Balances: " + user.ViewAccountBalances +
"\nManage Account: " + user.ManageAccount +
" Authorise Account Payments: " + user.AuthoriseAccountPayments +
"\nInput Account Payments: " + user.InputAccountPayments +
" View Audit Records: " + user.ViewAuditRecords +
"\nGenerate Audit Records: " + user.GenerateAuditRecords +
" Administration Report Privileges: " + user.AdministrationReportPrivileges +
"\nAdministration Full Access: " + user.AdministrationFullAccess;
}
}
}
|
455530d0559df906ca409cb635f79ef06c52dade
|
C#
|
atanas-georgiev/TelerikAcademy
|
/16.ASP.NET-Web-Forms/Homeworks/TestExam/TestExam.WebForms/Admin/Categories.aspx.cs
| 2.609375
| 3
|
using System;
using System.Data.Entity.Infrastructure;
using System.Linq;
using TestExam.Data.Models;
using TestExam.Data.Repositories;
namespace TestExam.WebForms.Admin
{
public partial class Categories : System.Web.UI.Page
{
GenericRepository<Category> categories = new GenericRepository<Category>();
protected void Page_Load(object sender, EventArgs e)
{
}
public IQueryable<Category> GridViewCategories_SelectItem()
{
return categories.All().OrderBy(c => c.Id); ;
}
public void GridViewCategories_UpdateItem(int id)
{
var category = categories.All().FirstOrDefault(c => c.Id == id);
if (category != null)
{
TryUpdateModel(category);
if (ModelState.IsValid)
{
try
{
categories.SaveChanges();
}
catch (DbUpdateException)
{
CustomValidator.IsValid = false;
CustomValidator.ErrorMessage = $"Category {category.Name} already exists";
}
}
}
this.GridViewCategories.DataBind();
}
public void GridViewCategories_DeleteItem(int id)
{
try
{
categories.Delete(id);
categories.SaveChanges();
}
catch (Exception)
{
CustomValidator.IsValid = false;
CustomValidator.ErrorMessage = "Error during update";
}
this.GridViewCategories.DataBind();
}
protected void ButtonInsertCategory_OnClick(object sender, EventArgs e)
{
var newCategory = new Category()
{
Name = this.TextBoxNewCategory.Text
};
try
{
categories.Add(newCategory);
categories.SaveChanges();
}
catch (Exception)
{
CustomValidator.IsValid = false;
CustomValidator.ErrorMessage = $"Category {newCategory.Name} already exists";
}
this.GridViewCategories.DataBind();
}
protected void ButtonCancel_OnClick(object sender, EventArgs e)
{
this.TextBoxNewCategory.Text = string.Empty;
}
}
}
|
43fa93bde227e1fee59318456011945042dd9904
|
C#
|
mygithubnelsonr/AdvancedProgramming
|
/ExtensionMethods/Program.cs
| 3
| 3
|
using System;
namespace ExtensionMethods
{
class Program
{
static void Main(string[] args)
{
// string von https://de.lipsum.com/
string post = "Lorem ipsum dolor sit amet, consectetur adipiscing elit Etiam lacus.";
var shortedPost = post.Shorten(0);
Console.WriteLine(shortedPost + " ...");
#if DEBUG
Console.WriteLine("press any key to finish");
Console.ReadKey();
#endif
}
}
}
|
be0b87ff8861ca271449490b5a83bb2724edd997
|
C#
|
shendongnian/download4
|
/code3/390704-8578888-19287601-1.cs
| 3.265625
| 3
|
private void Form1_Load(object sender, EventArgs e)
{
SetupClickEvents(this);
}
/// <summary>
/// This will loop through each control within the container and add a click handler to it
/// </summary>
/// <param name="container">The container whose children to handle clicks for</param>
private void SetupClickEvents(Control container)
{
foreach(Control control in container.Controls)
{
control.Click += (s, e) => { HandleClicks(s, e); };
}
}
private void HandleClicks(object sender, EventArgs e)
{
Control control = (Control)sender;
MessageBox.Show(string.Format("{0} was clicked!", control.Name));
}
|
b669fa72ffbd0110a49c6b44b6bbaeef74df3859
|
C#
|
thesilentpsycho/PongUnity3D
|
/Assets/Scenes/GameManager.cs
| 2.640625
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour {
public Ball ball;
public Paddle leftPaddle;
public Paddle rightPaddle;
public Text victoryMessage;
public int leftPlayerLife = 0;
public int rightPlayerLife = 0;
public int scoreToWin = 3;
public Text LeftHealthText;
public Text RightHealthText;
public static bool restartGame;
public static Vector2 bottomLeft;
public static Vector2 topRight;
// Use this for initialization
void Start () {
bottomLeft = Camera.main.ScreenToWorldPoint(new Vector2(0, 0));
topRight = Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, Screen.height));
}
void Update()
{
}
public void UpdateScore(string player)
{
if (player.Equals("left"))
{
Debug.Log("update score called");
leftPlayerLife += 1;
LeftHealthText.text = "Points: " + leftPlayerLife;
}
else if (player.Equals("right"))
{
Debug.Log("update score called");
rightPlayerLife += 1;
RightHealthText.text = "Points: " + rightPlayerLife;
}
CheckIfGameIsWon();
}
private void CheckIfGameIsWon()
{
if (leftPlayerLife >= scoreToWin) HandleEndGame("left");
else if (rightPlayerLife >= scoreToWin) HandleEndGame("right");
}
public void HandleEndGame(string playerWhoWon)
{
DisplayEndMessage(playerWhoWon);
}
public void DisplayEndMessage(string playerWhoWon)
{
string victoryMessage = "Player ";
if(playerWhoWon == "left")
{
victoryMessage += "1 Won !!";
}
else
{
victoryMessage += "2 Won !!";
}
this.victoryMessage.text = victoryMessage;
Time.timeScale = 0;
}
}
|
b77c9993cad976a83c416e2ea256f507126cfad1
|
C#
|
Marcossdavi00/LojaVirtual
|
/ApiLojaVirtual/Service/Service/ServiceProducts.cs
| 2.578125
| 3
|
using Domain.Entity;
using Domain.Interfaces.Repository;
using Domain.Interfaces.Service;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Service.Service
{
public class ServiceProducts: IServiceProduct
{
private readonly IRepositoryProducts _repository;
public ServiceProducts(IRepositoryProducts repository)
{
_repository = repository;
}
public async Task<bool> Delete(int Id)
{
return await _repository.Delete(Id);
}
public async Task<IList<ProductEntity>> FindAll()
{
return await _repository.FindAll();
}
public async Task<ProductEntity> FindById(int id)
{
return await _repository.FindById(id);
}
public async Task<ProductEntity> FindName(string name)
{
return await _repository.FindName(name);
}
public async Task<ProductEntity> Insert(ProductEntity product)
{
return await _repository.Insert(product);
}
public async Task<ProductEntity> Update(ProductEntity product)
{
return await _repository.Update(product);
}
}
}
|
4ed373b8c05838d727a8f12653eded01d227d884
|
C#
|
young-hwang/OOP_with_.Net
|
/CodeAnalysis2/Form1.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CodeAnalysis2
{
public partial class Form1 : Form
{
private Classes m_classes = new Classes();
public Form1()
{
InitializeComponent();
}
private void DisplayClasses()
{
AClass[] classes = new AClass[m_classes.Count];
for (int i = 0; i < m_classes.Count; i++)
{
//Using the indexer
classes[i] = m_classes[i];
}
this.listOfFiles.DataSource = classes;
linesOfCode.Text = "Lines of code: " + m_classes.LinesOfCode.ToString();
}
private void browse_Click(object sender, EventArgs e)
{
try
{
openSourceFile.Filter = "Visual C# files (*.cs)|*.cs";
System.Windows.Forms.DialogResult result;
result = openSourceFile.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
m_classes.ReadFromFile(openSourceFile.FileName);
}
DisplayClasses();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
|
e45b136a68fa8b01a94c8e084f09d89500abd25c
|
C#
|
Zuravvski/Mobile-Robots-Project
|
/robotymobilne_projekt/robotymobilne_projekt/GUI/ViewModels/Manual/ManualViewModel.cs
| 2.78125
| 3
|
using robotymobilne_projekt.GUI.Views.Manual;
using System.Collections.ObjectModel;
using System.Windows.Input;
namespace robotymobilne_projekt.GUI.ViewModels.Manual
{
public class ManualViewModel : ViewModel
{
private ICommand addUser;
private ICommand removeUser;
#region Setters & Getters
public int Rows { set; get; }
public int Cols { set; get; }
public ObservableCollection<UserInterface> Users { get; }
#endregion
public ManualViewModel()
{
Users = new ObservableCollection<UserInterface>();
}
#region Actions
public ICommand AddUser
{
get
{
if (null == addUser)
{
addUser = new DelegateCommand(delegate ()
{
if (Users.Count < 4)
{
var newUser = new UserInterface {DataContext = new UserViewModel(this)};
Users.Add(newUser);
manageLayout();
}
});
}
return addUser;
}
}
public ICommand RemoveUser
{
get
{
if(null == removeUser)
{
removeUser = new DelegateCommand<RobotViewModel>(delegate (RobotViewModel userVM)
{
for(int i = 0; i < Users.Count; i++)
{
if(Users[i].DataContext.Equals(userVM))
{
Users.Remove(Users[i]);
manageLayout();
}
}
});
}
return removeUser;
}
}
#endregion
#region Helper Methods
private void manageLayout()
{
switch (Users.Count)
{
case 1:
Rows = 1;
Cols = 1;
break;
case 2:
Rows = 1;
Cols = 2;
break;
case 3:
case 4:
Rows = 2;
Cols = 2;
break;
default:
Rows = 0;
Cols = 0;
break;
}
}
#endregion
}
}
|
5bfed6eeb1caa5c0d931760fa53456978f30ca02
|
C#
|
nnaabbcc/exercise
|
/windows/pw6e.official/CSharp/Chapter14/CustomGradient/CustomGradient/MainPage.xaml.cs
| 2.703125
| 3
|
using System.IO;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
namespace CustomGradient
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
Loaded += OnMainPageLoaded;
}
async void OnMainPageLoaded(object sender, RoutedEventArgs args)
{
WriteableBitmap bitmap = new WriteableBitmap(256, 256);
byte[] pixels = new byte[4 * bitmap.PixelWidth * bitmap.PixelHeight];
for (int y = 0; y < bitmap.PixelHeight; y++)
for (int x = 0; x < bitmap.PixelWidth; x++)
{
int index = 4 * (y * bitmap.PixelWidth + x);
pixels[index + 0] = (byte)x; // Blue
pixels[index + 1] = 0; // Green
pixels[index + 2] = (byte)y; // Red
pixels[index + 3] = 255; // Alpha
}
using (Stream pixelStream = bitmap.PixelBuffer.AsStream())
{
await pixelStream.WriteAsync(pixels, 0, pixels.Length);
}
bitmap.Invalidate();
image.Source = bitmap;
}
}
}
|
414767bcb0dfd76e9b354a7d4e24bd128087c94e
|
C#
|
jtarquino/SqlHttpPerf
|
/Client/SqlClient.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Runtime.Serialization.Formatters.Binary;
namespace HttpHandler
{
public class SqlClient
{
HttpClient client;
private const string openConnection = "https://localhost:5001/SqlClient/OpenConnection";
private const string createCommand = "https://localhost:5001/SqlClient/CreateCommand";
private const string executeReader = "https://localhost:5001/SqlClient/ExecuteReader";
private const string getRows = "https://localhost:5001/SqlClient/GetRows";
private const string getRowsBatch = "https://localhost:5001/SqlClient/GetRowsBatch";
private const string closeReader = "https://localhost:5001/SqlClient/CloseReader";
private const string closeConnection = "https://localhost:5001/SqlClient/CloseConnection";
private const string doNothing= "https://localhost:5001/SqlClient/DoNothing";
public void ReadData()
{
var sw = new Stopwatch();
client = new HttpClient();
sw.Reset();
sw.Start();
DoNothingThousand();
var result1 = $"Http1 that does nothing: {sw.ElapsedMilliseconds} milliseconds";
client = new HttpClient(new ForceHttp2Handler(new WinHttpHandler()));
sw.Reset();
sw.Start();
DoNothingThousand();
var result2 = $"Http2 that does nothing: {sw.ElapsedMilliseconds} milliseconds";
client = new HttpClient();
sw.Reset();
sw.Start();
ReadDataFromHttp();
var result3 = $"Http1: {sw.ElapsedMilliseconds} milliseconds";
client = new HttpClient(new ForceHttp2Handler(new WinHttpHandler()));
sw.Reset();
sw.Start();
ReadDataFromHttp();
var result4 = $"Http2: {sw.ElapsedMilliseconds} milliseconds";
sw.Reset();
sw.Start();
ReadDataFromSql();
var result5= $"Sql Native: {sw.ElapsedMilliseconds} milliseconds";
Console.WriteLine(result1);
Console.WriteLine(result2);
Console.WriteLine(result3);
Console.WriteLine(result4);
Console.WriteLine(result5);
//client = new HttpClient();
//sw.Reset();
//sw.Start();
//ReadDataFromHttpBatch();
//Console.WriteLine($"Http1 Batch: {sw.ElapsedMilliseconds} milliseconds");
}
private void ReadDataFromHttp()
{
for (int i = 0; i < 1000; i++)
{
Execute(openConnection);
Execute(createCommand);
Execute(executeReader);
Execute(getRows);
Execute(closeReader);
Execute(closeConnection);
if (i % 10 == 0) { Console.WriteLine(i); }
}
}
private void DoNothingThousand()
{
for (int i = 0; i < 1000; i++)
{
Execute(doNothing);
if (i % 10 == 0) { Console.WriteLine(i); }
}
}
private void ReadDataFromHttpBatch()
{
for (int i = 0; i < 1000; i++)
{
Execute(getRowsBatch);
Execute(closeReader);
Execute(closeConnection);
if (i % 10 == 0) { Console.WriteLine(i); }
}
}
private void ReadDataFromSql()
{
for (int i = 0; i < 1000; i++)
{
ReadeDataFromSqlOnce();
if (i % 10 == 0) { Console.WriteLine(i); }
}
}
private void ReadeDataFromSqlOnce()
{
var con = new SqlConnection(ConString.HackyConString);
con.Open();
var cmd = con.CreateCommand();
cmd.CommandText = "select top 1 ProductCategoryID FROM [SalesLT].[ProductCategory]";
var dataReader = cmd.ExecuteReader();
var rows = new List<object[]>();
int fieldCount = dataReader.FieldCount;
while (dataReader.Read())
{
object[] rowValues = new object[fieldCount];
for (int i = 0; i < fieldCount; i++)
{
rowValues[i] = dataReader.GetValue(i);
}
rows.Add(rowValues);
}
byte[] responseBytes = SerializeObjectToBinary(rows);
var response = CreateByteArrayResponse(responseBytes);
dataReader.Close();
con.Close();
}
private void Execute(string url)
{
HttpResponseMessage response = client.GetAsync(url).GetAwaiter().GetResult();
if (response.IsSuccessStatusCode)
{
var output = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
}
else
{
Console.WriteLine($"Error {response.StatusCode} , {response.Content.ReadAsStringAsync().GetAwaiter().GetResult()}");
}
}
private byte[] SerializeObjectToBinary(object value)
{
using (var stream = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(stream, value);
return stream.ToArray();
}
}
private HttpResponseMessage CreateByteArrayResponse(byte[] bytes)
{
HttpResponseMessage response = new HttpResponseMessage();
if (bytes != null)
{
response.Content = new ByteArrayContent(bytes);
}
return response;
}
}
}
|
a0f36551d1c3a9e7143f91ad3e2f0af61a40aa21
|
C#
|
marledidiplan/ProyectoWeb
|
/BLL/ArticuloBLL.cs
| 2.828125
| 3
|
using DAL;
using Entidades;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace BLL
{
public class ArticuloBLL
{
public static bool Guardar(Articulo articulo)
{
bool paso = false;
Contexto contexto = new Contexto();
try
{
if (contexto.articulos.Add(articulo) != null)
{
contexto.SaveChanges();
paso = true;
}
}
catch (Exception)
{
throw;
}
return paso;
}
public static bool Modificar(Articulo articulo)
{
bool paso = false;
Contexto contexto = new Contexto();
try
{
contexto.Entry(articulo).State = EntityState.Modified;
if (contexto.SaveChanges() > 0)
{
paso = true;
}
contexto.Dispose();
}
catch (Exception)
{
throw;
}
return paso;
}
public static Articulo Buscar(int id)
{
Contexto contexto = new Contexto();
Articulo articulo = new Articulo();
try
{
articulo = contexto.articulos.Find(id);
contexto.Dispose();
}
catch (Exception)
{
throw;
}
return articulo;
}
public static bool Eliminar(int id)
{
bool paso = false;
Contexto contexto = new Contexto();
Articulo articulo = new Articulo();
try
{
articulo = contexto.articulos.Find(id);
contexto.articulos.Remove(articulo);
if (contexto.SaveChanges() > 0)
{
paso = true;
}
}
catch (Exception)
{
throw;
}
return paso;
}
public static List<Articulo> GetList(Expression<Func<Articulo, bool>> expression)
{
Contexto contexto = new Contexto();
List<Articulo> articulos = new List<Articulo>();
try
{
articulos = contexto.articulos.Where(expression).ToList();
contexto.Dispose();
}
catch (Exception)
{
throw;
}
return articulos;
}
public static int CalcularGanancia(int costo, int precio)
{
int resultado;
resultado = precio - costo;
resultado = resultado / costo;
resultado *= 100;
return resultado;
}
}
}
|
bc3fca1006ba6b2061d0db04c70a166d248044bf
|
C#
|
ErtyHackward/utopia
|
/Utopia/Utopia/Worlds/Chunks/ChunkGraphics.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using S33M3DXEngine;
using S33M3DXEngine.Buffers;
using SharpDX.Direct3D;
using SharpDX.Direct3D11;
using Utopia.Resources.VertexFormats;
namespace Utopia.Worlds.Chunks
{
/// <summary>
/// Contains chunk visual information. Vertices, indices and other graphics stuff
/// </summary>
public class ChunkGraphics : IDisposable
{
private readonly VisualChunkBase _parentChunk;
private readonly D3DEngine _d3dEngine;
private bool _disposed;
private bool _ready2Draw;
//List are use instead of standard array because it's not possible to know the number of vertices/indices that will be produced at cubes creation time.
//After vertex/index buffer creation those collections are cleared.
public List<VertexCubeSolid> SolidCubeVertices; // Collection use to collect the vertices at the solid cube creation time
public List<ushort> SolidCubeIndices; // Collection use to collect the indices at the solid cube creation time
public List<VertexCubeLiquid> LiquidCubeVertices; // Collection use to collect the vertices at the liquid cube creation time
public List<ushort> LiquidCubeIndices; // Collection use to collect the indices at the liquid cube creation time
//Graphical chunk components Exposed VB and IB ==> Called a lot, so direct acces without property bounding
public VertexBuffer<VertexCubeSolid> SolidCubeVB; //Solid cube vertex Buffer
public IndexBuffer<ushort> SolidCubeIB; //Solid cube index buffer
public VertexBuffer<VertexCubeLiquid> LiquidCubeVB; //Liquid cube vertex Buffer
public IndexBuffer<ushort> LiquidCubeIB; //Liquid cube index Buffer
/// <summary>
/// Desired slice of the mesh
/// </summary>
public int SliceValue { get; set; }
/// <summary>
/// Actual slice value of the chunk mesh
/// </summary>
public int SliceOfMesh { get; set; }
/// <summary>
/// Whenever the chunk mesh are ready to be rendered to screen
/// </summary>
public bool IsExistingMesh4Drawing
{
get { return _ready2Draw; }
internal set
{
if (_ready2Draw != value)
{
_ready2Draw = value;
if (_ready2Draw)
_parentChunk.OnReadyToDraw(); //Event raised when the chunk is full ready to be rendered
}
}
}
/// <summary>
/// Indicates if the chunk is not visible from the camera and therefore should not be rendred
/// </summary>
public bool IsFrustumCulled { get; set; }
/// <summary>
/// Gets value indicating if the chunk can and should be rendered
/// </summary>
public bool NeedToRender { get { return IsExistingMesh4Drawing && !IsFrustumCulled; } }
public ChunkGraphics(VisualChunkBase parentChunk, D3DEngine d3DEngine)
{
SliceValue = -1;
_parentChunk = parentChunk;
_d3dEngine = d3DEngine;
}
public void InitializeChunkBuffers()
{
SolidCubeVertices = new List<VertexCubeSolid>();
SolidCubeIndices = new List<ushort>();
LiquidCubeVertices = new List<VertexCubeLiquid>();
LiquidCubeIndices = new List<ushort>();
}
public void SendCubeMeshesToBuffers()
{
if (_disposed) return;
SendSolidCubeMeshToGraphicCard(); //Solid Cubes
SendLiquidCubeMeshToGraphicCard(); //See Through Cubes
_parentChunk.State = ChunkState.DisplayInSyncWithMeshes;
IsExistingMesh4Drawing = true;
SliceOfMesh = SliceValue;
}
//Solid Cube
//Create the VBuffer + IBuffer from the List, then clear the list
//The Buffers are pushed to the graphic card. (SetData());
private void SendSolidCubeMeshToGraphicCard()
{
if (SolidCubeVertices.Count == 0)
{
if (SolidCubeVB != null) SolidCubeVB.Dispose();
SolidCubeVB = null;
return;
}
if (SolidCubeVB == null)
{
SolidCubeVB = new VertexBuffer<VertexCubeSolid>(_d3dEngine.Device, SolidCubeVertices.Count, PrimitiveTopology.TriangleList, "SolidCubeVB", ResourceUsage.Default, 10);
}
SolidCubeVB.SetData(_d3dEngine.ImmediateContext, SolidCubeVertices.ToArray());
SolidCubeVertices.Clear();
if (SolidCubeIB == null)
{
SolidCubeIB = new IndexBuffer<ushort>(_d3dEngine.Device, SolidCubeIndices.Count, "SolidCubeIB");
}
SolidCubeIB.SetData(_d3dEngine.ImmediateContext, SolidCubeIndices.ToArray());
SolidCubeIndices.Clear();
}
//Liquid Cube
//Create the VBuffer + IBuffer from the List, then clear the list
//The Buffers are pushed to the graphic card. (SetData());
private void SendLiquidCubeMeshToGraphicCard()
{
if (LiquidCubeVertices.Count == 0)
{
if (LiquidCubeVB != null) LiquidCubeVB.Dispose();
LiquidCubeVB = null;
return;
}
if (LiquidCubeVB == null)
{
LiquidCubeVB = new VertexBuffer<VertexCubeLiquid>(_d3dEngine.Device, LiquidCubeVertices.Count, PrimitiveTopology.TriangleList, "LiquidCubeVB", ResourceUsage.Default, 10);
}
LiquidCubeVB.SetData(_d3dEngine.ImmediateContext, LiquidCubeVertices.ToArray());
LiquidCubeVertices.Clear();
if (LiquidCubeIB == null)
{
LiquidCubeIB = new IndexBuffer<ushort>(_d3dEngine.Device, LiquidCubeIndices.Count, "LiquidCubeIB");
}
LiquidCubeIB.SetData(_d3dEngine.ImmediateContext, LiquidCubeIndices.ToArray());
LiquidCubeIndices.Clear();
}
//Ask the Graphical card to Draw the solid faces
public void DrawSolidFaces(DeviceContext context)
{
if (_disposed) return;
if (SolidCubeVB != null)
{
SolidCubeVB.SetToDevice(context, 0);
SolidCubeIB.SetToDevice(context, 0);
context.DrawIndexed(SolidCubeIB.IndicesCount, 0, 0);
}
}
//Ask the Graphical card to Draw the solid faces
public void DrawLiquidFaces(DeviceContext context)
{
if (_disposed) return;
if (LiquidCubeVB != null)
{
LiquidCubeVB.SetToDevice(context, 0);
LiquidCubeIB.SetToDevice(context, 0);
context.DrawIndexed(LiquidCubeIB.IndicesCount, 0, 0);
}
}
public void Dispose()
{
if (SolidCubeVB != null) SolidCubeVB.Dispose();
if (SolidCubeIB != null) SolidCubeIB.Dispose();
if (LiquidCubeVB != null) LiquidCubeVB.Dispose();
if (LiquidCubeIB != null) LiquidCubeIB.Dispose();
_disposed = true;
}
}
}
|
558642157ba05c005ce7315cedbf538cbb6e062a
|
C#
|
CodeMazeBlog/string-concatenation-csharp
|
/StringDemo/StringConcatenationExamples.cs
| 3.421875
| 3
|
using System;
using System.Diagnostics;
using System.Text;
namespace StringDemo
{
public class StringConcatenationExamples
{
private static readonly string _foo = "Morning!";
private static readonly string _bar = "Nice day for fishing, ain't it?";
private static readonly string _result = "Morning! Nice day for fishing, ain't it?";
private readonly string[] _foobar = { _foo, _bar };
private static readonly string _assertFailedMessage = "Not equal!";
public void CheckResult()
{
Debug.Assert(_result.Equals(Plus(_foo, _bar)), _assertFailedMessage);
Debug.Assert(_result.Equals(PlusEquals(_foo, " ", _bar)), _assertFailedMessage);
Debug.Assert(_result.Equals(Format(_foo, _bar)), _assertFailedMessage);
Debug.Assert(_result.Equals(Concat(_foo, _bar)), _assertFailedMessage);
Debug.Assert(_result.Equals(Join(_foo, _bar)), _assertFailedMessage);
Debug.Assert(_result.Equals(StringBuilder(_foo, _bar)), _assertFailedMessage);
}
// Example 1: + Operator
public string Plus(params string[] values)
{
return _foo + " " + _bar;
}
// Example 2: += Operator
public string PlusEquals(params string[] values)
{
string plusEqualsResult = String.Empty;
for (var index = 0; index < values.Length; index++)
{
plusEqualsResult += values[index];
}
return plusEqualsResult;
}
// Example 3: String.Format()
public string Format(params string[] values)
{
return String.Format("{0} {1}", _foo, _bar);
}
// Example 4: String.Concatenate() with values
public string Concat(params string[] values)
{
return String.Concat(_foo, " ", _bar);
}
// Example 5: Interpolation (C# 6 feature)
public string Interpolation(params string[] values)
{
return $"{_foo} {_bar}";
}
//Example 6: String.Join()
public string Join(params string[] values)
{
return String.Join(" ", _foobar);
}
//Example 7: StringBuilder.Append()
public string StringBuilder(params string[] values)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(_foo);
stringBuilder.Append(" ");
stringBuilder.Append(_bar);
return stringBuilder.ToString();
}
}
}
|
f7d31f5f79ba9ccae0a2fba3d70153f6cdab9cf3
|
C#
|
metodiev/Telerik-Academy
|
/First Semester/Csharp Part 1/Test and Exam/Projects/7. Test Preparation and Exam/FirTree/FirTree.cs
| 3.75
| 4
|
using System;
//Input:
//The input data should be read from the console.
//On the only input line you have an integer number N, showing the height of the tree.
//The input data will always be valid and in the format described. There is no need to check it explicitly.
//Output:
//The output data should be printed on the console.
//You must print the fir tree on the console. Each row contains only characters "." (point) or "*" (asterisk).
//The first row should have exactly one "*" in the middle (that is the top of the tree) and each of the next lines two more.
//The last line should have exactly one asterisk in the middle, showing the stem of the tree.
//Constraints:
//The number N is a positive integer between 4 and 100, inclusive.
class FirTree
{
static void Main()
{
int N = int.Parse(Console.ReadLine());
int count = 2;
int countNext = 1;
for (int i = 0; i < N - 1; countNext+=2,count+=1,i++)
{
for (int p = 0; p < N - count; p++)
{
Console.Write(".");
}
for (int q = 0; q < countNext; q++)
{
Console.Write("*");
}
for (int j = 0; j < N - count; j++)
{
Console.Write(".");
}
Console.WriteLine();
}
for (int i = 0; i < N - 2; i++)
{
Console.Write(".");
}
Console.Write("*");
for (int i = 0; i < N - 2; i++)
{
Console.Write(".");
}
}
}
|
9f9bcb18d17a2bfab3773368d109c66d80fb8db1
|
C#
|
dotnet/dotnet-api-docs
|
/snippets/csharp/System.Web.Services.Description/MessagePart/Message/messagepartcollection.cs
| 3.078125
| 3
|
// System.Web.Services.Description.MessagePartCollection.Item Property(Int32);
// System.Web.Services.Description.MessagePart.Message;
// System.Web.Services.Description.MessagePartCollection.CopyTo;
// System.Web.Services.Description.MessagePartCollection.Item Property (String);
// System.Web.Services.Description.MessagePartCollection.Contains;
// System.Web.Services.Description.MessagePartCollection.IndexOf;
// System.Web.Services.Description.MessagePartCollection.Remove;
// System.Web.Services.Description.MessagePartCollection;
/* The program reads a wsdl document "MathService.wsdl" and gets ServiceDescription instance.
A MessagePartCollection instance is then retrieved from each Message and it's members are demonstrated.
*/
// <Snippet8>
using System;
using System.Web.Services.Description;
using System.Collections;
using System.Xml;
class MyClass1
{
public static void Main()
{
Console.WriteLine("");
Console.WriteLine("MessagePartCollection Sample");
Console.WriteLine("============================");
Console.WriteLine("");
ServiceDescription myServiceDescription =
ServiceDescription.Read("MathService.wsdl");
// Get the message collection.
MessageCollection myMessageCollection = myServiceDescription.Messages;
Console.WriteLine("Total Messages in the document = " +
myServiceDescription.Messages.Count);
Console.WriteLine("");
Console.WriteLine("Enumerating PartCollection for each message...");
Console.WriteLine("");
// <Snippet1>
// <Snippet2>
// Get the message part collection for each message.
for(int i =0; i < myMessageCollection.Count; ++i)
{
Console.WriteLine("Message : " + myMessageCollection[i].Name);
// Get the message part collection.
MessagePartCollection myMessagePartCollection =
myMessageCollection[i].Parts;
// Display the part collection.
for(int k = 0; k < myMessagePartCollection.Count;k++)
{
Console.WriteLine("\t Part Name : " +
myMessagePartCollection[k].Name);
Console.WriteLine("\t Message Name : " +
myMessagePartCollection[k].Message.Name);
}
Console.WriteLine("");
}
// </Snippet2>
// </Snippet1>
Console.WriteLine("Displaying the array copied from the " +
"MessagePartCollection for the message AddHttpGetIn.");
// <Snippet3>
// <Snippet4>
Message myLocalMessage = myServiceDescription.Messages["AddHttpPostOut"];
if (myMessageCollection.Contains(myLocalMessage))
{
Console.WriteLine("Message : " + myLocalMessage.Name);
// Get the message part collection.
MessagePartCollection myMessagePartCollection = myLocalMessage.Parts;
MessagePart[] myMessagePart =
new MessagePart[myMessagePartCollection.Count];
// Copy the MessagePartCollection to an array.
myMessagePartCollection.CopyTo(myMessagePart,0);
for(int k = 0; k < myMessagePart.Length; k++)
{
Console.WriteLine("\t Part Name : " +
myMessagePartCollection[k].Name);
}
Console.WriteLine("");
}
// </Snippet4>
// </Snippet3>
// <Snippet5>
// <Snippet6>
// <Snippet7>
Console.WriteLine("Checking if message is AddHttpPostOut...");
Message myMessage = myServiceDescription.Messages["AddHttpPostOut"];
if (myMessageCollection.Contains(myMessage))
{
// Get the message part collection.
MessagePartCollection myMessagePartCollection = myMessage.Parts;
// Get the part named Body.
MessagePart myMessagePart = myMessage.Parts["Body"];
if (myMessagePartCollection.Contains(myMessagePart))
{
// Get the index of the part named Body.
Console.WriteLine("Index of Body in MessagePart collection = " +
myMessagePartCollection.IndexOf(myMessagePart));
Console.WriteLine("Deleting Body from MessagePart collection...");
myMessagePartCollection.Remove(myMessagePart);
if(myMessagePartCollection.IndexOf(myMessagePart)== -1)
{
Console.WriteLine("MessagePart Body successfully deleted " +
"from the message AddHttpPostOut.");
}
}
}
// </Snippet7>
// </Snippet6>
// </Snippet5>
}
}
// </Snippet8>
|
451c47ab14591204896b9dd37ac67b8516be5d99
|
C#
|
CarlSargunar/Developer-Test
|
/MVC Test/Classes/Alert.cs
| 2.828125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVC_Test.Classes
{
public class Alert : IHtmlString
{
public enum AlertStatus
{
Success,
Danger,
Info,
Warning
}
private readonly bool _dismissable;
public Alert(string message, bool dismissable = true)
{
_dismissable = dismissable;
Message = message;
}
public string Message { get; private set; }
public AlertStatus Status { get; set; }
public string ToHtmlString()
{
var tag = new TagBuilder("div");
var innerTag = new TagBuilder("div");
var button = new TagBuilder("button");
button.AddCssClass("close");
button.MergeAttribute("data-dismiss", "alert");
button.MergeAttribute("aria-hidden", "true");
button.InnerHtml = "×";
tag.AddCssClass("alert");
innerTag.AddCssClass("alert-inner");
switch (Status)
{
case AlertStatus.Success:
tag.AddCssClass("alert-success");
break;
case AlertStatus.Warning:
tag.AddCssClass("alert-warning");
break;
case AlertStatus.Danger:
tag.AddCssClass("alert-danger");
break;
case AlertStatus.Info:
tag.AddCssClass("alert-info");
break;
}
if (_dismissable)
{
tag.AddCssClass("alert-dismissable");
tag.InnerHtml = button.ToString();
}
innerTag.InnerHtml += Message;
tag.InnerHtml += innerTag;
return tag.ToString();
}
}
}
|
5481883b94b9f40c6314fff8a8587888e555540a
|
C#
|
aktauseef/Expense_Manager
|
/DAL/DataClasses/CategoryDAL.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Models;
namespace DAL.DataClasses
{
public class CategoryDAL
{
public int AddCategory(Models.Category Category)
{
int result = 0;
using(var db =new Expense_ManagerEntities())
{
if (Category.category_name != null)
{
category cat = new category();
cat.category_name = Category.category_name;
cat.user_id = Category.user_id;
if (IsCategoryExist(cat))
return 2;
db.category.Add(cat);
db.SaveChanges();
result = 1;
}
}
return result;
}
public bool IsCategoryExist(category Category)
{
bool result;
using (var db = new Expense_ManagerEntities())
{
category cat = new category();
result= db.category.Where(x => x.category_name == Category.category_name && x.user_id == Category.user_id).Any();
}
return result;
}
public List<Category> GetCategoryList(string userid)
{
List<Category> catListModel=new List<Category>();
if (userid != null)
{
using (var db = new Expense_ManagerEntities())
{
int id = int.Parse(userid);
int count = db.category.Where(m => m.user_id == id).Count();
List<category> catListDAL = new List<category>();
catListDAL = db.category.Where(m => m.user_id ==id).ToList();
foreach (var item in catListDAL)
{
Category catModel = new Category();
catModel.id = item.id;
catModel.category_name = item.category_name;
catModel.user_id = item.user_id;
catListModel.Add(catModel);
}
catListModel.Reverse(); //i am reversing it to display the latest added data on top
}
}
return catListModel;
}
public int DeleteCategory(int ctgryId)
{
int result = 0;
if (ctgryId > 0)
{
using (var db = new Expense_ManagerEntities())
{
var a = db.category.Find(ctgryId);
db.category.Remove(a);
db.SaveChanges();
result = 1;
}
}
return result;
}
public int EditCategory(int id,string name)
{
int result = 0;
if (id>0 && name!=null)
{
using (var db = new Expense_ManagerEntities())
{
var a = db.category.FirstOrDefault(x=>x.id==id);
if (a != null)
{
a.category_name = name;
db.SaveChanges();
result = 1;
}
}
}
return result;
}
}
}
|
2ac510eccd74fbf34dc404a8f642c262b815954d
|
C#
|
peterhumbert/JournalIndexExcel
|
/JournalIndexMaker/JournalIndexMaker/Subcategory.cs
| 3.140625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JournalIndexMaker
{
class Subcategory
{
private string Name { get; set; }
private List<DateTime> Entries = new List<DateTime>();
public Subcategory(string Name)
{
this.Name = Name;
}
public Subcategory(string Name, DateTime dt) : this(Name)
{
Entries.Add(dt);
}
public void addEntry(DateTime dt)
{
if (!Entries.Contains(dt))
{
Entries.Add(dt);
}
}
public List<DateTime> getEntries()
{
Entries.Sort();
return Entries;
}
}
}
|
26f9c4d5cddfc2c7e621b272f91541eeebf373ec
|
C#
|
nikitagru/ListPoker
|
/View/GameLabel.cs
| 2.953125
| 3
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace ListPoker.View
{
class GameLabel
{
public Label DrawNames(string name, int positionIteration)
{
Label label = new Label();
label.Text = name;
label.Font = MainFont.font;
label.Location = new Point(TableInfo.firstColumnWidth + TableInfo.secondColumnWidth + positionIteration * TableInfo.playerColumnWidth + TableInfo.secondRowHeight, 0);
return label;
}
public Label DrawNameDistrib(string name, int positionIteration)
{
Label label = new Label();
label.Text = name;
label.Font = MainFont.font;
label.Location = new Point(TableInfo.firstColumnWidth + 20, TableInfo.firstRowHeight + TableInfo.secondRowHeight + positionIteration * TableInfo.roundRowHeight + 5);
return label;
}
public Label CardCount(int counter, int positionIteration)
{
Label label = new Label();
label.Text = counter.ToString();
label.Font = MainFont.font;
label.Location = new Point(20, TableInfo.firstRowHeight + TableInfo.secondRowHeight + positionIteration * TableInfo.roundRowHeight + 5);
return label;
}
public Label PlayerInfo(int positionIteration, string info, int currentPlayer)
{
Label label = new Label();
label.Font = MainFont.playerInfo;
label.Text = info;
label.Size = new Size(69, 20);
label.Location = new Point(TableInfo.firstColumnWidth + TableInfo.secondColumnWidth + currentPlayer * TableInfo.playerColumnWidth + TableInfo.playerInfoColumnWidth * positionIteration + 15, TableInfo.roundRowHeight);
return label;
}
public Label PlayerScore(int score, int currentPlayerPosition, int currentStep)
{
Label label = new Label();
label.Font = MainFont.font;
label.Text = score.ToString();
label.Location = new Point(TableInfo.firstColumnWidth + TableInfo.secondColumnWidth + currentPlayerPosition * TableInfo.playerColumnWidth - TableInfo.playerInfoColumnWidth,
TableInfo.firstRowHeight + TableInfo.secondRowHeight + (currentStep - 1) * TableInfo.roundRowHeight);
return label;
}
}
}
|
497314199816f2bbf4ccf15edcafb50037846413
|
C#
|
IonutDjonIancu/myCSharpWork
|
/GuessGame.cs
| 3.5
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class GuessGame
{
static void Main(string[] args)
{
string secretMessage = "apothecary";
string guess = null;
int guessCounter = 4;
do
{
Console.Write("guess the word: ");
guess = Console.ReadLine();
guessCounter--;
}
while (guess != secretMessage && guessCounter>0);
if (guess.Equals(secretMessage))
{
Console.WriteLine("You win!");
}
else
{
Console.WriteLine("You lose!");
}
Console.ReadLine();
}
}
}
|
ceb091299f801aa34afed925383e49dceddc6c8e
|
C#
|
TihomirTE/TelerikAcademy
|
/C Sharp/03. C# OOP/05. OOP-Principles-Part-2/BankAccounts/Accounts/LoanAccount.cs
| 3.265625
| 3
|
namespace BankAccounts.Accounts
{
using System;
using BankAccounts.Customers;
using BankAccounts.Interfaces;
class LoanAccount : Account, IAcounts, IDeposit
{
// constructor
public LoanAccount(Customer customer, decimal balance, decimal interestRate)
: base(customer, balance, interestRate)
{
}
// calculation method
public override decimal CalculateInterest(int months)
{
if (months <= 0)
{
throw new ArgumentException("Montths must be positive value");
}
if (this.Customer.CustomerType == CustomerType.Company && months <= 2)
{
return 0;
}
if (this.Customer.CustomerType == CustomerType.Individual && months <= 3)
{
return 0;
}
return base.CalculateInterest(months);
}
}
}
|
64a0fd07115ca5686e1b62482356ca9fbf57a778
|
C#
|
jerhemy/DesignPatterns
|
/Prototype/Mob.cs
| 3.34375
| 3
|
namespace Prototype
{
abstract class MobPrototype
{
public abstract MobPrototype Clone();
}
class Mob : MobPrototype
{
public string Name { get; }
public int HP { get; }
public Mob(string name, int hp)
{
Name = name;
HP = hp;
}
public override MobPrototype Clone()
{
return MemberwiseClone() as MobPrototype;
}
}
}
|
a944797556c437b1fe763c930f1961f652ab452c
|
C#
|
EusebioDM/Fixture-System
|
/BackEnd/SilverFixture.Domain/Users/User.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using SilverFixture.Domain.Fixture;
namespace SilverFixture.Domain.User
{
public class User
{
public Role Role { get; set; }
private ICollection<Team> followedTeams;
public User()
{
followedTeams = new List<Team>();
}
public User(string userName) : this()
{
UserName = userName;
}
public User(Role role, string userName, string name, string surname, string password, string mail) : this(userName)
{
Name = name;
Surname = surname;
Password = password;
Mail = mail;
Role = role;
}
public User(Role role, string userName, string name, string surname, string password, string mail, ICollection<Team> followedTeams) : this(role, userName, name, surname, password, mail)
{
this.followedTeams = followedTeams;
}
public NonEmptyString UserName { get; set; }
public Name Name { get; set; }
public Name Surname { get; set; }
public NonEmptyString Password { get; set; }
public Mail Mail { get; set; }
public void AddFollowedTeam(Team team)
{
followedTeams.Add(team);
}
public void RemoveFollowedTeam(Team team)
{
followedTeams.Remove(team);
}
public IEnumerable<Team> FollowedTeams => followedTeams;
public override bool Equals(object obj)
{
var user = obj as User;
return user != null &&
UserName == user.UserName;
}
public override int GetHashCode()
{
return -1424944255 + EqualityComparer<string>.Default.GetHashCode(UserName);
}
}
}
|