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
|
|---|---|---|---|---|---|---|
b8e3672b1dec0dcfbf5f6fc66fdc87ee16139416
|
C#
|
shafin1984/task
|
/Assignment5/MyMVCApp/MyMVCApp/Controllers/CustomerController.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyMVCApp.BLL.BLL;
using MyMVCApp.Models.Models;
namespace MyMVCApp.Controllers
{
public class CustomerController : Controller
{
CustomerManager _customerManager =new CustomerManager();
private Customer _customer = new Customer();
// GET: Student
public ActionResult Add()
{
_customer.Name = "Gaus";
_customerManager.Add(_customer);
return View();
}
public ActionResult Delete()
{
_customer.ID = 1;
_customerManager.Delete(_customer);
return View();
}
public ActionResult Update()
{
_customer.ID = 6;
//Method 1
//_student.Name = "Kamal";
//_studentManager.Update(_student);
//Method 2
Customer aCustomer = _customerManager.GetByID(_customer);
if (aCustomer != null)
{
aCustomer.Name = "Ridoy";
_customerManager.Update(aCustomer);
}
return View();
}
public ActionResult GetByID()
{
_customer.ID = 3;
Customer bCustomer = _customerManager.GetByID(_customer);
return View();
}
public ActionResult GetAll()
{
List<Customer> bCustomer = _customerManager.GetAll();
return View();
}
}
}
|
c1143af337b166e79045ff1e7b7a63e718d43bab
|
C#
|
Mindkid/ProjDAD
|
/pacman/ConnectorLibrary/ChatRoom.cs
| 2.59375
| 3
|
using ConnectorLibrary;
using System;
using System.Collections.Generic;
using System.Threading;
namespace ConnectorLibrary
{
public class ChatRoom : MarshalByRefObject
{
private List<Message> conversation;
private List<ChatRoom> clientsChatRoom;
private Form1 conversationForm;
private IServer server;
public ChatRoom(IServer server, Form1 form)
{
this.server = server;
conversation = new List<Message>();
}
public void registerClient(String nickname, int port)
{
server.addClient(nickname, this);}
public void sendMessage(String message)
{
getChatRooms(server.getClients());
Thread thread = new Thread(() => broadCastMessage(message));
thread.Start();
}
public void receiveMessage(Message message)
{
conversation.Add(message);
conversation.Sort();
updateClientConversation(conversation);
}
private void broadCastMessage(String stringMessage)
{
Message message = new Message(stringMessage, conversation.Count + 1);
foreach (ChatRoom chat in clientsChatRoom)
chat.receiveMessage(message);
}
private void updateClientConversation(List<Message> conversation)
{
String messages = "";
foreach (Message x in conversation)
messages += x.getMessage() + "/r/n";
conversationForm.Invoke(conversationForm.refreshConversation, messages);
}
private void getChatRooms(Dictionary<String, int> usernames)
{
foreach(int port in usernames.Values)
{
ChatRoom chatRoom = (ChatRoom)Activator.GetObject(typeof(ChatRoom), ConnectionLibrary.buildChatRoomURL(port));
clientsChatRoom.Add(chatRoom);
}
}
}
}
|
03222c5b0a626c18dcc29980a11e4500adeebc21
|
C#
|
arifulHoqueCse/SchoolManagementSoftware
|
/SchoolApp-arif-9/SchoolApp/Models/DbGateway/ExamDbGateway.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using SchoolApp.Models.View;
namespace SchoolApp.Models.DbGateway
{
public class ExamDbGateway:Common
{
SqlConnectionManager aConnectionManager = new SqlConnectionManager();
internal string SaveExam(Exam aExam)
{
string sqlQuery = "INSERT INTO tblExam VALUES('" + aExam.Name + "', '" + aExam.ExamDate +
"', '" + aExam.Comment + "', '" + aExam.SchoolId + "')";
aSqlCommand = new SqlCommand(sqlQuery, aConnectionManager.GetConnection());
int ef = aSqlCommand.ExecuteNonQuery();
if (ef > 0)
{
return "Save";
}
else
{
return "fail";
}
}
internal List<Exam> GetAllExam(int schoolId)
{
List<Exam> aExamList = new List<Exam>();
string sqlQuery = "SELECT * FROM tblExam WHERE school_id = "+schoolId+"";
aSqlCommand = new SqlCommand(sqlQuery, aConnectionManager.GetConnection());
aReader = aSqlCommand.ExecuteReader();
while (aReader.Read())
{
Exam aExam = new Exam();
aExam.ExamId = Convert.ToInt32(aReader["exam_id"]);
aExam.Name = aReader["name"].ToString();
aExam.ExamDate = String.Format("{0:d-MMM-yyyy}", aReader["exam_date"]);
aExam.Comment = aReader["comment"].ToString();
aExamList.Add(aExam);
}
aConnectionManager.CloseConnection();
return aExamList;
}
internal Exam GetPostInfo(int ExampId)
{
Exam aExam = null;
string sqlQuery = "SELECT * FROM tblExam WHERE exam_id = " + ExampId + "";
aSqlCommand = new SqlCommand(sqlQuery, aConnectionManager.GetConnection());
aReader = aSqlCommand.ExecuteReader();
while (aReader.Read())
{
aExam = new Exam();
aExam.ExamId = Convert.ToInt32(aReader["exam_id"]);
aExam.Name = aReader["name"].ToString();
aExam.ExamDate = aReader["exam_date"].ToString();
aExam.Comment = aReader["comment"].ToString();
}
aConnectionManager.CloseConnection();
return aExam;
}
internal string UpdateMyExam(Exam aExam)
{
string sqlQuery = "UPDATE tblExam SET name = '" + aExam.Name + "', exam_date='" + aExam.ExamDate +
"', comment='" + aExam.Comment + "' WHERE exam_id='"+ aExam.ExamId +"' ";
aSqlCommand = new SqlCommand(sqlQuery, aConnectionManager.GetConnection());
int ef = aSqlCommand.ExecuteNonQuery();
if (ef > 0)
{
return "Updated";
}
else
{
return "fail";
}
}
internal string SaveExamGrade(ExamGrade aExamGrade)
{
string sqlQuery = "INSERT INTO tblGrade VALUES('" + aExamGrade.GradeName + "', " + aExamGrade.GradePoint +
", " + aExamGrade.MarkFrom + ", " + aExamGrade.MarkUpTo + ", '" + aExamGrade.Comment +
"', " + aExamGrade.SchoolId + ")";
aSqlCommand = new SqlCommand(sqlQuery, aConnectionManager.GetConnection());
int ef = aSqlCommand.ExecuteNonQuery();
if (ef > 0)
{
return "New Grade added successfully";
}
else
{
return "Fail";
}
}
internal List<ExamGrade> GetExamGradeList(int schoolId)
{
List<ExamGrade> aExamGradeList = new List<ExamGrade>();
string sqlQuery = "SELECT * FROM tblGrade WHERE school_id = " + schoolId + "";
aSqlCommand = new SqlCommand(sqlQuery, aConnectionManager.GetConnection());
aReader = aSqlCommand.ExecuteReader();
while (aReader.Read())
{
ExamGrade aExamGrade = new ExamGrade();
aExamGrade.ExamGradeId = Convert.ToInt32(aReader["grade_id"]);
aExamGrade.GradeName = aReader["name"].ToString();
aExamGrade.GradePoint = Convert.ToDouble(aReader["grade_point"]);
aExamGrade.MarkFrom = Convert.ToInt32(aReader["mark_from"]);
aExamGrade.MarkUpTo = Convert.ToInt32(aReader["mark_upto"]);
aExamGrade.Comment = aReader["comment"].ToString();
aExamGrade.SchoolId = Convert.ToInt32(aReader["school_id"]);
aExamGradeList.Add(aExamGrade);
}
return aExamGradeList;
}
internal string ManageClassMark(Mark aMark)
{
string sqlQuery = "INSERT INTO tblMark VALUES(" + aMark.MarkObtained + ", " + aMark.MarkTotal + ", '" +
aMark.Attendence + "', '" + aMark.Comment + "', " + aMark.StudentId + ", " +
aMark.SubjectId + ", " + aMark.ClassId + ", " + aMark.ExamId + ", " + aMark.SchoolId + ")";
aSqlCommand = new SqlCommand(sqlQuery, aConnectionManager.GetConnection());
int ef = aSqlCommand.ExecuteNonQuery();
if (ef > 0)
{
return "Student mark save successfully";
}
else
{
return "Fail!!";
}
}
internal List<ExamResultView> GetTheStudentResult(Mark aMark)
{
List<ExamResultView> aResultViews = new List<ExamResultView>();
string sqlQuery = "SELECT tblMark.mark_obtained, tblMark.mark_total, tblMark.attendance, tblSubject.name from tblMark join tblSubject on tblMark.subject_id = tblSubject.subject_id where tblSubject.class_id = " + aMark.ClassId + " AND tblMark.school_id = " + aMark.SchoolId + " AND tblMark.student_id = " + aMark.StudentId + " AND tblMark.exam_id = "+aMark.ExamId+"";
aSqlCommand = new SqlCommand(sqlQuery, aConnectionManager.GetConnection());
aReader = aSqlCommand.ExecuteReader();
while (aReader.Read())
{
ExamResultView aExamResultView = new ExamResultView();
aExamResultView.MarkObtain = Convert.ToDouble(aReader["mark_obtained"]);
aExamResultView.MarkTotal = Convert.ToDouble(aReader["mark_total"]);
aExamResultView.Attendence = aReader["attendance"].ToString();
aExamResultView.SubjectName = aReader["name"].ToString();
aResultViews.Add(aExamResultView);
}
aConnectionManager.CloseConnection();
return aResultViews;
}
internal string UpdateManageClassMark(Mark aMark)
{
string sqlQuery = "UPDATE tblMark SET mark_obtained = "+aMark.MarkObtained+", mark_total="+aMark.MarkTotal+", attendance = '"+aMark.Attendence+"', comment= '"+aMark.Comment+"' WHERE student_id="+aMark.StudentId+" AND subject_id="+aMark.SubjectId+" AND class_id="+aMark.ClassId+" AND exam_id="+aMark.ExamId+" AND school_id="+aMark.SchoolId+"";
aSqlCommand = new SqlCommand(sqlQuery, aConnectionManager.GetConnection());
int ef = aSqlCommand.ExecuteNonQuery();
if (ef > 0)
{
return "Result update succesfully";
}
else
{
return "Fail";
}
}
internal string SaveExamRoutine(ExamRoutine aExamRoutine)
{
string sqlQuery = "INSERT INTO tblExamRoutine VALUES('" + aExamRoutine.ExamTitle + "', '" + aExamRoutine.SubjectName +
"', '" + aExamRoutine.ExamDate + "', '" + aExamRoutine.ExamDay + "', '" + aExamRoutine.ExamTime +
"', " + aExamRoutine.ClassId + "," + aExamRoutine.SchoolId + ")";
aSqlCommand = new SqlCommand(sqlQuery, aConnectionManager.GetConnection());
int ef = aSqlCommand.ExecuteNonQuery();
if (ef > 0)
{
return "Subject has been added";
}
else
{
return "Fail to add";
}
}
internal List<ExamRoutineView> GetAllExamRoutine(int schoolId)
{
List<ExamRoutineView> aExamExamRoutineList = new List<ExamRoutineView>();
string sqlQuery = "SELECT tblExamRoutine.id, tblExamRoutine.exam_date, tblExamRoutine.exam_day, tblExamRoutine.exam_time, tblExamRoutine.exam_title,tblExamRoutine.school_id,tblExamRoutine.subject_name,tblClass.name FROM tblExamRoutine JOIN tblClass ON tblExamRoutine.class_id = tblClass.class_id WHERE tblExamRoutine.school_id = " + schoolId + "";
aSqlCommand = new SqlCommand(sqlQuery, aConnectionManager.GetConnection());
aReader = aSqlCommand.ExecuteReader();
while (aReader.Read())
{
ExamRoutineView aExamRoutine = new ExamRoutineView();
aExamRoutine.Id = Convert.ToInt32(aReader["id"]);
aExamRoutine.ExamTitle = aReader["exam_title"].ToString();
aExamRoutine.SubjectName = aReader["subject_name"].ToString();
aExamRoutine.ExamDate = aReader["exam_date"].ToString();
aExamRoutine.ExamDay = aReader["exam_day"].ToString();
aExamRoutine.ExamTime = aReader["exam_time"].ToString();
aExamRoutine.Classname = aReader["name"].ToString();
aExamRoutine.SchoolId = Convert.ToInt32(aReader["school_id"]);
aExamExamRoutineList.Add(aExamRoutine);
}
return aExamExamRoutineList;
}
internal ExamRoutine GetExamRoutineInfo(int? id)
{
string sqlQuery = "SELECT * FROM tblExamRoutine WHERE id = " + id + "";
aSqlCommand = new SqlCommand(sqlQuery, aConnectionManager.GetConnection());
aReader = aSqlCommand.ExecuteReader();
ExamRoutine aExamRoutine = new ExamRoutine();
while (aReader.Read())
{
aExamRoutine.Id = Convert.ToInt32(aReader["id"]);
aExamRoutine.ExamTitle = aReader["exam_title"].ToString();
aExamRoutine.SubjectName = aReader["subject_name"].ToString();
aExamRoutine.ExamDate = aReader["exam_date"].ToString();
aExamRoutine.ExamDay = aReader["exam_day"].ToString();
aExamRoutine.ExamTime = aReader["exam_time"].ToString();
aExamRoutine.ClassId = Convert.ToInt32(aReader["class_id"]);
aExamRoutine.SchoolId = Convert.ToInt32(aReader["school_id"]);
}
aConnectionManager.CloseConnection();
return aExamRoutine;
}
internal string UpdateExamRoutine(ExamRoutine aExamRoutineUpate)
{
string updateQuery = "UPDATE tblExamRoutine SET exam_title='" + aExamRoutineUpate.ExamTitle + "', subject_name='" + aExamRoutineUpate.SubjectName +
"', exam_date='" + aExamRoutineUpate.ExamDate + "', " +
"exam_day='" + aExamRoutineUpate.ExamDay + "', exam_time='" + aExamRoutineUpate.ExamTime + "', class_id='" +
aExamRoutineUpate.ClassId + "' WHERE id=" + aExamRoutineUpate.Id + "";
aSqlCommand = new SqlCommand(updateQuery, aConnectionManager.GetConnection());
int effectedrows = aSqlCommand.ExecuteNonQuery();
if (effectedrows > 0)
{
return "Data updated successfully";
}
else
{
return "Please fill all information correctly";
}
}
internal List<ExamRoutine> GetExamRoutineInfo(int schoolId, int clssId)
{
List<ExamRoutine> aExamRoutinesList = new List<ExamRoutine>();
string sqlQuery = "SELECT * FROM tblExamRoutine WHERE school_id = " + schoolId + " AND class_id=" + clssId + "";
aSqlCommand = new SqlCommand(sqlQuery, aConnectionManager.GetConnection());
aReader = aSqlCommand.ExecuteReader();
ExamRoutine aExamRoutine = null;
while (aReader.Read())
{
aExamRoutine = new ExamRoutine();
aExamRoutine.Id = Convert.ToInt32(aReader["id"]);
aExamRoutine.ExamTitle = aReader["exam_title"].ToString();
aExamRoutine.SubjectName = aReader["subject_name"].ToString();
aExamRoutine.ExamDate = aReader["exam_date"].ToString();
aExamRoutine.ExamDay = aReader["exam_day"].ToString();
aExamRoutine.ExamTime = aReader["exam_time"].ToString();
aExamRoutine.ClassId = Convert.ToInt32(aReader["class_id"]);
aExamRoutine.SchoolId = Convert.ToInt32(aReader["school_id"]);
aExamRoutinesList.Add(aExamRoutine);
}
aConnectionManager.CloseConnection();
return aExamRoutinesList;
}
internal ExamRoutine GetExamRoutineTitle(int schoolId, int clssId)
{
string sqlQuery = "SELECT * FROM tblExamRoutine WHERE school_id = " + schoolId + " AND class_id=" + clssId + "";
aSqlCommand = new SqlCommand(sqlQuery, aConnectionManager.GetConnection());
aReader = aSqlCommand.ExecuteReader();
ExamRoutine aExamRoutine = null;
while (aReader.Read())
{
aExamRoutine = new ExamRoutine();
aExamRoutine.ExamTitle = aReader["exam_title"].ToString();
}
aConnectionManager.CloseConnection();
return aExamRoutine;
}
internal string DeleteExamRoutine(int? id)
{
string sqlQuery = "DELETE FROM tblExamRoutine WHERE id =" + id + "";
aSqlCommand = new SqlCommand(sqlQuery, aConnectionManager.GetConnection());
int ef = aSqlCommand.ExecuteNonQuery();
if (ef > 0)
{
return "sucess";
}
else
{
return "fail";
}
}
}
}
|
1f5f906a5ce86bcba121a0d6246149e4a75128e6
|
C#
|
codemonkeycodes/ComputerVision
|
/AdvGraphics/Graphics.cs
| 2.953125
| 3
|
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace AdvGraphics
{
public class GraphicDisplay
{
private int[,] pixel_data;
private int W;
private int H;
private List<Point> points;
private void Init( int _H, int _W )
{
H = _H;
W = _W;
pixel_data = new int[H, W];
points = new List<Point>();
for (int i = 0; i < H; i++)
for (int j = 0; j < W; j++)
pixel_data[i, j] = -1;
}
public GraphicDisplay( int _H, int _W, Point p0, Point p1, Point p2, Point p3 )
{
Init(_H, _W);
points.Add(p0);
points.Add(p1);
points.Add(p2);
points.Add(p3);
}
public GraphicDisplay(int _H, int _W, Point p0, Point p1, Point p2 )
{
Init(_H, _W);
points.Add(p0);
points.Add(p1);
points.Add(p2);
}
public void DrawPointsToImage()
{
DrawPoints();
}
private void FillArea( bool blend, Color color, PictureBox pictbox )
{
//find maxH, minH, maxW, minW
int maxH = -1, minH = 99999999, maxW = -1, minW = 99999999;
foreach( Point p in points )
{
if (p.X > maxW)
maxW = p.X;
if (p.X < minW)
minW = p.X;
if (p.Y > maxH)
maxH = p.Y;
if (p.Y < minH)
minH = p.Y;
}
//walk to find the first point
for( int i = minH; i < maxH+1; i++ )
{
for(int j = minW; j < maxW+1; j++)
{
if( pixel_data[i,j] != -1 )
{
for( int jj = maxW; jj > j; jj--)
{
if( pixel_data[i,jj] != -1 )
{
if (blend)
{
DrawBresenhamLine(i, j, i, jj, Color.FromArgb(pixel_data[i, j]),
Color.FromArgb(pixel_data[i, jj]), pictbox);
break;
}
else
{
DrawBresenhamLine(i, j, i, jj, color,
color, pictbox);
break;
}
}
}
break;
}
}
}
}
public void DoFill(bool blend, Color color, PictureBox pictbox)
{
FillArea(blend, color, pictbox);
}
public void DrawLine(Color point1, Color point2, Color point3, PictureBox pictbox, bool blend )
{
DrawBresenhamLine(points[0].Y, points[0].X, points[1].Y, points[1].X, point1, point2, pictbox);
DrawBresenhamLine(points[1].Y, points[1].X, points[2].Y, points[2].X, point2, point3, pictbox);
DrawBresenhamLine(points[0].Y, points[0].X, points[2].Y, points[2].X, point1, point3, pictbox);
FillArea(blend, point1, pictbox);
}
public void DrawLine(Color point1, Color point2, Color point3, PictureBox pictbox )
{
DrawBresenhamLine( points[0].Y, points[0].X, points[1].Y, points[1].X, point1, point2, pictbox );
DrawBresenhamLine(points[1].Y, points[1].X, points[2].Y, points[2].X, point2, point3, pictbox);
DrawBresenhamLine(points[0].Y, points[0].X, points[2].Y, points[2].X, point1, point3, pictbox);
}
private void DrawPoints()
{
//draw and X for each "point"
foreach ( Point point in points )
{
pixel_data[point.Y, point.X] = Color.Yellow.ToArgb();
pixel_data[point.Y - 1, point.X] = Color.Yellow.ToArgb();
pixel_data[point.Y, point.X-1] = Color.Yellow.ToArgb();
pixel_data[point.Y+1, point.X] = Color.Yellow.ToArgb();
pixel_data[point.Y, point.X+1] = Color.Yellow.ToArgb();
pixel_data[point.Y+1, point.X+1] = Color.Yellow.ToArgb();
pixel_data[point.Y-1, point.X-1] = Color.Yellow.ToArgb();
pixel_data[point.Y-1, point.X+1] = Color.Yellow.ToArgb();
pixel_data[point.Y+1, point.X-1] = Color.Yellow.ToArgb();
pixel_data[point.Y + 2, point.X + 2] = Color.Yellow.ToArgb();
pixel_data[point.Y - 2, point.X - 2] = Color.Yellow.ToArgb();
pixel_data[point.Y - 2, point.X + 2] = Color.Yellow.ToArgb();
pixel_data[point.Y + 2, point.X - 2] = Color.Yellow.ToArgb();
pixel_data[point.Y + 3, point.X + 3] = Color.Yellow.ToArgb();
pixel_data[point.Y - 3, point.X - 3] = Color.Yellow.ToArgb();
pixel_data[point.Y - 3, point.X + 3] = Color.Yellow.ToArgb();
pixel_data[point.Y + 3, point.X - 3] = Color.Yellow.ToArgb();
}
}
public void Clear()
{
pixel_data = new int[H,W];
}
//bresenhamline
public void DrawBresenhamLine(int startH, int startW, int endH, int endW, Color color, Color end_color, PictureBox pictureBox )
{
int actual_startH = startH;
int actual_startW = startW;
int dx = Math.Abs(endW - startW);
int dy = Math.Abs(endH - startH);
int sx, sy;
if (startW < endW) sx = 1; else sx = -1;
if (startH < endH) sy = 1; else sy = -1;
int err = dx - dy;
Graphics g = null;
if (pictureBox != null)
g = pictureBox.CreateGraphics();
while (true)
{
if (startH < 0 || startW < 0 || startH >= H || startW >= W)
break;
double percent_startH = ((endH - actual_startH) - (startH - actual_startH)) / Convert.ToDouble(endH - actual_startH);
double percent_startW = ((endW - actual_startW) - (startW - actual_startW)) / Convert.ToDouble(endW - actual_startW);
double percent = 0.0;
if ((endH - actual_startH) > (endW - actual_startW))
percent = percent_startH;
else
percent = percent_startW;
int colorR = Convert.ToInt32(((percent * color.R) + ((1 - percent) * end_color.R)));
int colorG = Convert.ToInt32(((percent * color.G) + ((1 - percent) * end_color.G)));
int colorB = Convert.ToInt32(((percent * color.B) + ((1 - percent) * end_color.B)));
Color drawn_color = Color.FromArgb(colorR, colorG, colorB);
if (g != null)
g.DrawEllipse(new Pen(drawn_color), (float)startW, (float)startH, 1, 1);
pixel_data[startH, startW] = drawn_color.ToArgb();
if (startW == endW && startH == endH)
break;
int e2 = 2 * err;
if (e2 > -dy)
{
err = err - dy;
startW = startW + sx;
}
if (e2 < dx)
{
err = err + dx;
startH = startH + sy;
}
}
}
//bresenhamline
public void DrawBresenhamLine( int startH, int startW, int endH, int endW, Color color, ref PictureBox pictureBox )
{
DrawBresenhamLine(startH, startW, endH, endW, color, color, pictureBox);
}
//save to bitmap
public void OutputBitmap( byte[] byte_array, String file_name )
{
//create bitmap & copy byte array to bitmap data
Bitmap bitmap = new Bitmap(W, H, PixelFormat.Format32bppRgb);
BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, W, H),
ImageLockMode.WriteOnly,
bitmap.PixelFormat);
IntPtr ptr = bmpData.Scan0;
Marshal.Copy(byte_array, 0, ptr, byte_array.Length);
bitmap.UnlockBits(bmpData);
bitmap.Save(file_name);
}
//covert 2D array representing which pixels are "on" 1D byte array of BGR data
public byte[] ConvertArrayToPixel()
{
byte [] single_array = new byte[H*W*4];
int ii = 0;
for (int i = 0; i < H; i++)
{
for (int j = 0; j < W; j++)
{
//line will be white
//circle will be cyan
//BGRA not RGBA or even ARGB
Color color;
if (pixel_data[i, j] == -1)
{
color = Color.Black;
}
else
{
color = Color.FromArgb(pixel_data[i, j]);
}
if (color != Color.Black)
{
//white
single_array[ii++] = color.B;
single_array[ii++] = color.G;
single_array[ii++] = color.R;
single_array[ii++] = 0;
}
else
{
//white
single_array[ii++] = 0;
single_array[ii++] = 0;
single_array[ii++] = 0;
single_array[ii++] = 0;
}
}
}
return single_array;
}
public static GraphicDisplay operator +(GraphicDisplay g1, GraphicDisplay g2)
{
int max_h = (g1.H > g2.H ? g1.H : g2.H);
int max_w = (g1.W > g2.W ? g1.W : g2.W);
GraphicDisplay g_new = new GraphicDisplay(max_h, max_w, g1.points[0], g1.points[1], g1.points[2], g1.points[3]);
foreach( Point point in g2.points )
g_new.points.Add(point);
for (int i = 0; i < max_h; i++)
{
for (int j = 0; j < max_w; j++)
{
if (i < g1.H && j < g1.W)
g_new.pixel_data[i, j] = g1.pixel_data[i, j];
//2 overlaps 1...assume drawing in Z order from bottom to top
if (i < g2.H && j < g2.W)
g_new.pixel_data[i, j] = g1.pixel_data[i, j];
}
}
return g_new;
}
}
}
|
7f2a95bdc92e2b4c4c7a708435cc91fbb53386d2
|
C#
|
atopos0627/SocketServer
|
/TestServer/Event/ClientEventArgs.cs
| 2.828125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TestServer.Network;
namespace TestServer.Event
{
public class ClientEventArgs : EventArgs
{
#region Constructors
public ClientEventArgs(ClientConnection clientConnection)
: this(clientConnection, null)
{
}
public ClientEventArgs(ClientConnection clientConnection, Exception ex)
{
ClientConnection = clientConnection;
Error = ex;
}
#endregion
#region Public Properties
/// <summary>
/// Gets the channel associated with the raising of this event.
/// </summary>
public ClientConnection ClientConnection { get; private set; }
/// <summary>
/// Gets the exception associated with the raising of this event.
/// Will be null if was not raised as the result of an exception.
/// </summary>
public Exception Error { get; private set; }
/// <summary>
/// Gets a value indicating whether there was an exception associated w/ the creation of the event.
/// </summary>
/// <value>
/// <c>true</c> if this instance has an Exception; otherwise, <c>false</c>.
/// </value>
public bool HasError { get { return Error != null; } }
#endregion
}
}
|
3387d1db2d59918b55f4cf9d47531e6f5ebdd698
|
C#
|
constanline/Magician
|
/Magician.Common/Util/LogUtil.cs
| 2.96875
| 3
|
using System;
using System.IO;
namespace Magician.Common.Util
{
internal class LogUtil
{
private static readonly object logLock = string.Empty;
public static void Log(string message)
{
lock (logLock)
{
if (!Directory.Exists("log")) Directory.CreateDirectory("log");
var filePath = "log/" + DateTime.Today.ToString("yyyy-MM-dd") + ".log";
var fs = !File.Exists(filePath) ? File.Create(filePath) : new FileStream(filePath, FileMode.Append, FileAccess.Write);
var sw = new StreamWriter(fs);
sw.WriteLine(message);
sw.Close();
fs.Close();
}
}
}
}
|
8436110c6c59215f6b80a1f4b881c17b5de7926b
|
C#
|
ragnarstolsmark/Rstolsmark.PasswordHashTool
|
/Program.cs
| 2.765625
| 3
|
using System;
using static Rstolsmark.PasswordHashLib.PasswordHasher;
namespace Rstolsmark.PasswordHashTool
{
class Program
{
static void Main(string[] args)
{
if(args.Length == 0){
Console.WriteLine("\nUsage:");
Console.WriteLine("To generate a salted hashed password:");
Console.WriteLine("passwordhasher <password>");
return;
}
Console.WriteLine(HashPassword(args[0]));
}
}
}
|
828151136efff527920da076bbeccf072839debd
|
C#
|
monoman/NugetCracker
|
/Nuget/test/VisualStudio.Test/RecentPackageTest.cs
| 2.8125
| 3
|
using System.IO;
using System.Linq;
using Xunit;
namespace NuGet.VisualStudio.Test
{
using PackageUtility = NuGet.Test.PackageUtility;
public class RecentPackageTest
{
[Fact]
public void TestTheFirstConstructor()
{
// Arrange
IPackage basePackage = PackageUtility.CreatePackage(
"A",
"1.2",
content: new string[] { "one", "two" });
// Act
var package = basePackage;
var contents = package.GetContentFiles().ToList();
var content1 = ReadStream(contents[0].GetStream());
var content2 = ReadStream(contents[1].GetStream());
// Assert
Assert.Equal("A", package.Id);
Assert.Equal(new SemanticVersion("1.2"), package.Version);
Assert.Equal(2, contents.Count);
Assert.Equal("content\\one", content1);
Assert.Equal("content\\two", content2);
}
private string ReadStream(Stream stream)
{
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
}
|
25f09fbe20dea45b3056ada06353a40b8dd8569c
|
C#
|
tbebekis/Tripous
|
/Tripous.Data/SqlCache.cs
| 3.296875
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
namespace Tripous.Data
{
/// <summary>
/// A cache of <see cref="DataTable"/> instances, containing schema of a named sql statement, per connection.
/// </summary>
static public class SqlCache
{
static object syncLock = new LockObject();
static Dictionary<string, Dictionary<string, DataTable>> Cache = new Dictionary<string, Dictionary<string, DataTable>>();
/// <summary>
/// Returns true if there is a <see cref="DataTable"/> with schema information of a Sql statement specified by a name, under a connection specified by name.
/// </summary>
static public bool Contains(string ConnectionName, string StatementName)
{
return Find(ConnectionName, StatementName) != null;
}
/// <summary>
/// Finds and returns a schema <see cref="DataTable"/> if any, else null.
/// </summary>
static public DataTable Find(string ConnectionName, string StatementName)
{
if (!Cache.ContainsKey(ConnectionName))
{
return null;
}
Dictionary<string, DataTable> ConnectionStatements = Cache[ConnectionName];
return ConnectionStatements != null ? ConnectionStatements[StatementName] : null;
}
/// <summary>
/// Adds a schema <see cref="DataTable"/> to the cache.
/// </summary>
static public void Add(string ConnectionName, string StatementName, DataTable SchemaTable)
{
Dictionary<string, DataTable> ConnectionStatements = null;
if (!Cache.ContainsKey(ConnectionName))
{
ConnectionStatements = Cache[ConnectionName];
Cache[ConnectionName] = ConnectionStatements;
}
else
{
ConnectionStatements = Cache[ConnectionName];
}
ConnectionStatements[StatementName] = SchemaTable;
}
}
}
|
93b94e6b4784de6a7a83d31bbb2921ebeca3b8e6
|
C#
|
XuRuiO/CrmWebApi
|
/CRM.Freamwork/Cache/MemoryCache/MemoryCacheExtension.cs
| 2.84375
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.Caching.Memory;
namespace CRM.Freamwork.Cache.MemoryCache
{
/// <summary>
/// 2019.08.10 Rui MemoryCache(内存缓存)的接口实现
/// 方法定义的比较少,需要的话,可以在加
/// </summary>
public class MemoryCacheExtension : IMemoryCacheExtension
{
//引用Microsoft.Extensions.Caching.Memory;这个和.net 还是不一样,没有了Httpruntime了
private readonly IMemoryCache cache;
public MemoryCacheExtension(IMemoryCache cache)
{
this.cache = cache;
}
/// <summary>
/// 根据指定Key,设置内存缓存中的数据
/// </summary>
/// <param name="cacheKey">缓存键</param>
/// <param name="cacheValue">缓存值</param>
/// <param name="absoluteExpirationRelativeToNow">相对当前时间的绝对过期时间(使用TimeSpan)</param>
public void Set(string cacheKey, object cacheValue, TimeSpan absoluteExpirationRelativeToNow)
{
cache.Set(cacheKey, cacheValue, absoluteExpirationRelativeToNow);
}
/// <summary>
/// 根据指定Key,获取内存缓存中的数据
/// </summary>
/// <param name="cacheKey">缓存键</param>
/// <returns></returns>
public object Get(string cacheKey)
{
return cache.Get(cacheKey);
}
}
}
|
b9682d29261b90bdcc0f5199d3ecd7a7bf0090c1
|
C#
|
ming91915/CADDev
|
/eZcad/Examples/SplineHandler.cs
| 2.8125
| 3
|
using Autodesk.AutoCAD.ApplicationServices.Core;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
namespace eZcad.Examples
{
/// <summary> 根据两条样条曲线创建出位于其中间的一条新样条曲线
/// Finding an AutoCAD spline between two others using .NET </summary>
/// <remarks>参考:http://www.tuicool.com/articles/BFJVju </remarks>
public class SplineHandler
{
[CommandMethod("SBS")]
public static void SplineBetweenSplines()
{
var doc = Application.DocumentManager.MdiActiveDocument;
var db = doc.Database;
var ed = doc.Editor;
// Select our splines
var peo = new PromptEntityOptions("\nSelect first spline");
peo.SetRejectMessage("\nMust be a spline.");
peo.AddAllowedClass(typeof(Spline), true);
var per = ed.GetEntity(peo);
if (per.Status != PromptStatus.OK) return;
var spId1 = per.ObjectId;
peo.Message = "\nSelect second spline";
per = ed.GetEntity(peo);
if (per.Status != PromptStatus.OK) return;
var spId2 = per.ObjectId;
// Create a transaction
using (var tr = doc.TransactionManager.StartTransaction())
{
// Open our splines
var sp1 =
tr.GetObject(spId1, OpenMode.ForRead) as Spline;
var sp2 =
tr.GetObject(spId2, OpenMode.ForRead) as Spline;
if (sp1 != null && sp2 != null)
{
try
{
// Get Ge equivalents of the two splines
var cur1 = sp1.GetGeCurve() as NurbCurve3d;
var cur2 = sp2.GetGeCurve() as NurbCurve3d;
if (cur1 != null && cur2 != null)
{
// Find the middle curve between the two
var cur3 = MiddleCurve(cur1, cur2);
if (cur3 != null)
{
// Create a spline from this middle curve
var sp = Curve.CreateFromGeCurve(cur3);
if (sp != null)
{
// Add our new spline to the database
var btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
btr.AppendEntity(sp);
tr.AddNewlyCreatedDBObject(sp, true);
}
}
}
tr.Commit();
}
catch (Exception ex)
{
ed.WriteMessage("\nException: {0}", ex.Message);
}
}
}
}
/// <summary>
/// 根据两条样条曲线创建出位于其中间的一条新样条曲线
/// </summary>
/// <param name="cur1"></param>
/// <param name="cur2"></param>
/// <returns></returns>
private static NurbCurve3d MiddleCurve(NurbCurve3d cur1, NurbCurve3d cur2)
{
// Return a NurbCurve3d that's halfway between those passed in
// Start by getting the period of both curves
double per1, per2;
var ip1 = cur1.IsPeriodic(out per1);
var ip2 = cur2.IsPeriodic(out per2);
// Make the sure the curves have the same degree, period,
// number of control points, knots and weights
if (
cur1.Degree != cur2.Degree || ip1 != ip2 || per1 != per2 ||
cur1.NumberOfControlPoints != cur2.NumberOfControlPoints ||
cur1.NumberOfKnots != cur2.NumberOfKnots ||
cur1.NumWeights != cur2.NumWeights
)
return null;
var degree = cur1.Degree;
var period = ip1;
// Get the set of averaged control points
var numPoints = cur1.NumberOfControlPoints;
var pts = new Point3dCollection();
for (var i = 0; i < numPoints; i++)
{
var pt1 = cur1.ControlPointAt(i);
var pt2 = cur2.ControlPointAt(i);
pts.Add(pt1 + (pt2 - pt1) / 2);
}
// Get the set of averaged knots
var numKnots = cur1.NumberOfKnots;
var knots = new KnotCollection();
for (var i = 0; i < numKnots; i++)
{
knots.Add((cur1.KnotAt(i) + cur2.KnotAt(i)) / 2);
}
// Get the set of averaged weights
var numWeights = cur1.NumWeights;
var weights = new DoubleCollection();
for (var i = 0; i < numWeights; i++)
{
knots.Add((cur1.GetWeightAt(i) + cur2.GetWeightAt(i)) / 2);
}
// Create our new Ge curve based on all this data
return new NurbCurve3d(degree, knots, pts, weights, period);
}
}
}
|
426242a739d007f3ccba73b99184802680614355
|
C#
|
mitchelltaylor159/InvoiceSystem
|
/InvoiceSystem/Controllers/InvoiceItemsController.cs
| 2.8125
| 3
|
using InvoiceSystem.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace InvoiceSystem.Controllers
{
public class InvoiceItemsController
{
/// <summary>
/// The current working InvoiceItem.
/// </summary>
public InvoiceItem ActiveInvoiceItem { get; set; }
/// <summary>
/// A list of all InvoiceItems from the DB.
/// </summary>
public IEnumerable<InvoiceItem> InvoiceItems { get; set; }
/// <summary>
/// The default constructor.
/// </summary>
public InvoiceItemsController()
{
try
{
this.ActiveInvoiceItem = null;
}
catch (Exception ex)
{
throw new Exception(MethodInfo.GetCurrentMethod().DeclaringType.Name + "." +
MethodInfo.GetCurrentMethod().Name + " -> " + ex.Message);
}
}
/// <summary>
/// Loads all of the InvoiceItems into the class variable, InvoiceItems.
/// </summary>
public void LoadInvoiceItems()
{
try
{
// Call function from InvoiceItem
}
catch (Exception ex)
{
throw new Exception(MethodInfo.GetCurrentMethod().DeclaringType.Name + "." +
MethodInfo.GetCurrentMethod().Name + " -> " + ex.Message);
}
}
/// <summary>
/// Loads all of the InvoiceItems from an invoice into the class variable, InvoiceItems.
/// </summary>
public void LoadInvoiceItems(Invoice invoice)
{
try
{
// Call function from InvoiceItem
this.InvoiceItems = InvoiceItem.GetInvoiceItems(invoice.InvoiceID);
/*for(int i = 0; i<this.InvoiceItems.Count(); i++)
{
this.InvoiceItems.ElementAt(i).LineItem =
} addd method for*/
}
catch (Exception ex)
{
throw new Exception(MethodInfo.GetCurrentMethod().DeclaringType.Name + "." +
MethodInfo.GetCurrentMethod().Name + " -> " + ex.Message);
}
}
/// <summary>
/// Saves the active InvoiceItem object to the DB.
/// </summary>
public void SaveActiveInvoiceItem()
{
try
{
// Call function from Item
this.ActiveInvoiceItem.Save();
}
catch (Exception ex)
{
throw new Exception(MethodInfo.GetCurrentMethod().DeclaringType.Name + "." +
MethodInfo.GetCurrentMethod().Name + " -> " + ex.Message);
}
}
/// <summary>
/// Updates the active InvoiceItem object in the DB.
/// </summary>
public void UpdateActiveInvoiceItem()
{
try
{
// Call function from Item
this.ActiveInvoiceItem.Update();
}
catch (Exception ex)
{
throw new Exception(MethodInfo.GetCurrentMethod().DeclaringType.Name + "." +
MethodInfo.GetCurrentMethod().Name + " -> " + ex.Message);
}
}
/// <summary>
/// Deletes the active InvoiceItem object from the DB.
/// </summary>
public void DeleteActiveItem()
{
try
{
// Call function from Item
this.ActiveInvoiceItem.Delete();
}
catch (Exception ex)
{
throw new Exception(MethodInfo.GetCurrentMethod().DeclaringType.Name + "." +
MethodInfo.GetCurrentMethod().Name + " -> " + ex.Message);
}
}
}
}
|
28fb8274a0a3b0d1d7e7ca268d9f367a9cd3db6a
|
C#
|
alexccl/AutoTest
|
/Source_Code/AutoTest/AutoTestEngine/BoundaryType.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutoTestEngine
{
/// <summary>
/// Enumeration of the different boundaries the interception occured on
/// </summary>
enum BoundaryType
{
/// <summary>
/// Before calling the proxied object
/// </summary>
Entry,
/// <summary>
/// The exception thrown by the proxied object
/// </summary>
Exception,
/// <summary>
/// After calling the proxied object
/// </summary>
Exit
}
}
|
974618b3aa1324c71608a8d22466f14d627bbf96
|
C#
|
yjd6808/_YJD_P2PFileShare_vs19
|
/P2PTest/TestForFileCompressing.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using P2PShared;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace P2PTest
{
public class Block
{
public UInt32 Number { get; set; }
public byte[] Data { get; set; } = new byte[0];
#region Constructors
// Creates a new block of data w/ the supplied number
public Block(UInt32 number = 0)
{
Number = number;
}
// Creates a Block from a byte array
public Block(byte[] bytes)
{
// First four bytes are the number
Number = BitConverter.ToUInt32(bytes, 0);
// Data starts at byte 4
Data = bytes.Skip(4).ToArray();
}
#endregion // Constructors
public override string ToString()
{
// Take some of the first few bits of data and turn that into a string
String dataStr;
if (Data.Length > 8)
dataStr = Encoding.ASCII.GetString(Data, 0, 8) + "...";
else
dataStr = Encoding.ASCII.GetString(Data, 0, Data.Length);
return string.Format(
"[Block:\n" +
" Number={0},\n" +
" Size={1},\n" +
" Data=`{2}`]",
Number, Data.Length, dataStr);
}
// Returns the data in the block as a byte array
public byte[] GetBytes()
{
// Convert meta-data
byte[] numberBytes = BitConverter.GetBytes(Number);
// Join all the data into one bigger array
byte[] bytes = new byte[numberBytes.Length + Data.Length];
numberBytes.CopyTo(bytes, 0);
Data.CopyTo(bytes, 4);
return bytes;
}
}
[TestClass]
public class TestForFileCompressing
{
MD5 _hasher;
string _fileName;
string _directory;
Dictionary<uint, Block> _blocks;
byte[] _checkSum;
uint _fileSize;
const uint _maxBlockSize = 8 * 1024; // 8KB
[TestMethod, Ignore]
public void TestMain()
{
_hasher = MD5.Create();
_directory = @"C:\";
_fileName = @"YodaSyndrome - 몽환적인 노래 모음집 (2017-03-09).mp3";
_blocks = new Dictionary<UInt32, Block>();
//파일 압축 테스트
CompressedFile(_fileName);
}
private void CompressedFile(string requestedFile)
{
Console.WriteLine("Preparing the file to send...");
_fileSize = 0;
try
{
// Read it in & compute a checksum of the original file
byte[] fileBytes = File.ReadAllBytes(Path.Combine(_directory, requestedFile));
_checkSum = _hasher.ComputeHash(fileBytes);
_fileSize = Convert.ToUInt32(fileBytes.Length);
Console.WriteLine("{0} is {1} bytes.{2:0.####} kilo bytes {3:0.####} mega bytes {4:0.####} giga bytes", requestedFile, _fileSize, _fileSize.BytesToKilobytes(), _fileSize.BytesToMegabytes(), _fileSize.BytesToGigabytes());
// Compress it
Stopwatch timer = new Stopwatch();
using (MemoryStream compressedStream = new MemoryStream())
{
// Perform the actual compression
DeflateStream deflateStream = new DeflateStream(compressedStream, CompressionMode.Compress, true);
timer.Start();
deflateStream.Write(fileBytes, 0, fileBytes.Length);
deflateStream.Close();
timer.Stop();
// Put it into blocks
compressedStream.Position = 0;
long compressedSize = compressedStream.Length;
UInt32 id = 1;
while (compressedStream.Position < compressedSize)
{
// Grab a chunk
long numBytesLeft = compressedSize - compressedStream.Position;
long allocationSize = (numBytesLeft > _maxBlockSize) ? _maxBlockSize : numBytesLeft;
byte[] data = new byte[allocationSize];
compressedStream.Read(data, 0, data.Length);
// Create a new block
Block b = new Block(id++);
b.Data = data;
_blocks.Add(b.Number, b);
}
// Print some info and say we're good
Console.WriteLine("{0} compressed is {1} bytes large in {2:0.000}s.", requestedFile, compressedSize, timer.Elapsed.TotalSeconds);
Console.WriteLine("Sending the file in {0} blocks, using a max block size of {1} bytes.", _blocks.Count, _maxBlockSize);
}
}
catch (Exception e)
{
// Crap...
Console.WriteLine("Could not prepare the file for transfer, reason:");
Console.WriteLine(e.Message);
// Reset a few things
_blocks.Clear();
_checkSum = null;
}
}
//Preparing the file to send...
//YodaSyndrome - 몽환적인 노래 모음집(2017-03-09).mp3 is 42336621 bytes.
//YodaSyndrome - 몽환적인 노래 모음집(2017-03-09).mp3 compressed is 41894838 bytes large in 1.990s.
//Sending the file in 5115 blocks, using a max block size of 8192 bytes.
}
}
|
0d9b6f74928ec6148cc552abc8d2f53530be939c
|
C#
|
Garados007/IlarosLauncher
|
/IlarosLauncher/WriteAbleStreamFaker.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace IlarosLauncher
{
public class WriteAbleStreamFaker : Stream
{
Stream stream;
bool discardChanges, disposeBaseStream;
long virtualLength;
long position;
public WriteAbleStreamFaker(Stream baseStream, bool discardChanges, bool disposeBaseStream)
{
stream = baseStream ?? throw new ArgumentNullException("baseStream");
this.discardChanges = discardChanges;
if (!discardChanges) throw new NotImplementedException("caching changes is not implemented now");
this.disposeBaseStream = disposeBaseStream;
virtualLength = stream.Length;
}
public override bool CanRead => true;
public override bool CanSeek => true;
public override bool CanWrite => true;
public override long Length => stream.Length;
public override long Position
{
get => position;
set
{
if (value < 0 || value >= virtualLength) throw new ArgumentOutOfRangeException();
position = value;
if (position < stream.Length) stream.Position = value;
}
}
public override void Flush()
{
}
public override int Read(byte[] buffer, int offset, int count)
{
var t = 0;
int l;
if (position < stream.Length && position < virtualLength)
{
l = (int)Math.Min(count, Math.Min(stream.Length - position, virtualLength - position));
var r = stream.Read(buffer, offset, l);
count -= r;
offset += r;
t += r;
position += r;
}
l = (int)Math.Min(count, virtualLength - position);
for (int i = 0; i < l; ++i) buffer[i + offset] = 0;
position += l;
return t + l;
}
public override long Seek(long offset, SeekOrigin origin)
{
switch (origin)
{
case SeekOrigin.Begin: return Position = offset;
case SeekOrigin.End: return Position = virtualLength + offset - 1;
default: return Position = position + offset;
}
}
public override void SetLength(long value)
{
virtualLength = value;
}
public override void Write(byte[] buffer, int offset, int count)
{
position += count;
if (virtualLength < position) virtualLength = position;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposeBaseStream) stream.Dispose();
}
}
}
|
9a3076429a1aaf31a65e8c94bebc92c23eb5203e
|
C#
|
ERNICommunity/ActivityContext.NET
|
/src/ActivityContext/Data/ActivityInfoList.cs
| 2.59375
| 3
|
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
namespace ActivityContext.Data
{
/// <summary>
/// Data object representing list of activities.
/// </summary>
[CollectionDataContract(Name = ElementName, Namespace = ElementNamespace)]
public sealed class ActivityInfoList : List<ActivityInfo>
{
/// <summary>
/// Name of the XML element generated by <see cref="DataContractSerializer"/>.
/// </summary>
public const string ElementName = "Activities";
/// <summary>
/// Namespace of the XML element generated by <see cref="DataContractSerializer"/>.
/// </summary>
public const string ElementNamespace = Strings.ActivityContextNamespace;
/// <summary>
/// Default instance of <see cref="DataContractSerializer"/> for type <see cref="ActivityInfoList"/>.
/// </summary>
public static DataContractSerializer DefaultSerializer { get; } = new DataContractSerializer(typeof(ActivityInfoList));
/// <summary>
/// Default instance of <see cref="DefaultJsonSerializer"/> for type <see cref="ActivityInfoList"/>.
/// </summary>
public static DataContractJsonSerializer DefaultJsonSerializer { get; } = new DataContractJsonSerializer(typeof(ActivityInfoList));
}
}
|
b65b6419fe32fb6c1df767193779fec8dbcd394f
|
C#
|
ProneDragonJohn/Class_Average
|
/CIS3343 Assignment2 Velazquez.John/CIS3343 Assignment2 Velazquez.John/Program.cs
| 3.84375
| 4
|
/**********************************
* CIS 3343
* John Velazquez
*************************************
* Assignment 2
* Class Average
* Date: 9/10/2019
*************************************
* Takes as many inputs as user wants
* and takes the average and displays
* both the numerical value and the
* letter grade for the average.
*************************************/
using System;
namespace CIS3343_Assignment2_Velazquez.John
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to Gradebook v1.0\n");
//Variables to keep track of or calculate and assign to
double gradeSum = 0, gradeAvg;
int students = 0;
Grade CIS3343 = new Grade();
while(students != -1)
{
Console.Write("Enter a numeric grade or -1 to quit: ");
int input = Convert.ToInt32(Console.ReadLine());
//If user inputs '-1' program exits the loop
if(input == -1)
break;
else
{
gradeSum += input;//Adds input to value in gradeSum, assigns new sum
students++; //Students also gets incremented
}
}
gradeAvg = gradeSum / students; //Caculating average
//Console.WriteLine($"The average grade is {Math.Round(gradeAvg, 2)}");
Console.WriteLine($"The average grade is {gradeAvg:F2}");
Console.WriteLine($"The average letter grade for CIS3343 " +
$"is {CIS3343.ConvertToLetter((int)gradeAvg)}");
Console.WriteLine("\nPress Enter to exit...");
Console.ReadLine();
}
}
}
|
bae544603d6295b896e347d2904b0fdce9fe9013
|
C#
|
telerik/blazor-ui
|
/grid/batch-editing/Data/BatchEditingService.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BatchEditing.Data
{
public class BatchEditingService
{
private List<BatchEditModel> Data { get; set; }
public BatchEditingService()
{
if (Data == null)
{
var rng = new Random();
Data = Enumerable.Range(1, 50).Select(index => new BatchEditModel
{
Id = index,
Name = $"Name {index}",
Age = rng.Next(18, 100),
HireDate = DateTime.Now.Date.AddDays(-index)
}).ToList();
}
}
public Task<List<BatchEditModel>> GetData()
{
return Task.FromResult(Data);
}
public Task<List<BatchEditModel>> BatchUpdate(
List<BatchEditModel> deletedItems, List<BatchEditModel> insertedItems, List<BatchEditModel> updatedItems)
{
//just sample CRUD operations
//this is a singleton service to cater for all users at the same time
//in a real app it may be transient instead
//also, this code does not cater for concurrency conflicts and errors
//while a real service should take them into account
//e.g., insert instead of attempt an update on a missing item that another user deleted
//in this example this also returns the newly updated data for the grid
foreach (BatchEditModel item in deletedItems)
{
Data.Remove(item);
}
foreach (BatchEditModel item in insertedItems)
{
item.Id = Data.Max(item => item.Id) + 1;
Data.Insert(0, item);
}
foreach (BatchEditModel item in updatedItems)
{
var index = Data.FindIndex(i => i.Id == item.Id);
if (index != -1)
{
Data[index] = item;
}
}
//clean up the view model information to be sure we do not "predefine" user actions
foreach (BatchEditModel item in Data)
{
item.IsChanged = false;
item.IsDeleted = false;
item.IsNew = false;
}
return Task.FromResult(Data);
}
}
}
|
7d20b1772fb8263e8fd239a163c6b87de4f18f54
|
C#
|
ic-sys/SimplyMobile
|
/Core/SimplyMobile.Web/Extensions/HttpClientExtensions.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace SimplyMobile.Web
{
public static class HttpClientExtensions
{
public static async Task DownloadFile(this HttpClient httpClient, string url, string destination)
{
var stream = await httpClient.GetStreamAsync(url);
using (var writer = new StreamWriter(destination))
{
await stream.CopyToAsync(writer.BaseStream);
}
}
}
}
|
0aa03cebfbf943ac285bb5984ca6b1123a57fa07
|
C#
|
vivia1994/code_practice
|
/MyCSharp/RegularExpressions/Chinese character/Form1.cs
| 3.265625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Chinese_character
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string str = textBox1.Text;
if (isChanese(textBox1.Text))
{
textBox2.Text = "是汉字!";
}
else
{
textBox2.Text = "不是汉字!";
}
}
public bool isChanese(string str)
{
return Regex.IsMatch(str, @"^[\u4e00-\u9fa5]{1,}$");
//汉字字符编码:4e00-9fa5
//\u nnnn 使用十六进制表示形式匹配一个 Unicode 字符(由 nnnn 表示的四位数)。
// . 通配符:与除 \n 之外的任何单个字符匹配。
//若要匹配原意句点字符(. 或 \u002E),您必须在该字符前面加上转义符(\.)。 a.e "have" 中的 "ave", "mate" 中的 "ate"
}
}
}
|
3969ddf30f68f56ee1e7039e3ab0e726b705efd1
|
C#
|
Hassankashi/WebApplication1
|
/WebApplication1/Controllers/HomeController.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
public object MemoryCache { get; private set; }
class Cat
{
// Auto-implemented properties.
public int Age { get; set; }
public string Name { get; set; }
public string Date { get; set; }
}
[OutputCache(CacheProfile = "CacheMahsa")]
public ActionResult Mahsa()
{
Cat cat = new Cat { Age = 10, Name = "Fluffy", Date = DateTime.Now.ToString() };
ViewBag.Mahsa = cat.Date;
return View();
}
public ActionResult Index()
{
return View();
//if (System.Web.HttpContext.Current.Cache["Products"] != null)
// return View(System.Web.HttpContext.Current.Cache["Products"]);
//else
//{
// string products =DateTime.Now.ToString();
// System.Web.HttpContext.Current.Cache["Products"] = products;
// return View(products);
//}
//string data = MemoryCache.Default.Get("1") as string;
//if (data == null)
//{
// data = // actually get your data from the database here
// MemoryCache.Default.Add(MYCACHEKEY, data, DateTimeOffset.Now.AddHours(24));
//}
//ViewBag.Message = DateTime.Now.ToString();
//ObjectCache cache = EnterpriseLibraryContainer.Current.GetInstance<ObjectCache>(
//"CacheName");
//object valueToSet = new Object(); // Set this to the value to add to the cache
//// Example of an absolute expiration policy.
//// Item will expire in 2 minutes, regardless if it is accessed or not
//var absoluteExpirationPolicy = new CacheItemPolicy { AbsoluteExpiration = DateTime.Now.AddMinutes(2) };
//// Example of a sliding expiration cache item policy
//// item will expire if not accessed for more than 2 minutes
//var slidingExpirationPolicy = new CacheItemPolicy { SlidingExpiration = new TimeSpan(0, 0, 2, 0) };
//// Example of a policy that defines that item will not expire. It will only be // removed.
//// if the cache becomes full.
//var notExpiringPolicy = new CacheItemPolicy();
//// The add method will only add the item if it doesn't already exist
//bool added = cache.Add("CacheKey", valueToSet, notExpiringPolicy);
//// The set method will add or overwrite an item.
//cache.Set("CacheKey", valueToSet, notExpiringPolicy);
//// When setting a cache item using the indexer, it will always be set to
//// infinite expiration
//cache["CacheKey"] = valueToSet;
//// The AddOrGetExisting method will try to add it if it doesn't already
//// exist. If it has added it, then it will return the added item
//// else it will return the already cached item.
//var cachedValueOrValueToSet = cache.AddOrGetExisting("CacheKey", valueToSet,
// notExpiringPolicy);
//string date1 = DateTime.Now.ToString();
//if (ControllerContext.HttpContext.Cache["MyKey"] == null)
//{
// //ControllerContext.HttpContext.Cache.Insert.Items.Add("user" ,"lkl");
// ControllerContext.HttpContext.Cache.Insert("MyKey", date1, null, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration);
//// HttpRuntime.Cache.Insert(
////"MyKey", date1,
////null,
////DateTime.Now.AddMinutes(1440),
////System.Web.Caching.Cache.NoSlidingExpiration);
//}
//else
//{
// string s = ControllerContext.HttpContext.Cache["MyKey"].ToString();
//}
//return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
|
c4fdefff3995cdc30937082d2e281693475ff6a1
|
C#
|
fadookie/ggj2015
|
/Assets/code/utility/IListExtensions.cs
| 3.375
| 3
|
using UnityEngine;
using System.Collections.Generic;
using System.Text;
static class IListExtensions {
public static void Swap<T>(this IList<T> list, int firstIndex, int secondIndex) {
T tmp = list[firstIndex];
list[firstIndex] = list[secondIndex];
list[secondIndex] = tmp;
}
/// <summary>
/// Shuffle the array. Implements the Fisher-Yates/Knuth shuffle
/// </summary>
/// <typeparam name="T">Array element type.</typeparam>
/// <param name="array">Array to shuffle.</param>
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
for (int i = 0; i < n; i++)
{
int r = i + (int)(Random.value * (n - i));
T t = list[r];
list[r] = list[i];
list[i] = t;
}
}
public static string toString<T>(this IEnumerable<T> elements)
{
StringBuilder sb = new StringBuilder("[");
foreach (var element in elements)
{
sb.AppendFormat("{0},", element);
}
sb.Remove(sb.Length - 1, 1);
sb.Append("]");
return sb.ToString();
}
}
|
977989e216779deb08a6d497f021a9f2913a3e4d
|
C#
|
eshiett1995/Gambeat-Mimo
|
/Mimo/Assets/MimoAssets/Scripts/Tournament.cs
| 2.71875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class Tournament
{
public string id;
public string tournamentName;
public int totalPlayers;
public int playerLimit;
public bool hasStarted;
public bool hasFinished;
public bool matchEnded;
public long entryFee;
public long startTime;
public bool registered;
public int hr, day;
private List<string> players;
public Tournament(string name, int maxPlayers, long entryFee)
{
this.tournamentName = name;
this.totalPlayers = maxPlayers;
this.entryFee = entryFee;
hr = DateTime.Now.Hour;
day = DateTime.Now.Day;
updateDatabase();
}
public Tournament(string id,string name, int totalPlayers, int playerLimit, long entryFee, bool registered, long startTime, bool hasStarted, bool hasFinished, bool matchEnded)
{
this.id = id;
this.tournamentName = name;
this.totalPlayers = totalPlayers;
this.playerLimit = playerLimit;
this.entryFee = entryFee;
this.registered = registered;
this.startTime = startTime;
this.hasStarted = hasStarted;
this.hasFinished = hasFinished;
this.matchEnded = matchEnded;
hr = DateTime.Now.Hour;
day = DateTime.Now.Day;
}
public Tournament(string id, string name, int totalPlayers, int playerLimit, long entryFee)
{
this.id = id;
this.tournamentName = name;
this.totalPlayers = totalPlayers;
this.playerLimit = playerLimit;
this.entryFee = entryFee;
hr = DateTime.Now.Hour;
day = DateTime.Now.Day;
}
public void addPlayer(string playerID)
{
if (players.Count < totalPlayers)
players.Add(playerID);
Debug.Log("Player " + playerID + " added to Tournament " + tournamentName);
updateDatabase();
}
public string getTime()
{
int hrsLeft;
if (DateTime.Now.Day.Equals(day))
hrsLeft = 24 - (DateTime.Now.Hour - hr);
else
{
hrsLeft = hr - DateTime.Now.Hour;
}
return hrsLeft + " Hrs Left";
}
public int getPlayerCount()
{
return totalPlayers;
}
public int getPrize()
{
return (int)(entryFee/100 * totalPlayers);
}
public void updateDatabase()
{
if (id == null || id.Trim().Equals(""))
{
//Save New Tounament to Database
}
else
{
//Update Tournament on Database
}
Debug.Log("Tournament updated to Database");
}
}
|
66132f7db00d2fdc7f27170697d4f1b5ddd5fdbf
|
C#
|
mashiro11/rChess
|
/Assets/Scripts/GridManager.cs
| 2.59375
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GridManager : MonoBehaviour {
public static List<List<TileInfo>> Tiles;
public static List<List<Token>> Tokens;
// Use this for initialization
void Start () {
Tiles = new List<List<TileInfo>>();
for(int i = 0; i < 8; i++)
{
Tiles.Add(new List<TileInfo>());
for(int j = 0; j < 8; j++)
{
Tiles[i].Add(new TileInfo());
Tiles[i][j].SetPosition(new Vector2Int(i, j));
}
}
StartTable();
}
// Update is called once per frame
void Update () {
}
private void StartTable()
{
//linha varia com x
//coluna varia com y
//linhas serão da direita
//colunas serão da esquerda
//Torres baixo
List<string> Pecas = new List<string>();
Pecas.Add("Pecas/Torre");
Pecas.Add("Pecas/Cavalo");
Pecas.Add("Pecas/Bispo");
Pecas.Add("Pecas/Rainha");
Pecas.Add("Pecas/Rei");
Tokens = new List<List<Token>>();
Tokens.Add(new List<Token>());
Tokens.Add(new List<Token>());
GameObject aux;
for (int j = 0; j < 2; j++)
{
int line = (j == 0) ? 0 : 7;
for (int i = 0; i < Pecas.Count + 3; i++)
{
int peca = (i > 4) ? 7 - i : i;
aux = Tiles[i][line].inside = (GameObject)Instantiate(Resources.Load(Pecas[peca]), new Vector3(i, line, 0), Quaternion.identity);
Tokens[j].Add(aux.GetComponent<Token>());
Tokens[j][Tokens[j].Count - 1].player = j + 1;
}
line = (line == 0) ? 1 : 6;
for (int i = 0; i < 8; i++)
{
aux = Tiles[i][line].inside = (GameObject)Instantiate(Resources.Load("Pecas/Peao"), new Vector3(i, line, 0), Quaternion.identity);
Tokens[j].Add(aux.GetComponent<Token>());
Tokens[j][Tokens[j].Count - 1].player = j + 1;
}
}
for (int i = 0; i < Tiles.Count; i++)
{
for(int j = 0; j < Tiles[i].Count; j++)
{
GameObject auxObj = Tiles[i][j].inside;
Token auxTok;
if (auxObj && (auxTok = auxObj.GetComponent<Token>()) )
{
Debug.Log("[" + i + "][" + j + "]: " + auxTok.name + "| " + auxTok.transform.position + "player: " + auxTok.player);
}
}
}
}
public static List<TileInfo> GetFreeTiles()
{
List<TileInfo> freeTiles = new List<TileInfo>();
for(int i = 0; i < Tiles.Count; i++)
{
for(int j = 0; j < Tiles[i].Count; j++)
{
if (Tiles[i][j].IsFree())
{
freeTiles.Add(Tiles[i][j]);
}
}
}
return freeTiles;
}
}
/*
aux = Tiles[0][0].inside = (GameObject) Instantiate(Resources.Load("Torre"), new Vector3(0, 0, 0), Quaternion.identity);
Tokens[0].Add(aux.GetComponent<Token>());
Tokens[0][0].player = 1;
aux = Tiles[7][0].inside = (GameObject)Instantiate(Resources.Load("Torre"), new Vector3(7, 0, 0), Quaternion.identity);
Tokens[0].Add(aux.GetComponent<Token>());
Tokens[0][1].player = 1;
//Cavalos baixo
aux = Tiles[1][0].inside = (GameObject)Instantiate(Resources.Load("Cavalo"), new Vector3(1, 0, 0), Quaternion.identity);
Tokens[0].Add(aux.GetComponent<Token>());
Tokens[0][2].player = 1;
aux = Tiles[6][0].inside = (GameObject)Instantiate(Resources.Load("Cavalo"), new Vector3(6, 0, 0), Quaternion.identity);
Tokens[0].Add(aux.GetComponent<Token>());
Tokens[0][3].player = 1;
//Bispo baixo
aux = Tiles[2][0].inside = (GameObject)Instantiate(Resources.Load("Bispo"), new Vector3(2, 0, 0), Quaternion.identity);
Tokens[0].Add(aux.GetComponent<Token>());
Tokens[0][4].player = 1;
aux = Tiles[5][0].inside = (GameObject)Instantiate(Resources.Load("Bispo"), new Vector3(5, 0, 0), Quaternion.identity);
Tokens[0].Add(aux.GetComponent<Token>());
Tokens[0][5].player = 1;
//Rainha baixo
aux = Tiles[3][0].inside = (GameObject)Instantiate(Resources.Load("Rainha"), new Vector3(3, 0, 0), Quaternion.identity);
Tokens[0].Add(aux.GetComponent<Token>());
Tokens[0][6].player = 1;
//Rei baixo
aux = Tiles[4][0].inside = (GameObject)Instantiate(Resources.Load("Rei"), new Vector3(4, 0, 0), Quaternion.identity);
Tokens[0].Add(aux.GetComponent<Token>());
Tokens[0][7].player = 1;
//Torres cima
aux = Tiles[0][7].inside = (GameObject)Instantiate(Resources.Load("Torre"), new Vector3(0, 7, 0), Quaternion.identity);
Tokens[1].Add(aux.GetComponent<Token>());
Tokens[1][0].player = 2;
aux = Tiles[7][7].inside = (GameObject)Instantiate(Resources.Load("Torre"), new Vector3(7, 7, 0), Quaternion.identity);
Tokens[1].Add(aux.GetComponent<Token>());
Tokens[1][1].player = 2;
//Cavalos cima
aux = Tiles[1][7].inside = (GameObject)Instantiate(Resources.Load("Cavalo"), new Vector3(1, 7, 0), Quaternion.identity);
Tokens[1].Add(aux.GetComponent<Token>());
Tokens[1][2].player = 2;
aux = Tiles[6][7].inside = (GameObject)Instantiate(Resources.Load("Cavalo"), new Vector3(6, 7, 0), Quaternion.identity);
Tokens[1].Add(aux.GetComponent<Token>());
Tokens[1][3].player = 2;
//Bispo cima
aux = Tiles[2][7].inside = (GameObject)Instantiate(Resources.Load("Bispo"), new Vector3(2, 7, 0), Quaternion.identity);
Tokens[1].Add(aux.GetComponent<Token>());
Tokens[1][4].player = 2;
aux = Tiles[5][7].inside = (GameObject)Instantiate(Resources.Load("Bispo"), new Vector3(5, 7, 0), Quaternion.identity);
Tokens[1].Add(aux.GetComponent<Token>());
Tokens[1][5].player = 2;
//Rainha cima
aux = Tiles[3][7].inside = (GameObject)Instantiate(Resources.Load("Rainha"), new Vector3(3, 7, 0), Quaternion.identity);
Tokens[1].Add(aux.GetComponent<Token>());
Tokens[1][6].player = 2;
//Rei cima
aux = Tiles[4][7].inside = (GameObject)Instantiate(Resources.Load("Rei"), new Vector3(4, 7, 0), Quaternion.identity);
Tokens[1].Add(aux.GetComponent<Token>());
Tokens[1][7].player = 2;
*/
/*
//Peoes
for (int i = 0; i < 8; i++)
{
//baixo
aux = Tiles[i][1].inside = (GameObject)Instantiate(Resources.Load("Peao"), new Vector3(i, 1, 0), Quaternion.identity);
Tokens[0].Add(aux.GetComponent<Token>());
Tokens[0][i+8].player = 1;
//cima
aux = Tiles[i][6].inside = (GameObject)Instantiate(Resources.Load("Peao"), new Vector3(i, 6, 0), Quaternion.identity);
Tokens[1].Add(aux.GetComponent<Token>());
Tokens[1][i + 8].player = 2;
Debug.Log("i: " + i);
}
*/
|
646150d4330943332afc43f22ec0fd620f1bbd65
|
C#
|
arleyschrock/ScripTerasu.ManageAzureAD
|
/ScripTerasu.ManageAzureAD/Model/Automation/NewUser.cs
| 2.75
| 3
|
using ScripTerasu.ManageAzureAD.Properties;
using System;
using System.ComponentModel;
using System.Text.RegularExpressions;
namespace ScripTerasu.ManageAzureAD.Model.Automation
{
public class NewUser : IDataErrorInfo
{
#region Creation
public static NewUser CreateNewUser()
{
return new NewUser();
}
public static NewUser CreateNewUser(
string displayName,
string userPrincipalName)
{
return new NewUser
{
//DisplayName = displayName,
//UserPrincipalName = userPrincipalName
};
}
protected NewUser()
{
}
#endregion // Creation
#region IDataErrorInfo Members
string IDataErrorInfo.Error { get { return null; } }
string IDataErrorInfo.this[string propertyName]
{
get { return this.GetValidationError(propertyName); }
}
#endregion // IDataErrorInfo Members
#region Validation
/// <summary>
/// Returns true if this object has no validation errors.
/// </summary>
public bool IsValid
{
get
{
foreach (string property in ValidatedProperties)
if (GetValidationError(property) != null)
return false;
return true;
}
}
static readonly string[] ValidatedProperties =
{
"DisplayName",
"UserPrincipalName",
};
string GetValidationError(string propertyName)
{
if (Array.IndexOf(ValidatedProperties, propertyName) < 0)
return null;
string error = null;
switch (propertyName)
{
case "DisplayName":
error = this.ValidateDisplayName();
break;
case "UserPrincipalName":
error = this.ValidateUserPrincipalName();
break;
default:
//Debug.Fail("Unexpected property being validated on Customer: " + propertyName);
break;
}
return error;
}
string ValidateDisplayName()
{
//if (IsStringMissing(this.DisplayName))
//{
// return Strings.NewUser_Error_MissingDisplayName;
//}
return null;
}
string ValidateUserPrincipalName()
{
//if (IsStringMissing(this.UserPrincipalName))
//{
// return Strings.NewUser_Error_MissingUserPrincipalName;
//}
//else if (!IsValidUserPrincipalName(this.UserPrincipalName))
//{
// return Strings.NewUser_Error_InvalidUserPrincipalName;
//}
return null;
}
#endregion // Validation
}
}
|
0267ba2ab2df2458d2ed125e931c26cf97618963
|
C#
|
Jddrago/PlannedProject-RPG-
|
/PlannedProject-RPG-/PlannedProject-RPG-/Die.cs
| 2.828125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PlannedProject_RPG_
{
public class Die
{
private int numSides,lastRoll;
public Die(int numOfSides)
{
numSides = numOfSides;
}
public void roll()
{
Random roller = new Random();
lastRoll = roller.Next(numSides)+1;
}
public int getLastRoll()
{
return lastRoll;
}
}
}
|
ce2e2ea24dd1cf1e7830adc74388c6f1ff8998fa
|
C#
|
ywl20013/ywl.web.v3
|
/Ywl.Data.Entity.Models/NamedEntity.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Ywl.Data.Entity.Models
{
public class NamedEntity : Entity
{
[MaxLength(256)]
[Display(Name = "名称", Description = "")]
public string Name { get; set; }
public NamedEntity() { }
public NamedEntity(NamedEntity source) { this.CopyFrom(source); }
public virtual void CopyFrom(NamedEntity source)
{
base.CopyFrom(source);
this.Id = source.Id;
this.Name = source.Name;
}
}
public class CreatedEntity : NamedEntity
{
/// <summary>
/// 创建人
/// </summary>
[Display(Name = "创建人", Description = "")]
public int? Creator { get; set; }
///// <summary>
///// 创建人
///// </summary>
//[Display(Name = "创建人", Description = "")]
//[MaxLength(50)]
//public string CreatorName { get; set; }
/// <summary>
/// 创建时间; 创建时间
/// </summary>
[Display(Name = "创建时间", Description = "创建时间")]
public DateTime? CreateTime { get; set; }
public CreatedEntity() { }
public CreatedEntity(CreatedEntity source) { this.CopyFrom(source); }
public virtual void CopyFrom(CreatedEntity source)
{
base.CopyFrom(source);
this.CreateTime = source.CreateTime;
this.Creator = source.Creator;
//this.CreatorName = source.CreatorName;
}
}
}
|
b71492de0a008ac39aabfefb2f0cccc352f77a75
|
C#
|
keganm/AndroidDev
|
/Assets/Scripts/Engine/FileLoader.cs
| 2.8125
| 3
|
using UnityEngine;
using System.Collections;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
[XmlRoot("HighScoreCollection")]
public class HighScoreContainer
{
[XmlArray("HighScore"), XmlArrayItem("HighScore")]
public int[] HighScore;
public void Save(string path)
{
XmlSerializer serializer = new XmlSerializer (typeof(HighScoreContainer));
using( FileStream stream = new FileStream(path, FileMode.Create))
{
serializer.Serialize(stream, this);
}
}
public static HighScoreContainer Load(string path)
{
XmlSerializer serializer = new XmlSerializer (typeof(HighScoreContainer));
using (FileStream stream = new FileStream(path, FileMode.Open))
{
return serializer.Deserialize(stream) as HighScoreContainer;
}
}
public static HighScoreContainer LoadFromText(string text)
{
XmlSerializer serializer = new XmlSerializer (typeof(HighScoreContainer));
return serializer.Deserialize (new StringReader (text)) as HighScoreContainer;
}
}
public class FileLoader : MonoBehaviour {
void Start()
{
HighScoreContainer highScores = new HighScoreContainer ();
highScores.HighScore = new int[10];
Debug.Log ("Input");
for (int i = 0; i < highScores.HighScore.Length; i++) {
highScores.HighScore[i] = Random.Range(0,1000);
Debug.Log(i.ToString() + " :: " + highScores.HighScore[i].ToString());
}
highScores.Save (Path.Combine (Application.persistentDataPath, "HighScores.xml"));
Debug.Log ("Clear");
highScores = new HighScoreContainer ();
highScores.HighScore = new int[10];
for(int i = 0; i < highScores.HighScore.Length; i++)
{
Debug.Log(i.ToString() + " :: " + highScores.HighScore[i].ToString());
}
Debug.Log ("Loaded");
highScores = HighScoreContainer.Load(Path.Combine(Application.persistentDataPath, "HighScores.xml"));
for(int i = 0; i < highScores.HighScore.Length; i++)
{
Debug.Log(i.ToString() + " :: " + highScores.HighScore[i].ToString());
}
}
}
|
141ed948136b2f7036fa04c74461a9646f2574bd
|
C#
|
danslapman/PatternMatching
|
/Patterns/Matcher.cs
| 2.84375
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace Patterns
{
/// <summary>
/// Pattern matcher with void return type
/// </summary>
/// <typeparam name="T">Matcher argument type</typeparam>
public class Matcher<T> : IEnumerable<T>
{
/// <summary>
/// List of case expressions
/// </summary>
protected readonly List<BlockExpression> CaseExpressionsList = new List<BlockExpression>();
private ParameterExpression _parameter;
/// <summary>
/// Expression representing matching parameter
/// </summary>
protected ParameterExpression Parameter => _parameter ?? (_parameter = Expression.Parameter(typeof(T), "inputValue"));
private LabelTarget _retPoint;
/// <summary>
/// Expression representing return point
/// </summary>
protected LabelTarget RetPoint => _retPoint ?? (_retPoint = Expression.Label());
/// <summary>
/// Adds context-based matching case
/// </summary>
/// <typeparam name="TCtx">Context type</typeparam>
public void Add<TCtx>(Expression<Func<T, TCtx>> binder, Expression<Action<TCtx>> processor)
{
var bindResult = Expression.Variable(typeof(TCtx), "binded");
var caseExpr = Expression.Block(
new[] { bindResult },
Expression.Assign(bindResult, Expression.Invoke(binder, Parameter)),
Expression.IfThen(
Expression.NotEqual(Expression.Convert(bindResult, typeof(object)), Expression.Constant(null)),
Expression.Return(RetPoint, Expression.Invoke(processor, bindResult))
));
CaseExpressionsList.Add(caseExpr);
}
/// <summary>
/// Adds predicated-based matching case
/// </summary>
public void Add(Expression<Predicate<T>> condition, Expression<Action<T>> processor)
{
var caseExpr = Expression.Block(Expression.IfThen(
Expression.Invoke(condition, Parameter),
Expression.Return(RetPoint, Expression.Invoke(processor, Parameter))
));
CaseExpressionsList.Add(caseExpr);
}
private Action<T> CompileMatcher()
{
var finalExpressions = new Expression[]
{
Expression.Throw(Expression.Constant(new MatchException("Provided value was not matched with any case"))),
Expression.Label(RetPoint)
};
var matcherExpression = Expression.Block(CaseExpressionsList.Concat(finalExpressions)
);
return Expression.Lambda<Action<T>>(matcherExpression, Parameter).Compile();
}
private Action<T> _matcher;
private Action<T> MatcherFunc => _matcher ?? (_matcher = CompileMatcher());
/// <summary>
/// Performs match on the given value
/// </summary>
public void Match(T value)
{
MatcherFunc(value);
}
/// <summary>
/// Converts matcher into Action<T> instance
/// </summary>
public static implicit operator Action<T>(Matcher<T> matcher)
{
return matcher.Match;
}
/// <summary>
/// Creates Action<T> instance
/// </summary>
public Action<T> ToAction()
{
return MatcherFunc;
}
/// <summary>
/// Stub
/// </summary>
public IEnumerator<T> GetEnumerator()
{
throw new InvalidOperationException("This is a stub. There is nothing to enumerate in Matcher.");
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
/// <summary>
/// Pattern matcher
/// </summary>
/// <typeparam name="TIn">Argument type</typeparam>
/// <typeparam name="TOut">Return type</typeparam>
public class Matcher <TIn, TOut> : IEnumerable<TOut>
{
/// <summary>
/// List of case expressions
/// </summary>
protected readonly List<BlockExpression> CaseExpressionsList = new List<BlockExpression>();
private ParameterExpression _parameter;
/// <summary>
/// Expression representing matching parameter
/// </summary>
protected ParameterExpression Parameter => _parameter ?? (_parameter = Expression.Parameter(typeof (TIn), "inputValue"));
private LabelTarget _retPoint;
/// <summary>
/// Expression representing return point
/// </summary>
protected LabelTarget RetPoint => _retPoint ?? (_retPoint = Expression.Label(typeof (TOut)));
/// <summary>
/// Adds context-based matching case
/// </summary>
/// <typeparam name="TCtx">Context type</typeparam>
public void Add<TCtx>(Expression<Func<TIn, TCtx>> binder, Expression<Func<TCtx, TOut>> processor)
{
var bindResult = Expression.Variable(typeof (TCtx), "binded");
var caseExpr = Expression.Block(
new []{bindResult},
Expression.Assign(bindResult, Expression.Invoke(binder, Parameter)),
Expression.IfThen(
Expression.NotEqual(Expression.Convert(bindResult, typeof(object)), Expression.Constant(null)),
Expression.Return(RetPoint, Expression.Invoke(processor, bindResult))
));
CaseExpressionsList.Add(caseExpr);
}
/// <summary>
/// Adds predicated-based matching case
/// </summary>
public void Add(Expression<Predicate<TIn>> condition, Expression<Func<TIn, TOut>> processor)
{
var caseExpr = Expression.Block(Expression.IfThen(
Expression.Invoke(condition, Parameter),
Expression.Return(RetPoint, Expression.Invoke(processor, Parameter))
));
CaseExpressionsList.Add(caseExpr);
}
private Func<TIn, TOut> CompileMatcher()
{
var finalExpressions = new Expression[]
{
Expression.Throw(Expression.Constant(new MatchException("Provided value was not matched with any case"))),
Expression.Label(RetPoint, Expression.Default(typeof(TOut)))
};
var matcherExpression = Expression.Block(CaseExpressionsList.Concat(finalExpressions));
var lambda = Expression.Lambda<Func<TIn, TOut>>(matcherExpression, Parameter);
var matcher = lambda.Compile();
return matcher;
}
private Func<TIn, TOut> _matcher;
private Func<TIn, TOut> MatcherFunc => _matcher ?? (_matcher = CompileMatcher());
/// <summary>
/// Performs match on the given value
/// </summary>
public TOut Match(TIn value)
{
return MatcherFunc(value);
}
/// <summary>
/// Converts matcher into Func<T> instance
/// </summary>
public static implicit operator Func<TIn, TOut>(Matcher<TIn, TOut> matcher)
{
return matcher.Match;
}
/// <summary>
/// Creates Func<T> instance
/// </summary>
public Func<TIn, TOut> ToFunc()
{
return MatcherFunc;
}
/// <summary>
/// Stub
/// </summary>
public IEnumerator<TOut> GetEnumerator()
{
throw new InvalidOperationException("This is a stub. There is nothing to enumerate in Matcher.");
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
|
f0eb854970cceb1d03ef9ca53e5e8f1c3c719a15
|
C#
|
Grimelios/LudumDare46
|
/Engine/Shapes/3D/FlatShape3D.cs
| 2.890625
| 3
|
using System.Diagnostics;
using Engine.Shapes._2D;
using GlmSharp;
namespace Engine.Shapes._3D
{
// This represents any flat (i.e. 2D) shape with a 3D transform. Useful for combat calculations (plus probably
// other uses).
public class FlatShape3D : Shape3D
{
private Shape2D flatShape;
public FlatShape3D() : this(null)
{
}
public FlatShape3D(Shape2D flatShape, bool isOrientable = true) : base(ShapeTypes3D.Flat, isOrientable)
{
if (flatShape != null)
{
FlatShape = flatShape;
}
}
public Shape2D FlatShape
{
get => flatShape;
set
{
Debug.Assert(value != null, "Can't nullify a flat shape.");
Debug.Assert(value.Type != ShapeTypes2D.Line, "Can't create a 3D version of a 2D line (just use " +
"Line3D instead).");
flatShape = value;
}
}
protected override bool Contains(vec3 p)
{
// TODO: Finish this implementation (if needed).
return false;
}
}
}
|
9dc9ed124c3cba1ce2b556707e8694f2e2f9bd0a
|
C#
|
Fawnzz/TestPALM
|
/PalmBusinessLayer/Risk_RiskDB.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using PalmDataLayer;
using System.Data;
namespace PalmBusinessLayer
{
public class Risk_RiskDB
{
public void Insert_Risk(Risk myRisk) //insert method
{
SqlConnection conn = Connection.GetConnection();
SqlCommand cmd = new SqlCommand("spInsertRisk", conn);
cmd.CommandType = CommandType.StoredProcedure;
// cmd.Parameters.AddWithValue("@id",myRisk.Id); // first is table and second is variable
cmd.Parameters.AddWithValue("@status_id", myRisk.Status_id);
cmd.Parameters.AddWithValue("@closing_date", SqlDbType.DateTime).Value = Convert.ToDateTime(myRisk.Closing_date);
cmd.Parameters.AddWithValue("@value", myRisk.Value);
cmd.Parameters.AddWithValue("@description", myRisk.Description);
cmd.Parameters.AddWithValue("@mitigation", myRisk.Mitigation);
cmd.Parameters.AddWithValue("@user_id", myRisk.User_id);
cmd.Parameters.AddWithValue("@sch_likelihood", myRisk.Sch_likelihood);
cmd.Parameters.AddWithValue("@sch_impact", myRisk.Sch_impact);
cmd.Parameters.AddWithValue("@cost_likelihood", myRisk.Cost_likelihood);
cmd.Parameters.AddWithValue("@cost_impact", myRisk.Cost_impact);
cmd.Parameters.AddWithValue("@qty_likelihood", myRisk.Qty_likelihood);
cmd.Parameters.AddWithValue("@qty_impact", myRisk.Qty_impact);
cmd.Parameters.AddWithValue("@comment", myRisk.Comment);
cmd.Parameters.AddWithValue("@userClient", myRisk.UserClient);
cmd.Parameters.AddWithValue("@priority_id", myRisk.Priority_id);
cmd.Parameters.AddWithValue("@response_id", myRisk.Response_id);
cmd.Parameters.AddWithValue("@risk_orginal_id", myRisk.risk_orginal_id);
cmd.Parameters.AddWithValue("@calculate", myRisk.Calculate);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
}
public DataSet Select_Risks()
{
SqlConnection conn = Connection.GetConnection();
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter("Select * from Risks", conn);
DataSet ds = new DataSet();
adp.Fill(ds);
return ds;
}
public DataTable CalcSch()
{
SqlConnection conn = Connection.GetConnection();
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter("Select * from Risks", conn);
DataTable dt = new DataTable();
adp.Fill(dt);
int x = Convert.ToInt32(dt.Rows[0][6].ToString()); // converting into int
return dt;
}
public void Update_Risk(Risk myRisk) // my update method
{
Risk_RiskDB da = new Risk_RiskDB();
SqlConnection conn = Connection.GetConnection();
SqlCommand cmd = new SqlCommand("spUpdateRisk", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@status_id", myRisk.Status_id); // first is table name and second is my variable
cmd.Parameters.AddWithValue("@closing_date", myRisk.Closing_date);
cmd.Parameters.AddWithValue("@value", myRisk.risk_orginal_id);
cmd.Parameters.AddWithValue("@description", myRisk.Description);
cmd.Parameters.AddWithValue("@mitigation", myRisk.Mitigation);
cmd.Parameters.AddWithValue("@user_id", myRisk.User_id);
cmd.Parameters.AddWithValue("@sch_likelihood", myRisk.Sch_likelihood);
cmd.Parameters.AddWithValue("@sch_impact", myRisk.Sch_impact);
cmd.Parameters.AddWithValue("@cost_likelihood", myRisk.Cost_likelihood);
cmd.Parameters.AddWithValue("@cost_impact", myRisk.Cost_impact);
cmd.Parameters.AddWithValue("@qty_likelihood", myRisk.Qty_likelihood);
cmd.Parameters.AddWithValue("@qty_impact", myRisk.Qty_impact);
cmd.Parameters.AddWithValue("@comment", myRisk.Comment);
cmd.Parameters.AddWithValue("@userClient", myRisk.UserClient);
cmd.Parameters.AddWithValue("@priority_id", myRisk.Priority_id);
cmd.Parameters.AddWithValue("@response_id", myRisk.Response_id);
cmd.Parameters.AddWithValue("@risk_orginal_id", myRisk.risk_orginal_id);
cmd.Parameters.AddWithValue("@calculate", myRisk.Calculate);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
}
public void Delete_Risk(int id) // my Delete method
{
SqlConnection conn = Connection.GetConnection();
SqlCommand cmd = new SqlCommand("spDeleteRisk", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id", id);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
}
//private int calPriority(int a, int b, int c, int d, int ef, int f)
//{
// int v1 = (a * b) + (c * d) + (ef * f);
// int priority;
// if (v1 < 100)
// {
// priority = 2;
// }
// else if (v1 > 100 && v1 < 200)
// {
// priority = 5;
// }
// else if (v1 > 100)
// {
// priority = 3;
// }
// else
// {
// priority = 0;
// }
// return priority;
//}
}
}
|
5ff3a9bc15a4cfba6514caf0b9ea65a65d733d50
|
C#
|
aksu2612/WindowsForm-App
|
/Smartiys_/Gorevler.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Smartiys_
{
public partial class Gorevler : Form
{
public Gorevler()
{
InitializeComponent();
}
private void DrawIt()
{
Point[] points = {new Point(40, 60),new Point(50, 70),new Point(30, 90)};
GraphicsPath path = new GraphicsPath();
path.StartFigure(); // Start the first figure.
path.AddArc(175, 50, 50, 50, 0, -180);
path.AddLine(100, 0, 250, 20);
// First figure is not closed.
path.StartFigure(); // Start the second figure.
path.AddLine(50, 20, 5, 90);
path.AddCurve(points, 3);
path.AddLine(50, 150, 150, 180);
path.CloseFigure(); // Second figure is closed.
}
private void button1_Click(object sender, EventArgs e)
{
DrawIt();
}
private void Gorevler_Load(object sender, EventArgs e)
{
}
}
}
|
de2f040d52b1069cf802b4061beba82f6b4724e8
|
C#
|
bungeemonkee/Configgy
|
/Configgy/Source/FileSource.cs
| 3.03125
| 3
|
using System;
using System.IO;
namespace Configgy.Source
{
/// <summary>
/// An <see cref="IValueSource"/> that looks for files with the extension '.config', '.json', or '.xml' in the application base directory and have the same name as the requested value.
/// </summary>
public class FileSource : ValueSourceAttributeBase
{
private readonly string[] _fileExtensions;
/// <summary>
/// Creates a default FileSource that looks for files with the extensions '.conf', '.json', or '.xml'.
/// </summary>
public FileSource()
: this(".conf", ".json", ".xml")
{ }
/// <summary>
/// Creates a FileSource that looks for files with the given extensions.
/// </summary>
public FileSource(params string[] fileExtensions)
{
_fileExtensions = fileExtensions ?? new string[0];
}
/// <inheritdoc cref="IValueSource.Get"/>
public override bool Get(IConfigProperty property, out string value)
{
var baseDirectory = AppContext.BaseDirectory;
foreach (var extension in _fileExtensions)
{
var path = Path.Combine(baseDirectory, property.ValueName + extension);
try
{
value = File.ReadAllText(path);
return true;
}
catch (FileNotFoundException)
{
// Ignore files that are not found, but other errors are actual errors
}
}
value = null;
return false;
}
}
}
|
c1372b3ef82d69ce78a96f0a31312c908b150183
|
C#
|
bartosz-macczak/recruitment-tasks
|
/C#_tasks.cs
| 3.453125
| 3
|
using System;
using System.Collections.Generic;
namespace RecruitmentTasks
{
class Program
{
static void Main(string[] args)
{
}
//Task1
static string[] ReverseArray(string[] text)
{
int textLength = text.Length;
string[] reversedText = new string[textLength];
int x = 0;
for (int i = textLength - 1; i >= 0; i--)
{
reversedText[x] = text[i];
x++;
}
return reversedText;
}
//Task2
static void Palindrome(string text)
{
string[] nonLetters = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "=", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "+", " ", "[", "]", "{", "}", "/", ";", ":", "|", "'", ",", ".", "?", "<", ">" };
//left only letters
foreach (string x in nonLetters)
{
text = text.Replace(x, "");
}
text = text.ToLower();
int first = 0;
int last = text.Length - 1;
int pairsAmmount = text.Length / 2;
//check if palindrome
for(int i = pairsAmmount; i>0; i--)
{
if(text[first] != text[last])
{
Console.WriteLine("NO");
return;
}
first++; last--;
}
Console.WriteLine("YES");
}
//Task3
static string Permutation(int[]a, int[]b)
{
Array.Sort(a);
Array.Sort(b);
for(int i = a.Length-1; i>=0; i--)
{
if (a[i] != b[i])
return "NO";
}
return "YES";
}
//Task4
static string ExistingOfPower2(List<int> intList)
{
List<int> resultList = new List<int>();
string result = "";
foreach(int x in intList)
{
for (int i =31; i>=0; i--)
{
if(x==Math.Pow(2,i))
{
resultList.Add(x);
}
}
}
resultList.Sort();
foreach(int z in resultList)
{
result += z + ",";
}
if(result == "")
{
return "NA";
}
return result;
}
//Task5
static int[] FindingPrimes(int[,] numbers)
{
int cases = numbers[0, 0];
int[] results = new int[cases];
for(int z = 0; z<cases; z++)
{
bool ifPrime = false;
int min = numbers[z+1, 0];
int max = numbers[z+1, 1];
List<int> PrimesList = new List<int>();
//Find prime numbers in the interval
for (int i = min; i <= max; i++)//give number to check
{
for (int x = 2; x <= max; x++)//give divider
{
if (x != i)
{
if (i % x == 0)
{
ifPrime = true;
}
}
}
if (ifPrime != true)
{
if (i != 1)
PrimesList.Add(i);
}
ifPrime = false;
}
//Console.WriteLine(PrimesList.Count);
results[z] = PrimesList.Count;
}
return results;
}
//Task8
static int CommonDigit (int a, int[] b)
{
int[] count = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
string allDigits = "";
//string with all digits
for(int i = 0; i<a; i++)
{
allDigits += b[i];
}
//array with ammount of every digit
for(int x = 0; x<allDigits.Length; x++)
{
count[allDigits[x]-'0']++;
}
//find most common digit
int max = 0;
for (int z = 0; z<=9; z++)
{
if(count[z]>count[max] || count[z] == count[max])
{
max = z;
}
}
return max;
}
//Task 9
static int DigitSum(int a, int[] b)
{
int postitionOfMax = 0;
int[] sumArray = new int[a];
for(int i = 0; i<a; i++)
{
sumArray[i] = 0;
while (b[i] != 0)
{
sumArray[i] += b[i] % 10;
b[i] /= 10;
}
}
for (int z = 0; z < a; z++)
{
if (sumArray[z] > sumArray[postitionOfMax] || sumArray[z] == sumArray[postitionOfMax])
{
postitionOfMax = z;
}
}
return postitionOfMax;
}
}
}
|
a110e44c970eebd517ffba90e2ee76e407d6fc1d
|
C#
|
IllusiveJack/Homeworks
|
/Arrays-HW/ArraysHW/Binary Search/Program.cs
| 4.15625
| 4
|
using System;
namespace Binary_Search
{
class Program
{
class BinarySearch
{
static void Search(int[] arr, int start, int end, int element)
{
if (end <= start)
{
Console.WriteLine("Not Found!");
return;
}
else
{
int middle = start + (end - start) / 2;
if (element < arr[middle])
{
Search(arr, start, middle - 1, element);
}
else if (element > arr[middle])
{
Search(arr, middle + 1, end, element);
}
else
{
Console.WriteLine("The index of {0} is {1}", element, middle);
return;
}
}
}
static void Main()
{
Console.Write("Size of the array: ");
int N = int.Parse(Console.ReadLine());
int[] Arr = new int[N];
for (int index = 0; index < N; index++)
{
Console.WriteLine("Enter array #" + (index + 1) + ": ");
Arr[index] = int.Parse(Console.ReadLine());
}
Console.Write("Enter element to search for: ");
int element = int.Parse(Console.ReadLine());
Array.Sort(Arr);
Search(Arr, 0, Arr.Length, element);
}
}
}
}
|
647a001449d568b4398f1ecdacc3d7ac953bebea
|
C#
|
awenonian/GameProject
|
/GameProject/Enemy.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace GameProject
{
class Enemy : Object
{
private Plan shot;
private double shotTimer;
private Texture2D bulletLine;
private Random random;
public Enemy(Mesh mesh, Vector2 position, Texture2D bulletLine, Manager manager) : base(mesh, position, manager)
{
shot = null;
this.bulletLine = bulletLine;
random = new Random();
shotTimer = 1 + (.5 * random.NextDouble());
}
public override void update(GameTime gameTime, int width, int height)
{
shotTimer -= gameTime.ElapsedGameTime.TotalSeconds;
if (shotTimer <= 0)
{
double playerAngle = Math.Atan2(manager.Player.Position.Y - Position.X, manager.Player.Position.X - Position.X);
Console.WriteLine(playerAngle);
shot = new Plan(Position, 3, (float) (playerAngle - Math.PI / 8), (float) (playerAngle + Math.PI / 8), false, 1, bulletLine, manager);
shotTimer = 1.5 + (.5 * random.NextDouble());
}
if (shot != null)
{
if (shot.update(gameTime))
{
shot = null;
}
}
base.update(gameTime, width, height);
}
public override void draw(SpriteBatch sb)
{
if (shot != null)
{
shot.draw(sb);
}
base.draw(sb);
}
}
}
|
cc57664b1da532ca3a0dc3dd39ab57317d8da084
|
C#
|
rex-xulander/sentiments-product-catalog
|
/Product Catalog User Interface/Product Catalog User Interface/Operations.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DataOperations
{
public class Operations
{
private string ConnectionString = @"Data Source=DESKTOP-E0ADHLC\SQLEXPRESS;Initial Catalog='Master Sheets';Integrated Security=True; MultipleActiveResultSets=True";
public bool HasErrors { get; set; }
public string ExceptionMessage { get; set; }
private List<String> productNameList;
private List<String> patternNameList;
private List<String> colorNameList;
private List<String> sizeNameList;
private List<String> brandNameList;
public Operations()
{
productNameList = new List<String>();
patternNameList = new List<String>();
colorNameList = new List<String>();
sizeNameList = new List<String>();
brandNameList = new List<String>();
LoadExistingCategoryListData();
return;
}
private void LoadExistingCategoryListData()
{
using (SqlConnection cn = new SqlConnection { ConnectionString = ConnectionString })
{
cn.Open();
using (SqlCommand cmd2 = new SqlCommand { Connection = cn })
{
cmd2.CommandText = "SELECT DISTINCT PatternName FROM PatternAbrTable";
SqlDataReader reader = cmd2.ExecuteReader();
while (reader.Read())
{
patternNameList.Add(reader.GetString(0));
}
reader.Close();
}
using (SqlCommand cmd3 = new SqlCommand { Connection = cn })
{
cmd3.CommandText = "SELECT DISTINCT ColorName FROM ColorAbrTable";
SqlDataReader reader = cmd3.ExecuteReader();
while (reader.Read())
{
colorNameList.Add(reader.GetString(0));
}
}
using (SqlCommand cmd = new SqlCommand { Connection = cn })
{
cmd.CommandText = "SELECT DISTINCT ProductName FROM ProductAbrTable";
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
productNameList.Add(reader.GetString(0));
}
}
using (SqlCommand cmd4 = new SqlCommand { Connection = cn })
{
cmd4.CommandText = "SELECT DISTINCT SizeName FROM SizeAbrTable";
SqlDataReader reader = cmd4.ExecuteReader();
while (reader.Read())
{
sizeNameList.Add(reader.GetString(0));
}
}
using (SqlCommand cmd5 = new SqlCommand { Connection = cn })
{
cmd5.CommandText = "SELECT DISTINCT BrandName FROM BrandAbrTable";
SqlDataReader reader = cmd5.ExecuteReader();
while (reader.Read())
{
brandNameList.Add(reader.GetString(0));
}
}
cn.Close();
}
}
public List<String> getNamesList(string category)
{
switch (category)
{
case "Product":
return getProductNameList();
case "Pattern":
return getPatternNameList();
case "Color":
return getColorNameList();
case "Size":
return getSizeNameList();
case "Brand":
return getBrandNameList();
default:
return null;
}
}
public List<String> getAbbreviationsList(string category)
{
List<String> abbreviationsList = new List<string>();
using (SqlConnection cn = new SqlConnection { ConnectionString = ConnectionString })
{
cn.Open();
using (SqlCommand cmd = new SqlCommand { Connection = cn })
{
cmd.CommandText = ("SELECT DISTINCT " + category + "ABV FROM " + category + "AbrTable");
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
abbreviationsList.Add(reader.GetString(0));
}
reader.Close();
}
return abbreviationsList;
}
}
public List<String> getProductNameList()
{
return productNameList;
}
public List<String> getColorNameList()
{
return colorNameList;
}
public List<String> getPatternNameList()
{
return patternNameList;
}
public List<String> getSizeNameList()
{
return sizeNameList;
}
public List<String> getBrandNameList()
{
return brandNameList;
}
public List<String> getColorAbbreviationList()
{
List<String> colorAbbreviationList = new List<string>();
using (SqlConnection cn = new SqlConnection { ConnectionString = ConnectionString })
{
cn.Open();
using (SqlCommand cmd = new SqlCommand { Connection = cn })
{
cmd.CommandText = "SELECT DISTINCT ColorABV FROM ColorAbrTable";
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
colorAbbreviationList.Add(reader.GetString(0));
}
reader.Close();
}
return colorAbbreviationList;
}
}
public int tryToAddNewModelNumberToDatabase(string shape, string pattern, string color, string size, string brand)
{
int numOfExistingProducts = getCountOfExistingProducts(shape, pattern, color, size, brand);
if(numOfExistingProducts>0) {
MessageBox.Show("Existing Product Count: "+numOfExistingProducts);
} else {
MessageBox.Show("Adding new model number from operations");
addNewModelNumberToDatabase(shape, pattern, color, size, brand);
MessageBox.Show("New Model Number Added!");
}
return numOfExistingProducts;
}
private int getCountOfExistingProducts(string shape, string pattern, string color, string size, string brand)
{
int countOfSimilarProducts = -1;
using (SqlConnection cn = new SqlConnection { ConnectionString = ConnectionString })
{
using (SqlCommand cmd = new SqlCommand { Connection = cn })
{
cmd.CommandText = "getCountOfSimilarProducts";
cmd.CommandType = CommandType.StoredProcedure;
try
{
cmd.Parameters.AddWithValue("@shape", shape);
cmd.Parameters.AddWithValue("@pattern", pattern);
cmd.Parameters.AddWithValue("@color", color);
cmd.Parameters.AddWithValue("@size", size);
cmd.Parameters.AddWithValue("@brand", brand);
cmd.Parameters.AddWithValue("@count", null);
cmd.Parameters["@count"].Direction = ParameterDirection.Output;
cmd.Parameters["@count"].Size = 50;
cn.Open();
int return_code = Convert.ToInt32(cmd.ExecuteScalar());
cn.Close();
countOfSimilarProducts = Convert.ToInt32(cmd.Parameters["@count"].Value);
return countOfSimilarProducts;
}
catch (SqlException ex)
{
HasErrors = true;
ExceptionMessage = ex.Message;
Console.WriteLine(ExceptionMessage);
Console.WriteLine(ex.InnerException);
}
}
}
return countOfSimilarProducts;
}
private void addNewModelNumberToDatabase(string shape, string pattern, string color, string size, string brand){
using (SqlConnection cn = new SqlConnection { ConnectionString = ConnectionString })
{
using (SqlCommand cmd = new SqlCommand { Connection = cn })
{
cmd.CommandText = "addNewModelNumberToProductCatalog";
cmd.CommandType = CommandType.StoredProcedure;
try
{
cmd.Parameters.AddWithValue("@shape", shape);
cmd.Parameters.AddWithValue("@pattern", pattern);
cmd.Parameters.AddWithValue("@color", color);
cmd.Parameters.AddWithValue("@size", size);
cmd.Parameters.AddWithValue("@brand", brand);
cn.Open();
int return_code = Convert.ToInt32(cmd.ExecuteScalar());
cn.Close();
}
catch (SqlException ex)
{
HasErrors = true;
ExceptionMessage = ex.Message;
Console.WriteLine(ExceptionMessage);
Console.WriteLine(ex.InnerException);
}
}
}
}
public void tryToEditCurrentModelNumber(int SKU, string shape, string pattern, string color, string size, string brand){
int numOfExistingProducts = getCountOfExistingProducts(shape, pattern, color, size, brand);
if(numOfExistingProducts>0) {
MessageBox.Show("Existing Product Count: "+numOfExistingProducts);
} else
{
editModelNumberInDatabase(SKU, shape, pattern, color, size, brand);
MessageBox.Show("Model Number Edited!");
}
return;
}
private void editModelNumberInDatabase(int SKU, string shape, string pattern, string color, string size, string brand){
using (SqlConnection cn = new SqlConnection { ConnectionString = ConnectionString })
{
using (SqlCommand cmd = new SqlCommand { Connection = cn })
{
cmd.CommandText = "editModelNumberinProductCatalog";
cmd.CommandType = CommandType.StoredProcedure;
try
{
cmd.Parameters.AddWithValue("@SKU", SKU);
cmd.Parameters.AddWithValue("@shape", shape);
cmd.Parameters.AddWithValue("@pattern", pattern);
cmd.Parameters.AddWithValue("@color", color);
cmd.Parameters.AddWithValue("@size", size);
cmd.Parameters.AddWithValue("@brand", brand);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
catch (SqlException ex)
{
HasErrors = true;
ExceptionMessage = ex.Message;
Console.WriteLine(ExceptionMessage);
Console.WriteLine(ex.InnerException);
}
}
}
return;
}
public void addNewCategoryIntoDatabase(string typeOfCategory, string catName, string catAbbreviation)
{
//typeOfCategory will be either: Brand, Color, Pattern, Product, or Size
string databaseTable = typeOfCategory + "AbrTable";
string nameColumn = typeOfCategory + "Name";
string abbreviationColumn = typeOfCategory + "ABV";
string SQLInsertCommand = "INSERT INTO " + databaseTable + "(" + nameColumn + "," + abbreviationColumn + ") ";
SQLInsertCommand += "VALUES (@categoryName, @categoryAbbreviation)";
MessageBox.Show("Trying to insert into " + databaseTable);
MessageBox.Show("Column Name is " + nameColumn);
MessageBox.Show("abbr Column is " + abbreviationColumn);
MessageBox.Show("with values " + catName + ", " + catAbbreviation);
using (SqlConnection cn = new SqlConnection { ConnectionString = ConnectionString })
{
cn.Open();
using (SqlCommand cmd = new SqlCommand { Connection = cn })
{
cmd.CommandText = SQLInsertCommand;
cmd.Parameters.AddWithValue("@categoryName", catName);
cmd.Parameters.AddWithValue("@categoryAbbreviation", catAbbreviation);
cmd.ExecuteNonQuery();
}
}
}
}
}
|
abf845c18f03a4f7a774c364df146236ada5b126
|
C#
|
mathiasdose/master-thesis
|
/asp.net-mvc/asp.net-mvc/Models/SerialObject.cs
| 2.546875
| 3
|
using System.Collections.Generic;
namespace asp.net_mvc.models
{
public class SerialObject
{
public int Id { get; set; }
public int? aNull { get; set; }
public bool aBoolean { get; set; }
public int anInteger { get; set; }
public float aFloat { get; set; }
public string aString { get; set; }
public List<string> anArray { get; set; }
public TestObject anObject { get; set; }
//{"Id":0,"aNull":null,"aBoolean":true,"anInteger":68523,"aFloat":685230.15,
//"aString":"Testing s","anArray":[null,true,123,"any"],
//"anObject":{"aNull":null,"aBoolean":true,"anInteger":123,"aString":"any"}}
}
public class TestObject
{
public int? aNull { get; set; }
public bool aBoolean { get; set; }
public int anInteger { get; set; }
public string aString { get; set; }
}
}
|
44d2eb6dd3eb6e75245846ce26510ae250dad3d1
|
C#
|
taerd/NetWork
|
/NetWork/Form1.cs
| 2.75
| 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.Threading;
namespace NetWork
{
public partial class Form1 : Form
{
private Server server;
private int cnt;
public Form1()
{
InitializeComponent();
}
private void panelMain_MouseClick(object sender, MouseEventArgs e)
{
if (server == null)
{
server = new Server();
server.EventPrint += OnPrint;
cnt = 2;
label2.Text = "Запуск сервера...";
new Thread(() =>
{
server.Start();
}).Start();
}
}
private void OnPrint(String info)
{
switch (cnt)
{
case 0:
if (!label1.InvokeRequired)
{
label1.Text = label2.Text;
cnt++;
OnPrint(info);
}
else Invoke(new Server.Log(OnPrint), info);
break;
case 1:
if (!label2.InvokeRequired)
{
label2.Text = label3.Text;
cnt++;
OnPrint(info);
}
else Invoke(new Server.Log(OnPrint), info);
break;
case 2:
if (!label3.InvokeRequired)
{
if (label3.Text == "")
{
label3.Text = info;
cnt++;
}
else
{
label3.Text = label4.Text;
cnt++;
OnPrint(info);
}
}
else Invoke(new Server.Log(OnPrint), info);
break;
case 3:
if (!label4.InvokeRequired)
{
if (label4.Text == "")
{
label4.Text = info;
cnt++;
}
else
{
label4.Text = label5.Text;
cnt++;
OnPrint(info);
}
}
else Invoke(new Server.Log(OnPrint), info);
break;
case 4:
if (!label5.InvokeRequired)
{
label5.Text = info;
cnt = 0;
}
else Invoke(new Server.Log(OnPrint), info);
break;
}
}
}
}
|
e2dfcf0603788924eec83a15eab4a0284b527ea7
|
C#
|
M-JM/ProjectScrum
|
/MielsJimmyScrumProjectDAL/Repositories/TaskRepository.cs
| 2.703125
| 3
|
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using MielsJimmyScrumProjectDAL.Context;
using MielsJimmyScrumProjectDAL.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MielsJimmyScrumProjectDAL.Repositories
{
public class TaskRepository : ITaskRepository
{
private readonly AppDbContext _context;
private readonly ILogger<CompanyRepository> _logger;
public TaskRepository(AppDbContext context, ILogger<CompanyRepository> logger)
{
_context = context;
_logger = logger;
}
public BoardTask Create(BoardTask task)
{
try
{
if (task != null)
{
var newTaskEntityEntry = _context.Tasks.Add(task);
if (newTaskEntityEntry != null &&
newTaskEntityEntry.State == EntityState.Added)
{
var affectedRows = _context.SaveChanges();
if (affectedRows > 0)
{
_logger.LogInformation($"The {task.Title} was created.");
return newTaskEntityEntry.Entity;
}
}
}
_logger.LogInformation($"The task given as null.");
return null;
}
catch (Exception ex)
{
_logger.LogError(ex, $"When creating a task Failed.");
throw;
}
}
public BoardTask Delete(BoardTask task)
{
try
{
if (task != null)
{
var DeletedTaskEntityEntry = _context.Tasks.Update(task);
if (DeletedTaskEntityEntry != null &&
DeletedTaskEntityEntry.State == EntityState.Modified)
{
var affectedRows = _context.SaveChanges();
if (affectedRows > 0)
{
_logger.LogInformation($"The {task.Title} was soft deleted.");
return DeletedTaskEntityEntry.Entity;
}
}
}
_logger.LogInformation($"The task given as null.");
return null;
}
catch (Exception ex)
{
_logger.LogError(ex, $"When deleting the task Failed.");
throw;
}
}
public IEnumerable<BoardTask> GetAllTasksofUser(string id)
{
var AllTasks = _context.Tasks.Where(t => t.Userid == id && t.IsDeleted == false);
return AllTasks;
}
public IEnumerable<BoardTask> GetAllTasksofBoard(int boardid)
{
var AllTasks = _context.Tasks.Where(t => t.BoardId == boardid && t.IsDeleted == false);
return AllTasks;
}
public IEnumerable<BoardTask> GetAllToDoTask(int boardid)
{
var Todo = _context.Tasks.Where(t => t.Status == ScrumTaskStatus.ToDo && t.BoardId == boardid && t.IsDeleted != true ).Include(x => x.ApplicationUser);
return Todo;
}
public IEnumerable<BoardTask> GetAllDoingTask(int boardid)
{
var Doing = _context.Tasks.Where(t => t.Status == ScrumTaskStatus.Doing && t.BoardId == boardid && t.IsDeleted != true).Include(x => x.ApplicationUser);
return Doing;
}
public IEnumerable<BoardTask> GetAllDoneTask(int boardid)
{
var Done = _context.Tasks.Where(t => t.Status == ScrumTaskStatus.Done && t.BoardId == boardid && t.IsDeleted != true).Include(x => x.ApplicationUser);
return Done;
}
public BoardTask GetById(int id)
{
var task = _context.Tasks.Include(x => x.Board)
.Include(x => x.ApplicationUser)
.FirstOrDefault(x => x.Id == id);
return task;
}
public ApplicationUser GetCurrentUserId(string username)
{
var currentUser = _context.Users.Where(e => e.UserName == username).FirstOrDefault();
return currentUser;
}
public BoardTask Update(BoardTask task)
{
try
{
if (task != null)
{
var updateTaskEntityEntry = _context.Tasks.Update(task);
if (updateTaskEntityEntry != null &&
updateTaskEntityEntry.State == EntityState.Modified)
{
var affectedRows = _context.SaveChanges();
if (affectedRows > 0)
{
_logger.LogInformation($"The {task.Title} was updated.");
return updateTaskEntityEntry.Entity;
}
}
}
_logger.LogInformation($"The task given as null.");
return null;
}
catch (Exception ex)
{
_logger.LogError(ex, $"When updating a task Failed.");
throw;
}
}
}
}
|
12b0bf8ca21fe9c5df8eec8db74f6d3a7f040e5a
|
C#
|
SulfurAkaSera/Function
|
/ASYNC/ViewModel/ViewModel.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using ASYNC.Model;
namespace ASYNC.ViewModel
{
public class ViewModel : INotifyPropertyChanged
{
Points FuncPoints;
private const double Epsilon = 0.001;
private double result;
public double Result { get { return result; } set { result = value; OnPropertyChanged("Result"); } }
public ViewModel()
{
FuncPoints = new Points(0, 5);
Solution();
}
private void Solution()
{
double result;
bool ver = true;
if (Func(FuncPoints.point1) * Func(FuncPoints.point2) < 0)
{
while (ver)
{
result = (FuncPoints.point1 + FuncPoints.point2) / 2;
if (Func(result) * Func(FuncPoints.point1) > 0)
{
FuncPoints.point1 = result;
}
else if (Func(result) * Func(FuncPoints.point1) < 0)
{
FuncPoints.point2 = result;
}
if ((FuncPoints.point2 - FuncPoints.point1) / 2 < Epsilon)
{
ver = false;
Result = Math.Round(result, 3);
}
}
}
else
MessageBox.Show("Корня не существует", null, MessageBoxButton.OK);
}
private double Func(double x)
{
double result = Math.Log10(x) + x - 2;
return result;
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string prop = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
}
|
ca3c052ccc325a63869cb2096ac28b2c9b69a686
|
C#
|
arvidl02-edu/Programmering1
|
/Glosor/Form1.cs
| 2.6875
| 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 Glosor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Queue<string> swedishWords = new Queue<string>();
Queue<string> englishWords = new Queue<string>();
int rightAnswers = 0;
int totalAnswers = 0;
List<string> wrongAnswers = new List<string>();
string wrongAnswersInString = "";
private void ButtonAddGlosa_Click(object sender, EventArgs e)
{
if(textBoxSwedishInput.Text != "" && textBoxEnglishInput.Text != "")
{
swedishWords.Enqueue(textBoxSwedishInput.Text);
englishWords.Enqueue(textBoxEnglishInput.Text);
if (swedishWords.Count > 0)
{
buttonStartTest.Enabled = true;
}
totalAnswers++;
textBoxSwedishInput.Text = "";
textBoxEnglishInput.Text = "";
}
}
private void ButtonStartTest_Click(object sender, EventArgs e)
{
groupBoxInput.Enabled = false;
groupBoxTest.Enabled = true;
buttonStartTest.Enabled = false;
textBoxTestSwedish.Text = swedishWords.Dequeue();
}
private void ButtonTestAnswer_Click(object sender, EventArgs e)
{
if (textBoxTestEnglish.Text == englishWords.Peek())
{
rightAnswers++;
englishWords.Dequeue();
}
else
{
wrongAnswers.Add(englishWords.Dequeue());
}
textBoxTestEnglish.Text = "";
if(swedishWords.Count > 0)
{
textBoxTestSwedish.Text = swedishWords.Dequeue();
}
else
{
for (int i = 0; i < wrongAnswers.Count; i++)
{
wrongAnswersInString += wrongAnswers.ElementAt(i) + "\r\n";
}
labelResults.Text = rightAnswers + " av " + totalAnswers + " korrekt svarade glosor." + "\r\nFelaktiga svar: \r\n" + wrongAnswersInString;
}
}
}
}
|
d130db3964b22b0fc407125df9addb12c07e5eb6
|
C#
|
AntoniusBayu/SimpleMicroservicesArchitecture
|
/Application/BackEnd/CarService/Domain.Business/Business/mstSparePartDomain .cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Domain.DataAccess;
namespace Domain.Business
{
public class mstSparePartDomain : IMstSparePartDomain
{
private IUnitofWork _uow;
public mstSparePartDomain(IUnitofWork uow)
{
_uow = uow;
}
public void SaveData(mstSparePart data)
{
try
{
_uow.Open(DBConnection.BMIERP);
_uow.BeginTransaction();
var repo = new mstSparePartRepository(_uow);
repo.Add(data);
_uow.CommitTransaction();
}
catch (Exception)
{
_uow.RollbackTransaction();
throw;
}
finally
{
_uow.Dispose();
}
}
public void SaveDataFacade(mstSparePart data, IUnitofWork uow)
{
try
{
var repo = new mstSparePartRepository(uow);
if (data.SparePartDescription.Length > 10)
{
data.SparePartDescription = "Panjang karakter lebih dari 10";
}
else
{
data.SparePartDescription = "Panjang karakter tidak lebih dari 10";
}
repo.Add(data);
}
catch (Exception)
{
throw;
}
}
public void EditData(mstSparePart data)
{
try
{
_uow.Open(DBConnection.BMIERP);
_uow.BeginTransaction();
var repo = new mstSparePartRepository(_uow);
repo.Edit(data);
_uow.CommitTransaction();
}
catch (Exception)
{
_uow.RollbackTransaction();
throw;
}
finally
{
_uow.Dispose();
}
}
public void DeleteData(mstSparePart data)
{
try
{
_uow.Open(DBConnection.BMIERP);
_uow.BeginTransaction();
var repo = new mstSparePartRepository(_uow);
repo.Delete(data);
_uow.CommitTransaction();
}
catch (Exception)
{
_uow.RollbackTransaction();
throw;
}
finally
{
_uow.Dispose();
}
}
public List<mstSparePart> ReadAll()
{
try
{
_uow.Open(DBConnection.BMIERP);
var repo = new mstSparePartRepository(_uow);
List<mstSparePart> listCar = new List<mstSparePart>();
listCar = repo.ReadAllData().ToList();
return listCar;
}
catch (Exception)
{
throw;
}
finally
{
_uow.Dispose();
}
}
}
}
|
ca6e4963a54bc5d431389a2ea0570544acc1ffc1
|
C#
|
sagarpatel2570/Bomberman-Prototype
|
/Assets/Bomberman/Scripts/Character/DamageOnTouch.cs
| 2.71875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// attached this component to an object so that it can give damage when touch
/// </summary>
[RequireComponent(typeof(Collider2D))]
public class DamageOnTouch : MonoBehaviour
{
public LayerMask targetLayerMask;
private void OnTriggerEnter2D(Collider2D collider)
{
if (((1 << collider.gameObject.layer) & targetLayerMask) == 0)
{
return;
}
ITakeDamage obj = collider.GetComponent<ITakeDamage>();
if(obj != null)
{
obj.TakeDamage();
}
}
}
|
d443f117bd694ed497c30033db6972af92258d50
|
C#
|
juninhodigital/Framework.Cryptography
|
/Framework.Cryptography/Cryptography.cs
| 3.046875
| 3
|
using System;
using System.Security.Cryptography;
using System.Text;
namespace Framework.Cryptography
{
/// <summary>
/// Computes the System.Security.Cryptography.MD5 hash value for the input data
/// using the implementation provided by the cryptographic service provider (CSP).
/// This class cannot be inherited.
/// </summary>
public sealed class Cryptography
{
#region| Methods |
/// <summary>
/// Encrypt the given string using the specified key.
/// </summary>
/// <param name="textToEncrypt">The string to be encrypted</param>
/// <param name="SecurePhrase">The Secure Phrase used to encryption</param>
/// <returns>The Encrypted string.</returns>
public static string Encrypt(string textToEncrypt, string SecurePhrase)
{
try
{
var oTripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider();
var oMD5CryptoServiceProvider = new MD5CryptoServiceProvider();
byte[] byteHash, byteBuff;
byteHash = oMD5CryptoServiceProvider.ComputeHash(ASCIIEncoding.ASCII.GetBytes(SecurePhrase));
oTripleDESCryptoServiceProvider.Key = byteHash;
oTripleDESCryptoServiceProvider.Mode = CipherMode.ECB; //CBC, CFB
byteBuff = ASCIIEncoding.ASCII.GetBytes(textToEncrypt);
string Aux = Convert.ToBase64String(oTripleDESCryptoServiceProvider.CreateEncryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
oTripleDESCryptoServiceProvider.Dispose();
oMD5CryptoServiceProvider.Dispose();
return Aux;
}
catch (Exception ex)
{
return "Framework.Cryptography: " + ex.Message;
}
}
/// <summary>
/// Decrypt the given string using the specified key.
/// </summary>
/// <param name="textToDecrypt">The string to be encrypted</param>
/// <param name="SecurePhrase">The Secure Phrase used to decryption</param>
/// <returns>The Decrypted string.</returns>
public static string Decrypt(string textToDecrypt, string SecurePhrase)
{
try
{
var oTripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider();
var oMD5CryptoServiceProvider = new MD5CryptoServiceProvider();
byte[] byteHash, byteBuff;
byteHash = oMD5CryptoServiceProvider.ComputeHash(ASCIIEncoding.ASCII.GetBytes(SecurePhrase));
oTripleDESCryptoServiceProvider.Key = byteHash;
oTripleDESCryptoServiceProvider.Mode = CipherMode.ECB; //CBC, CFB
byteBuff = Convert.FromBase64String(textToDecrypt);
string Aux = ASCIIEncoding.ASCII.GetString(oTripleDESCryptoServiceProvider.CreateDecryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
oTripleDESCryptoServiceProvider.Dispose();
oMD5CryptoServiceProvider.Dispose();
return Aux;
}
catch (Exception ex)
{
return "Framework.Cryptography: " + ex.Message;
}
}
/// <summary>
/// Encrypts a given string using the ProtectedConfigurationProvider
/// </summary>
public static string EncryptUsingTripleDES(string encryptValue)
{
var output = string.Empty;
var tripleDES = new TripleDESProtectedConfigurationProvider();
output = tripleDES.EncryptString(encryptValue);
tripleDES = null;
return output;
}
/// <summary>
/// Decrypts a given string using the ProtectedConfigurationProvider
/// </summary>
public static string DecryptUsingTripleDES(string textToDecrypt)
{
var output = string.Empty;
var tripleDES = new TripleDESProtectedConfigurationProvider();
output = tripleDES.DecryptString(textToDecrypt);
tripleDES = null;
return output;
}
/// <summary>
/// Generates a unique key to be used as a token
/// </summary>
/// <param name="maxSize"></param>
/// <returns></returns>
public static string GenerateTokenUniqueKey(int maxSize = 15)
{
char[] chars = new char[62];
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
byte[] data = new byte[1];
using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider())
{
crypto.GetNonZeroBytes(data);
data = new byte[maxSize];
crypto.GetNonZeroBytes(data);
}
var result = new StringBuilder(maxSize);
foreach (byte b in data)
{
result.Append(chars[b % (chars.Length)]);
}
return result.ToString();
}
#endregion
}
}
|
9c9f5cd53d9069e022d83586a8e1cb5f6751370d
|
C#
|
karashak1/fallCSharp
|
/LinqHomework/UnitTestProject1/PeopleTests.cs
| 3.546875
| 4
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using LinqHomework;
using System.Linq;
using System.Collections.Generic;
namespace UnitTestProject1 {
[TestClass]
public class PeopleTests {
/* This is the #1 of the homework */
[TestMethod]
public void LoadNames() {
var names = new[] {"Bessie", "Vashti", "Frederica", "Nisha", "Kendall", "Magdalena", "Brendon"
, "Eve", "Manda", "Elvera", "Miquel", "Tyra", "Lucie", "Marvella", "Tracee", "Ramiro", "Irene", "Davina", "Jeromy" , "Siu"};
/* create a new list of people each one has a name from the
* list names
*/
var people = names.Select(x => new People { Name = x });
/*var people = from x in names
select new People {
Name = x,
};
*/
Assert.AreEqual(names.Count(), people.Count());
}
/* This is #2 of the homework */
[TestMethod]
public void PeopleStartWithM() {
var names = new[] {"Bessie", "Vashti", "Frederica", "Nisha", "Kendall", "Magdalena", "Brendon"
, "Eve", "Manda", "Elvera", "Miquel", "Tyra", "Lucie", "Marvella", "Tracee", "Ramiro", "Irene", "Davina", "Jeromy" , "Siu"};
var people = names.Select(x => new People { Name = x });
/* only get the ones with a name that starts with an M */
var peopleNameM = people.Where(x => x.Name.StartsWith("M"));
Assert.AreEqual(4, peopleNameM.Count());
}
/*This is #3 of the homework */
[TestMethod]
public void PeoplesNamesToUppercase() {
var names = new[] {"Bessie", "Vashti", "Frederica", "Nisha", "Kendall", "Magdalena", "Brendon"
, "Eve", "Manda", "Elvera", "Miquel", "Tyra", "Lucie", "Marvella", "Tracee", "Ramiro", "Irene", "Davina", "Jeromy" , "Siu"};
var people = names.Select(x => new People { Name = x });
// Create a new list of people but with the names to upper case
var peopleUpperCase = people.Select(x => x.Name = x.Name.ToUpper());
Assert.AreEqual(names.Count(), peopleUpperCase.Count());
}
/*This is #4 of the homework */
[TestMethod]
public void PeoplesNameLength() {
var names = new[] {"Bessie", "Vashti", "Frederica", "Nisha", "Kendall", "Magdalena", "Brendon"
, "Eve", "Manda", "Elvera", "Miquel", "Tyra", "Lucie", "Marvella", "Tracee", "Ramiro", "Irene", "Davina", "Jeromy" , "Siu"};
var people = names.Select(x => new People { Name = x });
/*create a list that holds the lengths of each people object and then turn it into an array
*/
var peopleNameLength = people.Select(x => x.Name.Length).ToArray();
Assert.AreEqual(names.Count(), peopleNameLength.Count());
}
/* This is #5 of the homework */
[TestMethod]
public void PeopleOrderSmallName() {
var names = new[] {"Bessie", "Vashti", "Frederica", "Nisha", "Kendall", "Magdalena", "Brendon"
, "Eve", "Manda", "Elvera", "Miquel", "Tyra", "Lucie", "Marvella", "Tracee", "Ramiro", "Irene", "Davina", "Jeromy" , "Siu"};
var people = names.Select(x => new People { Name = x });
/*create a new list of people witht he name shortened to just the first 3 letters
* and ordered by name
*/
var peopleOrderedShortend = people.Select(x => new People { Name = x.Name.Substring(0, 3) }).OrderBy(x => x.Name);
Assert.AreEqual(names.Count(), peopleOrderedShortend.Count());
}
}
}
|
6496f9a1a8e4f9c64f7414a764b907b0475efdac
|
C#
|
Curran-H/Soul-Wheel
|
/Soul Wheel/Assets/Dungeon Maker/Scripts/Objects/DungeonObject.cs
| 3.1875
| 3
|
using System.Collections.Generic;
using UnityEngine;
using DungeonMaker.Core;
namespace DungeonMaker
{
public class DungeonObject : MonoBehaviour
{
#region Private Variables
private DungeonData dungeon;
private RoomObject[,] map;
private List<RoomObject> rooms;
private int seed;
#endregion Private Variables
#region Properties
/// <summary>
/// Name of the DungeonData used to create this dungeon.
/// </summary>
public string Name { get { return dungeon.Name; } }
/// <summary>
/// It contains all the rooms in the form of a matrix.
/// </summary>
public RoomObject[,] Map { get { return map; } }
/// <summary>
/// It contains all the rooms in the form of a list.
/// </summary>
public List<RoomObject> Rooms { get { return rooms; } }
/// <summary>
/// Seed that has been used for the generation of this dungeon.
/// </summary>
public int Seed { get { return seed; } }
/// <summary>
/// Width of the dungeon map.
/// </summary>
public int Width { get { return map.GetLength(1); } }
/// <summary>
/// Height of the dungeon map.
/// </summary>
public int Height { get { return map.GetLength(0); } }
#endregion Properties
#region Constructor
public void Init(DungeonData d, RoomObject[,] m, int s)
{
dungeon = d;
map = m;
seed = s;
SetRooms();
}
#endregion Constructor
#region Main Methods
private void SetRooms()
{
rooms = new List<RoomObject>();
for (int y = 0; y < Height; y++)
for (int x = 0; x < Width; x++)
if (!IsNull(x, y))
rooms.Add(Get(x, y));
}
#endregion Main Methods
#region Utility Methods
/// <summary>
/// Returns information about the room of the specified position.
/// </summary>
public RoomObject Get(int x, int y)
{
return map[y, x];
}
/// <summary>
/// Returns room information for the specified identifier.
/// </summary>
public RoomObject Get(int id)
{
foreach (RoomObject r in rooms)
if (r.ID == id)
return r;
return null;
}
/// <summary>
/// Returns true if no room is found in the specified position.
/// </summary>
public bool IsNull(int x, int y)
{
return map[y, x] == null;
}
/// <summary>
/// Returns true if the specified position is within the boundaries of the dungeon map.
/// </summary>
public bool InBounds(int x, int y)
{
return x >= 0 && y >= 0
&& x < Width && y < Height;
}
/// <summary>
/// Scroll the width and height of the dungeon map and apply an action to each position.
/// </summary>
public void Process(XYDelegate function)
{
for (int y = 0; y < Height; y++)
for (int x = 0; x < Width; x++)
function(x, y);
}
/// <summary>
/// Prints a graphic representation of the dungeon map on the console.
/// </summary>
public void Print(string full = "X", string empty = " . ")
{
string result = string.Format("{0}\n", Name);
for (int y = Height - 1; y >= 0; y--)
{
for (int x = 0; x < Width; x++)
{
result += string.Format("{0} ", IsNull(x, y) ? empty : full);
}
result.Remove(result.Length - 1);
result += '\n';
}
Debug.Log(result);
}
#endregion Utility Methods
}
}
|
ca0dbfccc93de419ebc87fe753723522f66e44a5
|
C#
|
renanuness/UriOnline
|
/matematica/csharp/ex1240/ex1240.cs
| 3.4375
| 3
|
using System;
class URI
{
static void Main(string[] args)
{
var casosDeTeste = Int32.Parse(Console.ReadLine());
while(casosDeTeste-- > 0)
{
var entradas = Console.ReadLine();
var a = entradas.Split(' ')[0];
var b = entradas.Split(' ')[1];
var encaixa = true;
if(b.Length > a.Length)
{
encaixa = false;
Imprimir(encaixa);
continue;
}
var comprimentoA = a.Length;
for(int i = b.Length - 1; i >= 0; i--)
{
if(a[--comprimentoA] != b[i])
{
encaixa = false;
break;
}
}
Imprimir(encaixa);
}
}
public static void Imprimir(bool encaixa)
{
string naoEncaixaStr = "nao encaixa";
string encaixaStr = "encaixa";
var s = encaixa ? encaixaStr : naoEncaixaStr;
Console.Write("{0}\n", s);
}
}
|
29edebb326901c56b8c62c44f1e10d291c75f3d6
|
C#
|
shainotshy1/iFractal-Cross-Platform
|
/iFractal/iFractal/Models/Pixel.cs
| 3.5625
| 4
|
using System;
using System.Collections.Generic;
using System.Text;
namespace iFractal
{
public class Pixel
{
private int red;
private int green;
private int blue;
public Pixel(int r, int g, int b)
{
red = r;
green = g;
blue = b;
}
public void SetRed(int a)
{
red = a;
}
public void SetGreen(int a)
{
green = a;
}
public void SetBlue(int a)
{
blue = a;
}
public int GetRed()
{
return red;
}
public int GetGreen()
{
return green;
}
public int GetBlue()
{
return blue;
}
public int GetColorInt()
{
return red * 16 * 16 * 16 * 16 + green * 16 * 16 + blue; // to put into base 16
}
}
}
|
a209b8262b673593068c03b2d2ec884e365fa7d2
|
C#
|
ThansiJamal/MultiplicationConsole
|
/MultiplicationConsole/Program.cs
| 3.578125
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace MultiplicationConsole
{
class Program
{
static int i = 1;
static int n = 2;
static int [] arr = new int[] {1,9,2,8,3,7,4,6,5 };
public static void Multiplication()
{
Thread.Sleep(500);
if (i==arr.Length)
{
return;
}
Console.WriteLine(arr[i] + "X" + n + "=" + arr[i] * n);
i++;
Multiplication();
}
static void Main(string[] args)
{
Multiplication();
Console.ReadKey();
}
}
}
|
181848c27180e84900e32fe99f1679e3b24840c2
|
C#
|
ionicpanda/custom-payloads
|
/csharp/shellcode_injection_reverse.cs
| 2.546875
| 3
|
//Creates a living off the land through by utilizing InstallUti.exe to execute payload
//to obtain reverse shell
using System;
using System.Net;
using System.Diagnostics;
using System.Reflection;
using System.Configuration.Install;
using System.Runtime.InteropServices;
public class Program
{
public static void Main()
{
Console.WriteLine("Greetings from Mars");
Console.ReadKey();
}
}
[System.ComponentModel.RunInstaller(true)]
public class Sample : System.Configuration.Install.Installer
{
public override void Uninstall(System.Collections.IDictionary savedState)
{
LegitInstaller.Run();
}
}
public class LegitInstaller
{
public static void Run()
{
Process.Start("Path to exploit");
Console.ReadKey();
}
}
|
1efe8c1b81914fb3b2634a9c690a227a0a5d5d8f
|
C#
|
shendongnian/download4
|
/first_version_download2/59742-3643447-7615090-10.cs
| 2.8125
| 3
|
public class Test : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string name;
public string Name
{
get { return this.name; }
set { this.name = value; OnNotifyPropertyChanged("Name"); }
}
protected virtual void OnPropertyChanged(string name)
{
EventHamanger.OnEvent(this, PropertyChanged, new PropertyChangedEventArgs(name));
}
}
|
71198dc437e6331abd98275b93ffb5b5446eba14
|
C#
|
Ramcste/TestAngMvc
|
/AngularMvc/Controllers/BooksController.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using AngularMvc.Models;
namespace AngularMvc.Controllers
{
public class BooksController : Controller
{
private BookDBContext db = new BookDBContext();
// GET: Books
public ActionResult Index()
{
//var books = db.Books.ToList();
return View();
}
// GET: All books
public JsonResult GetAllBooks()
{
var bookslist = db.Books.ToList();
return Json(bookslist, JsonRequestBehavior.AllowGet);
}
// GET: Book by Id
public JsonResult GetBookById(string id)
{
int bookId = int.Parse(id);
var getBooksById = db.Books.Find(bookId);
return Json(getBooksById, JsonRequestBehavior.AllowGet);
}
//Update: Book
public string UpdateBook(Book book)
{
if (book != null)
{
int bookId = book.Id;
Book updatebook = db.Books.Where(b => b.Id == bookId).FirstOrDefault();
updatebook.Title = book.Title;
updatebook.Author = book.Author;
updatebook.Publisher = book.Publisher;
updatebook.Isbn = book.Isbn;
db.SaveChanges();
return "Book Record Updated Successfully";
}
else
{
return "Invalid Book Record";
}
}
// Add Book
public string AddBook(Book book)
{
if (book != null)
{
db.Books.Add(book);
db.SaveChanges();
return "Book Record Added Successfully";
}
else
{
return "Invalid book record";
}
}
// Delete Book
public string DeleteBook(string bookId)
{
if (!String.IsNullOrEmpty(bookId))
{
try
{
int _bookId = int.Parse(bookId);
var _book = db.Books.Find(_bookId);
db.Books.Remove(_book);
db.SaveChanges();
return "Selected book record deleted successfully";
}
catch (Exception)
{
return "Book details not found";
}
}
else{
return "Invalid operation";
}
}
}
}
|
6bfb639fa0c23db318788d62d647e60e9f19a1b3
|
C#
|
diamonds0805/diamond.github.io
|
/GitProjects/EmployeeTracker/EmployeeTracker/UI.cs
| 3.078125
| 3
|
using System;
namespace EmployeeTracker
{
public class UI
{
/* Sanford, Diamond
* 09/27/2020
* ADP
* Synopsis: This class contains the design and usability functions for the program
*/
//Create static method for header
public static void Header(string title)
{
Console.BackgroundColor = ConsoleColor.Magenta;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine($"{title.ToUpper(),20} ");
Console.ResetColor();
}
//Create static method for footer
public static void Footer(string footer)
{
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine($"{footer,20} ");
Console.ResetColor();
}
//Create static method separater
public static void Separater()
{
Console.WriteLine("---------------");
}
//create static method for displaying employees
public static void EmpUI()
{
Console.BackgroundColor = ConsoleColor.Magenta;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("================");
Console.ResetColor();
}
}
}
|
5ea1901c0b319d39435a67a03e7421864ce78e8c
|
C#
|
deepankarsharma/Flame
|
/Flame.Clr/TypeHelpers.cs
| 2.9375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using Flame.TypeSystem;
namespace Flame.Clr
{
/// <summary>
/// Defines helper methods for bridging the gap between
/// IL's implicit reference types and Flame's explicit
/// box pointers.
/// </summary>
public static class TypeHelpers
{
/// <summary>
/// Takes a type, examines it and boxes it if it
/// is a raw reference type.
/// It is appropriate to call this method on the type
/// of a value; IL values that happen to be reference
/// types are implicitly boxed. This function hints that
/// this implicit boxing is to be made explicit.
/// </summary>
/// <param name="type">
/// The type to box if it happens to be a reference type.
/// </param>
/// <returns>
/// A box-pointer type if <paramref name="type"/> is a
/// raw reference type; otherwise, <paramref name="type"/> itself.
/// </returns>
public static IType BoxIfReferenceType(IType type)
{
if (type.IsReferenceType())
{
return type.MakePointerType(PointerKind.Box);
}
else
{
return type;
}
}
/// <summary>
/// Takes a type, examines it and unboxes it if it
/// is a box pointer type.
/// </summary>
/// <param name="type">
/// The type to unbox if it happens to be a box pointer type.
/// </param>
/// <returns>
/// <paramref name="type"/>'s pointee if it is a box pointer type;
/// otherwise, <paramref name="type"/> itself.
/// </returns>
public static IType UnboxIfPossible(IType type)
{
var box = type as PointerType;
if (box != null && box.Kind == PointerKind.Box)
{
return box.ElementType;
}
else
{
return type;
}
}
/// <summary>
/// Replaces all raw reference types with boxed reference types.
/// </summary>
/// <param name="type">The type to completely box.</param>
/// <returns>A boxed type.</returns>
public static IType BoxReferenceTypes(IType type)
{
// TODO: do we really need this?
return ReferenceTypeBoxingVisitor.Instance.Visit(type);
}
private sealed class ReferenceTypeBoxingVisitor : TypeVisitor
{
private ReferenceTypeBoxingVisitor()
{ }
public static readonly ReferenceTypeBoxingVisitor Instance =
new ReferenceTypeBoxingVisitor();
protected override bool IsOfInterest(IType type)
{
// We obviously want to match reference types here.
//
// In addition, we want to guarantee idempotence,
// so we need to match on box pointers and make sure
// we don't accidentally box their contents twice.
//
// Instead of actually matching on box pointers here,
// we just mark all pointer types as interesting and
// then sort them out in `VisitInteresting`.
return type is PointerType || type.IsReferenceType();
}
protected override IType VisitInteresting(IType type)
{
if (type is PointerType)
{
var ptr = (PointerType)type;
var visitedElemType = ptr.Kind == PointerKind.Box
? VisitUninteresting(ptr.ElementType)
: Visit(ptr.ElementType);
return visitedElemType.MakePointerType(ptr.Kind);
}
else
{
return type.MakePointerType(PointerKind.Box);
}
}
}
/// <summary>
/// Takes a Flame type and converts it to a Cecil type reference.
/// For this to work, <paramref name="type"/> cannot reference
/// non-Cecil types.
/// </summary>
/// <param name="type">
/// The type to convert to a type reference.
/// </param>
/// <returns>
/// A type reference.
/// </returns>
public static Mono.Cecil.TypeReference ImportReference(
this Mono.Cecil.ModuleDefinition module,
IType type)
{
if (type is ClrTypeDefinition)
{
var typeRef = ((ClrTypeDefinition)type).Definition;
// The module can be null for testing purposes.
return module == null ? typeRef : module.ImportReference(typeRef);
}
else if (type is ClrGenericParameter)
{
// There's no need to "import" generic parameters: they can only be
// used in the same place where they are defined.
return ((ClrGenericParameter)type).Definition;
}
else if (type is PointerType)
{
var pointerType = (PointerType)type;
var elemType = pointerType.ElementType;
var elemTypeRef = module.ImportReference(elemType);
if (pointerType.Kind == PointerKind.Reference)
{
return new Mono.Cecil.ByReferenceType(elemTypeRef);
}
else if (pointerType.Kind == PointerKind.Box)
{
if (elemType.IsReferenceType())
{
var def = module.ImportReference(elemTypeRef);
return module == null ? def : module.ImportReference(def);
}
else
{
return module.ImportReference(module.TypeSystem.Object);
}
}
else
{
return new Mono.Cecil.PointerType(elemTypeRef);
}
}
IType elementType;
if (ClrArrayType.TryGetArrayElementType(type, out elementType))
{
// Handle arrays.
int rank;
ClrArrayType.TryGetArrayRank(type, out rank);
return new Mono.Cecil.ArrayType(module.ImportReference(elementType), rank);
}
else if (type is TypeSpecialization)
{
// Handle generics.
var instance = new Mono.Cecil.GenericInstanceType(
module.ImportReference(
type.GetRecursiveGenericDeclaration()));
foreach (var item in type.GetRecursiveGenericArguments())
{
instance.GenericArguments.Add(module.ImportReference(item));
}
return instance;
}
else
{
throw new NotSupportedException($"Cannot import ill-understood type '{type.FullName}'.");
}
}
/// <summary>
/// Gets a method's extended parameter list, consists of the method's
/// parameter list and an optional 'this' parameter as a prefix.
/// </summary>
/// <param name="method">
/// The method to examine.
/// </param>
/// <returns>
/// A list of parameters.
/// </returns>
public static IReadOnlyList<Mono.Cecil.ParameterDefinition> GetExtendedParameters(
Mono.Cecil.MethodDefinition method)
{
return method.HasThis
? new[] { method.Body.ThisParameter }.Concat(method.Parameters).ToArray()
: method.Parameters.ToArray();
}
/// <summary>
/// Takes a Flame method and converts it to a Cecil method reference.
/// For this to work, <paramref name="field"/> cannot reference
/// non-Cecil types or methods.
/// </summary>
/// <param name="field">
/// The method to convert to a method reference.
/// </param>
/// <returns>
/// A method reference.
/// </returns>
public static Mono.Cecil.MethodReference ImportReference(
this Mono.Cecil.ModuleDefinition module,
IMethod method)
{
if (method is ClrMethodDefinition)
{
var def = ((ClrMethodDefinition)method).Definition;
return module == null ? def : module.ImportReference(def);
}
else if (method is IndirectMethodSpecialization)
{
var specialization = (IndirectMethodSpecialization)method;
return CloneMethodWithDeclaringType(
module.ImportReference(specialization.Declaration),
module.ImportReference(specialization.ParentType));
}
else if (method is DirectMethodSpecialization)
{
var specialization = (DirectMethodSpecialization)method;
var genInst = new Mono.Cecil.GenericInstanceMethod(
module.ImportReference(specialization.Declaration));
foreach (var item in specialization.GenericArguments)
{
genInst.GenericArguments.Add(module.ImportReference(item));
}
return genInst;
}
else
{
throw new NotSupportedException($"Cannot import ill-understood method '{method.FullName}'.");
}
}
/// <summary>
/// Takes a Flame field and converts it to a Cecil field reference.
/// For this to work, <paramref name="field"/> cannot reference
/// non-Cecil types or methods.
/// </summary>
/// <param name="field">
/// The field to convert to a field reference.
/// </param>
/// <returns>
/// A field reference.
/// </returns>
public static Mono.Cecil.FieldReference ImportReference(
this Mono.Cecil.ModuleDefinition module,
IField field)
{
if (field is ClrFieldDefinition)
{
var def = ((ClrFieldDefinition)field).Definition;
return module == null ? def : module.ImportReference(def);
}
else if (field is IndirectFieldSpecialization)
{
var specialization = (IndirectFieldSpecialization)field;
var declarationRef = module.ImportReference(specialization.Declaration);
var typeRef = module.ImportReference(specialization.ParentType);
return new Mono.Cecil.FieldReference(
declarationRef.Name,
module.ImportReference(declarationRef.FieldType, typeRef), typeRef);
}
else
{
throw new NotSupportedException($"Cannot import ill-understood field '{field.FullName}'.");
}
}
private static Mono.Cecil.MethodReference CloneMethodWithDeclaringType(
Mono.Cecil.MethodReference methodDef,
Mono.Cecil.TypeReference declaringTypeRef)
{
if (!declaringTypeRef.IsGenericInstance || methodDef == null)
{
return methodDef;
}
var methodRef = new Mono.Cecil.MethodReference(methodDef.Name, methodDef.ReturnType, declaringTypeRef)
{
CallingConvention = methodDef.CallingConvention,
HasThis = methodDef.HasThis,
ExplicitThis = methodDef.ExplicitThis
};
foreach (Mono.Cecil.GenericParameter genParamDef in methodDef.GenericParameters)
{
methodRef.GenericParameters.Add(CloneGenericParameter(genParamDef, methodRef));
}
methodRef.ReturnType = declaringTypeRef.Module.ImportReference(methodDef.ReturnType, methodRef);
foreach (Mono.Cecil.ParameterDefinition paramDef in methodDef.Parameters)
{
methodRef.Parameters.Add(
new Mono.Cecil.ParameterDefinition(
paramDef.Name, paramDef.Attributes,
declaringTypeRef.Module.ImportReference(paramDef.ParameterType, methodRef)));
}
return methodRef;
}
private static Mono.Cecil.GenericParameter CloneGenericParameter(
Mono.Cecil.GenericParameter Parameter,
Mono.Cecil.IGenericParameterProvider ParameterProvider)
{
var genericParam = new Mono.Cecil.GenericParameter(Parameter.Name, ParameterProvider);
genericParam.Attributes = Parameter.Attributes;
foreach (var item in Parameter.Constraints)
{
genericParam.Constraints.Add(item);
}
return genericParam;
}
/// <summary>
/// Gets the 'invoke' method of a delegate type, provided
/// that it is indeed a delegate type.
/// </summary>
/// <param name="delegateType">
/// A type that may be a delegate type.
/// </param>
/// <param name="invokeMethod">
/// The delegate type's 'invoke' method, provided that
/// <paramref name="delegateType"/> is a delegate type with
/// an 'invoke' method
/// </param>
/// <returns><c>true</c> if <paramref name="delegateType"/>
/// is indeed a delegate type with an 'invoke' method;
/// otherwise, <c>false</c>.</returns>
public static bool TryGetDelegateInvokeMethod(
IType delegateType,
out IMethod invokeMethod)
{
// All delegate types must inherit from 'System.Delegate'
// or 'System.MulticastDelegate'.
if (delegateType == null || !InheritsFromDelegate(delegateType))
{
invokeMethod = null;
return false;
}
// Find a unique instance method called 'Invoke'.
var candidates = delegateType.Methods
.Where(method => !method.IsStatic && method.Name.ToString() == "Invoke")
.ToArray();
if (candidates.Length == 1)
{
invokeMethod = candidates[0];
return true;
}
else
{
invokeMethod = null;
return false;
}
}
private static bool InheritsFromDelegate(IType type)
{
return type.BaseTypes.Any(item => {
var fullName = item.FullName.ToString();
return fullName == nameof(System) + "." + nameof(Delegate)
|| fullName == nameof(System) + "." + nameof(MulticastDelegate);
});
}
}
}
|
909bad2d6b2d972c22def462f684ef92bbcdf38c
|
C#
|
truongpnhattien0299/ATBMHTTT
|
/Server/Server.cs
| 2.796875
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using Client;
namespace Server
{
class Server
{
static string ADDRESS = "127.0.0.1";
static int PORT = 3000;
static IPEndPoint IP = null;
static Socket listener = null, client = null;
static ArrayList listSocket = null, arrData = null; // danh sach socket cua client
static Data dataClient = null;
static void Main(string[] args)
{
Start();
//Connect();
}
static void Start()
{
IP = new IPEndPoint(IPAddress.Parse(ADDRESS), PORT);
listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
arrData = new ArrayList();
try
{
listener.Bind(IP);
Console.WriteLine($"Socket Bind to {IP} Waiting for connect");
listener.Listen(10);
Thread connect = new Thread(Connect);
connect.Start();
}
catch
{
IP = new IPEndPoint(IPAddress.Parse(ADDRESS), PORT);
listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
}
static void Connect()
{
listSocket = new ArrayList();
while (true)
{
try
{
client = listener.Accept();
listSocket.Add(client);
Console.WriteLine($"{client.RemoteEndPoint} Connected");
//if (arrData.Count > 0)
client.Send(Object2ByteArray(arrData));
Thread threadReceive = new Thread(Receive);
threadReceive.IsBackground = true;
threadReceive.Start(client);
}
catch
{
Console.WriteLine("Loi connect");
return;
}
}
}
//static void Send(Socket client)
//{
// client.Send(Object2ByteArray(dataClient));
//}
static void Receive(object obj)
{
Socket clientSocket = obj as Socket;
try
{
while (true)
{
byte[] data = new byte[1024 * 5000];
clientSocket.Receive(data);
dataClient = (Data)ByteArray2Object(data);
arrData.Add(dataClient);
Console.WriteLine($"{dataClient.text}");
//Send(clientSocket);
foreach (Socket item in listSocket)
{
item.Send(Object2ByteArray(dataClient));
}
}
}
catch
{
}
}
//static void Close()
//{
// client.Close();
//}
static byte[] Object2ByteArray(object obj)
{
//MemoryStream memoryStream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
using (MemoryStream memoryStream = new MemoryStream())
{
formatter.Serialize(memoryStream, obj);
return memoryStream.ToArray();
}
}
static object ByteArray2Object(byte[] data)
{
BinaryFormatter formatter = new BinaryFormatter();
using (MemoryStream memoryStream = new MemoryStream(data))
{
return formatter.Deserialize(memoryStream);
}
}
}
}
|
d38a569a282457251c7311d16476ef5c911dfaf2
|
C#
|
glzbcrt/nethpc
|
/src/netHPC.Samples.PrimeNumbers/Range.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace netHPC.Samples.PrimeNumbers
{
[Serializable]
public class Range
{
private UInt64 m_start;
private UInt64 m_finish;
public Range()
{
}
public Range(UInt64 start, UInt64 finish)
{
m_start = start;
m_finish = finish;
}
public UInt64 Start
{
get { return m_start; }
set { m_start = value; }
}
public UInt64 Finish
{
get { return m_finish; }
set { m_finish = value; }
}
}
}
|
d2cb52b9b2ea814fbf4e8ed9c38517105bbfde00
|
C#
|
goldmanpark/algorithm
|
/Baekjoon/String/10988.cs
| 3.359375
| 3
|
using System;
namespace Solution
{
public class Solution_10988
{
public static void Main(string[] args)
{
string str = Console.ReadLine();
int answer = 1;
for(int i = 0 ; i < str.Length / 2 ; i++){
if(str[i] == str[str.Length - 1 - i])
continue;
else{
answer = 0;
break;
}
}
Console.WriteLine(answer);
}
}
}
|
1cc7c439858734ec36cf95ff8b86abe68acdc9f4
|
C#
|
ch-sindhu/Logical8
|
/Selectionsort/Selectionsort/Program.cs
| 3.640625
| 4
|
using System;
namespace Selectionsort
{
class Program
{
public static void Selection_sort(int[] ar)
{
for(int i=0;i<ar.Length;i++)
{
var min = i;
for(int j=i+1;j<ar.Length;j++)
{
if(ar[min]>ar[i])
{
min = j;
}
}
if(min!=i)
{
var lowervalue = ar[min];
ar[min] = ar[i];
ar[i] = lowervalue;
}
}
}
static void Main(string[] args)
{
int[] ar = new int[] { 50 ,70 ,50, 80 ,89, 25, 78 ,58 ,83 ,73 };
Console.WriteLine("Before sorting");
foreach (var item in ar)
Console.Write(item + " ");
Console.WriteLine(" ");
Console.WriteLine("After sorting");
foreach (var item in ar)
Console.Write(item + " ");
}
}
}
|
b4172c42c6f12438713a8f450382e57c735779eb
|
C#
|
Oswinakamura/OBLeasing
|
/OBLeasing.Web/Data/Entities/Owner.cs
| 2.859375
| 3
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace OBLeasing.Web.Data.Entities
{
public class Owner
{
public int Id { get; set; }
[Display(Name = "Documento")]
[MaxLength(20, ErrorMessage = "El campo {0} no puede tener más de {1} caracteres.")]
[Required(ErrorMessage = "El campo {0} es obligatorio.")]
[Column(TypeName = "varchar(20)")]
public string Document { get; set; }
[Display(Name = "Nombre")]
[MaxLength(30, ErrorMessage = "El campo {0} no puede tener más de {1} caracteres.")]
[Required(ErrorMessage = "El campo {0} es obligatorio.")]
[Column(TypeName = "varchar(30)")]
public string FirstName { get; set; }
[Display(Name = "Apellido")]
[MaxLength(30, ErrorMessage = "El campo {0} no puede tener más de {1} caracteres.")]
[Required(ErrorMessage = "El campo {0} es obligatorio.")]
[Column(TypeName = "varchar(30)")]
public string LastName { get; set; }
[Display(Name = "Fijo")]
[MaxLength(10, ErrorMessage = "El campo {0} no puede tener más de {1} caracteres.")]
[Column(TypeName = "varchar(10)")]
public string FixedPhone { get; set; }
[Display(Name = "Celular")]
[MaxLength(10, ErrorMessage = "El campo {0} no puede tener más de {1} caracteres.")]
[Column(TypeName = "varchar(15)")]
public string CellPhone { get; set; }
[Display(Name = "Direccion")]
[MaxLength(50, ErrorMessage = "The {0} field can not have more than {1} characters.")]
[Column(TypeName = "varchar(50)")]
public string Address { get; set; }
[Display(Name = "Nombre Completo")]
public string FullName => $"{FirstName} {LastName}";
public string FullNameWithDocument => $"{FirstName} {LastName} - {Document}";
public ICollection<Property> Properties { get; set; }
public ICollection<Contract> Contracts { get; set; }
}
}
|
a386021a64eb5c2feef984d578c82400e7c93777
|
C#
|
JDjuxx/CadmusDistribuido
|
/CadmusCursosOnline/CadmusCursosOnline/Controlador/Curso.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CadmusCursosOnline.Controlador
{
class Curso
{
public String[] Select(String Select)
{
String[] data = new String[1];
SqlCommand cmd = new SqlCommand();
Conexion conexion = new Conexion();
cmd.Connection = conexion.IniciarConexion();
cmd.CommandText = Select;
cmd.ExecuteNonQuery();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
// String consulta = "SELECT Usuario, Contrasena, idMiembro, idDireccion, salt FROM Miembro WHERE Usuario = '" + Username + "'";
data[0] = Convert.ToString(dr[0]);
}
conexion.CerrarConexion();
return data;
}
}
}
|
8f25a61062eb1605eef823834b71f75a58d3041a
|
C#
|
HellFinger-s/Surveillance
|
/Assets/Scripts/targetControl.cs
| 2.53125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class targetControl : MonoBehaviour
{
public float speed;//скорость движения
public float lineChangeSpeed;//скорость перемещения между линиями
private float timer;
public int horizontalLineNumber;
private Rigidbody targetRb;
private string speedState = "common";//состояние движения
public bool moving = true;
private bool horizontalMoveCondition = false;
public GameObject frontArrow;
public GameObject backArrow;
public GameObject characterControlPanel;
private GameObject character;
public GameObject[] positions = new GameObject[0];
public Vector2 accelerationTimeIntervalBorders;//временной промежуток ускорения
public Vector2 brakingTimeIntervalBorders;//временной промежуток замедления
void Start()
{
targetRb = gameObject.GetComponent<Rigidbody>();
character = characterControlPanel.GetComponent<CharacterControl>().character;
}
public void FixedUpdate()
{
if (moving)//машина движется | target is moving
{
targetRb.velocity = new Vector3(-speed, 0, 0);
}
else
{
targetRb.velocity = new Vector3(0, 0, 0);
}
if (horizontalMoveCondition)//перемещение между линиями | changing line
{
gameObject.transform.position = new Vector3(
gameObject.transform.position.x,
gameObject.transform.position.y,
Mathf.Lerp(
gameObject.transform.position.z,
positions[horizontalLineNumber].transform.position.z,
lineChangeSpeed * Time.deltaTime
)
);
}
if (Math.Round(gameObject.transform.position.z, 2) == Math.Round(positions[horizontalLineNumber].transform.position.z, 2))//переместился ли игрок на позицию | moved to the position
{
gameObject.transform.position = new Vector3(
gameObject.transform.position.x,
gameObject.transform.position.y,
positions[horizontalLineNumber].transform.position.z
);
horizontalMoveCondition = false;
}
}
public void Update()
{
timer += Time.deltaTime;
if(timer > accelerationTimeIntervalBorders[0] && speedState != "acceleration")//пришло время ускоряться | time to accelerate
{
speed *= 1.2f;
speedState = "acceleration";
}
if(timer > accelerationTimeIntervalBorders[1] && speedState == "acceleration")//возвращаемся в спокойное состояние | return to calm state
{
speed *= 0.8f;
speedState = "common";
accelerationTimeIntervalBorders[0] = 90f;
accelerationTimeIntervalBorders[1] = 90f;
}
if (timer > brakingTimeIntervalBorders[0] && speedState != "braking")//пришло время снижения скорости | time to reduce speed
{
speed *= 0.8f;
speedState = "braking";
}
if (timer > brakingTimeIntervalBorders[1] && speedState == "braking")//возвращаемся в спокойное состояние | return to calm state
{
speed *= 1.2f;
speedState = "common";
brakingTimeIntervalBorders[0] = 90f;
brakingTimeIntervalBorders[1] = 90f;
}
}
public void OnBecameInvisible()//машина цель за пределами видимости | target vehicle is out of sight
{
characterControlPanel.GetComponent<CharacterControl>().targetInvis = true;
}
public void OnBecameVisible()//игрок видит машину | player see target car
{
characterControlPanel.GetComponent<CharacterControl>().targetInvis = false;
frontArrow.SetActive(false);
backArrow.SetActive(false);
}
public void Right()
{
horizontalLineNumber += 1;
horizontalMoveCondition = true;
}
public void Left()
{
horizontalLineNumber -= 1;
horizontalMoveCondition = true;
}
}
|
420143d9532793f8d6723614224b5771396d1382
|
C#
|
Berzeger/MI-RUN
|
/paa5/paa5/Formula.cs
| 3.71875
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace paa5
{
public class Formula
{
private readonly IList<Clause> clauses;
public Formula(IList<Clause> clauses)
{
this.clauses = clauses;
}
public int ClausesCount
{
get { return clauses.Count; }
}
public bool Satisfied(State state)
{
return clauses.All(clause => clause.Satisfied(state)); // All clauses must be satisfied
}
public int AverageWeight(State state)
{
return clauses.Sum(clause => clause.GetWeight(state))/clauses.Count;
}
// Number of unsatisfied clauses
public int NotSatisfied(State state)
{
return clauses.Count(clause => !clause.Satisfied(state));
}
public int Penalty(State state, int method, int formulaWeight)
{
switch (method)
{
case 0:
return 0;
case 1: // formula weight - unsatisfied * average clause weight
//Console.WriteLine("Penalty: {0}", formulaWeight - NotSatisfied(state) * AverageWeight(state));
return formulaWeight - NotSatisfied(state)*AverageWeight(state);
default:
return 0;
}
}
public void Print()
{
Console.WriteLine("Printing a formula:");
foreach (var clause in clauses)
{
Console.WriteLine(clause);
}
}
}
}
|
a133123a3e698021ac3d3f0fb66f595fdf326330
|
C#
|
ryanninjasheep/MooTUI
|
/MooTUI/Drawing/Color.cs
| 2.78125
| 3
|
using System.Data.Common;
using System.Text;
namespace MooTUI.Drawing
{
public enum Color
{
/// <summary>
/// No color. Usually rendered as transparent.
/// </summary>
None,
/// <summary>
/// Darkest base color. Background in dark themes.
/// </summary>
Base03,
/// <summary>
/// Second-darkest base color. Secondary background in dark themes.
/// </summary>
Base02,
/// <summary>
/// Third-darkest base color. Selection background in dark themes; emphasized foreground in light themes.
/// </summary>
Base01,
/// <summary>
/// Darker mid-tone base color. Secondary foreground in dark themes; primary foreground in light themes.
/// </summary>
Base00,
/// <summary>
/// Lighter mid-tone base color. Primary foreground in dark themes; secondary foreground in light themes.
/// </summary>
Base0,
/// <summary>
/// Third-lightest base color. Emphasized foreground in dark themes; selection background in light themes.
/// </summary>
Base1,
/// <summary>
/// Second-lightest base color. Secondary background in light themes.
/// </summary>
Base2,
/// <summary>
/// Lightest base color. Background in light themes.
/// </summary>
Base3,
Red,
Orange,
Yellow,
Green,
Cyan,
Blue,
Purple,
Magenta,
AltRed,
AltOrange,
AltYellow,
AltGreen,
AltCyan,
AltBlue,
AltPurple,
AltMagenta
}
}
|
f4e303954df89be2792d82a227fff696f148422b
|
C#
|
kajacx/Zapoctak
|
/Zapoctak/game/events/Event.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Zapoctak.game;
namespace Zapoctak.game.events
{
public class Event
{
public Entity source, target;
public EventData data;
public Event(Entity source, Entity target, EventData data)
{
this.source = source;
this.target = target;
this.data = data;
}
public override string ToString()
{
return String.Format("Event[from:{0}, to:{1}, data:{2}]", source, target, data);
}
}
}
|
b41d1aa62686984bec2f07b85608cfdec24764a8
|
C#
|
thomas4019/TravelingSalesman
|
/BBWorker.cs
| 2.578125
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Timers;
using System.Diagnostics;
namespace TSP
{
class BBWorker
{
public static int MaxWorkerCount = 8;
public static int MinAgendaSplitSize = 50;
public static int workerCount = 0;
public static long MaxRam = 0;
private static int MaxAgendaCount = 200000;
public delegate void UpdateAction(bool done);
public static UpdateAction updateGUI;
C5.IntervalHeap<BBState> Agenda;
static double initial_bound;
double[,] trueCosts;
int numPoints;
static double BSSF_cost;
public static BBState BSSF;
public static bool timeAvailable;
BBState initial;
public static int invalidSolutionsCount;
public static int failedCount;
public static int expansions;
public static int pruned;
public static int prunedChild;
public static int maxAgenda;
public BBWorker(BBState initial, double[,] trueCosts, int numPoints)
{
invalidSolutionsCount = failedCount = expansions = pruned = prunedChild = maxAgenda = 0;
workerCount = 0;
workerCount++;
this.initial = initial;
Agenda = new C5.IntervalHeap<BBState>();
BSSF_cost = double.PositiveInfinity;
this.trueCosts = trueCosts;
initial_bound = initial.bound;
this.numPoints = numPoints;
Agenda.Add(initial);
timeAvailable = true;
}
public BBWorker(double[,] trueCosts, int numPoints)
{
workerCount++;
this.trueCosts = trueCosts;
this.numPoints = numPoints;
}
public void setAgenda(C5.IntervalHeap<BBState> Agenda)
{
this.Agenda = Agenda;
}
public void run()
{
while(!Agenda.IsEmpty && timeAvailable && BSSF_cost != initial_bound) {
BBState u = Agenda.DeleteMin();
//Console.WriteLine(u.bound);
//Pruning
if (u.bound > BSSF_cost)
{
pruned++;
continue;
}
int x,y;
if (u.chooseNextEdge(out x, out y))
{
BBState exclude = u;
BBState include = new BBState(u);
exclude.exclude(x, y);
include.include(x, y);
expand(exclude);
expand(include);
expansions++;
if (expansions % 1000 == 0)
{
Process proc = Process.GetCurrentProcess();
MaxRam = Math.Max(MaxRam, proc.PrivateMemorySize64);
}
}
else
{
failedCount++;
if (failedCount % 100 == 0)
Console.WriteLine("failed " + failedCount);
}
splitCheck();
if (!timeAvailable)
break;
}
Console.WriteLine(Agenda.Count + " on agenda when ending");
workerCount--;
if (workerCount == 0)
{
updateGUI(true);
}
}
public BBState GetBSSFState()
{
return BSSF;
}
public static void setBSSF(double BSSF_cost)
{
BBWorker.BSSF_cost = BSSF_cost;
}
private void expand(BBState w) {
if (w.bound < BSSF_cost || BSSF == null) // See if bound is within cost
{
if (criterion(w))
{ // If full solution
BSSF = w;
BSSF_cost = BSSF.bound;
updateGUI(false);
Console.WriteLine("Found solution with cost " + BSSF.bound + " depth=" + BSSF.depth);
}
else if (w.depth < numPoints)
{ // Otherwise add to agenda
//Console.WriteLine(w.bound);
Agenda.Add(w);
}
else
{
invalidSolutionsCount++;
//if (triedCount % 50 == 0)
//{
Console.WriteLine("Failed Solution " + invalidSolutionsCount);
//}
}
}
else
{
prunedChild++;
}
}
private bool criterion(BBState w)
{
if (w.depth != numPoints)
{
return false;
}
return w.validateCycle();
}
public void splitCheck()
{
if (Agenda.Count > maxAgenda)
{
maxAgenda = Agenda.Count;
}
//Console.WriteLine(Agenda.Count);
if (workerCount < MaxWorkerCount && Agenda.Count > MinAgendaSplitSize)
{
Console.WriteLine("Splitting Agenda cost=" + BSSF_cost + " size=" + Agenda.Count);
C5.IntervalHeap<BBState> a = new C5.IntervalHeap<BBState>();
C5.IntervalHeap<BBState> b = new C5.IntervalHeap<BBState>();
//Split agenda into two
int counter = 0;
foreach (BBState s in Agenda)
{
if (counter++ % 2 == 0)
{
a.Add(s);
}
else
{
b.Add(s);
}
}
BBWorker child = new BBWorker(trueCosts, numPoints);
child.setAgenda(b);
setAgenda(a);
Thread nThread = new Thread(new ThreadStart(child.run));
nThread.Start();
}
}
}
class BBState : IComparable
{
private static double lambda = .0005;
private double[,] cost;
public double bound;
public double depth;
public double excludeCount;
public int numPoints;
List<Tuple<int, int>> segments;
public BBState(int numPoints)
: this(new double[numPoints, numPoints])
{
}
public BBState(double[,] cost)
{
this.cost = cost;
this.numPoints = cost.GetLength(1);
this.segments = new List<Tuple<int, int>>();
}
/// Copy Constructor
public BBState(BBState other)
{
this.cost = new double[other.numPoints, other.numPoints];
Array.Copy(other.cost, this.cost, other.numPoints * other.numPoints);
this.numPoints = other.numPoints;
this.depth = other.depth;
this.bound = other.bound;
this.segments = other.segments.ToList(); //deep clone is not necessary since we don't modify the tuples
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public double getPriority()
{
return lambda * bound + (1 - lambda) * (numPoints - depth);
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public int CompareTo(object obj)
{
return (int)(getPriority() - ((BBState)obj).getPriority());
}
/// <summary>
///
/// </summary>
/// <param name="chosenX"></param>
/// <param name="chosenY"></param>
public bool chooseNextEdgeOld(out int chosenX, out int chosenY)
{
for (int y = 0; y < numPoints; y++) {
for (int x = (depth >= 1) ? 0 : 1; x < numPoints; x++) {
if (!double.IsNaN(cost[x, y]) && !double.IsPositiveInfinity(cost[x,y]) )
{
chosenX = x;
chosenY = y;
return true;
}
}
}
chosenX = chosenY = 0;
return false;
}
public bool chooseNextEdge(out int chosenX, out int chosenY)
{
double min = double.MaxValue;
for (int y = 0; y < numPoints; y++)
for (int x = (depth >= 1) ? 0 : 1; x < numPoints; x++)
if (cost[x, y] < min)
{
min = cost[x, y];
}
for (int y = 0; y < numPoints; y++)
{
for (int x = (depth >= 1) ? 0 : 1; x < numPoints; x++)
{
if (min == cost[x, y])
{
chosenX = x;
chosenY = y;
return true;
}
}
}
chosenX = chosenY = 0;
return false;
}
/// <summary>
///
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
public void exclude(int x, int y)
{
cost[x, y] = double.PositiveInfinity;
excludeCount++;
reduce();
}
/// <summary>
///
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
public void include(int x, int y)
{
if (Double.IsNaN(cost[x, y]) || Double.IsPositiveInfinity(cost[x, y]))
{
throw new Exception();
}
bound += cost[x, y];
for (int i = 0; i < numPoints; i++)
{
cost[i, y] = double.PositiveInfinity;
cost[x, i] = double.PositiveInfinity;
}
cost[x, y] = double.NaN;
cost[y, x] = double.PositiveInfinity;
++depth;
//prevent cycles unless this is one edge away
if (depth < numPoints - 1)
{
int segmentX = x;
int segmentY = y;
for (int i = segments.Count - 1; i >= 0; i--)
{
Tuple<int, int> edge = segments[i];
if (edge.Item2 == segmentX)
{
segments.RemoveAt(i);
segmentX = edge.Item1;
}
else if (edge.Item1 == segmentY)
{
segments.RemoveAt(i);
segmentY = edge.Item2;
}
}
segments.Add(new Tuple<int, int>(segmentX, segmentY));
if (cost[segmentY, segmentX] != double.NaN)
cost[segmentY, segmentX] = double.PositiveInfinity;
}
reduce();
}
public ArrayList getRoute(City[] cities)
{
ArrayList cityList = null;
if (depth == numPoints)
{
cityList = new ArrayList();
int row = 0;
for (int i = 0; i < numPoints; ++i)
{
for (int x = 0; x < numPoints; ++x)
{
if ( Double.IsNaN(cost[x, row]) )
{
cityList.Add(cities[x]);
row = x;
break;
}
}
}
}
else
{
Console.WriteLine("STAAAHP!!!");
}
return cityList;
}
public double[,] getCostMatrix()
{
return cost;
}
/// <summary>
///
/// </summary>
private void reduce()
{
for (int x = 0; x < numPoints; x++) // Column reduction
{
double min = double.PositiveInfinity;
for (int y = 0; y < numPoints; y++) // Find minimum in column
{
if (cost[x, y] < min)
{
min = cost[x, y];
}
}
if (min > 0 && !double.IsPositiveInfinity(min))
{
for (int y = 0; y < numPoints; y++)
{
cost[x, y] -= min;
}
bound += min;
}
}
for (int y = 0; y < numPoints; y++) // Row reduction
{
double min = double.PositiveInfinity;
for (int x = 0; x < numPoints; x++) // Find minimum in row
{
if (cost[x, y] < min)
{
min = cost[x, y];
}
}
if (min > 0 && !double.IsPositiveInfinity(min) )
{
for (int x = 0; x < numPoints; x++)
{
cost[x, y] -= min;
}
bound += min;
}
}
}
public bool validateCycle()
{
int row = 0;
bool[] visited = new bool[numPoints];
for (int i = 0; i < numPoints; ++i)
{
for (int x = 0; x < numPoints; ++x)
{
if (Double.IsNaN(cost[x, row]))
{
if (visited[x])
{
Console.WriteLine(x + " cannot be used twice");
return false;
}
visited[x] = true;
row = x;
break;
}
}
}
return true;
}
}
}
|
b06665e79b2a41e132188dbff77fb942e4f1c39e
|
C#
|
trongphan/AnemicDomainModel
|
/Source/Ticketing.Infrastructure/Domain/TypeSafeEnum.cs
| 3.3125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Ticketing.Infrastructure.Domain
{
public abstract class TypeSafeEnum<TDerived, TValue> where TDerived : TypeSafeEnum<TDerived, TValue>
{
private TValue _value;
private string _caption;
static TypeSafeEnum()
{
Type valueType = typeof(TValue);
if (!valueType.IsValueType)
{
throw new ArgumentException("TValue must be a value type!");
}
}
protected TypeSafeEnum(TValue value, string caption)
{
_value = value;
_caption = caption;
}
public TValue Value
{
get { return _value; }
}
public string Caption
{
get { return _caption; }
}
#region Type Conversion Operators
public static explicit operator TypeSafeEnum<TDerived, TValue>(ValueType value)
{
TypeSafeEnum<TDerived, TValue> conversionResult = ConvertToInstanceOfDerived(value);
if (conversionResult != null)
{
return conversionResult;
}
throw new InvalidCastException();
}
public static explicit operator TypeSafeEnum<TDerived, TValue>(string caption)
{
TypeSafeEnum<TDerived, TValue> conversionResult = ConvertToInstanceOfDerived(caption);
if (conversionResult != null)
{
return conversionResult;
}
throw new InvalidCastException();
}
#endregion
private static TypeSafeEnum<TDerived, TValue> ConvertToInstanceOfDerived(object value)
{
TypeSafeEnum<TDerived, TValue> result = null;
Type derivedType = typeof(TDerived);
IEnumerable<FieldInfo> fields = derivedType
.GetFields(BindingFlags.Public | BindingFlags.Static)
.Where(f => f.IsInitOnly && f.FieldType.Equals(derivedType));
if (fields != null && fields.Any())
{
foreach (var field in fields)
{
TDerived fieldValue = field.GetValue(null) as TDerived;
if (fieldValue != null)
{
Type valueType = value.GetType();
if (valueType.IsValueType)
{
// assuming the values will actually fit in four bytes
int fieldAsInteger = (int)Convert.ChangeType(fieldValue.Value, typeof(int));
int valueAsInteger = (int)Convert.ChangeType(value, typeof(int));
if (fieldAsInteger.Equals(valueAsInteger))
{
result = fieldValue;
break;
}
}
else if (valueType == typeof(string))
{
if (fieldValue.Caption.Equals(value as string))
{
result = fieldValue;
break;
}
}
}
}
}
return result;
}
}
}
|
e70d115cfbf4f8ac2a0a71595a928a5406b8d05c
|
C#
|
Kaiose/PacketGenerator
|
/PacketMaker/PacketMaker/PacketGenerator.cs
| 2.625
| 3
|
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Office.Interop.Excel;
using System.Linq.Expressions;
namespace PacketMaker
{
class PacketGenerator
{
public static PacketGenerator instance = new PacketGenerator();
public string ExcelPath = Directory.GetCurrentDirectory();
public string ExcelName = "\\PacketDefinition.xlsx";
public string DefinitionProjectPath = "C:/Users/kaios/Desktop/CSharp_Network/CSharp Server/CSharp Server";
public string DefinitionFileName = "/Packet";
public Application app = new Application();
public Workbook workBook = null;
List<string> keywords = new List<string>();
public Dictionary<string, string> keyData = new Dictionary<string, string>();
public PacketStruct[] packetList = new PacketStruct[ushort.MaxValue];
private PacketGenerator() {
ReadExcel();
}
public void OpenWorkBook()
{
workBook = app.Workbooks.Open(ExcelPath + ExcelName, 0, false);
}
public void ReadKeyword(Range range)
{
for (int i = 2; i <= range.Columns.Count; i++)
{
var value = (range[1, i] as Range).Value2;
if (value != null)
{
keywords.Add(value.ToString());
}
}
}
public void ReadKeyData(Range range)
{
for (int i = 1; i <= 30; ++i)
{
if (keywords.Count < keyData.Count)
{
System.Console.WriteLine("Not matching !!! keyData's data was more then keywords");
return;
}
Range cell = range.Cells[i, 1] as Range;
if (cell.Value2 != null)
{
var key = cell.Value2.ToString();
if (keywords.Contains(key))
{
keyData[key] = (range.Cells[i, 2] as Range).Value2.ToString();
}
}
}
}
private void Ready2ReadSheet(Range range, out int start_row)
{
ReadKeyword(range);
ReadKeyData(range);
System.Int32.TryParse(keyData["DataRow"], out start_row);
}
public void ReadSheet(string sheetName)
{
Worksheet workSheet = workBook.Worksheets[sheetName] as Worksheet;
if(workSheet == null)
{
System.Console.WriteLine("Sheet is Not exist!");
return;
}
Range range = workSheet.UsedRange;
Ready2ReadSheet(range, out var row);
for (; row <= range.Rows.Count; ++row)
{
PacketStruct packetStruct = new PacketStruct();
//read protocol
Range cell = null;
cell = range.Cells[row, 1] as Range;
packetStruct.Classification = cell.Value2.ToString();
cell = range.Cells[row, 2] as Range;
packetStruct.ProtocolName = cell.Value2.ToString();
cell = range.Cells[row, 3] as Range;
packetStruct.ProtocolNumber = cell.Value2.ToString();
//read fields
int column = 4;
while(column <= range.Columns.Count)
{
DataStruct dataStruct = new DataStruct();
try
{
cell = range.Cells[row, column] as Range;
dataStruct.Data_Name = cell.Value2.ToString();
cell = range.Cells[row, column + 1] as Range;
dataStruct.Data_Type = cell.Value2.ToString();
column += 2;
}
catch(System.NullReferenceException e)
{
System.Console.WriteLine("Warning! Null Exception Error! you don't have to process this error");
break;
}
packetStruct.DataList.Add(dataStruct);
}
System.Int32.TryParse(packetStruct.ProtocolNumber, out var index);
if(packetList[index] != null)
{
System.Console.WriteLine("Protocol Number is overlapped!!! Checking Excel have required");
}
packetList[index] = packetStruct;
}
}
private void CloseExcel()
{
foreach(Worksheet workSheet in workBook.Sheets)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet.UsedRange);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
}
System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook.Sheets);
workBook.Save();
workBook.Close(true);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(app.Workbooks);
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
}
public void ReadExcel()
{
OpenWorkBook();
ReadSheet("ProtocolDefinition");
Clear();
}
private void Clear()
{
CloseExcel();
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
}
}
}
|
4af2ae43570ca35fa574ba21238fc5f6a14359b0
|
C#
|
Abdulmajeed-Almaymuni/Project04_Auth_CRUD_ASP.NET
|
/School/Controllers/RoomsController.cs
| 2.6875
| 3
|
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using School.Data;
using School.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace School.Controllers
{
[Authorize]
public class RoomsController : Controller
{
private readonly ApplicationDbContext _db;
public RoomsController(ApplicationDbContext context)
{
_db = context;
}
public IActionResult Index(bool? added = false, bool? deleted = false)
{
ViewData["Added"] = added;
ViewData["Deleted"] = deleted;
var Rooms = _db.Rooms.ToList();
ViewData["Rooms"] = Rooms;
return View();
}
public IActionResult Details(int? id)
{
var Room = _db.Rooms.FirstOrDefault(r => r.RoomId == id);
ViewBag.Room = Room;
return View();
}
public IActionResult Create()
{
return View();
}
[HttpPost]
public IActionResult Create([Bind("RoomSize")] Room room)
{
if (ModelState.IsValid)
{
_db.Rooms.Add(room);
_db.SaveChanges();
return RedirectToAction("Index", new { added = true });
}
return View(room);
}
public IActionResult Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var room = _db.Rooms.Find(id);
if (room == null)
{
return NotFound();
}
ViewData["Room"] = room;
return View(room);
}
[HttpPost]
public IActionResult Edit(int id, [Bind("RoomSize")] Room room)
{
room.RoomId = id;
_db.Rooms.Update(room);
_db.SaveChanges();
return RedirectToAction("Index");
}
public IActionResult Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var room = _db.Rooms.FirstOrDefault(r => r.RoomId == id);
if (room == null)
{
return NotFound();
}
ViewBag.RoomId = room.RoomId;
return View(room);
}
[HttpPost]
public IActionResult Delete(int id, [Bind("RoomSize")] Room room)
{
room.RoomId = id;
_db.Rooms.Remove(room);
_db.SaveChanges();
return RedirectToAction("Index", new { deleted = true });
}
}
}
|
8ede1a661bfe1d3d2b19befe33848fb2e9989c69
|
C#
|
SzymonPobiega/NetMX
|
/NetMX/MBeanServerConnectionExtensions.cs
| 2.6875
| 3
|
namespace NetMX
{
///<summary>
/// Extension methods for <see cref="IMBeanServerConnection"/>.
///</summary>
public static class MBeanServerConnectionExtensions
{
///<summary>
/// Creates a new dynamic proxy object that forwards method invocations and property gets/sets to specified <see cref="IMBeanServerConnection"/>.
///</summary>
///<param name="connection">A connection to use.</param>
///<param name="name">An object name of MBean that this proxy applies to.</param>
///<returns></returns>
public static dynamic CreateDynamicProxy(this IMBeanServerConnection connection, ObjectName name)
{
return new DynamicMBeanProxy(name, connection);
}
}
}
|
c7c230b7ca0f0992bb02ac5662b5027d9d881582
|
C#
|
C41-233/TypeName.Sharp
|
/project/TypeName.Sharp/MethodName/MethodNameExtend.cs
| 2.625
| 3
|
using System.Reflection;
using TypeName.Filter;
namespace TypeName
{
public static class MethodNameExtend
{
public static string GetDefinitionNameString(this MethodInfo method, TypeNameFlag flags = TypeNameFlag.Default)
{
return GetDefinitionName(method, flags).ToString();
}
public static string GetDefinitionFullNameString(this MethodInfo method, TypeNameFlag flags = TypeNameFlag.Default)
{
return GetDefinitionFullName(method, flags).ToString();
}
public static IMethodName GetDefinitionFullName(this MethodInfo method, TypeNameFlag flags = TypeNameFlag.Default)
{
return new MethodName(method, flags);
}
public static IMethodName GetDefinitionName(this MethodInfo method, TypeNameFlag flags = TypeNameFlag.Default)
{
var name = new MethodName(method, flags);
var filter = new NamespaceFilter();
name.FilterNamespace(filter);
filter.ClearNamespace();
return name;
}
}
}
|
1bda5a8c7b34e72bcdd198ee4802e4aa9ea1fe42
|
C#
|
YVEF/RssAtomFid
|
/RssAtomFid.Api/DAL/Interfaces/IAuthRepository.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using RssAtomFid.Api.DAL.Entity.Account;
namespace RssAtomFid.Api.DAL.Interfaces
{
public interface IAuthRepository
{
/// <summary>
/// Register method without cheking of user exists
/// </summary>
/// <param name="user"></param>
/// <param name="password"></param>
/// <returns></returns>
Task<User> Register(User user, string password);
/// <summary>
/// Just login method
/// </summary>
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns></returns>
Task<User> Login(string username, string password);
/// <summary>
/// Check user exists
/// </summary>
/// <param name="email"></param>
/// <returns></returns>
Task<bool> UserExists(string email);
Task<User> GetUser(string email);
Task<User> GetUser(int id);
}
}
|
5384eecaa5914652ddce20c51e8a531bd2485f95
|
C#
|
NadiaKaradjova/SoftUni
|
/C# Advanced/Sets And Dictionaries - Exercises/10 Population Counter/Population Counter.cs
| 3.453125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace _10_Population_Counter
{
public class _10_Population_Counter
{
public static void Main()
{
var result = new Dictionary<string, Dictionary<string, int>>();
var countryPopulation = new Dictionary<string, long>();
var input = Console.ReadLine();
while (input != "report")
{
var line = input.Split('|');
var town = line[0];
var country = line[1];
var population = int.Parse(line[2]);
if (!result.ContainsKey(country))
{
result[country] = new Dictionary<string, int>();
countryPopulation[country] = 0;
}
var towns = result[country];
if (!towns.ContainsKey(town))
{
towns[town] = 0;
}
towns[town] = population;
countryPopulation[country] += population;
input = Console.ReadLine();
}
foreach (var country in countryPopulation.OrderByDescending(x => x.Value))
{
Console.WriteLine($"{country.Key} (total population: {country.Value})");
var currentTown = result.First(x => x.Key == country.Key);
var towns = currentTown.Value;
foreach (var item in towns.OrderByDescending(x => x.Value))
{
Console.WriteLine($"=>{item.Key}: {item.Value}");
}
}
}
}
}
|
b8b7f300dc9e3d99b35e33e982a7673f3a2fc77d
|
C#
|
kimtz/CIKMovies
|
/CIK.Movies/CIK.Movies.Core/MovieCollection.cs
| 3.328125
| 3
|
using System.Collections.Generic;
using System.Linq;
namespace CIK.Movies.Core
{
public class MovieCollection
{
private readonly IStorage _storage;
public IEnumerable<Movie> Movies => _storage.GetAll();
public MovieCollection(IStorage storage)
{
_storage = storage;
}
public void AddMovie(string name)
{
int id = GetMovieId();
var movie = new Movie(id, name);
_storage.Add(movie);
}
public void RemoveMovie(Movie movie)
{
if (Movies.Contains(movie))
{
_storage.Remove(movie);
}
else
{
throw new System.ArgumentException("The movie does not exist");
}
}
public void RemoveAll()
{
_storage.RemoveAll();
}
public int GetMovieId()
{
return _storage.GetAll().Count() + 1;
}
}
}
|
ca810425ea610a9abd6e345104e63ff44d4fa2b8
|
C#
|
Arugess/Crazy-Asteroid
|
/FireMissile.cs
| 2.546875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//This will make a missile fire from the missle spawner.//
public class FireMissile : MonoBehaviour
{
public GameObject missile1;
public Transform earthArrow;
public static bool canFire;
void Start ()
{
canFire = true;
}
void Update ()
{
if (Input.GetKeyDown(KeyCode.Mouse0) && canFire)
{
GameObject missile1Instance;
missile1Instance = Instantiate(missile1, earthArrow.position, earthArrow.rotation);
missile1Instance.GetComponent<Rigidbody2D>().AddForce(transform.up * 600);
canFire = false;
StartCoroutine("Reload");
}
}
IEnumerator Reload()
{
yield return new WaitForSeconds(3.0f);
canFire = true;
}
}
|
2b572c644186eb951088c3d825300685775eda25
|
C#
|
paulmarrington/Able
|
/Assets/Askowl/Able/Scripts/Memory/Selector.cs
| 2.796875
| 3
|
// Copyright 2018 (C) paul@marrington.net http://www.askowl.net/unity-packages
using System;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;
namespace Askowl {
/// <a href="http://bit.ly/2OrRfQp">Pick one item from a list.</a> <inheritdoc />
public sealed class Selector<T> : Pick<T> {
/// <a href="http://bit.ly/2OrRfQp">Defaults to random. Set false to cycle through entries sequentially</a>
public bool IsRandom = true;
/// <a href="http://bit.ly/2OvCQ5Q">If the list is shorter then select items randomly, but never choose one a second time until all have been picked. This is useful for short lists to reduce repeats.</a>
public int ExhaustiveBelow = 1;
private T[] choices = { };
private Func<T> picker;
/// <a href="http://bit.ly/2OrRfQp">Method called to pick an item</a> <inheritdoc />
public T Pick() {
if (picker != null) return picker();
if (choices.Length == 0) {
picker = () => default;
} else if (choices.Length == 1) {
picker = () => choices[0];
} else if (!IsRandom) { // cycle through list
cycleIndex = -1;
picker = () => choices[++cycleIndex % choices.Length];
} else if (choices.Length >= ExhaustiveBelow) { // random selection
picker = () => choices[cycleIndex = Random.Range(0, choices.Length)];
} else {
remainingSelections = new List<T>(collection: choices);
picker = () => { // different random choice until list exhausted, then repeat
if (remainingSelections.Count == 0) remainingSelections = new List<T>(collection: choices);
cycleIndex = Random.Range(0, remainingSelections.Count);
T result = remainingSelections[index: cycleIndex];
remainingSelections.RemoveAt(index: cycleIndex);
return result;
};
}
next = -1;
return picker();
}
/// <a href="">Called when a pick fails and we need to try something else</a> //#TBD#//
public T Next() {
if (next == -1) next = cycleIndex;
next = (next + 1) % choices.Length;
return next == (cycleIndex % choices.Length) ? default : choices[next];
}
/// <a href=""></a> //#TBD#//
public void Top() => cycleIndex = -1;
/// <a href="http://bit.ly/2OvDtMK">Used to update the choices to a new set using the same picker.</a>
public T[] Choices {
get => choices;
set {
choices = value;
picker = null;
}
}
private int cycleIndex, next;
/// <a href="http://bit.ly/2NU0GsC">The location of the next choice in the sequence.</a>
public int CycleIndex => cycleIndex % choices.Length;
private List<T> remainingSelections;
/// <a href="http://bit.ly/2OrRfQp">Remove all choices for an empty list</a>
public void Reset() => choices = emptyChoices;
private readonly T[] emptyChoices = { };
}
}
|
0c8bac9e75701f229bddb97b190839dd9dd0ee3a
|
C#
|
jackjet870/DJS
|
/code/DJS/DJS.BLL/TriggerGroup.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DJS.BLL
{
public class TriggerGroup
{
#region 属性
/// <summary>
/// 触发器组接口
/// </summary>
private static IDAL.ITriggerGroup iTriggerGroup = null;
#endregion
#region 构造函数
static TriggerGroup()
{
iTriggerGroup = DJS.DAL.DataAccessFactory.DataAccessFactory.CreateITriggerGroup();
}
#endregion
#region 获取触发器组数据 +List<Model.TriggerGroup> GetModels()
/// <summary>
/// 获取触发器组数据
/// </summary>
/// <returns></returns>
public static List<Model.TriggerGroup> GetModels()
{
return iTriggerGroup.GetModels();
}
/// <summary>
/// 获取触发器组数据
/// </summary>
/// <returns></returns>
public static List<Model.TriggerGroup> GetModels(Predicate<Model.TriggerGroup> pre)
{
List<Model.TriggerGroup> models = GetModels();
if (models != null && models.Count > 0)
{
models = models.FindAll(pre);
}
return models;
}
#endregion
#region 根据名称判断是否存在 +static bool IsExist(string name)
/// <summary>
/// 根据名称判断是否存在
/// </summary>
/// <param name="name">名称</param>
/// <returns>true:存在 false:不存在</returns>
public static bool IsExist(string name)
{
return iTriggerGroup.IsExist(name);
}
#endregion
#region 根据id删除数据 +bool DelById(Guid Id)
/// <summary>
/// 根据id删除数据
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
public static bool DelById(Guid Id)
{
return iTriggerGroup.DelById(Id);
}
#endregion
#region 添加 +static bool Add(Model.TriggerGroup model)
/// <summary>
/// 添加实体
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static bool Add(Model.TriggerGroup model)
{
return iTriggerGroup.Add(model);
}
#endregion
}
}
|
00d39990509f555477918a542ff6bdcaff716ef3
|
C#
|
GermanKuber-zz/SweetMachine
|
/SweetMachine/Candies.cs
| 3.53125
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace SweetMachine
{
public class Candies : ICandies
{
private readonly Queue<ICandy> _candies = new Queue<ICandy>();
public Candies(IEnumerable<ICandy> candies)
{
if (candies == null)
throw new ArgumentNullException(nameof(candies));
candies.ToList().ForEach(x => _candies.Enqueue(x));
}
public ICandy GiveMe(int countOfCandies = 1) => new PackOfCandies(Enumerable.Range(0, countOfCandies)
.ToList()
.Select(x =>
{
if (_candies.TryDequeue(out var candy))
return candy;
return new NothingCandy();
})
.ToList());
public void Add(ICandy candy)
{
_candies.Enqueue(candy);
}
}
}
|
37a121c8783f8c5b14f463b177a636cdb5c0e667
|
C#
|
RandomityGuy/PQ-Rewind-Prototype
|
/PQ-Rewind/RewindServer.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TcpFramework;
namespace PQ_Rewind
{
public class RewindService : TcpServiceClientBase
{
public static TcpService<RewindService> Instance;
internal Stack<FrameData> frames = new Stack<FrameData>();
int popcount;
bool isReplay = false;
protected override ValueTask OnClose()
{
return new ValueTask();
}
protected override void OnConnect()
{
Console.WriteLine("Connected " + this.ClientEndPoint.ToString());
var args = CommandLineParser.cmdline;
if (args != null)
{
if (args.Count() > 0)
{
frames.Clear();
//We are loading a saved replay on the stack
var replaydata = File.ReadLines(args[0]);
foreach (var line in replaydata)
{
if (line == "") continue;
if (line == "pushFrame") continue;
frames.Push(new FrameData(GetWords(line,1,18)));
}
Console.WriteLine("Loaded Replay " + args[0]);
isReplay = true;
}
}
StartReceive();
}
protected override ValueTask OnReceive(Memory<byte> segment)
{
var bytestr = string.Concat(Encoding.ASCII.GetChars(segment.ToArray()));
var msgtype = GetWord<string>(bytestr, 0);
if (msgtype == "pushFrame")
{
var rawdata = GetWords(bytestr, 1, 18);
Console.WriteLine("PushFrame: " + rawdata);
Console.WriteLine("Frames: " + frames.Count);
PushFrame(rawdata);
}
if (msgtype == "popFrame")
{
if (frames.Count == 0) return new ValueTask();
var frame = PopFrame();
var msg = new List<string>() { "FRAME", frame.ms.ToString(), frame.deltaMs.ToString(), frame.position.x.ToString(), frame.position.y.ToString(), frame.position.z.ToString(), frame.velocity.x.ToString(), frame.velocity.y.ToString(), frame.velocity.z.ToString(), frame.spin.x.ToString(), frame.spin.y.ToString(), frame.spin.z.ToString(), frame.powerup,frame.timebonus.ToString(),frame.mpstates,frame.gemcount.ToString(),frame.gemstates,frame.ttstates }.Aggregate((i, j) => i + " " + j) + Environment.NewLine;
var bytemsg = Encoding.ASCII.GetBytes(msg.ToCharArray());
Console.WriteLine("PopFrame: " + msg);
Console.WriteLine("Frames: " + frames.Count);
popcount++;
Send(bytemsg, 0, bytemsg.Count());
}
if (msgtype == "clearFrames")
{
if (isReplay) return new ValueTask();
Console.WriteLine("Clearing Frames");
popcount = 0;
var s = new StreamWriter(File.OpenWrite(DateTime.Now.ToFileTime().ToString() + ".rwx"));
foreach (var frame in frames)
{
var msg = new List<string>() { "FRAME", frame.ms.ToString(), frame.deltaMs.ToString(), frame.position.x.ToString(), frame.position.y.ToString(), frame.position.z.ToString(), frame.velocity.x.ToString(), frame.velocity.y.ToString(), frame.velocity.z.ToString(), frame.spin.x.ToString(), frame.spin.y.ToString(), frame.spin.z.ToString(), frame.powerup, frame.timebonus.ToString(), frame.mpstates, frame.gemcount.ToString(), frame.gemstates,frame.ttstates }.Aggregate((i, j) => i + " " + j);
s.WriteLine(msg);
}
s.Flush();
s.Close();
frames.Clear();
}
return new ValueTask();
}
public static void Start()
{
Instance = TcpService<RewindService>.Create(28005);
Instance.Start();
}
public static void Stop()
{
Instance.Dispose();
}
public void PushFrame(string rawframe)
{
try
{
frames.Push(new FrameData(rawframe));
}
catch (Exception) { };
}
public FrameData PopFrame()
{
return (frames.Count != 0) ? frames.Pop() : new FrameData("0 0 0 0 0 0 0 0 0 0 0 none 0 [] 0 []");
}
T GetWord<T>(string str, int pos)
{
return (T)Convert.ChangeType(str.Split(' ')[pos], typeof(T));
}
string GetWords(string str, int pos,int count)
{
var skipped = str.Split(' ').Skip(pos);
var ret = skipped.Take(count);
return ret.Aggregate((i, j) => i + " " + j);
}
}
}
|
b7ba6da775383dd338ef09ced18e452e2d678671
|
C#
|
Odenysyuk/Learning
|
/Csharp/Troelsen/Core C# Programing/NullableTypes/Program.cs
| 3.09375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NullableTypes
{
class Program
{
static void Main(string[] args)
{
//bool myBool = null; errror, because Boolean isn't reference type
Console.WriteLine();
bool? myBool = null;
Console.WriteLine("my Bool = {0}", myBool);
Nullable<bool> nullableInt = null;
Console.WriteLine("my Bool != null =>{0}", nullableInt.HasValue);
Console.WriteLine("my Bool != null => {0}", nullableInt != null);
Console.WriteLine("Operator ??");
nullableInt = nullableInt ?? false;
Console.WriteLine("my Bool = {0}", nullableInt);
Console.WriteLine("my Bool != null => {0}", nullableInt != null);
Console.WriteLine("Operator ??");
nullableInt = nullableInt ?? true;
Console.WriteLine("my Bool = {0}", nullableInt);
Console.WriteLine("my Bool != null => {0}", nullableInt != null);
}
}
}
|
bcdbacae9832cad48cc836c3c83d4400a41cba73
|
C#
|
Lutwidge/Procedural-2D-3D-caves
|
/Assets/Scripts/2D/MeshGenerator.cs
| 3.03125
| 3
|
using UnityEngine;
using System.Collections.Generic;
// Class reponsible for creating mesh with the marching squares method
public class MeshGenerator : MonoBehaviour
{
#region Nodes Squares and Triangles Declarations
public class Node
{
public Vector3 Position;
public int VertexIndex = -1;
public Node(Vector3 pos)
{
Position = pos;
}
}
// Nodes controlling 2 others
public class ControlNode : Node
{
public bool Active;
public Node Above;
public Node Right;
public ControlNode(Vector3 pos, bool active, float squareSize) : base(pos)
{
Active = active;
// Create the two nodes controlled by this control node
Above = new Node(Position + Vector3.forward * squareSize / 2.0f);
Right = new Node(Position + Vector3.right * squareSize / 2.0f);
}
}
// Square with 4 control nodes as vertices, and regular nodes as the center of the sides
public class Square
{
public ControlNode TopLeft, TopRight, BottomLeft, BottomRight;
public Node CenterTop, CenterRight, CenterBottom, CenterLeft;
public int Configuration = 0; // The configuration the square is in (16 possibles in marching squares)
public Square(ControlNode topLeft, ControlNode topRight, ControlNode bottomRight, ControlNode bottomLeft)
{
TopLeft = topLeft;
TopRight = topRight;
BottomLeft = bottomLeft;
BottomRight = bottomRight;
CenterTop = TopLeft.Right;
CenterRight = BottomRight.Above;
CenterBottom = BottomLeft.Right;
CenterLeft = BottomLeft.Above;
// Determine the configuration based on the active nodes
if (TopLeft.Active) // 1000 = 8
Configuration += 8;
if (TopRight.Active) // 0100 = 4
Configuration += 4;
if (BottomRight.Active) // 0010 = 2
Configuration += 2;
if (BottomLeft.Active) // 0001 = 1
Configuration += 1;
}
}
// Holds a 2D array of squares
public class SquareGrid
{
public Square[,] Squares;
public SquareGrid(int[,] map, float squareSize)
{
int nodeCountX = map.GetLength(0);
int nodeCountY = map.GetLength(1);
float mapWidth = nodeCountX * squareSize;
float mapHeight = nodeCountY * squareSize;
ControlNode[,] controlNodes = new ControlNode[nodeCountX, nodeCountY];
Vector3 pos = Vector3.zero;
for (int i = 0; i < nodeCountX; i++)
{
for (int j = 0; j < nodeCountY; j++)
{
pos.x = -mapWidth / 2.0f + i * squareSize + squareSize / 2.0f;
pos.z = -mapHeight / 2.0f + j * squareSize + squareSize / 2.0f;
controlNodes[i, j] = new ControlNode(pos, map[i, j] == 1, squareSize);
}
}
Squares = new Square[nodeCountX - 1, nodeCountY - 1]; // There is one less square than there are nodes
for (int i = 0; i < nodeCountX - 1; i++)
{
for (int j = 0; j < nodeCountY - 1; j++)
{
Squares[i, j] = new Square(controlNodes[i, j + 1], controlNodes[i + 1, j + 1], controlNodes[i + 1, j], controlNodes[i, j]);
}
}
}
}
struct Triangle
{
public int vertexIndexA;
public int vertexIndexB;
public int vertexIndexC;
int[] vertices;
public Triangle(int a, int b, int c)
{
vertexIndexA = a;
vertexIndexB = b;
vertexIndexC = c;
vertices = new int[3];
vertices[0] = a;
vertices[1] = b;
vertices[2] = c;
}
public int this[int i]
{
get
{
return vertices[i];
}
}
public bool Contains(int vertexIndex)
{
return vertexIndex == vertexIndexA || vertexIndex == vertexIndexB || vertexIndex == vertexIndexC;
}
}
#endregion
[SerializeField] private int _wallHeight;
[SerializeField] private MeshFilter _caveMesh;
[SerializeField] private MeshFilter _wallMesh;
private MeshCollider _wallCollider;
private SquareGrid _squareGrid;
private List<Vector3> _vertices;
private List<int> _triangles;
private Dictionary<int, List<Triangle>> _triangleDictionary = new Dictionary<int, List<Triangle>>();
private List<List<int>> _outlines = new List<List<int>>();
private HashSet<int> _checkedVertices = new HashSet<int>(); // HashSet to have much quicker contain checks than a list
public void GenerateMesh(int[,] map, float squareSize)
{
// Clear the outlines
_outlines.Clear();
_checkedVertices.Clear();
_triangleDictionary.Clear();
// Clear the collider
if (_wallCollider != null)
Destroy(_wallCollider);
_wallCollider = _wallMesh.gameObject.AddComponent<MeshCollider>();
_squareGrid = new SquareGrid(map, squareSize);
_vertices = new List<Vector3>();
_triangles = new List<int>();
// Go through all the squares of the square grid and triangulate them
for (int i = 0; i < _squareGrid.Squares.GetLength(0); i++)
{
for (int j = 0; j < _squareGrid.Squares.GetLength(1); j++)
{
TriangulateSquare(_squareGrid.Squares[i, j]);
}
}
// Create the mesh
Mesh mesh = new Mesh();
_caveMesh.mesh = mesh;
mesh.vertices = _vertices.ToArray();
mesh.triangles = _triangles.ToArray();
mesh.RecalculateNormals();
CreateWallMesh();
}
private void TriangulateSquare(Square square)
{
// Look through the 16 configuration cases
// Define each time the triangle to be produced in ccw order
switch (square.Configuration)
{
// No mesh
case 0:
break;
// 1 points:
case 1:
MeshFromPoints(square.CenterLeft, square.CenterBottom, square.BottomLeft);
break;
case 2:
MeshFromPoints(square.BottomRight, square.CenterBottom, square.CenterRight);
break;
case 4:
MeshFromPoints(square.TopRight, square.CenterRight, square.CenterTop);
break;
case 8:
MeshFromPoints(square.TopLeft, square.CenterTop, square.CenterLeft);
break;
// 2 points:
case 3:
MeshFromPoints(square.CenterRight, square.BottomRight, square.BottomLeft, square.CenterLeft);
break;
case 6:
MeshFromPoints(square.CenterTop, square.TopRight, square.BottomRight, square.CenterBottom);
break;
case 9:
MeshFromPoints(square.TopLeft, square.CenterTop, square.CenterBottom, square.BottomLeft);
break;
case 12:
MeshFromPoints(square.TopLeft, square.TopRight, square.CenterRight, square.CenterLeft);
break;
case 5:
MeshFromPoints(square.CenterTop, square.TopRight, square.CenterRight, square.CenterBottom, square.BottomLeft, square.CenterLeft);
break;
case 10:
MeshFromPoints(square.TopLeft, square.CenterTop, square.CenterRight, square.BottomRight, square.CenterBottom, square.CenterLeft);
break;
// 3 point:
case 7:
MeshFromPoints(square.CenterTop, square.TopRight, square.BottomRight, square.BottomLeft, square.CenterLeft);
break;
case 11:
MeshFromPoints(square.TopLeft, square.CenterTop, square.CenterRight, square.BottomRight, square.BottomLeft);
break;
case 13:
MeshFromPoints(square.TopLeft, square.TopRight, square.CenterRight, square.CenterBottom, square.BottomLeft);
break;
case 14:
MeshFromPoints(square.TopLeft, square.TopRight, square.BottomRight, square.CenterBottom, square.CenterLeft);
break;
// 4 point:
case 15:
MeshFromPoints(square.TopLeft, square.TopRight, square.BottomRight, square.BottomLeft);
// In this case, none of the vertices can be outlines, so we can mark them as checked
_checkedVertices.Add(square.TopLeft.VertexIndex);
_checkedVertices.Add(square.TopRight.VertexIndex);
_checkedVertices.Add(square.BottomRight.VertexIndex);
_checkedVertices.Add(square.BottomLeft.VertexIndex);
break;
}
}
// Creates a mesh based on points
private void MeshFromPoints(params Node[] points)
{
AssignVertices(points);
if (points.Length >= 3) // 3 or more points, we create a triangle
CreateTriangle(points[0], points[1], points[2]);
if (points.Length >= 4) // 4 or more points, we create another triangle
CreateTriangle(points[0], points[2], points[3]);
if (points.Length >= 5) // 5 or more points, we create another triangle
CreateTriangle(points[0], points[3], points[4]);
if (points.Length >= 6) // 6 points, we create another triangle
CreateTriangle(points[0], points[4], points[5]);
}
private void AssignVertices(Node[] points)
{
for (int i = 0; i < points.Length; i++)
{
if (points[i].VertexIndex == -1) // Point not assigned
{
points[i].VertexIndex = _vertices.Count;
_vertices.Add(points[i].Position);
}
}
}
private void CreateTriangle(Node a, Node b, Node c)
{
_triangles.Add(a.VertexIndex);
_triangles.Add(b.VertexIndex);
_triangles.Add(c.VertexIndex);
Triangle triangle = new Triangle(a.VertexIndex, b.VertexIndex, c.VertexIndex);
AddTriangleToDictionary(triangle.vertexIndexA, triangle);
AddTriangleToDictionary(triangle.vertexIndexB, triangle);
AddTriangleToDictionary(triangle.vertexIndexC, triangle);
}
private void AddTriangleToDictionary(int index, Triangle triangle)
{
if (_triangleDictionary.ContainsKey(index))
{
_triangleDictionary[index].Add(triangle);
}
else
{
List<Triangle> newTriangleList = new List<Triangle>();
newTriangleList.Add(triangle);
_triangleDictionary.Add(index, newTriangleList);
}
}
// If the two vertices only share one triangle, it is an outline edge
private bool IsOutlineEdge(int vertexA, int vertexB)
{
List<Triangle> vertexATriangles = _triangleDictionary[vertexA];
int sharedTriangleCount = 0;
for (int i = 0; i < vertexATriangles.Count; i++)
{
if (vertexATriangles[i].Contains(vertexB))
{
sharedTriangleCount++;
if (sharedTriangleCount > 1)
{
break;
}
}
}
return sharedTriangleCount == 1;
}
// Find another vertex to form an outline edge
private int GetConnectedOutlineVertex(int vertexIndex)
{
List<Triangle> vertexIndexTriangles = _triangleDictionary[vertexIndex];
// Loop through all the vertices in thess triangles, check if they are outline, and if so return the index
for (int i = 0; i < vertexIndexTriangles.Count; i++)
{
Triangle triangle = vertexIndexTriangles[i];
for (int j = 0; j < 3; j++)
{
int vertexB = triangle[j];
if (vertexB != vertexIndex && !_checkedVertices.Contains(vertexB))
{
if (IsOutlineEdge(vertexIndex, vertexB))
{
return vertexB;
}
}
}
}
return -1; // Outline not found
}
// Go through all the vertices in the map and find the outlines
private void CalculateMeshOutlines()
{
for (int vertexIndex = 0; vertexIndex < _vertices.Count; vertexIndex++)
{
if (!_checkedVertices.Contains(vertexIndex))
{
int newOutlineVertex = GetConnectedOutlineVertex(vertexIndex);
if (newOutlineVertex != -1) // Outline found
{
_checkedVertices.Add(vertexIndex);
List<int> newOutline = new List<int>();
newOutline.Add(vertexIndex);
_outlines.Add(newOutline);
FollowOutline(newOutlineVertex, _outlines.Count - 1);
_outlines[_outlines.Count - 1].Add(vertexIndex); // Add the original vertex to close the outline (make it loop)
}
}
}
}
private void FollowOutline(int vertexIndex, int outlineIndex)
{
_outlines[outlineIndex].Add(vertexIndex);
_checkedVertices.Add(vertexIndex);
int nextVertexIndex = GetConnectedOutlineVertex(vertexIndex);
if (nextVertexIndex != -1)
{
FollowOutline(nextVertexIndex, outlineIndex);
}
}
private void CreateWallMesh()
{
CalculateMeshOutlines();
List<Vector3> wallVertices = new List<Vector3>();
List<int> wallTriangles = new List<int>();
Mesh wallMesh = new Mesh();
foreach (List<int> outline in _outlines)
{
for (int i = 0; i < outline.Count - 1; i++)
{
int startIndex = wallVertices.Count;
wallVertices.Add(_vertices[outline[i]]); // Left vertex
wallVertices.Add(_vertices[outline[i + 1]]); // Right vertex
wallVertices.Add(_vertices[outline[i]] - Vector3.up * _wallHeight); // Bottom Left vertex
wallVertices.Add(_vertices[outline[i + 1]] - Vector3.up * _wallHeight); // Bottom Right vertex
// We view the walls from inside, so ccw order
wallTriangles.Add(startIndex + 0);
wallTriangles.Add(startIndex + 2);
wallTriangles.Add(startIndex + 3);
wallTriangles.Add(startIndex + 3);
wallTriangles.Add(startIndex + 1);
wallTriangles.Add(startIndex + 0);
}
}
wallMesh.vertices = wallVertices.ToArray();
wallMesh.triangles = wallTriangles.ToArray();
_wallMesh.mesh = wallMesh;
// Create the wall colider
_wallCollider.sharedMesh = wallMesh;
}
}
|
a6724785084de12a00ccfe4b9d2a506085a686f8
|
C#
|
simosabba/alaska
|
/src/foundation/Alaska.Foundation.Core/Extensions/StringExtensions.cs
| 3.25
| 3
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Alaska.Foundation.Core.Extensions
{
public static class StringExtensions
{
public static T ParseEnum<T>(this string value)
where T : struct
{
return (T)Enum.Parse(typeof(T), value, true);
}
public static string TruncateBeforeChar(this string value, char c)
{
int index = value.IndexOf(c);
if (index > 0)
value = value.Substring(0, index);
return value;
}
public static string RemoveQueryString(this string value)
{
return value.TruncateBeforeChar('?');
}
public static string RemoveFirstOccurrence(this string value, string str)
{
return RemoveFirstOccurrence(value, str, false);
}
public static string RemoveFirstOccurrence(this string value, string str, bool ignoreCase)
{
if ((ignoreCase && value.StartsWith(str, StringComparison.InvariantCultureIgnoreCase)) ||
(!ignoreCase && value.StartsWith(str)))
return value.Substring(str.Length);
return value;
}
public static string EnsureSlashPrefix(this string value)
{
return value.EnsurePrefix("/");
}
public static string EnsurePrefix(this string value, string prefix)
{
return value.StartsWith(prefix) ? value : prefix + value;
}
public static string EnsureSlashSuffix(this string value)
{
return value.EnsureSuffix("/");
}
public static string EnsureSuffix(this string value, string suffix)
{
return value.EndsWith(suffix) ? value : value + suffix;
}
public static string ToTitleCase(this string value)
{
var textInfo = new CultureInfo("en-US", false).TextInfo;
return textInfo.ToTitleCase(value.ToLower());
}
public static string ToKebabCase(this string value)
{
return string.Concat(value.Select((x, i) => i > 0 && char.IsUpper(x) ? "-" + x.ToString() : x.ToString())).ToLower();
}
public static string ToSnakeCase(this string value)
{
return string.Concat(value.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString() : x.ToString())).ToLower();
}
public static string RemoveBrackets(this string value)
{
return value.Replace("{", string.Empty).Replace("}", string.Empty);
}
public static int GetCommonPrefixLength(this string value, string other, bool ignoreCase)
{
if (ignoreCase)
{
value = value.ToLower();
other = other.ToLower();
}
var index = 0;
for (; index < Math.Min(value.Length, other.Length); index++)
if (value[index] != other[index])
break;
return index;
}
}
}
|
147e205325a4f7fba3af0d1a8c0fe06dca7c5a42
|
C#
|
ljubicaboneva/InternetTehnologii
|
/LAB3 VP/Koshnicka_VI_Lab4/NovProdukt.cs
| 2.859375
| 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 Koshnicka_VI_Lab4
{
public partial class Form2 : Form
{
public Product produkt { get; set; }
public Form2()
{
InitializeComponent();
}
private void btnDodadi_Click(object sender, EventArgs e)
{
produkt = new Product();
produkt.Name = txtName.Text;
produkt.Kateogrija = txtCategory.Text;
int.TryParse(txtPrice.Text,out int price);
produkt.Cena = price;
DialogResult = DialogResult.OK ;
}
private void btnOtkazi_Click(object sender, EventArgs e)
{
DialogResult =DialogResult.Cancel;
}
private void txtName_Validating(object sender, CancelEventArgs e)
{
if (txtName.Text.Trim().Length == 0)
{
e.Cancel = true;
validatorName.SetError(txtName, "Внесете име!");
}
else
{
validatorName.SetError(txtName, null);
}
}
private void txtCategory_Validating(object sender, CancelEventArgs e)
{
if (txtCategory.Text.Trim().Length == 0)
{
e.Cancel = true;
validatorCategory.SetError(txtCategory, "Внеси категорија");
}
else
{
validatorCategory.SetError(txtCategory, null);
}
}
private void txtPrice_Validating(object sender, CancelEventArgs e)
{
if (txtPrice.Text.Trim().Length == 0)
{
e.Cancel = true;
validatorPrice.SetError(txtPrice, "Внеси цена");
}
else if (!(int.TryParse(txtPrice.Text, out int c)))
{
e.Cancel = true;
validatorPrice.SetError(txtPrice, "Грешка формат");
}
else
{
validatorPrice.SetError(txtPrice, null);
}
}
}
}
|
ba1eb19588a58cc7c6f665cfd1b2f31a292de5e2
|
C#
|
shendongnian/download4
|
/first_version_download2/487132-44035551-145627735-2.cs
| 3.59375
| 4
|
static Bitmap DrawChart(float[] Values, int Width, int Height)
{
var n = Values.Count();
if (n % 2 == 1) throw new Exception("Invalid data");
//Split the data into lists for easy access
var x = new List<float>();
var y = new List<float>();
for (int i = 0; i < n - 1; i += 2)
{
x.Add(Values[i]);
y.Add(Values[i + 1]);
}
//Chart axis limits, change here to get custom ranges like -1,+1
var minx = x.Min();
var miny = y.Min();
var maxx = x.Max();
var maxy = y.Max();
var dxOld = maxx - minx;
var dyOld = maxy - miny;
//Rescale the y-Range to add a border at the top and bottom
miny -= dyOld * 0.2f;
maxy += dyOld * 0.2f;
var dxNew = (float)Width;
var dyNew = (float)Height;
//Draw the data
Bitmap res = new Bitmap(Width, Height);
using (var g = Graphics.FromImage(res))
{
g.Clear(Color.Black);
for (int i = 0; i < x.Count; i++)
{
//Calculate the coordinates
var px = Interpolate(x[i], minx, maxx, 0, dxNew);
var py = Interpolate(y[i], miny, maxy, 0, dyNew);
//Draw, put the ellipse center around the point
g.FillEllipse(Brushes.ForestGreen, px - 1.0f, py - 1.0f, 2.0f, 2.0f);
}
}
return res;
}
static float Interpolate(float Value, float OldMin, float OldMax, float NewMin, float NewMax)
{
//Linear interpolation
return ((NewMax - NewMin) / (OldMax - OldMin)) * (Value - OldMin) + NewMin;
}
|
ec65d1dea0f29af2f7f394307c46f79de06a78e5
|
C#
|
DamCarduner/HGC.slicePizza
|
/perso.googleHashCode.slicePizza/Tools/RectangleComparer.cs
| 3.109375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace perso.googleHashCode.slicePizza
{
/// <summary>
/// Class allowing to sort rectangles
/// </summary>
public class RectangleComparer : Comparer<int[]>
{
//Compare by area
public override int Compare(int[] first, int[] second)
{
if ((first[0] * first[1]).CompareTo(second[0] * second[1]) != 0)
{
return (first[0] * first[1]).CompareTo(second[0] * second[1]);
}
else
{
return 0;
}
}
}
}
|
d695e0d2d1ece440a13a2a1d28723dbc0cde0caf
|
C#
|
Fyzxs/MicroObjectsCalculator
|
/MicroObjectsCalculator/MainWindow.xaml.cs
| 2.65625
| 3
|
using System.Windows;
using System.Windows.Controls;
using MicroObjectsCalculator.CalcNodes;
using MicroObjectsCalculator.Ops;
namespace MicroObjectsCalculator
{
public interface IMainWindow { }
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : IMainWindow
{
private ICalcNode _lastOperation;
private bool _lastDisplayResult;
private static ICalcNode _inputNode;
public MainWindow()
{
InitializeComponent();
_inputNode = new ContentControlValueCalcNode(LblCurrentResult);
_lastOperation = _inputNode;
}
private void Digit_OnClick(object sender, RoutedEventArgs e)
{
string content = ((ContentControl)sender).Content.ToString();
if (_lastDisplayResult)
{
LblCurrentResult.Content = content;
_lastDisplayResult = false;
return;
}
LblCurrentResult.Content += content;
}
private void BtnAddition_OnClick(object sender, RoutedEventArgs e)
=> Operation(new AdditionInitialCreateNode(_lastOperation, _inputNode));
private void BtnSubtraction_OnClick(object sender, RoutedEventArgs e)
=> Operation(new SubtractionInitialCreateNode(_lastOperation, _inputNode));
private void BtnMultiplication_OnClick(object sender, RoutedEventArgs e)
=> Operation(new MultiplicationInitialCreateNode(_lastOperation, _inputNode));
private void BtnDivision_OnClick(object sender, RoutedEventArgs e)
=> Operation(new DivisionInitialCreateNode(_lastOperation, _inputNode));
private void Operation(ICreateNode createNode)
{
if (_lastDisplayResult) return;
_lastOperation = createNode.Create();
LblCurrentResult.Content = (int)_lastOperation.Value();
LblButtonSequence.Content = (string)_lastOperation.Sequence();
_lastDisplayResult = true;
}
private void BtnEquals_OnClick(object sender, RoutedEventArgs e)
{
_lastOperation = _lastOperation.Copy();
LblCurrentResult.Content = (int)_lastOperation.Value();
LblButtonSequence.Content = "";
_lastDisplayResult = false;
_lastOperation = new ContentControlValueCalcNode(LblCurrentResult);
}
private void BtnClear_OnClick(object sender, RoutedEventArgs e)
{
_lastOperation = new ContentControlValueCalcNode(LblCurrentResult);
LblButtonSequence.Content = "";
LblCurrentResult.Content = "";
_lastDisplayResult = false;
}
}
}
|
378db376d723af14476a98d1813883f4ae51df5e
|
C#
|
zhouhongjie/dnd-table-online
|
/DndTable.Core.Test/UnitTests/AttackRollTest.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DndTable.Core.Dice;
using NUnit.Framework;
namespace DndTable.Core.Test.UnitTests
{
[TestFixture]
public class AttackRollTest
{
[TestCase(0, 9, false)]
[TestCase(0, 10, true)]
[TestCase(1, 9, true)]
public void SuccessTest(int bonus, int roll, bool shouldHit)
{
var attackRoll = new AttackRoll(null, DiceRollEnum.Attack, bonus, roll, 10, 20);
Assert.AreEqual(shouldHit, attackRoll.Success);
}
[TestCase(0)]
[TestCase(10)]
[TestCase(20)]
[TestCase(100)]
public void AutoSuccessTest(int ac)
{
var attackRoll = new AttackRoll(null, DiceRollEnum.Attack, 0, 20, 10, ac);
Assert.That(attackRoll.Success);
}
[TestCase(0)]
[TestCase(10)]
[TestCase(20)]
[TestCase(100)]
public void AutoFailTest(int ac)
{
var attackRoll = new AttackRoll(null, DiceRollEnum.Attack, 0, 1, 10, ac);
Assert.That(!attackRoll.Success);
}
[TestCase(19, 20, false)]
[TestCase(19, 19, true)]
[TestCase(20, 20, true)]
[TestCase(20, 19, true)]
public void ThreatTest(int roll, int threatRange, bool shouldThreat)
{
var attackRoll = new AttackRoll(null, DiceRollEnum.Attack, 5, roll, 10, threatRange);
Assert.AreEqual(shouldThreat, attackRoll.IsThreat);
}
}
}
|
ce6c8d9b842b791c2c249de539f709e82abadd5d
|
C#
|
WoolMagician/8-Cores
|
/Assets/Sharp Text Mesh/Script/SharpText.cs
| 2.765625
| 3
|
using UnityEngine;
using System.Collections;
public class SharpText : MonoBehaviour {
public float sizeInUnits; // Set size of text in units. Most fonts have a lot of empty space above and below the characters. So it won't probably match the grid.
public TextMesh textMesh; //In inspector assign the Text Mesh component
private float sharpness;
// Update is called once per frame
void Update () {
sharpness = Screen.height / (20 * Camera.main.orthographicSize);
textMesh.fontSize = Mathf.RoundToInt(sharpness*sizeInUnits);
textMesh.characterSize = 1/(float)sharpness;
}
}
|
d2b47d0b9587c3e8cc78cd4d5c704fa857965bf3
|
C#
|
NoricoG/MidiPianoRico
|
/MidiPianoRico/FileHandler.cs
| 2.96875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;
using System.Drawing;
namespace MidiPianoRico
{
static class FileHandler
{
public static Settings LoadSettings()
{
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MidiPianoRico");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
path += "/settings.txt";
if (File.Exists(path))
{
List<string> lines = new List<string>();
using (StreamReader streamReader = new StreamReader(path))
{
string line = "";
while ((line = streamReader.ReadLine()) != null)
lines.Add(line);
}
return new Settings(lines);
}
else
{
Settings settings = new Settings();
SaveSettings(settings);
return settings;
}
}
public static void SaveSettings(Settings settings)
{
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MidiPianoRico/settings.txt");
using (StreamWriter streamWriter = new StreamWriter(path))
{
foreach (string line in settings.ToLines())
{
streamWriter.WriteLine(line);
}
}
}
public static List<string> GetFilePaths(string path)
{
List<string> paths = new List<string>();
//MessageBox.Show("The selected path is: " + path);
string[] found = Directory.GetFiles(path, "*.mscz");
for (int i = 0; i < found.Length; i++)
{
int filenameLength = found[i].Length - path.Length - 6;
string filename = found[i].Substring(path.Length + 1, filenameLength);
paths.Add(filename);
}
paths.Sort();
return paths;
}
public static Bitmap[] LoadPages(string path, string song, int width)
{
string[] found = Directory.GetFiles(path, song + "-?.png");
Bitmap[] result = new Bitmap[found.Length];
for (int i = 0; i < found.Length; i++)
{
try
{
using (Image temp = Image.FromFile(found[i]))
{
result[i] = new Bitmap(temp);
}
float ratio = (float)result[i].Width / width;
if (ratio > 1)
{
result[i] = new Bitmap(result[i], (int)((float)result[i].Width / ratio), (int)((float)result[i].Height / ratio));
}
}
catch (Exception)
{
MessageBox.Show("Failed to load an image");
result[i] = new Bitmap(width, 100);
}
}
return result;
}
}
}
|
a15f28731e7acf2e42eb93da6165fb63120ba863
|
C#
|
topfayez/gizmofort.connector.erpnext
|
/Libs/GizmoFort.Connector.ERPNext/PublicTypes/DocType.cs
| 2.734375
| 3
|
using System;
namespace GizmoFort.Connector.ERPNext.PublicTypes
{
public struct DocType
{
public static readonly DocType Customer = new DocType("Customer");
#region Internal
public string Name { get; }
public DocType(string name)
{
this.Name = name;
}
public override string ToString()
{
return Name;
}
#endregion
#region Equality implementation
public static bool operator==(DocType a, DocType b)
{
return Equals(a, b);
}
public static bool operator !=(DocType a, DocType b)
{
return !(a == b);
}
public bool Equals(DocType other)
{
return string.Equals(Name, other.Name);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is DocType && Equals((DocType)obj);
}
public override int GetHashCode()
{
return (Name != null ? Name.GetHashCode() : 0);
}
#endregion
}
}
|
15133f188ad5e548127aa8b47d6eca46c3acf090
|
C#
|
Botyto/Magic
|
/Assets/Magic/Spell/SpellDescriptor.cs
| 2.765625
| 3
|
using System;
using System.Reflection;
using UnityEngine;
/// <summary>
/// Object used to describe a spell.
/// A wizard contains such objects in a list and needs one to cast it.
/// </summary>
[Serializable]
[CreateAssetMenu(fileName = "New Spell", menuName = "Magic/Spell Descriptor")]
public class SpellDescriptor : ScriptableObject
{
#region Types
public enum SpellTargetType
{
/// <summary>
/// Works with any or no target.
/// </summary>
None,
/// <summary>
/// Requires a Unit as a target.
/// </summary>
Unit,
/// <summary>
/// Requires an EnergyManifestation as a target.
/// </summary>
Manifestation,
/// <summary>
/// Requires an inanimate object as a target.
/// </summary>
Inanimate,
}
public enum SpellCastResult
{
/// <summary>
/// Spell successfully cast
/// </summary>
Success,
/// <summary>
/// Invalid spell descriptor
/// </summary>
InvalidDescriptor,
/// <summary>
/// No suitable target provided/found for the spell
/// </summary>
NoTarget,
}
#endregion
#region Technical fields
/// <summary>
/// Universally unique identifier
/// </summary>
public Guid guid;
/// <summary>
/// Unique spell identifier
/// </summary>
public string id;
/// <summary>
/// Name of the spell class
/// </summary>
public string spellClass;
/// <summary>
/// The type of target this spell requires
/// </summary>
public SpellTargetType targetType;
/// <summary>
/// If a target is required or optional
/// </summary>
public bool targetRequired;
/// <summary>
/// Parameters passed to the spell
/// </summary>
public SpellParameters parameters;
#endregion
#region Visual properties
/// <summary>
/// Visual name of the spell
/// </summary>
public string displayName;
/// <summary>
/// Visual icon of the spell
/// </summary>
public Sprite icon;
/// <summary>
/// If the spell is visible by default
/// </summary>
public bool visible = true;
#endregion
#region Spell info
/// <summary>
/// Get the class type of the spell to be cast
/// </summary>
public virtual Type spellType { get { return Type.GetType(spellClass); } }
/// <summary>
/// If this spell is a toggel spell type
/// </summary>
public bool isToggle { get { var ty = spellType; return (ty != null) ? (ty.IsSubclassOf(typeof(ToggleSpellComponent))) : false; } }
#endregion
#region Spell casting
/// <summary>
/// Cast this spell
/// </summary>
public virtual SpellCastResult Cast(Wizard wizard, GameObject target, out SpellComponent spell)
{
Debug.AssertFormat(parameters.level >= 1, "Invalid 'Level' parameter of spell '{0}'!", id);
//Get class
var type = spellType;
if (type == null)
{
//No such class - invalid descriptor
MagicLog.LogErrorFormat("Casting spell '{0}' failed! Class '{1}' not found!", id, type.Name);
spell = null;
return SpellCastResult.InvalidDescriptor;
}
//Try find target, if required
if (!CheckTargetType(target))
{
target = TryFindTarget(wizard);
//Can't find target
if (!CheckTargetType(target) && targetRequired)
{
MagicLog.LogErrorFormat("Casting spell '{0}' failed! Requires target, but none was found!", id);
spell = null;
return SpellCastResult.NoTarget;
}
}
//Cast successfully
spell = wizard.gameObject.AddComponent(type) as SpellComponent;
spell.param = parameters;
spell.target = target;
return SpellCastResult.Success;
}
public virtual GameObject TryFindTarget(Wizard wizard)
{
var type = spellType;
if (type == null)
{
return null;
}
var tryFindTargetMethod = type.GetMethod("TryFindTarget", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
var target = tryFindTargetMethod != null ? (tryFindTargetMethod.Invoke(null, new[] { wizard }) as GameObject) : null;
return target;
}
public virtual bool CheckTargetType(GameObject target)
{
//Anything goes
if (targetType == SpellTargetType.None)
{
return target != null;
}
//No target - since requirement isn't 'None', then we fail
if (target == null)
{
return false;
}
//Check different requirements
switch (targetType)
{
case SpellTargetType.Unit:
return target.GetComponent<Unit>() != null || !targetRequired;
case SpellTargetType.Manifestation:
return target.GetComponent<EnergyManifestation>() != null || !targetRequired;
case SpellTargetType.Inanimate:
return target.GetComponent<Unit>() == null || !targetRequired;
}
//Invalid requirement? Fail...
return false;
}
#endregion
#region Internals
public SpellDescriptor()
{
guid = Guid.NewGuid();
}
#endregion
}
|
dd68c5033c2c22300780d8ebe4a2f0ee5936f200
|
C#
|
tony-jang/PlurCrawler
|
/PlurCrawler/Format/JsonFormat.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PlurCrawler.Format.Base;
using PlurCrawler.Search.Base;
namespace PlurCrawler.Format
{
/// <summary>
/// json 형태로 반환하는 포맷을 나타냅니다.
/// </summary>
/// <typeparam name="TResult"></typeparam>
public class JsonFormat<TResult> : BaseFormat<TResult, string> where TResult : ISearchResult
{
/// <summary>
/// <see cref="JsonFormat{TResult}"/>을 초기화합니다.
/// </summary>
/// <param name="indented">Json 파일을 빈칸 형태로 보기 좋게 정리할지에 대한 여부입니다.</param>
public JsonFormat(bool indented)
{
this.Indented = indented;
}
/// <summary>
/// Json 파일을 빈칸 형태로 보기 좋게 정리할지에 대한 여부입니다.
/// </summary>
public bool Indented { get; set; }
/// <summary>
/// <see cref="IEnumerable{T}"/> 형태의 데이터를 json 기반 string으로 반환합니다.
/// </summary>
/// <param name="resultData"></param>
/// <returns></returns>
public override string FormattingData(IEnumerable<TResult> resultData)
{
return JsonConvert.SerializeObject(resultData, (Indented ? Formatting.Indented : Formatting.None));
}
}
}
|
0c5741396b97e41915f356ac16df6ceb085264dd
|
C#
|
brianmains/Nucleo.NET
|
/src_wip/Nucleo.Core/Collections/ObjectCollection.cs
| 3.5
| 4
|
using System;
using System.Collections;
using System.Collections.Generic;
namespace Nucleo.Collections
{
/// <summary>
/// A collection of objects to use in general situations.
/// </summary>
public class ObjectCollection : CollectionBase<Object>
{
#region " Constructors "
/// <summary>
/// Creates an empty collection.
/// </summary>
public ObjectCollection() { }
/// <summary>
/// Creates with a prepopulated collection.
/// </summary>
/// <param name="obj">The initial list of objects.</param>
public ObjectCollection(IEnumerable<object> obj)
{
this.AddRange(obj);
}
#endregion
#region " Methods "
/// <summary>
/// Adds an enumerable list of items to the collection.
/// </summary>
/// <param name="list">The list to add.</param>
public void AddRange(IEnumerable list)
{
IEnumerator en = list.GetEnumerator();
while (en.MoveNext())
this.Add(en.Current);
}
/// <summary>
/// Adds a generic list of items to the collection.
/// </summary>
/// <typeparam name="T">The type of items in the list.</typeparam>
/// <param name="list">The list of items to add, which will be unboxed.</param>
public void AddRange<T>(IEnumerable<T> list)
{
IEnumerator<T> en = list.GetEnumerator();
while (en.MoveNext())
this.Add(en.Current);
}
#endregion
}
}
|
9b44666ffd8156c63c4fdc84e870fe35b9ac8c73
|
C#
|
tchira/UBB.CS-Labs
|
/AI/AI-lab-2/AI-lab-2/Population.cs
| 3.28125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AI_lab_2
{
class Population
{
Individual[] individuals;
public Population(int popSize, bool init, List<Cube> clist)
{
individuals = new Individual[popSize];
if (init)
{
for (int i = 0; i < size(); i++)
{
Individual newIndiv = new Individual();
newIndiv.generateIndividual(clist);
saveIndividual(i, newIndiv);
}
}
}
public Individual getIndividual(int index)
{
return individuals[index];
}
public Individual getFittest()
{
Individual fittest = individuals[0];
for(int i=0;i<size();i++){
if(fittest.getFitness() <= this.getIndividual(i).getFitness()){
fittest=getIndividual(i);
}
}
return fittest;
}
public int size()
{
return individuals.Length;
}
public void saveIndividual(int index, Individual indiv)
{
individuals[index] = indiv;
}
}
}
|
562cdbbe85a5bb4e2bb8ac13d4ed73d71b4d778a
|
C#
|
Webcontentor/Windows-SDK
|
/src/AccelaSDK/AccelaMobileLogger.cs
| 2.5625
| 3
|
/**
* Copyright 2014 Accela, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Accela.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Accela.WindowsStoreSDK
{
internal class AccelaSDKLogger
{
public static void logInfo(string action, object obj, AccelaLogLevel level)
{
string format = @"[{0}, Method: {1}, {2}] " + Environment.NewLine + "{3}";
string time = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
string message = string.Empty;
var dic = obj as IDictionary<string, object>;
if (dic != null)
{
var strBuilder = new StringBuilder();
foreach (var d in dic)
{
strBuilder.AppendLine(string.Format("{0}: {1}", d.Key, d.Value));
}
message = strBuilder.ToString();
}
else
message = obj.ToString();
if (level <= AccelaSDK.LogLevel && level != AccelaLogLevel.None)
Debug.WriteLine(format, level, action, time, message);
}
}
/// <summary>
/// Accela Log Level
/// </summary>
public enum AccelaLogLevel
{
/// <summary>
/// Fatal error or application crash.
/// </summary>
Critical = 1,
/// <summary>
/// Recoverable error.
/// </summary>
Error = 2,
/// <summary>
/// Noncritical problem.
/// </summary>
Warning = 4,
/// <summary>
/// Informational message.
/// </summary>
Info = 8,
/// <summary>
/// Debugging trace.
/// </summary>
Debug = 16,
/// <summary>
/// No output log.
/// </summary>
None = 32,
}
}
|
ed3d286249b09111b4940feca5ac73c07a41da44
|
C#
|
Vareniedimka/KIS
|
/Управление финансами/Приложение финансы/ERP_Fin/ClassLibrary/Oplata.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary
{
public class Oplata : Zapis
{
public int ID_oplati { get; set; }
public DateTime DataSdelki { get; set; }
public string Data { get { return DataSdelki.ToString("dd.MM.yyyy H:mm:ss"); } }
public int Schet { get; set; }
public string get(string s)
{
switch (s)
{
case "Дата": return Data;
case "Счет": return Schet.ToString();
default: return "";
}
}
}
}
|
a9d99f1ae17649fe9ff18a47ec90fa43c9df9258
|
C#
|
deep39/LFA.MVC
|
/Shared Project/LFA.Biz/LFA.Biz/Ado/UserRepository.cs
| 2.5625
| 3
|
using LFA.Data;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LFA.Biz
{
/// <summary>
/// User Repository to get all data related to users
/// </summary>
public class UserRepository
{
//private static List<User> _listUsers;
DataAccess db;
public UserRepository()
{
//_listUsers = new List<User>();
//User u1 = new User { UserId = 1, UserName = "user1", Password = "password" };
//User u2 = new User { UserId = 2, UserName = "user2", Password = "password" };
//List<User> listUsers = new List<User>();
//listUsers.Add(u1);
//listUsers.Add(u2);
//for (int i = 3; i < 10; i++)
//{
// User u = new User { UserId = i, UserName = "user" + i, Password = "password" };
// listUsers.Add(u);
//}
//_listUsers = listUsers;
db = new DataAccess("Data Source=.;uid=sa;password=system;initial catalog=LFABlog;");
}
public List<User> GetAll()
{
//User u1 = new User { UserID = 1, UserName = "user1", Password = "password" };
//User u2 = new User { UserID = 2, UserName = "user2", Password = "password" };
//List<User> listUsers = new List<User>();
//listUsers.Add(u1);
//listUsers.Add(u2);
//for (int i = 3; i < 10; i++)
//{
// User u = new User { UserID = i, UserName = "user" + i, Password = "password" };
// listUsers.Add(u);
//}
//_listUsers = listUsers;
SqlDataReader dr = db.ExecDataReader("SELECT * FROM dbo.Users");
List<User> lstUsers = new List<User>();
while (dr.Read())
{
User objUser = new User();
objUser.UserId = int.Parse(dr[0].ToString());
objUser.UserName = dr[1].ToString();
objUser.Password = dr[2].ToString();
objUser.Email = dr[3].ToString();
objUser.CreatedDate = DateTime.Parse(dr[4].ToString());
objUser.RoleId = int.Parse(dr[5].ToString());
lstUsers.Add(objUser);
}
dr.Close();
return lstUsers;
}
public int Add(User objUser)
{
objUser.UpdateDate = DateTime.Now;
objUser.UpdateUserID = 1;
return db.ExecNonQueryProc("dbo.InsertUsers", "@UserName", objUser.UserName, "@Password", objUser.Password, "@Email", objUser.Email, "@RoleId", objUser.RoleId);
}
public int Edit(User objUser)
{
return db.ExecNonQueryProc("dbo.UpdateUser", "@UserId", objUser.UserId, "@UserName", objUser.UserName, "@Password", objUser.Password, "@Email", objUser.Email, "@RoleId", objUser.RoleId);
}
public int Delete(int UserId)
{
return db.ExecNonQueryProc("dbo.DeleteUser", "@UserId", UserId);
}
}
}
|
615ca6cb8415204ced6a2ba894c4bdb6a9034b20
|
C#
|
lpopodi/HumaneSociety-
|
/HumaneSociety/HumaneSociety/MainMenu.cs
| 3.46875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HumaneSociety
{
public class MainMenu
{
string visitorChoice;
public MainMenu()
{
Console.WriteLine("Welcome to the Humane Society Application");
MenuVisitorSelection();
}
public void MenuVisitorSelection()
{
Console.WriteLine("Please enter A for Adoptee, or E for Employee");
visitorChoice = Console.ReadLine().ToUpper();
switch (visitorChoice)
{
case "A":
case "ADOPTER":
Console.WriteLine("You have selected Adopter, press any key to continue");
Console.ReadKey();
AdopterMenu adopterMenu = new AdopterMenu();
break;
case "E":
case "EMPLOYEE":
Console.WriteLine("You have selected Employee, press any key to continue");
Console.ReadKey();
EmployeeMenu employeeMenu = new EmployeeMenu();
break;
default:
Console.WriteLine("Your input was not regognized, press any key to go back to the Main Menu");
Console.ReadKey();
MenuVisitorSelection();
break;
}
}
}
}
|
29ca6fb02e5982eb693324351def0e1218d160b8
|
C#
|
jun7th/TestFrom
|
/程序单例运行与重新启动/Program.cs
| 2.953125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 程序单例运行与重新启动
{
//使用线程互斥变量. 通过定义互斥变量来判断是否已运行实例. 把program.cs文件里的Main()函数改为如下代码:
static class Program
{
[DllImport("user32.dll")]
private static extern bool FlashWindow(IntPtr hWnd, bool bInvert);
[DllImport("user32.dll")]
private static extern bool FlashWindowEx(int pfwi);
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
bool runone;
System.Threading.Mutex run = new System.Threading.Mutex(true, "single_test", out runone);
if (runone)
{
run.ReleaseMutex();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 frm = new Form1();
int hdc = frm.Handle.ToInt32(); // write to ...
Application.Run(frm);
IntPtr a = new IntPtr(hdc);
}
else
{
MessageBox.Show("已经运行了一个实例了。");
//IntPtr hdc = new IntPtr(1312810); // read from...
//bool flash = FlashWindow(hdc, true);
}
}
}
}
|
31ca3ba51c95ef760aa8e7ffb778274e6729a767
|
C#
|
shendongnian/download4
|
/code6/1109728-29074484-85933219-2.cs
| 2.75
| 3
|
List<DateTimeRange> availableTimes = new List<DateTimeRange>()
{
new DateTimeRange(new DateTime(2015, 3, 16, 00, 00, 00), new DateTime(2015, 3, 16, 1, 00, 00)),
new DateTimeRange(new DateTime(2015, 3, 16, 08, 00, 00), new DateTime(2015, 3, 16, 10, 00, 00)),
new DateTimeRange(new DateTime(2015, 3, 16, 12, 00, 00), new DateTime(2015, 3, 16, 14, 00, 00)),
new DateTimeRange(new DateTime(2015, 3, 16, 15, 00, 00), new DateTime(2015, 3, 16, 16, 00, 00)),
new DateTimeRange(new DateTime(2015, 3, 16, 19, 00, 00), new DateTime(2015, 3, 16, 23, 59, 59)),
};
var gap = GetGapsForDay(availableTimes);
public IEnumerable<DateTimeRange> GetGapsForDay(List<DateTimeRange> ranges)
{
var start = ranges.First().StartDate.Date;
var end = ranges.First().StartDate.Date.AddDays(1).AddMinutes(-1);
foreach(var item in ranges.OrderBy(i => i.StartDate))
{
if(start < item.StartDate)
yield return new DateTimeRange(start, item.StartDate);
start = item.EndDate;
}
if (ranges.Max(i => i.EndDate) < end)
yield return new DateTimeRange(start, end);
}
|