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
|
|---|---|---|---|---|---|---|
efd0f2f476178ab891c9c60b5878f9657dc9edc4
|
C#
|
swkMagdeburg/2015-06-08_LicenseLottery
|
/src/LicenseLottery.Infrastructure.Database/ParticipantRepository.cs
| 2.828125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using LicenseLottery.Core.Entities;
using LicenseLottery.Core.UseCases.Implementations;
namespace LicenseLottery.Infrastructure.Database
{
public class ParticipantRepository : IParticipantRepository
{
private static readonly List<Participant> Participants = new List<Participant>
{
Participant.New("Uma", "Thurman"),
Participant.New("Quentin", "Tarantino"),
Participant.New("Samuel", "L. Jackson"),
Participant.New("Harvey", "Keitel")
};
public void Add(Participant participant)
{
Participants.Add(participant);
}
public List<Participant> All()
{
return Participants;
}
public Participant GetOneById(Guid id)
{
return Participants.FirstOrDefault(p => p.Id == id);
}
}
}
|
d7f24339b0c0fad167432980ecd97cbb4e67be98
|
C#
|
dariosoltani/FlatFiles
|
/src/FlatFiles/SeparatedValueComplexColumn.cs
| 3.265625
| 3
|
using System;
using System.IO;
using System.Text;
namespace FlatFiles
{
/// <summary>
/// Represents a string column that has contains multiple, nested values
/// </summary>
public class SeparatedValueComplexColumn : ColumnDefinition
{
private readonly SeparatedValueSchema schema;
private SeparatedValueOptions options;
/// <summary>
/// Initializes a new SeparatedValueComplexColumn with no schema or options.
/// </summary>
/// <param name="columnName">The name of the column.</param>
public SeparatedValueComplexColumn(string columnName)
: this(columnName, null, new SeparatedValueOptions(), false)
{
}
/// <summary>
/// Initializes a new SeparatedValueComplexColumn with the given schema and default options.
/// </summary>
/// <param name="columnName">The name of the column.</param>
/// <param name="schema">The schema of the data embedded in the column.</param>
public SeparatedValueComplexColumn(string columnName, SeparatedValueSchema schema)
: this(columnName, schema, new SeparatedValueOptions(), true)
{
}
/// <summary>
/// Initializes a new SeparatedValueComplexColumn with the given options.
/// </summary>
/// <param name="columnName">The name of the column.</param>
/// <param name="options">The options to use when parsing the embedded data.</param>
public SeparatedValueComplexColumn(string columnName, SeparatedValueOptions options)
: this(columnName, null, options, false)
{
}
/// <summary>
/// Initializes a new SeparatedValueComplexColumn with the given schema and options.
/// </summary>
/// <param name="columnName">The name of the column.</param>
/// <param name="schema">The schema of the data embedded in the column.</param>
/// <param name="options">The options to use when parsing the embedded data.</param>
public SeparatedValueComplexColumn(string columnName, SeparatedValueSchema schema, SeparatedValueOptions options)
: this(columnName, schema, options, true)
{
}
private SeparatedValueComplexColumn(string columnName, SeparatedValueSchema schema, SeparatedValueOptions options, bool hasSchema)
: base(columnName)
{
if (hasSchema && schema == null)
{
throw new ArgumentNullException("schema");
}
if (options == null)
{
throw new ArgumentNullException("options");
}
this.schema = schema;
this.options = options;
}
/// <summary>
/// Gets the type of the values in the column.
/// </summary>
public override Type ColumnType
{
get { return typeof(object[]); }
}
/// <summary>
/// Gets or sets the separated value options.
/// </summary>
public SeparatedValueOptions Options
{
get { return options; }
set { options = value ?? new SeparatedValueOptions(); }
}
/// <summary>
/// Extracts a single record from the embedded data.
/// </summary>
/// <param name="value">The value containing the embedded data.</param>
/// <returns>
/// An object array containing the values read from the embedded data -or- null if there is no embedded data.
/// </returns>
public override object Parse(string value)
{
if (Preprocessor != null)
{
value = Preprocessor(value);
}
if (NullHandler.IsNullRepresentation(value))
{
return null;
}
StringReader stringReader = new StringReader(value);
SeparatedValueReader reader = getReader(stringReader);
if (reader.Read())
{
return reader.GetValues();
}
return null;
}
private SeparatedValueReader getReader(StringReader stringReader)
{
if (schema == null)
{
return new SeparatedValueReader(stringReader, options);
}
else
{
return new SeparatedValueReader(stringReader, schema, options);
}
}
/// <summary>
/// Formats the given object array into an embedded record.
/// </summary>
/// <param name="value">The object array containing the values of the embedded record.</param>
/// <returns>A formatted string containing the embedded data.</returns>
public override string Format(object value)
{
object[] values = value as object[];
if (values == null)
{
return NullHandler.GetNullRepresentation();
}
StringWriter writer = new StringWriter();
SeparatedValueRecordWriter recordWriter = new SeparatedValueRecordWriter(writer, schema, options);
recordWriter.WriteRecord(values);
return writer.ToString();
}
}
}
|
471c4fb44b56b292e844c1dcc8dbc6e733145f04
|
C#
|
dayhi/Pool
|
/Program.cs
| 2.640625
| 3
|
using System;
using System.Data;
using System.Diagnostics;
using MySql.Data.MySqlClient;
using MySql_Pool.Helper;
namespace MySql_Pool {
class Program {
static void Main (string[] args) {
const int count = 10000;
//测试机配置:2c3g
test (count);
test1 (count);
}
static void test (int count) {
string connStr = "Host=127.0.0.1;port=3308;database=mytest;uid=root;pwd=123456";
Stopwatch sw = new Stopwatch ();
sw.Start ();
for (int i = 0; i < count; i++) {
using (MySqlConnection conn = new MySqlConnection (connStr)) {
using (MySqlCommand comm = conn.CreateCommand ()) {
conn.Open ();
}
}
}
sw.Stop ();
Console.WriteLine ("正常使用:" + sw.ElapsedMilliseconds); //正常使用:9633
}
static void test1 (int count) {
string connStr = "Host=127.0.0.1;port=3308;database=mytest;uid=root;pwd=123456";
DayPool<MysqlInfo> mysqlPool = new DayPool<MysqlInfo> (100, 1000, ()=>new MysqlInfo(connStr));
Stopwatch sw = new Stopwatch ();
sw.Start ();
for (int i = 0; i < count; i++) {
MysqlInfo mysqlInfo = mysqlPool.GetMysqlInfo ();
mysqlPool.FreeInfo (mysqlInfo);
}
sw.Stop ();
Console.WriteLine ("使用池:" + sw.ElapsedMilliseconds); //使用池:3
}
}
}
|
00ce3be8b8278597584931885a34790aa096f7ef
|
C#
|
tnimas/TicTacToe
|
/src/Factory.cs
| 2.546875
| 3
|
namespace TicTacToe
{
/// <summary>
/// Реализация singleton фабрики классов для приложения
/// </summary>
public class Factory
{
public static Factory Instance { get; private set; }
static Factory()
{
Instance = new Factory();
}
public IWorker CreateWorker()
{
return new TcpWorker();
}
public IView CreateView()
{
return new View();
}
public ITTTProtocol CreateTTTProtocol()
{
return new TTTProtocol();
}
public IExtensions CreateExtensions()
{
return new Extensions();
}
}
}
|
fab98a8216ce5eded72c5e7374d6c9c5effbb02e
|
C#
|
Zalzadip/Brush-up-Student-exercise
|
/Tester/Program.cs
| 3.203125
| 3
|
using System;
using Brush_up__Student;
namespace Tester
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
CreateStudent();
//Console.WriteLine(student.Name);
//Console.WriteLine(student.Address);
}
static void CreateStudent()
{
Student student = new Student();
student.Name = "Morten";
student.Address = "Knud";
student.Semester = 3;
student.Gender = GenderType.Male;
Console.WriteLine(student.ToString());
}
}
}
|
70f71d667db3ecf50842be019480e9fe79af71db
|
C#
|
qlalberta/OtherLabTLG
|
/otherLabsTLG/OIC/CSharp/Labs/Lab7/Part3/TestContact/TestContact/TestContact.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class TestContact
{
public static void Main(string[] args)
{
Contact cont;
cont = new Contact(7, "testetstetsetetsteatetstestetewtwetertetetet", "testetestetestaetetetaewtetwetewtetioerweruieotewth@gmail.com");
ShowContact(cont);
cont.ChangeEmail("hahahahhahahahhahahahhahahahahahahahahahahahhaahiiiiiiiiiiiiii@test.org");
ShowContact(cont);
}
private static void ShowContact(Contact cont)
{
Console.WriteLine("Contact id is {0}, contact name is {1} and contact email is {2}", cont.GetId(), cont.GetName(), cont.GetEmail());
}
}
|
bd64ce4748809215c4a29cd6f2d38a8ae7363057
|
C#
|
tzieba1/.NETProjects
|
/Sorting/LambdaSorting/Sorting/Form1.cs
| 3.5
| 4
|
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 Sorting
{
public partial class Form1 : Form
{
List<Student> students;
public Form1()
{
InitializeComponent();
// Initialiate the Model
students = new List<Student>();
students.Add(new Student("Joe", "Smith", 75, 87 ));
students.Add(new Student("Joanne", "Smith", 75, 88 ));
students.Add(new Student("Harsh", "Patel", 55, 91 ));
students.Add(new Student("Mitel", "Patel", 82, 66 ));
students.Add(new Student("Ishwar", "Singh", 91, 93 ));
students.Add(new Student("Amy", "Nguyen", 91, 65 ));
populateList();
}
private void SortGrade1Button_Click(object sender, EventArgs e)
{
students.Sort((s2, s1) =>
{
if (s2.Grade1 > s1.Grade1)
return -1;
else if (s2.Grade1 < s1.Grade1)
return 1;
return 0;
});
populateList();
}
private void SortGrade2Button_Click(object sender, EventArgs e)
{
students.Sort((s1, s2) => s2.Grade2 - s1.Grade2);
populateList();
}
private void SortAverageButton_Click(object sender, EventArgs e)
{
// Delcare a function to match the exprected delegate
Comparison<Student> AverageCompare = (s1, s2) => (s2.Average - s1.Average) > 0 ? 1
: (s1.Average - s2.Average) > 0 ? -1 : 0;
students.Sort((s1, s2) => (s2.Average - s1.Average) > 0 ? 1
: (s1.Average - s2.Average) > 0 ? -1 : 0);
// or
students.Sort(AverageCompare);
populateList();
}
// Populate Form Data
private void populateList()
{
StudentListBox.Items.Clear();
foreach (Student s in students)
StudentListBox.Items.Add(s);
}
private void SortNameButton_Click(object sender, EventArgs e)
{
students.Sort((s1, s2) => s1.LastName.CompareTo(s2.LastName));
populateList();
}
private void Grade1Then2Button_Click(object sender, EventArgs e)
{
students.Sort((s2, s1) =>
{
// Grade 1 is the primary sort
if (s2.Grade1 > s1.Grade1)
return -1;
else if (s2.Grade1 < s1.Grade1)
return 1;
else
{
// Grade 2 is the secondary sort when grade1 is the same
if (s2.Grade2 > s1.Grade2)
return -1;
else if (s2.Grade2 > s2.Grade2)
return 1;
}
return 0;
});
populateList();
}
}
}
|
787b0923c1cef5d7d5f5ff219d539ce988dc7cbb
|
C#
|
t-ondrej/ShiftScheduling
|
/ShiftScheduleUtilities/SingletonFactory.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
namespace ShiftScheduleUtilities
{
public static class SingletonFactory
{
private static readonly IDictionary<Type, object> Instances = new Dictionary<Type, object>();
public static object GetInstance(Type type)
{
if (Instances.ContainsKey(type))
return Instances[type];
var newInstance = Activator.CreateInstance(type);
Instances.Add(type, newInstance);
return newInstance;
}
}
}
|
3b29203381ccdfe49494acbc95648fd85d2c9907
|
C#
|
nnaidenov/TelerikAcademy
|
/WebDevelopmentExams/WebServices/BlogSystem/BlogSystem.Repositories/DbUserRepository.cs
| 3.015625
| 3
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BlogSystem.Models;
namespace BlogSystem.Repositories
{
public class DbUserRepository : IRepository<User>
{
private readonly DbContext dbContext;
private readonly DbSet<User> entitySet;
private static readonly Random rand = new Random();
private const int SessionKeyLength = 50;
private const string ValidSessionKeyCharacters = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
public DbUserRepository(DbContext context)
{
this.dbContext = context;
this.entitySet = this.dbContext.Set<User>();
}
public User Add(User item)
{
//Validation
this.entitySet.Add(item);
this.dbContext.SaveChanges();
return item;
}
public User Get(int id)
{
return this.entitySet.Find(id);
}
public IQueryable<User> All()
{
return this.entitySet;
}
public User Update(User item, int id, bool flagForLogin)
{
var user = this.entitySet.Find(id);
if (flagForLogin == true)
{
if (user.SessionKey == null)
{
user.SessionKey = this.GenerateSessionKey(id);
}
else if (user.SessionKey != null)
{
throw new InvalidOperationException("Invalid username or password");
}
}
else
{
if (user.SessionKey != null)
{
user.SessionKey = null;
}
else if (user.SessionKey == null)
{
throw new InvalidOperationException("Invalid username or password");
}
}
this.dbContext.SaveChanges();
return user;
}
private string GenerateSessionKey(int userId)
{
StringBuilder sessionKey = new StringBuilder();
sessionKey.Append(userId);
while (sessionKey.Length < SessionKeyLength)
{
int index = rand.Next(ValidSessionKeyCharacters.Length);
sessionKey.Append(ValidSessionKeyCharacters[index]);
}
return sessionKey.ToString();
}
}
}
|
bd6fb50f3c00c8dcdc2e66cba9f461b85914fc8a
|
C#
|
paddyb/edge_case
|
/proxy/DataProxy.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace proxy
{
public class DataProxy
{
private readonly IEnumerable<string> data = new[] { "s1", "s2", "s3" };
public async Task<object> GetProxy(object args)
{
return new { getData = (Func<object, Task<object>>)GetData };
}
public async Task<object> GetData(object args)
{
//return data;
return await Task.Run(()=> data);
}
}
}
|
36cc062d6a2275edec6008aa7f0a1d56f6a665fb
|
C#
|
SilentWave/ObjConvert
|
/src/Obj2Gltf/Gltf/Extensions.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace SilentWave.Gltf
{
static class Extensions
{
// TODO: lock all those add operations in a way that is per model (eg add a static dictionary of model / lock )
public static Int32 AddBuffer(this GltfModel model, Buffer buffer)
{
var index = model.Buffers.Count;
model.Buffers.Add(buffer);
return index;
}
public static Int32 AddBufferView(this GltfModel gltfModel, BufferView bufferView)
{
var bufferViewIndex = gltfModel.BufferViews.Count;
gltfModel.BufferViews.Add(bufferView);
return bufferViewIndex;
}
public static Int32 AddAccessor(this GltfModel model, Accessor accessor)
{
var index = model.Accessors.Count;
model.Accessors.Add(accessor);
return index;
}
public static Int32 AddImage(this GltfModel gltfModel, Image image)
{
var imageIndex = gltfModel.Images.Count;
gltfModel.Images.Add(image);
return imageIndex;
}
}
}
|
1da02298ce8824e0c365c1641d5abc34808025b8
|
C#
|
CsegodiCsongor/PentruFaculta
|
/ProiectArhitecturaCsegodiCsongor/ProiectArhitecturaCsegodiCsongor/Program.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProiectArhitecturaCsegodiCsongor
{
class Program
{
public static string nrCitit;
public static int lungimeZecim = 0;
public static string nrInZecim;
public static int[] nrInZecimInt = new int[100];
public static double[] rezultatInZecim = new double[100];
public static double peZecim = 0;
public static int indexPeZecim = 0;
public static bool punct = false;
public static int bazaOrigin, bazaRezult;
public static int lungime = 0;
public static string nrInString;
public static int[] nrInInt = new int[100];
public static int[] rezultInInt = new int[100];
public static int pe10=0;
public static int indexDePe10 = 0;
public static void Citire()
{
Console.Write("Introduceti numarul care vreti sa fie transformat:");
nrCitit = Console.ReadLine();
Console.Write("Intrudeci din ce baza este numarul[0,36]:");
bazaOrigin = Convert.ToInt32(Console.ReadLine());
Console.Write("Introducei in ce baza vreti sa fie transormat numarul[0,36]:");
bazaRezult = Convert.ToInt32(Console.ReadLine());
}
public static void despartire ()
{
int i = 0;
for(int k=0;k<nrCitit.Length;k++)
{
if (nrCitit[k] == '.') { punct = true; }
}
if (punct == true)
{
while (nrCitit[i] != '.')
{
if (i == nrCitit.Length - 1)
{
break;
}
i++;
}
nrInString = nrCitit.Remove(i);
nrInZecim = nrCitit.Remove(0, i + 1);
}
else { nrInString = nrCitit; }
}
public static void Corectare()
{
for (int i = 0; i < nrInString.Length; i++)
{
if (Char.IsLetter(nrInString[i]))
{
if (nrInString[i] == 'A' || nrInString[i] == 'a') nrInInt[i] = 10;
if (nrInString[i] == 'B' || nrInString[i] == 'b') nrInInt[i] = 11;
if (nrInString[i] == 'C' || nrInString[i] == 'c') nrInInt[i] = 12;
if (nrInString[i] == 'D' || nrInString[i] == 'd') nrInInt[i] = 13;
if (nrInString[i] == 'E' || nrInString[i] == 'e') nrInInt[i] = 14;
if (nrInString[i] == 'F' || nrInString[i] == 'f') nrInInt[i] = 15;
if (nrInString[i] == 'G' || nrInString[i] == 'g') nrInInt[i] = 16;
if (nrInString[i] == 'H' || nrInString[i] == 'h') nrInInt[i] = 17;
if (nrInString[i] == 'I' || nrInString[i] == 'i') nrInInt[i] = 18;
if (nrInString[i] == 'J' || nrInString[i] == 'j') nrInInt[i] = 19;
if (nrInString[i] == 'K' || nrInString[i] == 'k') nrInInt[i] = 20;
if (nrInString[i] == 'L' || nrInString[i] == 'l') nrInInt[i] = 21;
if (nrInString[i] == 'M' || nrInString[i] == 'm') nrInInt[i] = 22;
if (nrInString[i] == 'N' || nrInString[i] == 'n') nrInInt[i] = 23;
if (nrInString[i] == 'O' || nrInString[i] == 'o') nrInInt[i] = 24;
if (nrInString[i] == 'P' || nrInString[i] == 'p') nrInInt[i] = 25;
if (nrInString[i] == 'Q' || nrInString[i] == 'q') nrInInt[i] = 26;
if (nrInString[i] == 'R' || nrInString[i] == 'r') nrInInt[i] = 27;
if (nrInString[i] == 'S' || nrInString[i] == 's') nrInInt[i] = 28;
if (nrInString[i] == 'T' || nrInString[i] == 't') nrInInt[i] = 29;
if (nrInString[i] == 'U' || nrInString[i] == 'u') nrInInt[i] = 30;
if (nrInString[i] == 'V' || nrInString[i] == 'v') nrInInt[i] = 31;
if (nrInString[i] == 'W' || nrInString[i] == 'w') nrInInt[i] = 32;
if (nrInString[i] == 'X' || nrInString[i] == 'x') nrInInt[i] = 33;
if (nrInString[i] == 'Y' || nrInString[i] == 'y') nrInInt[i] = 34;
if (nrInString[i] == 'Z' || nrInString[i] == 'z') nrInInt[i] = 35;
lungime++;
}
else { nrInInt[i] = Convert.ToInt32(nrInString[i]) - 48; lungime++; }
}
if (punct == true) {
for (int i = 0; i < nrInZecim.Length; i++)
{
if (Char.IsLetter(nrInZecim[i]))
{
if (nrInZecim[i] == 'A' || nrInZecim[i] == 'a') nrInZecimInt[i] = 10;
if (nrInZecim[i] == 'B' || nrInZecim[i] == 'b') nrInZecimInt[i] = 11;
if (nrInZecim[i] == 'C' || nrInZecim[i] == 'c') nrInZecimInt[i] = 12;
if (nrInZecim[i] == 'D' || nrInZecim[i] == 'd') nrInZecimInt[i] = 13;
if (nrInZecim[i] == 'E' || nrInZecim[i] == 'e') nrInZecimInt[i] = 14;
if (nrInZecim[i] == 'F' || nrInZecim[i] == 'f') nrInZecimInt[i] = 15;
if (nrInZecim[i] == 'G' || nrInZecim[i] == 'g') nrInZecimInt[i] = 16;
if (nrInZecim[i] == 'H' || nrInZecim[i] == 'h') nrInZecimInt[i] = 17;
if (nrInZecim[i] == 'I' || nrInZecim[i] == 'i') nrInZecimInt[i] = 18;
if (nrInZecim[i] == 'J' || nrInZecim[i] == 'j') nrInZecimInt[i] = 19;
if (nrInZecim[i] == 'K' || nrInZecim[i] == 'k') nrInZecimInt[i] = 20;
if (nrInZecim[i] == 'L' || nrInZecim[i] == 'l') nrInZecimInt[i] = 21;
if (nrInZecim[i] == 'M' || nrInZecim[i] == 'm') nrInZecimInt[i] = 22;
if (nrInZecim[i] == 'N' || nrInZecim[i] == 'n') nrInZecimInt[i] = 23;
if (nrInZecim[i] == 'O' || nrInZecim[i] == 'o') nrInZecimInt[i] = 24;
if (nrInZecim[i] == 'P' || nrInZecim[i] == 'p') nrInZecimInt[i] = 25;
if (nrInZecim[i] == 'Q' || nrInZecim[i] == 'q') nrInZecimInt[i] = 26;
if (nrInZecim[i] == 'R' || nrInZecim[i] == 'r') nrInZecimInt[i] = 27;
if (nrInZecim[i] == 'S' || nrInZecim[i] == 's') nrInZecimInt[i] = 28;
if (nrInZecim[i] == 'T' || nrInZecim[i] == 't') nrInZecimInt[i] = 29;
if (nrInZecim[i] == 'U' || nrInZecim[i] == 'u') nrInZecimInt[i] = 30;
if (nrInZecim[i] == 'V' || nrInZecim[i] == 'v') nrInZecimInt[i] = 31;
if (nrInZecim[i] == 'W' || nrInZecim[i] == 'w') nrInZecimInt[i] = 32;
if (nrInZecim[i] == 'X' || nrInZecim[i] == 'x') nrInZecimInt[i] = 33;
if (nrInZecim[i] == 'Y' || nrInZecim[i] == 'y') nrInZecimInt[i] = 34;
if (nrInZecim[i] == 'Z' || nrInZecim[i] == 'z') nrInZecimInt[i] = 35;
lungimeZecim++;
}
else { nrInZecimInt[i] = Convert.ToInt32(nrInZecim[i]) - 48; lungimeZecim++; }
}
}
}
public static bool Verificare()
{
for (int i = 0; i < lungime; i++)
{
if (nrInInt[i] >= bazaOrigin || bazaRezult>36 || bazaOrigin>36)
{
return false;
}
}
for (int i = 0; i < lungimeZecim; i++)
{
if (nrInZecimInt[i] >= bazaOrigin)
{
return false;
}
}
return true;
}
public static void Convertare ()
{
if(bazaOrigin==bazaRezult)
{
Console.Write("Numarul transformat este:");
for (int i = 0; i < nrInString.Length; i++)
{
Console.Write(nrInString[i]);
}
if (punct == true)
{
Console.Write(".");
for (int i = 0; i < nrInZecim.Length; i++)
{
Console.Write(nrInZecim[i]);
}
}
}
else if(bazaOrigin!=10&&bazaRezult==10)
{
dePeCevaPe10(bazaOrigin);
Console.WriteLine("Nr-u transformat este: {0}",pe10+peZecim);
}
else if(bazaOrigin!=10&&bazaRezult!=10)
{
dePeCevaPe10(bazaOrigin);
dePe10PeCeva(bazaRezult);
Console.Write("Numarul transformat este:");
Scriere();
}
else if(bazaOrigin==10&&bazaRezult!=10)
{
Recreare();
dePe10PeCeva(bazaRezult);
Console.Write("Numarul transformat este:");
Scriere();
}
}
public static void dePe10PeCeva(int r)
{
while (pe10>0)
{
rezultInInt[indexDePe10] = pe10 % r;
pe10 = pe10 / r;
indexDePe10++;
}
if(punct==true)
{
while(peZecim!=1)
{
if (peZecim*r > 1)
{
rezultatInZecim[indexPeZecim] = Math.Floor(peZecim*r);
peZecim = peZecim*r -Math.Floor(peZecim*r);
indexPeZecim++;
if(indexPeZecim==99)
{
break;
}
}
else
{
rezultatInZecim[indexPeZecim] = Math.Floor(peZecim * r);
peZecim = peZecim * r;
indexPeZecim++;
if (indexPeZecim == 99)
{
break;
}
}
}
}
}
public static void dePeCevaPe10(int o)
{
int index = -1;
int putere = 1;
for(int i=lungime-1;i>=0;i--)
{
index++;
for(int j=0;j<index;j++)
{
putere = putere * o;
}
putere = putere * nrInInt[i];
pe10 = pe10 + putere;
putere = 1;
}
if(punct==true)
{
int indexZecim = 0;
for(int i=0;i<lungimeZecim;i++)
{
indexZecim--;
peZecim =peZecim +nrInZecimInt[i]* Math.Pow(o, indexZecim);
}
}
}
public static void Recreare()
{
for(int i=0;i<lungime;i++)
{
pe10 = pe10 * 10 + nrInInt[i];
}
if(punct==true)
{
for(int i=lungimeZecim-1;i>=0;i--)
{
peZecim = peZecim / 10 + nrInZecimInt[i];
}
peZecim = peZecim / 10;
}
}
public static void Scriere()
{
for(int i=indexDePe10-1;i>=0;i--)
{
if(rezultInInt[i]<=9)
{
Console.Write(rezultInInt[i]);
}
if (rezultInInt[i] == 10) { Console.Write("A"); }
if (rezultInInt[i] == 11) { Console.Write("B"); }
if (rezultInInt[i] == 12) { Console.Write("C"); }
if (rezultInInt[i] == 13) { Console.Write("D"); }
if (rezultInInt[i] == 14) { Console.Write("E"); }
if (rezultInInt[i] == 15) { Console.Write("F"); }
if (rezultInInt[i] == 16) { Console.Write("G"); }
if (rezultInInt[i] == 17) { Console.Write("H"); }
if (rezultInInt[i] == 18) { Console.Write("I"); }
if (rezultInInt[i] == 19) { Console.Write("J"); }
if (rezultInInt[i] == 20) { Console.Write("K"); }
if (rezultInInt[i] == 21) { Console.Write("L"); }
if (rezultInInt[i] == 22) { Console.Write("M"); }
if (rezultInInt[i] == 23) { Console.Write("N"); }
if (rezultInInt[i] == 24) { Console.Write("O"); }
if (rezultInInt[i] == 25) { Console.Write("P"); }
if (rezultInInt[i] == 26) { Console.Write("Q"); }
if (rezultInInt[i] == 27) { Console.Write("R"); }
if (rezultInInt[i] == 28) { Console.Write("S"); }
if (rezultInInt[i] == 29) { Console.Write("T"); }
if (rezultInInt[i] == 30) { Console.Write("U"); }
if (rezultInInt[i] == 31) { Console.Write("V"); }
if (rezultInInt[i] == 32) { Console.Write("W"); }
if (rezultInInt[i] == 33) { Console.Write("X"); }
if (rezultInInt[i] == 34) { Console.Write("Y"); }
if (rezultInInt[i] == 35) { Console.Write("Z"); }
}
if (punct == true)
{
Console.Write(".");
for (int i = 0; i < indexPeZecim; i++)
{
if (rezultatInZecim[i] <= 9)
{
Console.Write(rezultatInZecim[i]);
}
if (rezultatInZecim[i] == 10) { Console.Write("A"); }
if (rezultatInZecim[i] == 11) { Console.Write("B"); }
if (rezultatInZecim[i] == 12) { Console.Write("C"); }
if (rezultatInZecim[i] == 13) { Console.Write("D"); }
if (rezultatInZecim[i] == 14) { Console.Write("E"); }
if (rezultatInZecim[i] == 15) { Console.Write("F"); }
if (rezultatInZecim[i] == 16) { Console.Write("G"); }
if (rezultatInZecim[i] == 17) { Console.Write("H"); }
if (rezultatInZecim[i] == 18) { Console.Write("I"); }
if (rezultatInZecim[i] == 19) { Console.Write("J"); }
if (rezultatInZecim[i] == 20) { Console.Write("K"); }
if (rezultatInZecim[i] == 21) { Console.Write("L"); }
if (rezultatInZecim[i] == 22) { Console.Write("M"); }
if (rezultatInZecim[i] == 23) { Console.Write("N"); }
if (rezultatInZecim[i] == 24) { Console.Write("O"); }
if (rezultatInZecim[i] == 25) { Console.Write("P"); }
if (rezultatInZecim[i] == 26) { Console.Write("Q"); }
if (rezultatInZecim[i] == 27) { Console.Write("R"); }
if (rezultatInZecim[i] == 28) { Console.Write("S"); }
if (rezultatInZecim[i] == 29) { Console.Write("T"); }
if (rezultatInZecim[i] == 30) { Console.Write("U"); }
if (rezultatInZecim[i] == 31) { Console.Write("V"); }
if (rezultatInZecim[i] == 32) { Console.Write("W"); }
if (rezultatInZecim[i] == 33) { Console.Write("X"); }
if (rezultatInZecim[i] == 34) { Console.Write("Y"); }
if (rezultatInZecim[i] == 35) { Console.Write("Z"); }
}
}
}
static void Main(string[] args)
{
Citire();
despartire();
Corectare();
if (Verificare() == true)
{
Convertare();
}
else { Console.WriteLine("ai dat nr prea mare pt baza {0} sau ai dat o baza pe care nu pot lucra", bazaOrigin); }
Console.Read();
}
}
}
|
b71217927fae351e7b7c971cf762b6fdfc442925
|
C#
|
AmbientActivity/R2G2V1
|
/APIClient/Keebee.AAT.ApiClient/Clients/InteractiveActivityTypesClient.cs
| 2.5625
| 3
|
using Keebee.AAT.ApiClient.Models;
using System.Collections.Generic;
using Newtonsoft.Json;
using RestSharp;
namespace Keebee.AAT.ApiClient.Clients
{
public interface IInteractiveActivityTypesClient
{
IEnumerable<InteractiveActivityType> Get();
}
public class InteractiveActivityTypesClient : BaseClient, IInteractiveActivityTypesClient
{
public IEnumerable<InteractiveActivityType> Get()
{
var request = new RestRequest("interactiveactivitytypes", Method.GET);
var data = Execute(request);
var interactiveActivityTypes = JsonConvert.DeserializeObject<IEnumerable<InteractiveActivityType>>(data.Content);
return interactiveActivityTypes;
}
}
}
|
f6f4df863ebb0734376b3c912f8152531493facc
|
C#
|
onestow/LeetCode
|
/LeetCode/problems/344.cs
| 3.15625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace LeetCode.problems
{
class _344 : BaseClass
{
public override void Run()
{
throw new NotImplementedException();
}
public void ReverseString(char[] s)
{
int m = s.Length >> 1, r = s.Length - 1;
char t;
for (int i = 0; i < m; ++i, --r)
{
t = s[i];
s[i] = s[r];
s[r] = t;
}
}
}
}
|
6d66dcc24ef6fe0350f1cdd297c904002a338c2a
|
C#
|
georgeSoton/jam
|
/Assets/Scripts/Conversation.cs
| 2.890625
| 3
|
using UnityEngine;
using System.Collections;
public class Conversation {
ArrayList sentances = new ArrayList();
int sentance = 0;
public Color person1;
public Color person2;
bool isperson1 = true;
public void addSentance(string str)
{
Debug.Log ("ConvCount:" + sentances.Count);
sentances.Add (str);
//sentances[sentances.Count] = str;
}
public bool hasNextSentance()
{
return sentance < sentances.Count;
}
public SentanceObject getNextSentance()
{
string str = (string)sentances [sentance];
sentance++;
SentanceObject obj = new SentanceObject ();
obj.content = str;
if (isperson1) {
obj.color = person1;
obj.Alignment = "left";
} else {
obj.color = person2;
obj.Alignment = "right";
}
return str;
}
public void reset()
{
sentance = 0;
}
}
|
3d2cc495d65d9f1739f7b3daca5f31e4417b6576
|
C#
|
SinaC/TetriNET
|
/TetriNET.Client.Achievements/Achievements/SomeLikeItHot.cs
| 2.53125
| 3
|
using TetriNET.Client.Achievements.Achievements.Base;
namespace TetriNET.Client.Achievements.Achievements
{
internal class SomeLikeItHot : TetriminoCountBase
{
public SomeLikeItHot()
{
Id = 25;
Points = 50;
Title = "Some like it hot";
Description = "Drop a total of 100,000 Tetriminos";
OnlyOnce = true;
BronzeLevel = 1;
SilverLevel = 2;
GoldLevel = 10;
}
public override int CountToAchieve => 100000;
}
}
|
5170174c26c333ae887d9a586ce0fcedcfa643d4
|
C#
|
danielmarbach/bbv.Common
|
/source/bbv.Common.Data/DatasetHelper.cs
| 2.828125
| 3
|
//-------------------------------------------------------------------------------
// <copyright file="DatasetHelper.cs" company="bbv Software Services AG">
// Copyright (c) 2008-2011 bbv Software Services AG
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-------------------------------------------------------------------------------
namespace bbv.Common.Data
{
using System.Collections;
using System.Collections.Generic;
using System.Data;
/// <summary>
/// Contains static methods helping to work with Datasets
/// </summary>
public static class DatasetHelper
{
/// <summary>
/// Creates a new DataTable from the rows currently active in the given view.
/// </summary>
/// <param name="dataView">DataView to create the table from.</param>
/// <returns>
/// Returns a new DataTable with the same schema as the table,
/// which the view is based on.
/// </returns>
public static DataTable CreateTableFromView(DataView dataView)
{
DataTable dataTable = dataView.Table.Clone();
foreach (DataRowView rowView in dataView)
{
dataTable.ImportRow(rowView.Row);
}
return dataTable;
}
/// <summary>
/// Creates a DataView showing the same entries as the original View
/// </summary>
/// <param name="originalView">the original view from which the new View is created</param>
/// <returns>the created new View</returns>
public static DataView CloneView(DataView originalView)
{
DataView newView = new DataView(originalView.Table)
{
Sort = originalView.Sort,
RowFilter = originalView.RowFilter,
RowStateFilter = originalView.RowStateFilter
};
return newView;
}
/// <summary>
/// Returns the columns that were changed in the row.
/// </summary>
/// <param name="row">the row to be examined</param>
/// <returns>the changed columns</returns>
public static DataColumn[] GetChangedColumns(DataRow row)
{
List<DataColumn> changedColumns = new List<DataColumn>(row.Table.Columns.Count);
switch (row.RowState)
{
case DataRowState.Unchanged:
break; // nothing has changed
case DataRowState.Modified:
// find out what has changed
foreach (DataColumn column in row.Table.Columns)
{
if (!row[column, DataRowVersion.Original].Equals(row[column, DataRowVersion.Current]))
{
changedColumns.Add(column);
}
}
break;
case DataRowState.Added:
case DataRowState.Deleted:
// everything has changed
foreach (DataColumn column in row.Table.Columns)
{
changedColumns.Add(column);
}
break;
}
return changedColumns.ToArray();
}
/// <summary>
/// Checks if certain Columns in a row have a changed value.
/// </summary>
/// <param name="columns">a list of the columns to be checked</param>
/// <param name="row">the row to be analyzed</param>
/// <returns>true if any of that columns in the row has changed</returns>
public static bool HasColumnChanged(DataColumn[] columns, DataRow row)
{
ArrayList columnArray = new ArrayList(GetChangedColumns(row));
foreach (DataColumn dataColumn in columns)
{
if (columnArray.Contains(dataColumn))
{
return true;
}
}
return false;
}
/// <summary>
/// Updates columns in <paramref name="columnsToUpdate"/> of <paramref name="destinationRow"/>
/// that are different from <paramref name="sourceRow"/>.
/// </summary>
/// <param name="sourceRow">Row to compare with</param>
/// <param name="destinationRow">Ro to update</param>
/// <param name="columnsToUpdate">Columns to verify</param>
public static void UpdateColumnsIfDifferent(DataRow sourceRow, DataRow destinationRow, string[] columnsToUpdate)
{
List<string> columns = new List<string>(columnsToUpdate);
foreach (DataColumn column in destinationRow.Table.Columns)
{
if (sourceRow.Table.Columns.Contains(column.ColumnName) && columns.Contains(column.ColumnName))
{
if (destinationRow[column.ColumnName] != sourceRow[column.ColumnName])
{
destinationRow[column.ColumnName] = sourceRow[column.ColumnName];
}
}
}
}
}
}
|
95271548476ea9ef761806f9c872693d6f14f508
|
C#
|
gleblebedev/ImageSharp.Textures
|
/src/ImageSharp.Textures/Formats/Dds/Processing/BlockFormats/Dxt3.cs
| 2.765625
| 3
|
// Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0.
namespace SixLabors.ImageSharp.Textures.Formats.Dds.Processing
{
using System;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Textures.Formats.Dds;
using SixLabors.ImageSharp.Textures.Formats.Dds.Processing.BlockFormats;
public struct Dxt3 : IBlock<Dxt3>
{
public int BitsPerPixel => 32;
public byte PixelDepthBytes => 4;
public byte DivSize => 4;
public byte CompressedBytesPerBlock => 16;
public bool Compressed => true;
public Image GetImage(byte[] blockData, int width, int height)
{
byte[] decompressedData = this.Decompress(blockData, width, height);
return Image.LoadPixelData<ImageSharp.PixelFormats.Rgba32>(decompressedData, width, height);
}
public byte[] Decompress(byte[] blockData, int width, int height)
{
IBlock self = this;
var colors = new ImageSharp.PixelFormats.Rgb24[4];
return Helper.InMemoryDecode<Dxt3>(blockData, width, height, (byte[] stream, byte[] data, int streamIndex, int dataIndex, int stride) =>
{
/*
* Strategy for decompression:
* -We're going to decode both alpha and color at the same time
* to save on space and time as we don't have to allocate an array
* to store values for later use.
*/
// Remember where the alpha data is stored so we can decode simultaneously
int alphaPtr = streamIndex;
// Jump ahead to the color data
streamIndex += 8;
// Colors are stored in a pair of 16 bits
ushort color0 = blockData[streamIndex++];
color0 |= (ushort)(blockData[streamIndex++] << 8);
ushort color1 = (blockData[streamIndex++]);
color1 |= (ushort)(blockData[streamIndex++] << 8);
// Extract R5G6B5 (in that order)
colors[0].R = (byte)((color0 & 0x1f));
colors[0].G = (byte)((color0 & 0x7E0) >> 5);
colors[0].B = (byte)((color0 & 0xF800) >> 11);
colors[0].R = (byte)(colors[0].R << 3 | colors[0].R >> 2);
colors[0].G = (byte)(colors[0].G << 2 | colors[0].G >> 3);
colors[0].B = (byte)(colors[0].B << 3 | colors[0].B >> 2);
colors[1].R = (byte)((color1 & 0x1f));
colors[1].G = (byte)((color1 & 0x7E0) >> 5);
colors[1].B = (byte)((color1 & 0xF800) >> 11);
colors[1].R = (byte)(colors[1].R << 3 | colors[1].R >> 2);
colors[1].G = (byte)(colors[1].G << 2 | colors[1].G >> 3);
colors[1].B = (byte)(colors[1].B << 3 | colors[1].B >> 2);
// Used the two extracted colors to create two new colors
// that are slightly different.
colors[2].R = (byte)((2 * colors[0].R + colors[1].R) / 3);
colors[2].G = (byte)((2 * colors[0].G + colors[1].G) / 3);
colors[2].B = (byte)((2 * colors[0].B + colors[1].B) / 3);
colors[3].R = (byte)((colors[0].R + 2 * colors[1].R) / 3);
colors[3].G = (byte)((colors[0].G + 2 * colors[1].G) / 3);
colors[3].B = (byte)((colors[0].B + 2 * colors[1].B) / 3);
for (int i = 0; i < 4; i++)
{
byte rowVal = blockData[streamIndex++];
// Each row of rgb values have 4 alpha values that are
// encoded in 4 bits
ushort rowAlpha = blockData[alphaPtr++];
rowAlpha |= (ushort)(blockData[alphaPtr++] << 8);
for (int j = 0; j < 8; j += 2)
{
byte currentAlpha = (byte)((rowAlpha >> (j * 2)) & 0x0f);
currentAlpha |= (byte)(currentAlpha << 4);
var col = colors[((rowVal >> j) & 0x03)];
data[dataIndex++] = col.R;
data[dataIndex++] = col.G;
data[dataIndex++] = col.B;
data[dataIndex++] = currentAlpha;
}
dataIndex += self.PixelDepthBytes * (stride - self.DivSize);
}
return streamIndex;
});
}
}
}
|
074502a946ecedff01355a302efa0006f20f8362
|
C#
|
domejuanan/club
|
/club/Services/MemberService.cs
| 2.875
| 3
|
using System;
using AutoMapper;
using System.Collections.Generic;
using System.Threading.Tasks;
using club.Models;
using club.Repositories;
using club.Resources;
using club.Responses;
namespace club.Services
{
public interface IMemberService
{
Task<MemberListResponse> ListAsync(int pageNum = 1, int pageSize = 50);
Task<MemberResponse> GetAsync(int id);
Task<MemberResponse> SaveAsync(MemberSaveResource memberSaveResource);
Task<MemberResponse> UpdateAsync(int id, MemberSaveResource memberSaveResource);
Task<MemberResponse> DeleteAsync(int id);
}
public class MemberService : IMemberService
{
private readonly IMemberRepository _memberRepository;
private readonly IMapper _mapper;
public MemberService(IMemberRepository memberRepository, IMapper mapper)
{
_memberRepository = memberRepository;
_mapper = mapper;
}
public async Task<MemberListResponse> ListAsync(int pageNum = 1, int pageSize = 50)
{
if (pageNum < 1 || pageSize < 1)
return new MemberListResponse(400, "Wrong pagination", "Pagination",
"The pageNum and pageSize params must be greater than zero.");
int totalRecords = await _memberRepository.CountAsync();
var items = await _memberRepository.ListAsync(pageNum, pageSize);
var resources = _mapper.Map<IEnumerable<Member>, IEnumerable<MemberResource>>(items);
var resourceList = new MemberListResource(resources, pageNum, pageSize, totalRecords);
return new MemberListResponse(resourceList);
}
public async Task<MemberResponse> GetAsync(int id)
{
var existingItem = await _memberRepository.FindByIdAsync(id);
if (existingItem == null)
return new MemberResponse(404, "Item id not found", "Id", "Member id not found.");
var responseResource = _mapper.Map<Member, MemberResource>(existingItem);
return new MemberResponse(responseResource);
}
public async Task<MemberResponse> SaveAsync(MemberSaveResource memberSaveResource)
{
try
{
var item = _mapper.Map<MemberSaveResource, Member>(memberSaveResource);
await _memberRepository.AddAsync(item);
var responseResource = _mapper.Map<Member, MemberResource>(item);
return new MemberResponse(responseResource);
}
catch (Exception ex)
{
return new MemberResponse(400, "Unexpected error", "Error", ex.Message);
}
}
public async Task<MemberResponse> UpdateAsync(int id, MemberSaveResource memberSaveResource)
{
var existingItem = await _memberRepository.FindByIdAsync(id);
if (existingItem == null)
return new MemberResponse(404, "Item id not found", "Id", "Member id not found.");
existingItem.Name = memberSaveResource.Name;
existingItem.Phone = memberSaveResource.Phone;
existingItem.Surname = memberSaveResource.Surname;
existingItem.Address = memberSaveResource.Address;
try
{
_memberRepository.Update(existingItem);
var responseResource = _mapper.Map<Member, MemberResource>(existingItem);
return new MemberResponse(responseResource);
}
catch (Exception ex)
{
return new MemberResponse(400, "Unexpected error", "Error", ex.Message);
}
}
public async Task<MemberResponse> DeleteAsync(int id)
{
var existingItem = await _memberRepository.FindByIdAsync(id);
if (existingItem == null)
return new MemberResponse(404, "Item id not found", "Id", "Member id not found.");
try
{
_memberRepository.Remove(existingItem);
var responseResource = _mapper.Map<Member, MemberResource>(existingItem);
return new MemberResponse(responseResource);
}
catch (Exception ex)
{
return new MemberResponse(400, "Unexpected error", "Error", ex.Message);
}
}
}
}
|
d997934ebadb8f08ca58f295aee3d2202f4ebfc6
|
C#
|
jansierakowski/CarTryApplication
|
/CarTry.Domain/Entity/Item.cs
| 2.515625
| 3
|
using CarTry.Domain.Common;
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace CarTry.Domain.Entity
{
public class Item : BaseEntity
{
[XmlElement("Car brand")]
public string CarBrand { get; set; }
[XmlElement("Car model")]
public string CarModel { get; set; }
[XmlElement("Car location")]
public string CarLocation { get; set; }
public Item()
{
}
public Item(int id, string carModel, string carBrand, DateTime dateTime, string carLocation)
{
CarModel = carModel;
CarBrand = carBrand;
Id = id;
CreatedDateTime = dateTime;
CarLocation = carLocation;
}
}
}
|
593813dafc432695f1ccaf7ac25def4db81da5d6
|
C#
|
SnakyBeaky/dd-trace-csharp
|
/src/DataDog.Tracing/TraceSource.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.Reactive.Subjects;
using System.Text;
namespace DataDog.Tracing
{
/// <summary>
/// For creating new traces.
/// </summary>
public class TraceSource : IObservable<Trace>, ISpanSource
{
readonly Subject<Trace> _subject = new Subject<Trace>();
/// <summary>
/// Begins a new trace.
/// </summary>
/// <param name="name">
/// The name of the trace. This will be the title of the trace when viewing the trace.
/// </param>
/// <param name="serviceName">This is the name of the service. e.g. my_appication, memcached, dynamodb, etc.</param>
/// <param name="resource">The underlying resource. e.g. /home for web or GET for memcached. This shouldn't have too many unique combinations.</param>
/// <param name="type">The category of the service. Typically web, db, or cache.</param>
/// <returns>The new trace.</returns>
public ISpan Begin(string name, string serviceName, string resource, string type) => new RootSpan(_subject)
{
TraceId = Util.NewTraceId(),
SpanId = Util.NewSpanId(),
Name = name,
Resource = resource,
Type = type,
Service = serviceName,
Start = Util.GetTimestamp(),
};
/// <summary>
/// Subscribes to traces that originate from this source instance when they complete.
/// </summary>
/// <param name="observer">The observer.</param>
/// <returns>An unsubscribe disposable.</returns>
public IDisposable Subscribe(IObserver<Trace> observer)
{
return _subject.Subscribe(observer);
}
}
}
|
05dae0a38c787484873891dbca38ff863061fc07
|
C#
|
umb16/EBConsole
|
/Runtime/Scripts/Utils/CircularBuffer.cs
| 3.109375
| 3
|
namespace ExpressoBits.Console.Utils
{
public class CircularBuffer<T>
{
public readonly T[] Array;
private int m_StartIndex;
public int Count { get; private set; }
public T this[int index] => Array[(m_StartIndex + index) % Array.Length];
public CircularBuffer(int capacity)
{
Array = new T[capacity];
}
public void Add(T value)
{
if (Count < Array.Length)
{
Array[Count++] = value;
}
else
{
Array[m_StartIndex] = value;
if (++m_StartIndex >= Array.Length)
m_StartIndex = 0;
}
}
}
}
|
9def5de9e0c50091d32a0faf0dc15274111354a2
|
C#
|
zackwag/DotNetHelper
|
/Extensions/IEnumerableExtensions.cs
| 3.515625
| 4
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Helper.Extensions
{
public static class EnumerableExtensions
{
public static bool HasItems(this IEnumerable value)
{
if (value.IsNull())
return false;
try
{
var enumerator = value.GetEnumerator();
if (enumerator.HasValue() && enumerator.MoveNext())
return true;
}
catch(Exception)
{
//fail silently
}
return false;
}
public static IEnumerable<T> Each<T>(this IEnumerable<T> value, Action<T> action)
{
foreach (var val in value)
{
action(val);
}
return value;
}
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> value)
{
var r = new Random((int) DateTime.Now.Ticks);
return value.Select(x => new { Number = r.Next(), Item = x }).OrderBy(x => x.Number).Select(x => x.Item).ToList();
}
public static bool None<T>(this IEnumerable<T> value)
{
return value.Any() == false;
}
public static bool None<T>(this IEnumerable<T> value, Func<T, bool> query)
{
return value.Any(query) == false;
}
}
}
|
2ae78298fde58b43df687e712d77e8bbfdc0ca6c
|
C#
|
shendongnian/download4
|
/code2/302928-6303894-13701094-6.cs
| 2.546875
| 3
|
Private mUsings As New HashSet(Of String)
Sub InitializeAllMembers()
Try
Dim assignmentPattern As New Regex("(?<Indent>\s*)(?:(?<DeclaredType>\S+)\s+)?(?<VariableName>[\S=]+)\s*=\s*(?<new>new)?\s*(?<CreatedType>[^\s\(]+)")
Dim selection As EnvDTE.TextSelection = CType(DTE.ActiveDocument.Selection(), EnvDTE.TextSelection)
Dim editPoint As EditPoint = selection.BottomPoint.CreateEditPoint
' Get info from current line in editor
editPoint.StartOfLine()
Dim match As Match = assignmentPattern.Match(editPoint.GetText(editPoint.LineLength))
If Not match.Success Then
MessageBox.Show("No assignment on row")
Exit Sub
End If
Dim foundDeclaredType As Boolean = match.Groups("DeclaredType").Success AndAlso match.Groups("DeclaredType").Value <> "var"
Dim foundCreatedType As Boolean = match.Groups("new").Success
If Not (foundDeclaredType OrElse foundCreatedType) Then
MessageBox.Show("Can't find type on row")
Exit Sub
End If
Dim typeToExpand As String = If(foundDeclaredType, match.Groups("DeclaredType"), match.Groups("CreatedType")).Value
' Traverse upwards in current file and record all using statements
Dim currentFunction As CodeElement = FindCodeElement(selection.ActivePoint, DTE.ActiveDocument.ProjectItem.FileCodeModel.CodeElements)
If currentFunction Is Nothing Then
MessageBox.Show("Can't find current function")
Exit Sub
End If
mUsings.Clear()
FindAllUsings(currentFunction)
' Loop all projects in solution to find requested type
Dim classType As CodeElement = DTE.Solution.Projects.Cast(Of Project) _
.Select(Function(x) FindClassInProjectItems(x.ProjectItems, typeToExpand)) _
.FirstOrDefault(Function(x) x IsNot Nothing)
If classType Is Nothing Then
MessageBox.Show("Can't find type in solution: " & typeToExpand)
Exit Sub
End If
PrintMemberAssignments(editPoint, match.Groups("Indent").Value & match.Groups("VariableName").Value, GetMembers(classType))
Catch objException As System.Exception
MessageBox.Show(objException.Message)
End Try
End Sub
' Records all using statements active for a codeelement
Sub FindAllUsings(ByVal elem As Object)
If TypeOf elem Is CodeFunction Then
FindAllUsings(CType(elem, CodeFunction).Parent)
ElseIf TypeOf elem Is CodeClass Then
mUsings.Add(CType(elem, CodeClass).FullName)
FindAllUsings(CType(elem, CodeClass).Parent)
ElseIf TypeOf elem Is CodeStruct Then
mUsings.Add(CType(elem, CodeStruct).FullName)
FindAllUsings(CType(elem, CodeStruct).Parent)
ElseIf TypeOf elem Is CodeNamespace Then
mUsings.Add(CType(elem, CodeNamespace).FullName)
For Each ns As String In CType(elem, CodeNamespace).Members.OfType(Of CodeImport) _
.Select(Function(x) x.Namespace)
mUsings.Add(ns)
Next
FindAllUsings(CType(elem, CodeNamespace).Parent)
ElseIf TypeOf elem Is FileCodeModel Then
For Each ns As String In CType(elem, FileCodeModel).CodeElements.OfType(Of CodeImport) _
.Select(Function(x) x.Namespace)
mUsings.Add(ns)
Next
End If
End Sub
' Find code element (i.e. function) for current line
Public Function FindCodeElement(ByVal caretPosition As TextPoint, ByVal elems As CodeElements) As CodeElement
If elems Is Nothing Then Return Nothing
Return elems.Cast(Of CodeElement) _
.Where(Function(x) x.StartPoint.LessThan(caretPosition) AndAlso _
x.EndPoint.GreaterThan(caretPosition)) _
.Select(Function(x) If(FindCodeElement(caretPosition, GetMembers(x)), x)) _
.FirstOrDefault()
End Function
Public Sub PrintMemberAssignments(ByVal editPoint As EditPoint, ByVal prefix As String, ByVal members As CodeElements)
For Each member As CodeElement In members
Dim text As String
If TypeOf member Is CodeProperty Then
If CType(member, CodeProperty).Setter Is Nothing Then Continue For
If CType(member, CodeProperty).Setter.Access <> vsCMAccess.vsCMAccessPublic Then Continue For
If CType(member, CodeProperty).Setter.IsShared Then Continue For
text = MemberAssignment(prefix, member.Name, CType(member, CodeProperty).Type)
ElseIf TypeOf member Is CodeVariable Then
If CType(member, CodeVariable).Access <> vsCMAccess.vsCMAccessPublic Then Continue For
If CType(member, CodeVariable).IsConstant Then Continue For
If CType(member, CodeVariable).IsShared Then Continue For
text = MemberAssignment(prefix, member.Name, CType(member, CodeVariable).Type)
Else
Continue For
End If
editPoint.EndOfLine()
editPoint.Insert(ControlChars.NewLine)
editPoint.Insert(text)
Next
End Sub
Private Function MemberAssignment(ByVal prefix As String, ByVal membername As String, ByVal typeref As EnvDTE.CodeTypeRef) As String
Dim typekind As EnvDTE.vsCMTypeRef = typeref.TypeKind
Dim value As String
If typekind = vsCMTypeRef.vsCMTypeRefArray Then
value = "{0}.{1} = new {2}[1];"
If typeref.ElementType.TypeKind = vsCMTypeRef.vsCMTypeRefCodeType Then
value = value & ControlChars.NewLine & "{0}.{1}[0] = new {2}();"
End If
Return String.Format(value, prefix, membername, TrimKnownNamespace(typeref.ElementType.AsString))
ElseIf typekind = vsCMTypeRef.vsCMTypeRefBool Then
value = "false"
ElseIf typekind = vsCMTypeRef.vsCMTypeRefChar Then
value = "'x'"
ElseIf typekind = vsCMTypeRef.vsCMTypeRefDecimal Then
value = "0.00m"
ElseIf typekind = vsCMTypeRef.vsCMTypeRefDouble Then
value = "0.00"
ElseIf typekind = vsCMTypeRef.vsCMTypeRefInt Then
value = "0"
ElseIf typekind = vsCMTypeRef.vsCMTypeRefLong Then
value = "0"
ElseIf typekind = vsCMTypeRef.vsCMTypeRefShort Then
value = "0"
ElseIf typekind = vsCMTypeRef.vsCMTypeRefByte Then
value = "0"
ElseIf typekind = vsCMTypeRef.vsCMTypeRefString Then
value = """" & membername & """"
ElseIf typekind = vsCMTypeRef.vsCMTypeRefArray Then
value = "new " & TrimKnownNamespace(typeref.ElementType.AsString) & "[1]"
ElseIf typekind = vsCMTypeRef.vsCMTypeRefCodeType AndAlso _
typeref.AsString = "System.DateTime" Then
value = String.Format("new DateTime({0:yyyy},{0:%M},{0:%d})", DateTime.Today)
Else
value = "new " & TrimKnownNamespace(typeref.AsString) & "()"
End If
Return String.Format("{0}.{1} = {2};", prefix, membername, value)
End Function
Private Function TrimKnownNamespace(ByVal fullName As String) As String
Return fullName.Substring(mUsings.Where(Function(x) fullName.StartsWith(x) AndAlso _
fullName.Length > x.Length AndAlso _
fullName(x.Length) = "."c) _
.Select(Function(x) x.Length + 1) _
.DefaultIfEmpty(0) _
.Max())
End Function
Private Function FindClassInProjectItems(ByVal nprojectItems As ProjectItems, ByVal classname As String) As CodeElement
If nprojectItems Is Nothing Then Return Nothing
For Each nprojectitem As ProjectItem In nprojectItems
Dim found As CodeElement
If nprojectitem.Kind = EnvDTE.Constants.vsProjectItemKindPhysicalFile Then
If nprojectitem.FileCodeModel Is Nothing Then Continue For
found = FindClassInCodeElements(nprojectitem.FileCodeModel.CodeElements, classname)
If found IsNot Nothing Then Return found
End If
If nprojectitem.SubProject IsNot Nothing Then
found = FindClassInProjectItems(nprojectitem.SubProject.ProjectItems, classname)
If found IsNot Nothing Then Return found
End If
found = FindClassInProjectItems(nprojectitem.ProjectItems, classname)
If found IsNot Nothing Then Return found
Next
End Function
Private Function FindClassInCodeElements(ByVal elems As CodeElements, ByVal classname As String) As CodeElement
If elems Is Nothing Then Return Nothing
For Each elem As CodeElement In elems
If IsClassType(elem) Then
If classname = elem.Name Then Return elem
ElseIf Not TypeOf elem Is CodeNamespace Then
Continue For
End If
If mUsings.Contains(elem.FullName) Then
Dim found As CodeElement = FindClassInCodeElements(GetMembers(elem), classname)
If found IsNot Nothing Then Return found
End If
Next
Return Nothing
End Function
Private Function GetMembers(ByVal elem As CodeElement) As CodeElements
If TypeOf elem Is CodeClass Then
Return CType(elem, CodeClass).Members
ElseIf TypeOf elem Is CodeNamespace Then
Return CType(elem, CodeNamespace).Members
ElseIf TypeOf elem Is CodeStruct Then
Return CType(elem, CodeStruct).Members
ElseIf TypeOf elem Is CodeInterface Then
Return CType(elem, CodeInterface).Members
End If
Return Nothing
End Function
Private Function IsClassType(ByVal elem As CodeElement) As Boolean
Return TypeOf elem Is CodeClass OrElse TypeOf elem Is CodeStruct OrElse TypeOf elem Is CodeInterface
End Function
|
e345ca3ebf969a1dea9b35dd955d1ad46527c753
|
C#
|
gbortnikov/TaskManagerServer
|
/Ws/WebSocket.cs
| 2.953125
| 3
|
using SuperSocket.SocketBase;
using System;
using SuperWebSocket;
namespace Ws
{
class WebSocket
{
private static WebSocketServer wsServer = new WebSocketServer();
/// <summary>
/// Инициализация websocket
/// </summary>
public void WSInit(int port)
{
wsServer.Setup(port);
wsServer.NewSessionConnected += WsServer_NewSessionConnected;
wsServer.NewMessageReceived += WsServer_NewMessageReceived;
wsServer.NewDataReceived += WsServer_NewDataReceived;
wsServer.SessionClosed += WsServer_SessionClosed;
wsServer.Start();
Console.WriteLine("Server is run " + port);
}
private void WsServer_SessionClosed(WebSocketSession session, CloseReason value)
{
Console.WriteLine("SessionClosed");
}
private void WsServer_NewDataReceived(WebSocketSession session, byte[] value)
{
Console.WriteLine("NewDataReceived" + wsServer.SessionCount);
}
private void WsServer_NewMessageReceived(WebSocketSession session, string value)
{
Console.WriteLine("NewMessageReceived: " + value + "\tfrom:" + session.SocketSession.RemoteEndPoint.Address);
ProcessingResponsesWS processingResponses = new ProcessingResponsesWS(value); //обработка сообщения
session.Send(processingResponses.AnswerBD); // отправка ответа клиенту
}
private void WsServer_NewSessionConnected(WebSocketSession session)
{
Console.WriteLine("NewSessionConnected");
}
}
}
|
96358e763825b041fe2572e67a48e230e06976a8
|
C#
|
walkerscott6482/ScanResultsPractical
|
/ScanResults/Services/WhoisService.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Threading.Tasks;
using ScanResults.Models;
using Serilog;
using Whois.NET;
namespace ScanResults.Services
{
public class WhoisService
{
public WhoisService()
{
Log.Information("WhoisService started.");
}
public WhoisData GetWhoisInformation(string ipDomain)
{
if (String.IsNullOrEmpty(ipDomain))
{
Log.Error("WhoisService.GetWhoisInformation - Null or empty IP");
throw new Exception("Null or empty IP");
}
Log.Debug("WhoisService.GetWhoisInformation: " + ipDomain);
WhoisData wd = new WhoisData();
try
{
// Whois
var result = WhoisClient.Query(ipDomain);
wd.address = ipDomain;
wd.addressrange = result.AddressRange.ToString();
wd.organizationname = result.OrganizationName;
wd.respondedservers = result.RespondedServers.ToString();
}
catch (Exception ex)
{
Log.Error("WhoisService.GetWhoisInformation - An error occurred: " + ex);
throw;
}
return wd;
}
}
}
|
4af9f4c2118abac8533e4c87a6659d3f861870ac
|
C#
|
marianafcruz17/Introducao-ao-C-
|
/lacos_condicionais.cs
| 3.28125
| 3
|
using System;
using System.Collections.Generic;
using System.Ling;
using System.Text;
using System.Threading.Tasks;
namespace LacosCondicionais{
class Program{
static void Main(string[] args){
//laço if/else
int hora = 16;
if(hora<=15)
Console.WriteLine("São menos que 15hrs!");
else if(hora<=17)
Console.WriteLine("A hora é menor ou igual a 17!");
else{
Console.WriteLine("Já passou das 17hrs!");
if(hora==18)
Console.WriteLine("São 18hrs!");
else
Console.WriteLine("Já passou das 18hrs!");
}
//laço switch
switch(hora){
case 15:
Console.WriteLine("São 15hrs!");
break;
case 13:
Console.WriteLine("São 13hrs!");
break;
case 18:
Console.WriteLine("São 18hrs!");
break;
default:
Console.WriteLine("Hora indefinida!");
break;
}
Ano mes = Ano.Maio;
/*if(mes==Ano.Janeiro)
Console.WriteLine("Estamos em Janeiro");
else if(mes==Ano.Fevereiro)
Console.WriteLine("Estamos em Fevereiro");*/
switch(mes){
case Ano.Janeiro:
Console.WriteLine("Estamos em Janeiro");
break;
case Ano.Fevereiro:
Console.WriteLine("Estamos em Fevereiro");
break;
case Ano.Marco:
Console.WriteLine("Estamos em Marco");
break;
case Ano.Abril:
Console.WriteLine("Estamos em Abril");
break;
case Ano.Maio:
Console.WriteLine("Estamos em Maio");
break;
case Ano.Junho:
Console.WriteLine("Estamos em Junho");
break;
default:
Console.WriteLine("Estamos no Segundo Semestre");
break;
}
}
}
public enum Ano{
Janeiro, Fevereiro, Marco, Abril, Maio, Junho, Julho, Agosto, Setembro, Outubro, Novembro, Dezembro;
}
}
|
e87a697790a38fa3cd88a3334c43f5a4d4fdd137
|
C#
|
nefdulin/ColorFill
|
/Assets/Scripts/State/BlockState.cs
| 3.015625
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace ColorFill.States
{
[System.Serializable]
public class BlockState : IState
{
[System.Serializable]
public struct CollisionAction
{
public BlockStateType type;
public Action<Block> action;
public CollisionAction(BlockStateType type, Action<Block> action)
{
this.type = type;
this.action = action;
}
}
[SerializeField]
public Block Block;
public List<CollisionAction> CollisionRegistry = new List<CollisionAction>();
public BlockState(Block b) => Block = b;
public virtual void RegisterForCollision(BlockStateType type, Action<Block> action)
=> CollisionRegistry.Add(new CollisionAction(type, action));
public virtual void OnCollision(Block other)
{
for (int i = 0; i < CollisionRegistry.Count; i++)
{
if (CollisionRegistry[i].type == other.StateType)
{
CollisionRegistry[i].action(other);
}
}
}
public virtual IEnumerator Start()
{
yield break;
}
public virtual IEnumerator Tick()
{
yield break;
}
public virtual IEnumerator Exit()
{
yield break;
}
}
}
|
6645c0b369fc459a87ebae2a80dac764c7392ba9
|
C#
|
BlueDress/School
|
/C# OOP Advanced/Enumerations and Attributes Exercises/Card Game/Card.cs
| 3.9375
| 4
|
using System;
namespace Card_Game
{
public class Card : IComparable<Card>
{
private CardSuit cardSuit;
private CardRank cardRank;
public Card(string cardSuit, string cardRank)
{
this.cardSuit = (CardSuit)Enum.Parse(typeof(CardSuit), cardSuit);
this.cardRank = (CardRank)Enum.Parse(typeof(CardRank), cardRank);
}
public int CalculatePower()
{
return (int)this.cardSuit + (int)this.cardRank;
}
public string CardName
{
get { return $"{this.cardRank} of {this.cardSuit}"; }
}
public override string ToString()
{
return this.CardName;
}
public int CompareTo(Card other)
{
return this.CalculatePower().CompareTo(other.CalculatePower());
}
}
}
|
10809258dda3cefd7038a2e48e3ef032237d0cd2
|
C#
|
VhenBongbonga/CasebookAutomatedTesting
|
/CasebookAutomation/SubscriptionExpirationDate.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using CasebookAutomation;
namespace CasebookAutomation
{
public class SubscriptionExpirationDate
{
public static void Save(string expirationdate)
{
string path = System.IO.Path.GetDirectoryName(System.IO.Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory())) + "\\Subscription Expiration\\";
string filename = "SubscriptionExpiration.txt";
string document = string.Format("{0}{1}", path, filename);
if (System.IO.Directory.Exists(path))
{
goto checkfile;
}
else
{
System.IO.Directory.CreateDirectory(path);
goto checkfile;
}
checkfile:
#region check and create error logs
if (System.IO.File.Exists(document))
{
using (StreamWriter sw = System.IO.File.CreateText(document))
{
sw.Write(expirationdate);
}
}
else
{
using (StreamWriter sw = System.IO.File.CreateText(document))
{
sw.Write(expirationdate);
}
}
#endregion
}
public static string Get()
{
string path = System.IO.Path.GetDirectoryName(System.IO.Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory())) + "\\Subscription Expiration\\";
string filename = "SubscriptionExpiration.txt";
string document = string.Format("{0}{1}", path, filename);
System.IO.StreamReader file = new System.IO.StreamReader(document);
return file.ReadLine();
}
}
}
|
dc9eab101f757142e7de8901080f23fb2ad59ae1
|
C#
|
PlamenYordanov/C-_Advanced
|
/FilesAndStreams/SlicingFile/Program.cs
| 3.296875
| 3
|
namespace SlicingFile
{
using System;
using System.IO;
public class Program
{
public static void Main()
{
int numSplices = int.Parse(Console.ReadLine());
using (FileStream readStream = new FileStream(@"..\OddLines\Files\sliceMe.mp4", FileMode.OpenOrCreate))
{
var size = readStream.Length;
var fileChunk = readStream.Length / numSplices;
var buffer = new Byte[readStream.Length];
int offset = 0;
for (int i = 0; i < numSplices - 1; i++)
{
string fileName = $"Part-{i}.mp4";
using (FileStream writer = File.OpenWrite($@"..\OddLines\Files\{fileName}"))
{
int bytesRead;
while ((bytesRead =
readStream.Read(buffer, 0, fileChunk)) > 0)
{
writer.Write(buffer, 0, bytesRead);
}
}
fileChunk *= 2;
}
}
}
}
}
|
122e032e64d5be90e63ca14c6ec0cae7c6e611fe
|
C#
|
fabricioborges/ProjetoCinema
|
/Server/Projeto_Cinema/Projeto_Cinema.Domain/Features/Base/Exceptions/DomainException.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Projeto_Cinema.Domain.Features.Base.Exceptions
{
public class DomainException : Exception
{
private string v;
public DomainException(ErrorCode errorCode, string message) : base(message)
{
ErrorCode = errorCode;
}
protected DomainException(string v)
{
this.v = v;
}
public ErrorCode ErrorCode { get; }
}
}
|
5b099187ffe95a2607f5fc69b1617bb972ad612a
|
C#
|
mxashlynn/Parquet
|
/ParquetClassLibrary/Items/InventoryConfiguration.cs
| 2.828125
| 3
|
using System.IO;
using System.Text;
namespace Parquet.Items
{
/// <summary>
/// Provides rules for working with an <see cref="InventoryCollection"/>.
/// </summary>
public static class InventoryConfiguration
{
#region Class Defaults
/// <summary>The capacity to use for an <see cref="InventoryCollection"/> when the configuration cannot be read.</summary>
private const int FallbackCapacity = 16;
#endregion
#region Characteristics
/// <summary>The capacity to use for an <see cref="InventoryCollection"/> when none is specified.</summary>
public static int DefaultCapacity { get; set; } = FallbackCapacity;
#endregion
#region Self Serialization
/// <summary>
/// Reads <see cref="InventoryConfiguration"/> data from the appropriate file.
/// </summary>
/// <returns>The instances read.</returns>
public static void GetRecord()
{
using var reader = new StreamReader(FilePath);
// Skip the header.
reader.ReadLine();
// Read in the value.
var value = reader.ReadLine();
// Parse.
DefaultCapacity = int.TryParse(value, out var parsedCapacity)
? parsedCapacity
: Logger.DefaultWithParseLog(value, nameof(DefaultCapacity), FallbackCapacity);
}
/// <summary>
/// Writes <see cref="InventoryConfiguration"/> data to the appropriate file.
/// </summary>
public static void PutRecord()
{
using var writer = new StreamWriter(FilePath, false, new UTF8Encoding(true, true));
writer.Write($"{nameof(DefaultCapacity)}\n");
writer.Write($"{DefaultCapacity}\n");
}
/// <summary>
/// Returns the filename and path associated with <see cref="InventoryConfiguration"/>'s definition file.
/// </summary>
/// <returns>A full path to the associated file.</returns>
public static string FilePath
=> $"{All.ProjectDirectory}/{nameof(InventoryConfiguration)}.csv";
#endregion
}
}
|
5023b1e039d5f0df8f235b6541377db7c7aeb714
|
C#
|
CameronBell1337/ATProject03
|
/AT_Open_World/Assets/Scripts/OW/TreeManager.cs
| 2.765625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TreeManager
{
public static List<Vector2> Create(float r, Vector2 bound, int s = 15)
{
float gridS = r / Mathf.Sqrt(2);
int[,] grid = new int[Mathf.CeilToInt(bound.x / gridS), Mathf.CeilToInt(bound.y / gridS)];
List<Vector2> points = new List<Vector2>();
List<Vector2> startP = new List<Vector2>();
startP.Add(bound / 2);
while (startP.Count > 0)
{
int spawnIndex = Random.Range(0, startP.Count);
Vector2 origin = startP[spawnIndex];
bool checkCoordTrue = false;
for (int i = 0; i <s; i++)
{
float angle = Random.value * Mathf.PI * 2;
Vector2 dir = new Vector2(Mathf.Sin(angle), Mathf.Cos(angle));
Vector2 checkCoord = origin + dir * Random.Range(r, 2 * r);
if (ValidCheck(checkCoord, bound, gridS, r, points, grid))
{
points.Add(checkCoord);
startP.Add(checkCoord);
grid[(int)(checkCoord.x / gridS), (int)(checkCoord.y / gridS)] = points.Count;
checkCoordTrue = true;
break;
}
}
if (!checkCoordTrue)
{
startP.RemoveAt(spawnIndex);
}
}
return points;
}
//Checks if the new point overlaps with another point. if so discard
static bool ValidCheck(Vector2 point, Vector2 bound, float cell, float r, List<Vector2> pL, int[,] grid)
{
if (point.x >= 0 && point.x < bound.x && point.y >= 0 && point.y < bound.y)
{
int cX = (int)(point.x / cell);
int cY = (int)(point.y / cell);
int checkSX = Mathf.Max(0, cX - 2);
int checkEX = Mathf.Min(cX + 2, grid.GetLength(0) - 1);
int checkSY = Mathf.Max(0, cY - 2);
int checkEY = Mathf.Min(cY + 2, grid.GetLength(1) - 1);
for (int x = checkSX; x <= checkEX; x++)
{
for (int y = checkSY; y <= checkEY; y++)
{
int pI = grid[x, y] - 1;
if (pI != -1)
{
float sqrDst = (point - pL[pI]).sqrMagnitude;
if (sqrDst < r * r)
{
return false;
}
}
}
}
return true;
}
return false;
}
}
|
6ba99a1b156fe312f027dfc027a434d4aaf66f65
|
C#
|
GinaKonidaris/3Task2019
|
/Task1_18013130GADE/Map.cs
| 3.015625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
namespace Task1_18013130GADE
{
class Map
{ //makes map
int numUnits = 0;
TextBox txtInfo;
Random r = new Random();
private Unit[] units;
public Unit[] Units
{
get { return units; }
set { units = value; }
}
public Map(int n, TextBox txt)
{
numUnits = n;
txtInfo = txt;
}
public Map(int maxX, int maxY, int numUnits)
{ //spawns units on map
units = new Unit[numUnits];
for (int i = 0; i < numUnits; i++)
{
if (i % 2 == 0)
{
MeleeUnit u = new MeleeUnit(r.Next(0, maxY), r.Next(0, maxX), r.Next(5, 10) * 10, r.Next(5, 20), 1, 1, "M", i % 2);
Units[i] = u;
}
}
}
}
}
|
b82570a63764a905ff52021d671e69e8c0f00699
|
C#
|
IceVenOm98/UnifiedSystemofAbiturient
|
/UnifiedSystemofAbiturient/UserDecorator.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UnifiedSystemofAbiturient
{
public abstract class UserDecorator : User
{
protected User User;
public void setUser(User user)
{
User = user;
Name = User.Name;
Points = User.Points;
}
}
}
|
0c2b317da54227d354b2594c90af66e2de34db65
|
C#
|
Vailucory/LifeStat
|
/LifeStat.Application/UseCases/DailyPlanTemplates/Commands/UpdateDailyPlanTemplate/UpdateDailyPlanTemplateCommandHandler.cs
| 2.515625
| 3
|
using Domain.Models;
using LifeStat.Application.Interfaces;
using LifeStat.Domain.Interfaces.Repositories;
using LifeStat.Domain.Interfaces.UnitOfWork;
using LifeStat.Domain.Shared;
namespace LifeStat.Application.UseCases.DailyPlanTemplates;
public class UpdateDailyPlanTemplateCommandHandler : ICommandHandler<UpdateDailyPlanTemplateCommand>
{
private readonly IDailyPlanTemplateRepository _dailyPlanTemplateRepository;
private readonly IUnitOfWork _unitOfWork;
public UpdateDailyPlanTemplateCommandHandler(IDailyPlanTemplateRepository dailyPlanTemplateRepository, IUnitOfWork unitOfWork)
{
_dailyPlanTemplateRepository = dailyPlanTemplateRepository;
_unitOfWork = unitOfWork;
}
public async Task<Result> Handle(UpdateDailyPlanTemplateCommand request, CancellationToken cancellationToken)
{
DailyPlanTemplate template = new DailyPlanTemplate()
{
Id = request.DailyPlanTemplateId,
Name = request.DailyPlanTemplateName,
Activities = request.Activities
.Select(dpad => new DailyPlanActivityDuration()
{
Duration = dpad.Duration,
ActivityTemplate = new ActivityTemplate()
{ Id = dpad.ActivityTemplateId}
}).ToList(),
};
return _dailyPlanTemplateRepository.Update(template, request.UserId)
.MergeFrom(await _unitOfWork.SaveChangesAsync(cancellationToken));
}
}
|
c4cdcc0c4d60d55fc6fae8baa62a894fa92671e9
|
C#
|
de3key/amd
|
/Project/ConsoleApplication3/Program.cs
| 3.453125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Привет мир,а я сережа");
Console.ReadKey();
Console.WriteLine("Как тебя зовут???");
string myName = Console.ReadLine(); // ЧУВАК ЗАЧЕМ ТЫ НА ЭТО ПОДПИСАЛСЯ ТЫ ШО ЗАБЫЛ ТУТ?
int age, weight, height;
Console.WriteLine("Сколько тебе лет, ноунейм?");
age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Сколько ты весишь быдлан?");
weight = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Какой у тебя рост дюймовочка?");
height = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Здарова," + myName);
Console.WriteLine("Ваш возраст," + age+" лет");
Console.WriteLine("Ваш ростик," + height/100.0+" метров");
Console.WriteLine("Здарова," + weight*1000+" грамм");
Console.ReadKey(); // ЭТО КОРОЧЕ ЗАКРЫЛОСЬ ЧТОБ
}
}
}
|
fd930a503072968a1a63c2adba9792778a5ce433
|
C#
|
bgertonson/CogsDB
|
/src/CogsDB.Engine/Indexing/IndexMap.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
namespace CogsDB.Engine.Indexing
{
public class IndexMap
{
private IList<IndexMapEntry> _entries = new List<IndexMapEntry>();
public void AddEntry(IndexMapEntry entry)
{
_entries.Add(entry);
}
public static IndexMap InferMap<T>()
{
var map = new IndexMap();
Type type = typeof (T);
var properties = type.GetProperties();
foreach (var propertyInfo in properties)
{
if (!propertyInfo.PropertyType.Equals(typeof(String))) continue;
IndexMapEntry entry;
var name = propertyInfo.Name;
if(name.Equals("id", StringComparison.OrdinalIgnoreCase))
{
entry = new IndexMapEntry(name, true, false);
map.AddEntry(entry);
continue;
}
entry = new IndexMapEntry(name, true, false);
map.AddEntry(entry);
}
return map;
}
}
public class IndexMapEntry
{
public IndexMapEntry(string field, bool store, bool analyze)
{
Field = field;
Store = store;
Analyze = analyze;
}
public string Field { get; private set; }
public bool Store { get; private set; }
public bool Analyze { get; private set; }
}
}
|
bfd947f5e80a7f39e05bdcfee6c2451db5343c89
|
C#
|
JakeM321/todo-list-backend
|
/todo-list-backend/Repositories/NotificationRepository.cs
| 2.6875
| 3
|
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using todo_list_backend.Models.Notification;
using todo_list_backend.Services;
namespace todo_list_backend.Repositories
{
public class NotificationRepository: INotificationRepository
{
private AppDbContext _db;
private ILogger _logger;
public NotificationRepository(AppDbContext db, ILoggerFactory factory)
{
_db = db;
_logger = factory.CreateLogger("User Respository");
}
public UserNotificationRecord Save(UserNotificationRecord record)
{
var newRecord = _db.Add(record);
_db.SaveChanges();
return newRecord.Entity;
}
public IEnumerable<UserNotificationRecord> GetUserNotifications(Func<UserNotificationRecord, bool> predicate)
{
return _db.Notifications.Where(predicate);
}
public void UpdateNotifications(Func<UserNotificationRecord, bool> predicate, Func<UserNotificationRecord, UserNotificationRecord> update)
{
var existingRecords = _db.Notifications.Where(predicate);
var updatedRecords = existingRecords.Select(record => update(record));
_db.Notifications.UpdateRange(updatedRecords);
_db.SaveChanges();
}
}
}
|
9c01a66366da513c973445cfa8807e90277a05e4
|
C#
|
pwyszynski/TextToXmlParser
|
/Parser.API/Services/XMLParserService/Models/Sentence.cs
| 3.609375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
namespace Parser.Models
{
/// <summary>
/// Class representing a sentence.
/// </summary>
public class Sentence
{
/// <summary>
/// Default parameterless constructor for serialization.
/// </summary>
public Sentence()
{
}
/// <summary>
/// Constructor that takes an array of words (strings) as parameter, sorts them and adds them to the internal Words list <see cref="Words"/>.
/// </summary>
/// <param name="words">Array of unsorted words (strings).</param>
public Sentence(string[] words)
{
var sortedWords = words.ToList();
sortedWords.Sort();
foreach(var word in sortedWords)
{
this.Words.Add(word);
}
}
/// <summary>
/// List of words contained in the sentence.
/// </summary>
[XmlElement("word")]
public List<string> Words {get; set;} = new List<string>();
}
}
|
d3387b3345ec482a55e4b4aec0bf07cdf9f5f7bd
|
C#
|
Jonathan-Treloggen/The_Tech_Academy_Basic_C-Sharp_Projects
|
/Basic_C#_Programs/Notes and practice on C#/String/String/Program.cs
| 3.875
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace String
{
class Program
{
static void Main(string[] args)
{
string name = "Jon";
string quote = "The man said, \"Hello\", Jon. \nHello on a new line. \n\tHello on a tab";
string fileName = "C:\\User\\Jon";
// OR DO IT THIS WAY WITH AN @ SYMBOL
string fileName2 = @"C:\User\Jon";
// DOES A NAME CONTAIN A SPECIFIC LETTER
bool trueOrFalse = name.Contains("n");
// WHAT IT ENDS WITH
trueOrFalse = name.EndsWith("o");
// HOW LONG A NAME IS
int length = name.Length;
// LOWER CASE STRING
name = name.ToLower();
// UPPER CASE STRING
name = name.ToUpper();
// IF THIS HAPPENS YOU ARE ADDING CODE NOT REPLACING
string name2 = "Jon";
name2 = "Megan";
// PERFERED WAY
StringBuilder sb = new StringBuilder();
sb.Append("My name is Jon");
Console.WriteLine(sb);
Console.ReadLine();
}
}
}
|
7c032b73893939761e220838cfd2fe6784453fc6
|
C#
|
lavn0/CodeAnalysis
|
/FxCopCustom/Rules/LinqResultComparedByNull.cs
| 2.734375
| 3
|
using Microsoft.FxCop.Sdk;
using System.Collections.Generic;
namespace FxCopCustom.Rules
{
/// <summary>LINQのクエリ結果がnullと比較されている場合を検出する</summary>
public class LinqResultComparedByNull : BaseRule
{
private readonly Dictionary<Local, Node> assignmented = new Dictionary<Local, Node>();
public LinqResultComparedByNull()
: base(typeof(LinqResultComparedByNull).Name)
{
}
public override ProblemCollection Check(Member member)
{
if (member != null)
{
switch (member.NodeType)
{
case NodeType.Method:
this.Visit(member);
break;
}
}
return base.Check(member);
}
public override void VisitAssignmentStatement(AssignmentStatement assignment)
{
base.VisitAssignmentStatement(assignment);
if (assignment == null)
{
return;
}
var targetLocal = assignment.Target as Local;
if (targetLocal != null)
{
this.assignmented[targetLocal] = assignment.Source;
}
}
public override void VisitBinaryExpression(BinaryExpression binaryExpression)
{
base.VisitBinaryExpression(binaryExpression);
if (binaryExpression == null)
{
return;
}
switch (binaryExpression.NodeType)
{
case NodeType.Cgt_Un: // != null比較はコレ
case NodeType.Cgt: // 一応保険でチェック
case NodeType.Clt_Un: // 一応保険でチェック
case NodeType.Clt: // 一応保険でチェック
case NodeType.Ceq: // 一応保険でチェック
Local targetLocal = null;
if (RuleUtilities.IsLiteralForNull(binaryExpression.Operand1))
{
targetLocal = binaryExpression.Operand2 as Local;
}
else if (RuleUtilities.IsLiteralForNull(binaryExpression.Operand2))
{
targetLocal = binaryExpression.Operand1 as Local;
}
if (targetLocal != null && this.assignmented.ContainsKey(targetLocal))
{
var methodCall = this.assignmented[targetLocal] as MethodCall;
if (methodCall != null &&
((MemberBinding)methodCall.Callee).BoundMember.DeclaringType == SystemMembers.Enumerable)
{
this.Violate(binaryExpression, targetLocal.Name.Name);
}
}
break;
}
}
}
}
|
4d926e0c3c34e81f6559e754ebbc530390e96e0e
|
C#
|
jovanemarques/JustEatItProject
|
/src/JustEatIt/Data/Entities/MockDishRepository.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using JustEatIt.Data.Entities;
namespace JustEatIt.Models
{
public class MockDishRepository : IDishRepository
{
//private User partner => new User { Id = 1, FirstName = "John", LastName = "Lennon" };
private static IQueryable<Dish> dishes = new List<Dish>().AsQueryable();
public MockDishRepository()
{
LoadData();
}
private void LoadData()
{
//dishes.Append<Dish>(
// new Dish
// {
// Id = 1,
// Description = "Pepperoni Pizza",
// Price = 5.99f,
// BestBefore = new DateTime(2019, 12, 25),
// Image = "https://img.buzzfeed.com/thumbnailer-prod-us-east-1/" +
// "dc23cd051d2249a5903d25faf8eeee4c/BFV36537_CC2017_2IngredintDough4Ways-FB.jpg",
// Type = "Pizza",
// Restaurant = "Italian",
// //Partner = partner,
// Quantity = 50
// }
//);
//dishes.Append<Dish>(
// new Dish
// {
// Id = 2,
// Description = "Cheese Pizza",
// Price = 5.99f,
// BestBefore = new DateTime(2019, 12, 26),
// Image = "https://www.countrysidecravings.com/wp-content/uploads/2017/03/Three-Cheese-Pizza-2-500x375.jpg",
// Type = "Pizza",
// Restaurant = "Italian",
// //Partner = partner,
// Quantity = 25
// }
//);
}
public IQueryable<Dish> GetAll { get { return dishes; } }
/* public IQueryable<Dish> Dishes => new List<Dish> {
new Dish {Id = 1, Description = "Pepperoni Pizza", Price = 5.99f, BestBefore = new DateTime(2019, 12, 25),
Image = "https://img.buzzfeed.com/thumbnailer-prod-us-east-1/" +
"dc23cd051d2249a5903d25faf8eeee4c/BFV36537_CC2017_2IngredintDough4Ways-FB.jpg",
Type = "Pizza", Restaurant = "Italian", Partner = partner, Quantity = 50
},
new Dish {Id = 2, Description = "Cheese Pizza", Price = 5.99f, BestBefore = new DateTime(2019, 12, 26),
Image = "https://www.countrysidecravings.com/wp-content/uploads/2017/03/Three-Cheese-Pizza-2-500x375.jpg",
Type = "Pizza", Restaurant = "Italian", Partner = partner, Quantity = 25
}
}.AsQueryable<Dish>();*/
public int Save(Dish dish)
{
throw new NotImplementedException();
}
public Dish Get(int dishId)
{
throw new NotImplementedException();
}
public Dish Delete(int dishId)
{
throw new NotImplementedException();
}
}
}
|
74837ed6babd9a0e0080116cd2a20d0ee0e1912e
|
C#
|
camillaryskjaer/H2Opgaver
|
/KaffeMaskinen Del1/DataClasses/Grinder.cs
| 2.875
| 3
|
using KaffeMaskinen.Interface;
using System;
using System.Collections.Generic;
using System.Text;
namespace KaffeMaskinen.DataClasses
{
public class Grinder : Machine, IPower
{
private IngredientContainer ingredientContainer;
public IngredientContainer IngredientContainer
{
get { return ingredientContainer; }
set { ingredientContainer = value; }
}
public Grinder(string model, float height, float width, float depth, float weight, IngredientContainer ingredientContainer) : base(model, height, width, depth, weight)
{
IngredientContainer = ingredientContainer;
}
public Powder Grind(int ingredient)
{
return new Powder((IngredientList)ingredient + " " + "Powder" );
}
public void TurnOff()
{
TurnedOn = false;
}
public void TurnOn()
{
TurnedOn = true;
}
}
}
|
9bb076a8c10e1c9bcd92310e70f1621f79a53385
|
C#
|
DigitalOxCanada/MonoTarget
|
/Day4/Background.cs
| 2.828125
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace MonoTarget
{
public class Background
{
public Background()
{
MaterialAction = new Dictionary<Color, Action>
{
[Color.White] = () => ShotBreakGlass(),
[Color.Purple] = () => ShotMissed(),
[new Color(255,216,0,255)] = () => ShotRicochet(),
[new Color(72,0,255,255)] = () => ShotBarberPole()
};
}
private void ShotBarberPole()
{
Debug.WriteLine("Action: ShotBarberPole");
_game.barberPole.Hit = true;
}
private void ShotRicochet()
{
Debug.WriteLine("Action: ShotRicochet");
_game.SoundLibrary["ricochet1"].Play(1.0f, 0.0f, 0.0f);
}
private void ShotMissed()
{
Debug.WriteLine("Action: ShotMissed");
}
private void ShotBreakGlass()
{
Debug.WriteLine("Action: ShotBreakGlass");
//play breaking glass sound
_game.SoundLibrary["breakglass1"].Play(1.0f, 0.0f, 0.0f);
}
private Game1 _game;
public Texture2D BGImage { get; set; }
public Texture2D BGMaterials { get; set; }
public Color[] BGMaterialColorData { get; set; }
public Dictionary<Color, Action> MaterialAction { get; set; }
public void Initialize(Texture2D tex, Texture2D mat, Game1 game)
{
_game = game;
BGImage = tex;
BGMaterials = mat;
//make colour map data of bg materials image
//? we don't really need the texture anymore
BGMaterialColorData = new Color[BGMaterials.Width * BGMaterials.Height];
BGMaterials.GetData<Color>(BGMaterialColorData);
}
public void Update(GameTime gameTime)
{
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(BGImage, new Vector2(0, 0), Color.White);
}
internal Color GetColorAtPos(int x, int y)
{
//formula for 2d coords on a 1d array = y * width + x;
return BGMaterialColorData[y * BGMaterials.Width + x];
}
internal void CheckHitMaterial(Color pixel)
{
if(MaterialAction.ContainsKey(pixel))
{
//we have something defined for that color so call the action
MaterialAction[pixel]();
}
}
}
}
|
a6760ec412d98a48761daf4407ddfe761a4a8699
|
C#
|
HJBell/TRL
|
/TRL_Source/Assets/Scripts/World/DeckOverride.cs
| 2.625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DeckOverride : MonoBehaviour {
[SerializeField]
private bool Override = false;
[SerializeField]
private List<string> Cards = new List<string>();
//-----------------------------Unity Functions-----------------------------
private void Awake()
{
if (Override)
OverrideDeck();
}
//----------------------------Public Functions-----------------------------
public void OverrideDeck()
{
for (int i = 0; i < 4; i++)
{
PlayerPrefs.SetString("Card" + i, "");
if(i < Cards.Count)
PlayerPrefs.SetString("Card" + i, Cards[i]);
}
}
}
|
35d02fd1ac2e4a6e8754a54fcb1671f67c5e5fb8
|
C#
|
AkinSabriCam/AracKiralamaSistemi
|
/AracKiralamaApp/Business/BLLs/MusteriBilgileriBLL.cs
| 2.546875
| 3
|
using DAL.Concretes;
using Model.DTOs;
using Model.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Business.BLLs
{
public class MusteriBilgileriBLL
{
public void Add(MusteriBilgileri model)
{
using (MusteriRepository musteriRepo = new MusteriRepository())
{
try
{
musteriRepo.Add(model);
}
catch(Exception ex)
{
throw;
}
}
}
public List<MusteriBilgileriDTO> Get()
{
using(MusteriRepository musteriRepo = new MusteriRepository())
{
try
{
var Musteriler = new List<MusteriBilgileriDTO>();
var model = musteriRepo.Get();
foreach (var ent in model.ToList())
{
var musteridto = new MusteriBilgileriDTO();
musteridto.acikAdres = ent.acikAdres;
musteridto.adi = ent.adi;
musteridto.cinsiyet = ent.cinsiyet;
musteridto.dogumTarihi = ent.dogumTarihi;
musteridto.ehliyetTarihi = ent.ehliyetTarihi;
musteridto.ilID = ent.ilID;
musteridto.musteriID = ent.musteriID;
musteridto.Sehir = ent.İl.ilAdi;
musteridto.soyadi = ent.soyadi;
musteridto.telNo = ent.telNo;
Musteriler.Add(musteridto);
}
return Musteriler;
}
catch(Exception ex)
{
throw;
}
}
}
public MusteriBilgileriDTO GetById(int id)
{
using (MusteriRepository musteriRepo = new MusteriRepository())
{
try
{
var ent = musteriRepo.GetById(id);
var musteridto = new MusteriBilgileriDTO();
musteridto.acikAdres = ent.acikAdres;
musteridto.adi = ent.adi;
musteridto.cinsiyet = ent.cinsiyet;
musteridto.dogumTarihi = ent.dogumTarihi;
musteridto.ehliyetTarihi = ent.ehliyetTarihi;
musteridto.ilID = ent.ilID;
musteridto.musteriID = ent.musteriID;
musteridto.Sehir = ent.İl.ilAdi;
musteridto.soyadi = ent.soyadi;
musteridto.telNo = ent.telNo;
return musteridto;
}
catch (Exception ex)
{
throw;
}
}
}
}
}
|
96821fe2da40c5a3e067788a166a2d16e0baee45
|
C#
|
Manotech-272/HaloOnRails
|
/Assets/Scripts/ScoreBoard.cs
| 2.609375
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScoreBoard : MonoBehaviour
{
int score = 0;
Text scoreText;
public static ScoreBoard instance;
private void Awake()
{
if (instance == null)
{
instance = this;
}
}
void Start()
{
scoreText = GetComponent<Text>();
scoreText.text = score.ToString();
}
void Update()
{
scoreText.text = score.ToString();
}
public void ScoreHit(int scoreIncrement)
{
score += scoreIncrement;
}
}
|
f176a17bde73f2e35ca5d9bb6aea8ad4e6383250
|
C#
|
Jake33rus/UniversityProjects
|
/Testing/Testing/Form1.cs
| 2.546875
| 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 KursachSerg
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int res = 0;
Boolean dataChange = false, obrChange = false;
private void textBox2_TextChanged(object sender, EventArgs e)
{
if (textBox2.Text == "Стол" || textBox2.Text == "стол" || textBox2.Text == "СТОЛ")
res += 25;
}
private void textBox2_MouseClick(object sender, MouseEventArgs e)
{
textBox2.Text = "";
}
private void textBox3_MouseClick(object sender, MouseEventArgs e)
{
textBox3.Text = "";
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
if (textBox3.Text == "66")
res += 25;
}
private void comboBox3_TextChanged(object sender, EventArgs e)
{
if (comboBox3.Text == "ИЯРИНО" || comboBox3.Text == "иярино")
res += 25;
}
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
obrChange = true;
if (checkedListBox1.SelectedItem == "Гуманитарное")
res += 25;
}
private void button1_Click(object sender, EventArgs e)
{
if (checkTest() == true)
{
MessageBox.Show("Ошибка, заполните все поля", "Тестирование");
}
else
{
if (res >= 100)
{
textBox4.ForeColor = Color.Lime;
textBox4.Text = "Поздравляем, Вы приняты";
res = 0;
}
else
{
textBox4.ForeColor = Color.Red;
textBox4.Text = "Сожалеем, но Вы нам не подходите";
res = 0;
}
}
}
private Boolean rbCheck()
{
if (radioButton1.Checked)
{
res += 25;
return true;
}
if (radioButton2.Checked)
return true;
else return false;
}
private Boolean checkTest()
{
if (richTextBox1.Text == "Почему вам интересна работа в нашей компании?" || textBox1.Text == "ФИО" || textBox2.Text == "Ответ:" || textBox3.Text == "Ответ:" || comboBox1.Text == "Образование" || comboBox2.Text == "Пол" || dataChange == false || comboBox3.Text == "Ответ:" || obrChange == false || rbCheck() == false)
return true;
else return false;
}
private void textBox1_MouseDown(object sender, MouseEventArgs e)
{
textBox1.Text = "";
}
private void richTextBox1_MouseDown(object sender, MouseEventArgs e)
{
richTextBox1.Text = "";
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
dataChange = true;
}
}
}
|
a31a82f002e775132ac19a7dcdf19281086b5c03
|
C#
|
CodePenguin/pinspaces
|
/Pinspaces/Extensions/DebouncedAction.cs
| 2.796875
| 3
|
using Pinspaces.Core.Interfaces;
using System;
using System.Windows.Threading;
namespace Pinspaces.Extensions
{
public class DebouncedAction : IDelayedAction
{
private readonly Action action;
private readonly Dispatcher dispatcher;
private readonly int intervalMilliseconds;
private bool isPending = true;
private DispatcherTimer timer = null;
public DebouncedAction(Action action, int intervalMilliseconds, Dispatcher dispatcher = null)
{
this.action = action;
this.intervalMilliseconds = intervalMilliseconds;
this.dispatcher = dispatcher ?? Dispatcher.CurrentDispatcher;
}
public void Execute()
{
timer?.Stop();
timer = null;
isPending = true;
timer = new DispatcherTimer(TimeSpan.FromMilliseconds(intervalMilliseconds), DispatcherPriority.ApplicationIdle, (s, e) =>
{
if (timer == null || !isPending)
{
return;
}
timer?.Stop();
timer = null;
action.Invoke();
isPending = false;
}, dispatcher);
timer.Start();
}
public void Stop(bool executeNowIfPending = true)
{
timer?.Stop();
timer = null;
if (executeNowIfPending && isPending)
{
dispatcher.Invoke(action);
isPending = false;
}
}
}
}
|
115657b3561abba1a103033bb923afd0976fe0c3
|
C#
|
shendongnian/download4
|
/first_version_download2/37299-2044693-24741703-2.cs
| 2.984375
| 3
|
[DllImport("kernel32.dll", SetLastError = true)]
static extern SafeFileHandle CreateFile(string lpFileName, FileAccess dwDesiredAccess,
uint dwShareMode, IntPtr lpSecurityAttributes, FileMode dwCreationDisposition,
uint dwFlagsAndAttributes, IntPtr hTemplateFile);
private void Print()
{
// Command to be sent to the printer
string command = "^XA^FO10,10,^AO,30,20^FDFDTesting^FS^FO10,30^BY3^BCN,100,Y,N,N^FDTesting^FS^XZ";
// Create a buffer with the command
Byte[] buffer = new byte[command.Length];
buffer = System.Text.Encoding.ASCII.GetBytes(command);
// Use the CreateFile external func to connect to the LPT1 port
SafeFileHandle printer = CreateFile("LPT1:", FileAccess.ReadWrite, 0, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero);
// Aqui verifico se a impressora é válida
if (printer.IsInvalid == true)
{
return;
}
// Open the filestream to the lpt1 port and send the command
FileStream lpt1 = new FileStream(printer, FileAccess.ReadWrite);
lpt1.Write(buffer, 0, buffer.Length);
// Close the FileStream connection
lpt1.Close();
}
|
a45f1a51e5d1dee264d1056f97136471d0d4beab
|
C#
|
LaymanHacks/LucentDb
|
/LucentDb.Common/IO/DefaultFileService.cs
| 2.546875
| 3
|
using System.IO;
namespace LucentDb.Validator
{
public class DefaultFileService : IFileService
{
private readonly FileInfo _fileInfo;
public DefaultFileService(string fileFullPath)
{
_fileInfo = new FileInfo(fileFullPath);
}
public bool Exists()
{
return _fileInfo.Exists;
}
public StreamReader OpenText()
{
return _fileInfo.OpenText();
}
}
}
|
634f0053195e0699a6c5a9cb2d19c4ff45ac716d
|
C#
|
zhangdinet/DotSpatial
|
/Source/DotSpatial.Positioning/PointD.cs
| 2.546875
| 3
|
// ********************************************************************************************************
// Product Name: DotSpatial.Positioning.dll
// Description: A library for managing GPS connections.
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from http://geoframework.codeplex.com/ version 2.0
//
// The Initial Developer of this original code is Jon Pearson. Submitted Oct. 21, 2010 by Ben Tombs (tidyup)
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// -------------------------------------------------------------------------------------------------------
// | Developer | Date | Comments
// |--------------------------|------------|--------------------------------------------------------------
// | Tidyup (Ben Tombs) | 10/21/2010 | Original copy submitted from modified GeoFrameworks 2.0
// | Shade1974 (Ted Dunsford) | 10/21/2010 | Added file headers reviewed formatting with resharper.
// ********************************************************************************************************
using System;
using System.Globalization;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
#if !PocketPC || DesignTime
using System.ComponentModel;
#endif
namespace DotSpatial.Positioning
{
#if !PocketPC || DesignTime
/// <summary>
/// Represents a highly-precise pixel coordinate.
/// </summary>
/// <remarks><para>This class behaves similar to the <strong>PointF</strong> structure in the
/// <strong>System.Drawing</strong> namespace, except that it supports double-precision
/// values and can be converted into a geographic coordinate. This structure is also
/// supported on the Compact Framework version of the <strong>DotSpatial.Positioning</strong>,
/// whereas <strong>PointF</strong> is not.</para>
/// <para>Instances of this class are guaranteed to be thread-safe because the class is
/// immutable (its properties can only be changed via constructors).</para></remarks>
[TypeConverter("DotSpatial.Positioning.Design.PointDConverter, DotSpatial.Positioning.Design, Culture=neutral, Version=1.0.0.0, PublicKeyToken=b4b0b185210c9dae")]
#endif
public struct PointD : IFormattable, IEquatable<PointD>, IXmlSerializable
{
/// <summary>
///
/// </summary>
private double _x;
/// <summary>
///
/// </summary>
private double _y;
#region Fields
/// <summary>
/// Returns a point with no value.
/// </summary>
public static readonly PointD Empty = new PointD(0, 0);
/// <summary>
/// Represents an invalid coordinate.
/// </summary>
public static readonly PointD Invalid = new PointD(double.NaN, double.NaN);
#endregion Fields
#region Constructors
/// <summary>
/// Creates a new instance for the specified coordinates.
/// </summary>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
public PointD(double x, double y)
{
_x = x;
_y = y;
}
/// <summary>
/// Initializes a new instance of the <see cref="PointD"/> struct.
/// </summary>
/// <param name="value">The value.</param>
public PointD(string value)
: this(value, CultureInfo.CurrentCulture)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="PointD"/> struct.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="culture">The culture.</param>
public PointD(string value, CultureInfo culture)
{
// Trim the string and remove double spaces
value = value.Replace(" ", " ").Trim();
// And separate it via the list separator
string[] values = value.Split(Convert.ToChar(culture.TextInfo.ListSeparator, culture));
// Return the converted values
_x = double.Parse(values[0], NumberStyles.Any, culture);
_y = double.Parse(values[1], NumberStyles.Any, culture);
}
/// <summary>
/// Initializes a new instance of the <see cref="PointD"/> struct.
/// </summary>
/// <param name="reader">The reader.</param>
public PointD(XmlReader reader)
{
_x = _y = 0.0;
ReadXml(reader);
}
#endregion Constructors
#region Public Properties
/// <summary>
/// Gets or sets the x-coordinate of this PointD.
/// </summary>
/// <value>The X.</value>
public double X
{
get
{
return _x;
}
set
{
_x = value;
}
}
/// <summary>
/// For projected coordinates, this is the factor Lamda or the longitude parameter.
/// For readability only, the value is X.
/// </summary>
/// <value>The lam.</value>
public double Lam
{
get
{
return _x;
}
set
{
_x = value;
}
}
/// <summary>
/// Gets or sets the x-coordinate of this PointD.
/// </summary>
/// <value>The Y.</value>
public double Y
{
get
{
return _y;
}
set
{
_y = value;
}
}
/// <summary>
/// For projected coordinates, this is the factor Phi or the latitude parameter.
/// For readability only, the value is Y.
/// </summary>
/// <value>The phi.</value>
public double Phi
{
get
{
return _y;
}
set
{
_y = value;
}
}
/// <summary>
/// Returns whether the current instance has no value.
/// </summary>
public bool IsEmpty
{
get
{
return (_x == 0 && _y == 0);
}
}
/// <summary>
/// Returns whether the current instance has an invalid value.
/// </summary>
public bool IsInvalid
{
get
{
double fail = _x * _y;
return (double.IsNaN(fail) || double.IsInfinity(fail));
}
}
#endregion Public Properties
#region Public Methods
/*
/// <summary>Calculates the direction from one point to another.</summary>
public Azimuth BearingTo(PointD value)
{
double Result = value.Subtract(this).ToPolarCoordinate().Theta.DecimalDegrees;
return new Azimuth(Result).Normalize();
}
*/
/// <summary>
/// Calculates the distance to another pixel.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
public double DistanceTo(PointD value)
{
return Math.Sqrt(Math.Abs(value.X - _x) * Math.Abs(value.X - _x)
+ Math.Abs(value.Y - _y) * Math.Abs(value.Y - _y));
}
/// <summary>
/// Indicates if the current instance is closer to the top of the monitor than the
/// specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns><c>true</c> if the specified value is above; otherwise, <c>false</c>.</returns>
public bool IsAbove(PointD value)
{
return _y < value.Y;
}
/// <summary>
/// Indicates if the current instance is closer to the bottom of the monitor than the
/// specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns><c>true</c> if the specified value is below; otherwise, <c>false</c>.</returns>
public bool IsBelow(PointD value)
{
return _y > value.Y;
}
/// <summary>
/// Indicates if the current instance is closer to the left of the monitor than the
/// specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns><c>true</c> if [is left of] [the specified value]; otherwise, <c>false</c>.</returns>
public bool IsLeftOf(PointD value)
{
return _x < value.X;
}
/// <summary>
/// Indicates if the current instance is closer to the right of the monitor than the
/// specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns><c>true</c> if [is right of] [the specified value]; otherwise, <c>false</c>.</returns>
public bool IsRightOf(PointD value)
{
return _x > value.X;
}
/// <summary>
/// Returns the current instance with its signs switched.
/// </summary>
/// <returns></returns>
/// <remarks>This method returns a new point where the signs of X and Y are flipped. For example, if
/// a point, represents (20, 40), this function will return (-20, -40).</remarks>
public PointD Mirror()
{
return new PointD(-_x, -_y);
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <param name="format">The format.</param>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public string ToString(string format)
{
return ToString(format, CultureInfo.CurrentCulture);
}
/// <summary>
/// Returns the current instance rotated about (0, 0).
/// </summary>
/// <param name="angle">The angle.</param>
/// <returns></returns>
public PointD Rotate(Angle angle)
{
return Rotate(angle.DecimalDegrees);
}
/// <summary>
/// Returns the current instance rotated about (0, 0).
/// </summary>
/// <param name="angle">The angle.</param>
/// <returns></returns>
public PointD Rotate(double angle)
{
// Convert the angle to radians
double angleRadians = Radian.FromDegrees(angle).Value;
double angleCos = Math.Cos(angleRadians);
double angleSin = Math.Sin(angleRadians);
// Yes. Rotate the point about 0, 0
return new PointD(angleCos * _x - angleSin * _y, angleSin * _x + angleCos * _y);
}
/// <summary>
/// Returns the current instance rotated about the specified point.
/// </summary>
/// <param name="angle">The angle.</param>
/// <param name="center">The center.</param>
/// <returns></returns>
public PointD RotateAt(Angle angle, PointD center)
{
return RotateAt(angle.DecimalDegrees, center);
}
/// <summary>
/// Rotates at.
/// </summary>
/// <param name="angle">The angle.</param>
/// <param name="center">The center.</param>
/// <returns></returns>
public PointD RotateAt(double angle, PointD center)
{
if (angle == 0)
return this;
// Shift the point by its center, rotate, then add the center back in
return Subtract(center).Rotate(angle).Add(center);
}
#endregion Public Methods
#region Overrides
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">Another object to compare to.</param>
/// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj)
{
if (obj is PointD)
return Equals((PointD)obj);
return false;
}
/// <summary>
/// Returns a unique code used for hash tables.
/// </summary>
/// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns>
public override int GetHashCode()
{
return _x.GetHashCode() ^ _y.GetHashCode();
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public override string ToString()
{
return ToString("G", CultureInfo.CurrentCulture);
}
#endregion Overrides
#region Static Methods
/// <summary>
/// Parses the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
public static PointD Parse(string value)
{
return new PointD(value);
}
/// <summary>
/// Parses the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="culture">The culture.</param>
/// <returns></returns>
public static PointD Parse(string value, CultureInfo culture)
{
return new PointD(value, culture);
}
#endregion Static Methods
#region Operators
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(PointD left, PointD right)
{
return left.Equals(right);
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(PointD left, PointD right)
{
return !left.Equals(right);
}
/// <summary>
/// Implements the operator +.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static PointD operator +(PointD left, PointD right)
{
return new PointD(left.X + right.X, left.Y + right.Y);
}
/// <summary>
/// Implements the operator -.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static PointD operator -(PointD left, PointD right)
{
return new PointD(left.X - right.X, left.Y - right.Y);
}
/// <summary>
/// Implements the operator *.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static PointD operator *(PointD left, PointD right)
{
return new PointD(left.X * right.X, left.Y * right.Y);
}
/// <summary>
/// Implements the operator /.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static PointD operator /(PointD left, PointD right)
{
return new PointD(left.X / right.X, left.Y / right.Y);
}
/// <summary>
/// Returns the sum of two points by adding X and Y values together.
/// </summary>
/// <param name="offset">The offset.</param>
/// <returns></returns>
/// <remarks>This method adds the X and Y coordinates and returns a new point at that location.</remarks>
public PointD Add(PointD offset)
{
return new PointD(_x + offset.X, _y + offset.Y);
//return Offset(offset.X, offset.Y);
}
/// <summary>
/// Returns the sum of two points by adding X and Y values together.
/// </summary>
/// <param name="offsetX">The offset X.</param>
/// <param name="offsetY">The offset Y.</param>
/// <returns></returns>
/// <remarks>This method adds the X and Y coordinates and returns a new point at that location.</remarks>
public PointD Add(double offsetX, double offsetY)
{
return new PointD(_x + offsetX, _y + offsetY);
}
/// <summary>
/// Returns the difference of two points by subtracting the specified X and Y values.
/// </summary>
/// <param name="offset">The offset.</param>
/// <returns></returns>
/// <remarks>This method subtracts the X and Y coordinates and returns a new point at that location.</remarks>
public PointD Subtract(PointD offset)
{
return new PointD(_x - offset.X, _y - offset.Y);
}
/// <summary>
/// Returns the difference of two points by subtracting the specified X and Y values.
/// </summary>
/// <param name="offsetX">The offset X.</param>
/// <param name="offsetY">The offset Y.</param>
/// <returns></returns>
/// <remarks>This method subtracts the X and Y coordinates and returns a new point at that location.</remarks>
public PointD Subtract(double offsetX, double offsetY)
{
return new PointD(_x - offsetX, _y - offsetY);
}
/// <summary>
/// Returns the product of two points by multiplying X and Y values together.
/// </summary>
/// <param name="offset">The offset.</param>
/// <returns></returns>
/// <remarks>This method multiplies the X and Y coordinates together and returns a new point at that location. This
/// is typically used to scale a point from one coordinate system to another.</remarks>
public PointD Multiply(PointD offset)
{
return new PointD(_x * offset.X, _y * offset.Y);
}
/// <summary>
/// Multiplies the specified offset X.
/// </summary>
/// <param name="offsetX">The offset X.</param>
/// <param name="offsetY">The offset Y.</param>
/// <returns></returns>
public PointD Multiply(double offsetX, double offsetY)
{
return new PointD(_x * offsetX, _y * offsetY);
}
/// <summary>
/// Divides the specified offset.
/// </summary>
/// <param name="offset">The offset.</param>
/// <returns></returns>
public PointD Divide(PointD offset)
{
return new PointD(_x / offset.X, _y / offset.Y);
}
/// <summary>
/// Divides the specified offset X.
/// </summary>
/// <param name="offsetX">The offset X.</param>
/// <param name="offsetY">The offset Y.</param>
/// <returns></returns>
public PointD Divide(double offsetX, double offsetY)
{
return new PointD(_x / offsetX, _y / offsetY);
}
#endregion Operators
#region Conversions
/// <summary>
/// Performs an explicit conversion from <see cref="DotSpatial.Positioning.PointD"/> to <see cref="System.String"/>.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator string(PointD value)
{
return value.ToString();
}
#endregion Conversions
#region IEquatable<PointD> Members
/// <summary>
/// Equalses the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
public bool Equals(PointD value)
{
return (_x == value.X) && (_y == value.Y);
}
/// <summary>
/// Equalses the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="precision">The precision.</param>
/// <returns></returns>
public bool Equals(PointD value, int precision)
{
return ((Math.Round(_x, precision) == Math.Round(value.X, precision))
&& (Math.Round(_y, precision) == Math.Round(value.Y, precision)));
}
#endregion IEquatable<PointD> Members
#region IFormattable Members
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <param name="format">The format to use.-or- A null reference (Nothing in Visual Basic) to use the default format defined for the type of the <see cref="T:System.IFormattable"/> implementation.</param>
/// <param name="formatProvider">The provider to use to format the value.-or- A null reference (Nothing in Visual Basic) to obtain the numeric format information from the current locale setting of the operating system.</param>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public string ToString(string format, IFormatProvider formatProvider)
{
CultureInfo culture = (CultureInfo)formatProvider ?? CultureInfo.CurrentCulture;
if (string.IsNullOrEmpty(format))
format = "G";
return _x.ToString(format, formatProvider)
+ culture.TextInfo.ListSeparator
+ _y.ToString(format, formatProvider);
}
#endregion IFormattable Members
#region IXmlSerializable Members
/// <summary>
/// This method is reserved and should not be used. When implementing the IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method, and instead, if specifying a custom schema is required, apply the <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute"/> to the class.
/// </summary>
/// <returns>An <see cref="T:System.Xml.Schema.XmlSchema"/> that describes the XML representation of the object that is produced by the <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)"/> method and consumed by the <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)"/> method.</returns>
XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
/// <summary>
/// Converts an object into its XML representation.
/// </summary>
/// <param name="writer">The <see cref="T:System.Xml.XmlWriter"/> stream to which the object is serialized.</param>
public void WriteXml(XmlWriter writer)
{
writer.WriteAttributeString("X",
_x.ToString("G17", CultureInfo.InvariantCulture));
writer.WriteAttributeString("Y",
_y.ToString("G", CultureInfo.InvariantCulture));
}
/// <summary>
/// Generates an object from its XML representation.
/// </summary>
/// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized.</param>
public void ReadXml(XmlReader reader)
{
double.TryParse(reader.GetAttribute("X"), NumberStyles.Any, CultureInfo.InvariantCulture, out _x);
double.TryParse(reader.GetAttribute("Y"), NumberStyles.Any, CultureInfo.InvariantCulture, out _y);
reader.Read();
}
#endregion IXmlSerializable Members
}
}
|
9d052095728506faf940cc87794a46fe0e63361e
|
C#
|
pedul/KenKen
|
/LearnKenKen/UserControls/KenCell.ascx.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using LearnKenKen.UIModels;
namespace LearnKenKen.UserControls
{
public partial class KenCell : System.Web.UI.UserControl
{
internal CellViewModel Cell
{
set
{
SetValue(value.Value);
spanUnusableNumbers.InnerHtml = value.UnusableNumbers;
spanPossibilities.InnerHtml = GetPossibilities(value.Possibilities);
spanCellId.InnerHtml = value.CellId;
spanOperation.InnerHtml = value.CellId.Contains('a') ? value.Operator : string.Empty;
spanTargetValue.InnerHtml = value.CellId.Contains('a') ? value.TargetValue : string.Empty;
}
}
private void SetValue(string value)
{
spanValue.InnerHtml = value;
if (value.Length > 0)
{
spanValue.Visible = true;
spanPossibilities.Visible = false;
spanUnusableNumbers.Visible = false;
this.MarkSolved();
}
}
private string GetPossibilities(string possibilities)
{
int index = -1;
int counter = 0;
while (counter < 4 && ((index = possibilities.IndexOf("<br/>", index + 1)) >= 0))
counter++;
if (counter == 4)
return possibilities.Substring(0, index - 1) + " ...";
return possibilities;
}
internal void Highlight()
{
this.AddStyle("background-color", "#FFFF00");
}
internal void MarkSolved()
{
this.AddStyle("background-color", "#F6F9ED");
}
public void AddStyle(string key, string value)
{
cellContainer.Style.Add(key, value);
}
}
}
|
157e21acc886b60532bd79c39ddc909134cd77e3
|
C#
|
KomilzodaHusnoro/Player
|
/Program.cs
| 3.046875
| 3
|
using System;
namespace interface234
{
class Program
{
static void Main(string[] args)
{
Player Fayzullo = new Player();
Fayzullo.Play();
Fayzullo.Pause();
Fayzullo.Record();
Fayzullo.Stop();
Fayzullo.Stop2();
}
}
class Player : IPlayable, IRecodable
{
public void Play()
{
System.Console.WriteLine("Can you hear this? It is playing");
}
public void Pause ()
{
System.Console.WriteLine("Playing has been paused");
}
public void Stop ()
{
System.Console.WriteLine("Playing has been stopped");
}
public void Record()
{
System.Console.WriteLine("It is recording");
}
public void Stop2 ()
{
System.Console.WriteLine("Recording has been stopped");
}
}
interface IPlayable
{
public void Play();
public void Pause ();
public void Stop ();
}
interface IRecodable
{
void Record();
void Pause ();
void Stop2 ();
}
}
|
750b69f8f4b78969685d276ad9ffd08084ff7145
|
C#
|
AtWinner/CSharp_Project
|
/Random_/Random_/Program.cs
| 2.953125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Random_
{
class Program
{
static void Main(string[] args)
{
string a[,,,]=new string[7,7,7];
Random rd = new Random();
for (int i = 0; i <= 10; i++)
{
int value = rd.Next(1, 100);
Console.Write(value+" ");
}
}
}
}
|
5e09f7c93f107f87c323a7fd3b9b211d93b09b2c
|
C#
|
AuroraStefanova/BasicSoftUni2017
|
/homework/SimpleConditionStatement/06.01.BonusScore/BonusScore.cs
| 3.703125
| 4
|
using System;
class BonusScore
{
static void Main()
{
int number = int.Parse(Console.ReadLine());
double bonusScore = 0;
if (number <= 100)
{
bonusScore += 5;
}
else if ((number > 100) && (number <= 1000))
{
bonusScore += 0.2 * number;
}
else
{
bonusScore += 0.1 * number;
}
if (number % 2 == 0)
{
bonusScore += 1;
}
if (number % 10 == 5)
{
bonusScore += 2;
}
double totalScore = bonusScore + number;
Console.WriteLine(bonusScore);
Console.WriteLine(totalScore);
}
}
|
e9dde27d07d09560645b8b168ef8d4d9b3d9b37e
|
C#
|
broadcastzero/swe2_backoffice
|
/EPU-Backoffice/EPUBackofficeTests/PositiveIntOrMinusOneValidatorTest.cs
| 2.671875
| 3
|
namespace EPUBackofficeTests
{
using EPU_Backoffice_Panels.Rules;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
/// <summary>
///This is a test class for PositiveIntOrMinusOneValidatorTest and is intended
///to contain all PositiveIntOrMinusOneValidatorTest Unit Tests
///</summary>
[TestClass()]
public class PositiveIntOrMinusOneValidatorTest
{
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
//You can use the following additional attributes as you write your tests:
//
//Use ClassInitialize to run code before running the first test in the class
//[ClassInitialize()]
//public static void MyClassInitialize(TestContext testContext)
//{
//}
//
//Use ClassCleanup to run code after all tests in a class have run
//[ClassCleanup()]
//public static void MyClassCleanup()
//{
//}
//
//Use TestInitialize to run code before running each test
//[TestInitialize()]
//public void MyTestInitialize()
//{
//}
//
//Use TestCleanup to run code after each test has run
//[TestCleanup()]
//public void MyTestCleanup()
//{
//}
//
#endregion
/// <summary>
///A test for Eval
///</summary>
[TestMethod()]
public void EvalTest1()
{
PositiveIntOrMinusOneValidator target = new PositiveIntOrMinusOneValidator(); // TODO: Initialize to an appropriate value
string input = "-1"; // TODO: Initialize to an appropriate value
target.Eval(input);
Assert.AreEqual(target.HasErrors, false);
}
/// <summary>
///A test for Eval
///</summary>
[TestMethod()]
public void EvalTest2()
{
PositiveIntOrMinusOneValidator target = new PositiveIntOrMinusOneValidator();
string input = "-2";
target.Eval(input);
Assert.AreEqual(target.HasErrors, true);
}
/// <summary>
///A test for Eval
///</summary>
[TestMethod()]
public void EvalTest3()
{
PositiveIntOrMinusOneValidator target = new PositiveIntOrMinusOneValidator();
string input = "0";
target.Eval(input);
Assert.AreEqual(target.HasErrors, false);
}
/// <summary>
///A test for Eval
///</summary>
[TestMethod()]
public void EvalTest4()
{
PositiveIntOrMinusOneValidator target = new PositiveIntOrMinusOneValidator();
string input = "10";
target.Eval(input);
Assert.AreEqual(target.HasErrors, false);
}
/// <summary>
///A test for Eval
///</summary>
[TestMethod()]
public void EvalTest5()
{
PositiveIntOrMinusOneValidator target = new PositiveIntOrMinusOneValidator();
string input = "10,55";
target.Eval(input);
Assert.AreEqual(target.HasErrors, true);
}
}
}
|
0243aeda8170dff1aa18a2a002ad065ef2bfdbed
|
C#
|
AlbertoMoreta/Dr.Handy
|
/DrHandy/Model/SintromTreatmentItem.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace DrHandy.Model {
public class SintromTreatmentItem : SintromItem {
public string UserId { get; set; }
public DateTime Date { get; set; }
private string _imageName;
public string ImageName {
get {return _imageName;}
set { _imageName = value; ImageNameToFraction(); }
}
public string Fraction { get; private set; }
public string Medicine { get; set; }
public SintromTreatmentItem() { }
public SintromTreatmentItem(string userId, DateTime date, string imageName, string medicine) {
UserId = userId;
Date = date;
ImageName = imageName;
Medicine = medicine;
}
private void ImageNameToFraction() {
switch (_imageName) {
case "sintrom_1": Fraction = "1"; break;
case "sintrom_1_2": Fraction = "1/2"; break;
case "sintrom_1_4": Fraction = "1/4"; break;
case "sintrom_1_8": Fraction = "1/8"; break;
case "sintrom_3_4": Fraction = "3/4"; break;
}
}
}
}
|
2705a5353337a4a7bfc6a281af2d2f70a19eea77
|
C#
|
ravenboilinux/testEFcore
|
/TestEFcore/Program.cs
| 2.84375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace TestEFcore
{
class Program
{
static void Main(string[] args)
{
BloggingContext context = new BloggingContext();
foreach (var blog in context.Blogs)
{
}
Blog b=new Blog()
{
Url = "hello"
};
b.Posts.Add(new Post()
{
Content = "jfajsdfkljas;kdlfja;skdlfja;ksldjfl;djskf;lkdslksa",
Title = "Help me"
});
context.Blogs.Add(b);
context.SaveChanges();
}
}
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;");
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
}
|
7b138d61979f03de74cacc7e442999e03abb5dfc
|
C#
|
nurefexc/Perfomance-Viewer
|
/PrefomanceViewer/Battery.cs
| 2.703125
| 3
|
using System.Windows.Forms;
namespace SystemManager.SystemInformations
{
static class Battery
{
private static PowerStatus status = SystemInformation.PowerStatus;
private static string LastPercent = "";
private static string percent = "";
public static string Percent
{
get
{
float percent2 = status.BatteryLifePercent;
string percent_text = percent2.ToString("P0");
if (IsThere == true)
{
percent = percent_text;
if (percent != LastPercent)
{
LastPercent = percent;
}
return percent_text;
}
return "";
}
}
public static bool IsThere
{
get
{
if (status.BatteryChargeStatus != BatteryChargeStatus.NoSystemBattery)
{
return true;
}
return false;
}
}
public static bool IsPower
{
get
{
if (status.PowerLineStatus == PowerLineStatus.Online && IsThere == true)
{
return true;
}
else
{
return false;
}
}
}
}
}
|
a82c57abfb88ff48a31d4fe901f016c9c2908907
|
C#
|
Adexandria/LAMS
|
/BookData/Model/SignupRepository.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BookData.Model
{
public class SignupRepository : ISign_up
{
private readonly AppDbcontext db;
public SignupRepository(AppDbcontext db)
{
this.db = db;
}
public Signup Add(Signup signup)
{
db.Signups.Add(signup);
return signup;
}
public int Commit()
{
return db.SaveChanges();
}
public string GetAll(string username)
{
var query = db.Signups.Where(a=>a.UserName==username).FirstOrDefault();
var pass = Encryption.DecodeFrom64(query.Password);
return pass;
}
public Signup UserSearch(string username, string password)
{
return db.Signups.Where(p => p.UserName == username && p.Password == password ).FirstOrDefault();
}
}
}
|
a526cbcacffbe0a2c8159f8b95cc074d3f17a71d
|
C#
|
Austin-Derrick/-Nature-of-Code-Unity-Remix-Excercises
|
/Assets/Scripts/IntroExcercise3ADerrickson.cs
| 2.609375
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IntroExcercise3ADerrickson : MonoBehaviour
{
public GameObject walkerPrefab;
private GameObject walkerGO;
private WalkerEx3 walker;
// Start is called before the first frame update
void Start()
{
GameObject walkerGameObject = new GameObject();
walker = walkerGameObject.AddComponent<WalkerEx3>();
}
// Update is called once per frame
void Update()
{
walker.step();
walker.draw();
}
}
public class WalkerEx3 : MonoBehaviour
{
public int x;
public int y;
private float mouseY;
private float mouseX;
float num;
GameObject walkerGO;
// Start is called before the first frame update
void Start()
{
walkerGO = GameObject.CreatePrimitive(PrimitiveType.Sphere);
x = 0;
y = 0;
}
// Update is called once per frame
void Update()
{
num = Random.Range(0f, 1f);
mouseX = Input.GetAxis("Mouse X");
mouseY = Input.GetAxis("Mouse Y");
}
public void step()
{
if (num < 0.1F)
{
x++;
}
else if (num < 0.2F)
{
x--;
}
else if (num < .3F)
{
y++;
}
else if (num < 0.4f)
{
y--;
}
else
{
x += Mathf.RoundToInt(mouseX);
y += Mathf.RoundToInt(mouseY);
}
walkerGO.transform.position = new Vector3(x, y, 0F);
}
public void draw()
{
GameObject sphere = Instantiate(walkerGO);
sphere.transform.position = new Vector3(walkerGO.transform.position.x, walkerGO.transform.position.y, 0F);
}
}
|
0069ac1bb3840c0c9137ccd110d0a744ed08f354
|
C#
|
woshizuoyue/Design_Pattern_Practice
|
/Decorator/Program.cs
| 3.21875
| 3
|
using System;
namespace Decorator
{
class Program
{
static void Main(string[] args)
{
Beverage beverage = new Espresso();
Console.WriteLine($"{beverage.GetDescription()} ${beverage.Cost()}");
Beverage beverage1 = new Decat();
beverage1 = new Mocha(beverage1);
beverage1 = new Mocha(beverage1);
beverage1 = new Whip(beverage1);
Console.WriteLine($"{beverage1.GetDescription()} ${beverage1.Cost()}");
Beverage beverage2 = new HouseBlend();
beverage2 = new Soy(beverage2);
beverage2 = new Mocha(beverage2);
beverage2 = new Whip(beverage2);
Console.WriteLine($"{beverage2.GetDescription()} ${beverage2.Cost()}");
}
}
}
|
d997c597b58385ecd8174e5c7e8f626444c60448
|
C#
|
RickStrahl/markdig
|
/src/Markdig.Tests/Specs/DefinitionListSpecs.cs
| 3.015625
| 3
|
// Generated: 21. 01. 2019 14:26:34
// --------------------------------
// Definition Lists
// --------------------------------
using System;
using NUnit.Framework;
namespace Markdig.Tests.Specs.DefinitionLists
{
[TestFixture]
public class TestExtensionsDefinitionLists
{
// # Extensions
//
// This section describes the different extensions supported:
//
// ## Definition lists
//
// A custom container is similar to a fenced code block, but it is using the character `:` to declare a block (with at least 3 characters), and instead of generating a `<pre><code>...</code></pre>` it will generate a `<div>...</dib>` block.
[Test]
public void ExtensionsDefinitionLists_Example001()
{
// Example 1
// Section: Extensions / Definition lists
//
// The following Markdown:
//
// Term 1
// : This is a definition item
// With a paragraph
// > This is a block quote
//
// - This is a list
// - with an item2
//
// ```java
// Test
//
//
// ```
//
// And a last line
// : This ia another definition item
//
// Term2
// Term3 *with some inline*
// : This is another definition for term2
//
// Should be rendered as:
// <dl>
// <dt>Term 1</dt>
// <dd><p>This is a definition item
// With a paragraph</p>
// <blockquote>
// <p>This is a block quote</p>
// </blockquote>
// <ul>
// <li>This is a list</li>
// <li>with an item2</li>
// </ul>
// <pre><code class="language-java">Test
//
//
// </code></pre>
// <p>And a last line</p>
// </dd>
// <dd>This ia another definition item</dd>
// <dt>Term2</dt>
// <dt>Term3 <em>with some inline</em></dt>
// <dd>This is another definition for term2</dd>
// </dl>
Console.WriteLine("Example 1\nSection Extensions / Definition lists\n");
TestParser.TestSpec("\nTerm 1\n: This is a definition item\n With a paragraph\n > This is a block quote\n\n - This is a list\n - with an item2\n\n ```java\n Test\n\n\n ```\n\n And a last line\n: This ia another definition item\n\nTerm2\nTerm3 *with some inline*\n: This is another definition for term2", "<dl>\n<dt>Term 1</dt>\n<dd><p>This is a definition item\nWith a paragraph</p>\n<blockquote>\n<p>This is a block quote</p>\n</blockquote>\n<ul>\n<li>This is a list</li>\n<li>with an item2</li>\n</ul>\n<pre><code class=\"language-java\">Test\n\n\n</code></pre>\n<p>And a last line</p>\n</dd>\n<dd>This ia another definition item</dd>\n<dt>Term2</dt>\n<dt>Term3 <em>with some inline</em></dt>\n<dd>This is another definition for term2</dd>\n</dl>", "definitionlists+attributes|advanced");
}
// A definition term can be followed at most by one blank line. Lazy continuations are supported for definitions:
[Test]
public void ExtensionsDefinitionLists_Example002()
{
// Example 2
// Section: Extensions / Definition lists
//
// The following Markdown:
// Term 1
//
// : Definition
// with lazy continuation.
//
// Second paragraph of the definition.
//
// Should be rendered as:
// <dl>
// <dt>Term 1</dt>
// <dd><p>Definition
// with lazy continuation.</p>
// <p>Second paragraph of the definition.</p>
// </dd>
// </dl>
Console.WriteLine("Example 2\nSection Extensions / Definition lists\n");
TestParser.TestSpec("Term 1\n\n: Definition\nwith lazy continuation.\n\n Second paragraph of the definition.", "<dl>\n<dt>Term 1</dt>\n<dd><p>Definition\nwith lazy continuation.</p>\n<p>Second paragraph of the definition.</p>\n</dd>\n</dl>", "definitionlists+attributes|advanced");
}
// The definition must be indented to 4 characters including the `:`.
[Test]
public void ExtensionsDefinitionLists_Example003()
{
// Example 3
// Section: Extensions / Definition lists
//
// The following Markdown:
// Term 1
// : Invalid with less than 3 characters
//
// Should be rendered as:
// <p>Term 1
// : Invalid with less than 3 characters</p>
Console.WriteLine("Example 3\nSection Extensions / Definition lists\n");
TestParser.TestSpec("Term 1\n: Invalid with less than 3 characters", "<p>Term 1\n: Invalid with less than 3 characters</p>", "definitionlists+attributes|advanced");
}
// The `:` can be indented up to 3 spaces:
[Test]
public void ExtensionsDefinitionLists_Example004()
{
// Example 4
// Section: Extensions / Definition lists
//
// The following Markdown:
// Term 1
// : Valid even if `:` starts at most 3 spaces
//
// Should be rendered as:
// <dl>
// <dt>Term 1</dt>
// <dd>Valid even if <code>:</code> starts at most 3 spaces</dd>
// </dl>
Console.WriteLine("Example 4\nSection Extensions / Definition lists\n");
TestParser.TestSpec("Term 1\n : Valid even if `:` starts at most 3 spaces", "<dl>\n<dt>Term 1</dt>\n<dd>Valid even if <code>:</code> starts at most 3 spaces</dd>\n</dl>", "definitionlists+attributes|advanced");
}
// But more than 3 spaces before `:` will trigger an indented code block:
[Test]
public void ExtensionsDefinitionLists_Example005()
{
// Example 5
// Section: Extensions / Definition lists
//
// The following Markdown:
// Term 1
//
// : Not valid
//
// Should be rendered as:
// <p>Term 1</p>
// <pre><code>: Not valid
// </code></pre>
Console.WriteLine("Example 5\nSection Extensions / Definition lists\n");
TestParser.TestSpec("Term 1\n\n : Not valid", "<p>Term 1</p>\n<pre><code>: Not valid\n</code></pre>", "definitionlists+attributes|advanced");
}
// Definition lists can be nested inside list items
[Test]
public void ExtensionsDefinitionLists_Example006()
{
// Example 6
// Section: Extensions / Definition lists
//
// The following Markdown:
// 1. First
//
// 2. Second
//
// Term 1
// : Definition
//
// Term 2
// : Second Definition
//
// Should be rendered as:
// <ol>
// <li><p>First</p></li>
// <li><p>Second</p>
// <dl>
// <dt>Term 1</dt>
// <dd>Definition</dd>
// <dt>Term 2</dt>
// <dd>Second Definition</dd>
// </dl></li>
// </ol>
Console.WriteLine("Example 6\nSection Extensions / Definition lists\n");
TestParser.TestSpec("1. First\n \n2. Second\n \n Term 1\n : Definition\n \n Term 2\n : Second Definition", "<ol>\n<li><p>First</p></li>\n<li><p>Second</p>\n<dl>\n<dt>Term 1</dt>\n<dd>Definition</dd>\n<dt>Term 2</dt>\n<dd>Second Definition</dd>\n</dl></li>\n</ol>", "definitionlists+attributes|advanced");
}
}
}
|
a3c72bd128e8e6b9da4c4e8a76d98626bfc9d155
|
C#
|
ruzyqwerty/RegOnlineSchoolKursach
|
/App1/Forms/KursForm.cs
| 2.546875
| 3
|
using App1.SQL;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace App1.Forms
{
public partial class KursForm : Form
{
private SQLManager SQLManager = new SQLManager();
private int currentKurs = -1;
public KursForm()
{
InitializeComponent();
}
public KursForm(int kursId)
{
InitializeComponent();
currentKurs = kursId;
}
private void KursForm_Load(object sender, EventArgs e)
{
if (currentKurs == -1)
UpdateAddForm();
else UpdateEditForm();
}
// обновление окна для добавление курса
private void UpdateAddForm()
{
string sql = $"SELECT NAME_ORG from Organizatsia";
List<string> orgNames = SQLManager.GetStringValues(sql);
orgNameComboBox.Items.Clear();
foreach (string name in orgNames)
{
orgNameComboBox.Items.Add(name);
}
orgNameComboBox.SelectedIndex = 0;
sql = $"SELECT IMYA_PD from Prepodavateli";
List<string> prepodImyas = SQLManager.GetStringValues(sql);
sql = $"SELECT FAM_PD from Prepodavateli";
List<string> prepodFams = SQLManager.GetStringValues(sql);
sql = $"SELECT OTCH_PD from Prepodavateli";
List<string> prepodOtchs = SQLManager.GetStringValues(sql);
prepodNameComboBox.Items.Clear();
for (int i = 0; i < prepodImyas.Count; i++)
{
prepodNameComboBox.Items.Add($"{prepodFams[i]} {prepodImyas[i]} {prepodOtchs[i]}");
}
prepodNameComboBox.SelectedIndex = 0;
AcceptBtn.Text = "Добавить";
}
// обновление окна для редактирования курса
private void UpdateEditForm()
{
string sql = $"SELECT CODE_ORG, CODE_PD, NAME_KURS, CHASOV, PRICE from Kurs WHERE CODE_CY = {currentKurs}";
int orgCode = SQLManager.GetIntValue(sql, 0);
int prepodCode = SQLManager.GetIntValue(sql, 1);
string nameKurs = SQLManager.GetStringValue(sql, 2);
int chasov = SQLManager.GetIntValue(sql, 3);
decimal price = SQLManager.GetMoneyValue(sql, 4);
sql = $"SELECT NAME_ORG from Organizatsia WHERE CODE_ORG = {orgCode}";
string orgName = SQLManager.GetStringValue(sql, 0);
sql = $"SELECT NAME_ORG from Organizatsia";
List<string> orgNames = SQLManager.GetStringValues(sql);
orgNameComboBox.Items.Clear();
foreach (string name in orgNames)
{
orgNameComboBox.Items.Add(name);
}
orgNameComboBox.SelectedItem = orgName;
sql = $"SELECT IMYA_PD from Prepodavateli WHERE CODE_PD = {prepodCode}";
List<string> prepodImyas = SQLManager.GetStringValues(sql);
sql = $"SELECT FAM_PD from Prepodavateli WHERE CODE_PD = {prepodCode}";
List<string> prepodFams = SQLManager.GetStringValues(sql);
sql = $"SELECT OTCH_PD from Prepodavateli WHERE CODE_PD = {prepodCode}";
List<string> prepodOtchs = SQLManager.GetStringValues(sql);
sql = $"SELECT FAM_PD, IMYA_PD, OTCH_PD from Prepodavateli";
string prepodFam = SQLManager.GetStringValue(sql, 0);
string prepodName = SQLManager.GetStringValue(sql, 1);
string prepodOtch = SQLManager.GetStringValue(sql, 2);
prepodNameComboBox.Items.Clear();
for (int i = 0; i < prepodImyas.Count; i++)
{
prepodNameComboBox.Items.Add($"{prepodFams[i]} {prepodImyas[i]} {prepodOtchs[i]}");
}
prepodNameComboBox.SelectedItem = $"{prepodFam} {prepodName} {prepodOtch}";
kursNameTextBox.Text = nameKurs;
chasovNumUD.Value = chasov;
priceNumUD.Value = price;
}
// отмена добавления / изменения
private void cancelBtn_Click(object sender, EventArgs e)
{
this.Close();
}
// принятие добавления / изменения
private void AcceptBtn_Click(object sender, EventArgs e)
{
if (currentKurs == -1)
AddKurs();
else
EditKurs();
this.Close();
}
// добавляем курс
private void AddKurs()
{
string sql = $"SELECT CODE_ORG from Organizatsia WHERE NAME_ORG = '{orgNameComboBox.SelectedItem}'";
int orgId = SQLManager.GetIntValue(sql, 0);
string fam = prepodNameComboBox.SelectedItem.ToString().Split(' ')[0];
string name = prepodNameComboBox.SelectedItem.ToString().Split(' ')[1];
sql = $"SELECT CODE_PD from Prepodavateli WHERE FAM_PD = '{fam}' AND IMYA_PD = '{name}'";
int prepodId = SQLManager.GetIntValue(sql, 0);
sql = "INSERT INTO Kurs (CODE_ORG, CODE_PD, NAME_KURS, CHASOV, PRICE) " +
$"VALUES ({orgId}, {prepodId}, '{kursNameTextBox.Text}', {chasovNumUD.Value}, {priceNumUD.Value})";
SQLManager.ExecuteSQLCommand(sql);
}
// вносим изменения в курс
private void EditKurs()
{
string sql = $"SELECT CODE_ORG from Organizatsia WHERE NAME_ORG = '{orgNameComboBox.SelectedItem}'";
int orgId = SQLManager.GetIntValue(sql, 0);
string fam = prepodNameComboBox.SelectedItem.ToString().Split(' ')[0];
string name = prepodNameComboBox.SelectedItem.ToString().Split(' ')[1];
sql = $"SELECT CODE_PD from Prepodavateli WHERE FAM_PD = '{fam}' AND IMYA_PD = '{name}'";
int prepodId = SQLManager.GetIntValue(sql, 0);
sql = $"UPDATE Kurs SET CODE_ORG = {orgId} WHERE CODE_CY = {currentKurs};";
SQLManager.ExecuteSQLCommand(sql);
sql = $"UPDATE Kurs SET CODE_PD = {prepodId} WHERE CODE_CY = {currentKurs};";
SQLManager.ExecuteSQLCommand(sql);
sql = $"UPDATE Kurs SET NAME_KURS = '{kursNameTextBox.Text}' WHERE CODE_CY = {currentKurs};";
SQLManager.ExecuteSQLCommand(sql);
sql = $"UPDATE Kurs SET CHASOV = {chasovNumUD.Value} WHERE CODE_CY = {currentKurs};";
SQLManager.ExecuteSQLCommand(sql);
sql = $"UPDATE Kurs SET PRICE = {float.Parse(priceNumUD.Value.ToString())} WHERE CODE_CY = {currentKurs};";
SQLManager.ExecuteSQLCommand(sql);
}
}
}
|
093a39f5b1de60d8676144637e5cc1300bd6b95c
|
C#
|
frakiec89/WSR_SAMARA_2020
|
/WSR_SAMARA_2020/MethodClass.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WSR_SAMARA_2020
{
public interface IMethodClass
{
/// <summary>
/// Метод возвращает Короткую запись ФИО типа «Иванов И.И.»
/// </summary>
/// <param name="Name">Имя</param>
/// <param name="surname">Фамилия</param>
/// <param name="patronymic">Отчество</param>
/// <returns></returns>
string GetInitials(string Name, string surname, string patronymic);
/// <summary>
/// Метод конвертирования телефона в единый числовой формат
/// </summary>
/// <param name="number">Номер телефона</param>
/// <returns></returns>
int GetMobilePhoneNumber(string number);
/// <summary>
/// метод преобразования контента в хеш
/// </summary>
/// <param name="content">контент</param>
/// <param name="has">вид хеширования</param>
/// <returns></returns>
string GetHash(string content , TypeHas has) ;
/// <summary>
/// конвертер продажи валют банку
/// </summary>
/// <param name="cash"></param>
/// <param name="currency">валюта '$' or '€'</param>
/// <returns></returns>
double ConvertCurrency(double cash, char currency );
/// <summary>
/// Растояние до детского сада
/// </summary>
/// <param name="xColumn"> координата дома </param>
/// <param name="xRow"> координата дома </param>
/// <returns></returns>
double DistanceToKindergarten(int xRow, int xColumn);
/// <summary>
/// Возвращает колл-во полных лет
/// </summary>
/// <param name="DateOfBirth">дата рождения</param>
/// <returns></returns>
int GetAge(DateTime DateOfBirth);
/// <summary>
/// возмедение числа в степень
/// </summary>
/// <param name="x">число</param>
/// <param name="stepen">степень</param>
/// <returns></returns>
int GetPow(int x , int stepen);
/// <summary>
/// Ход конем
/// </summary>
/// <param name="chessCellStart">стартовая позиция </param>
/// <param name="ChessCellEnd">планируемый ход </param>
/// <returns></returns>
bool HorseRide(ChessCell chessCellStart, ChessCell ChessCellEnd);
}
public class MethodClass : IMethodClass
{
}
public struct ChessBoard
{
public List<ChessCell> chessCells { get; set; }
}
public struct ChessCell
{
public char C { get; set; }
public int I { get; set; }
public char Color { get; set; }
public Figure figure { get; set; }
}
public struct Figure
{
public char Name { get; set; }
public char Color { get; set; }
}
}
|
968e1020b789eef69d934abda1925187aadd19d4
|
C#
|
Andrey1916/BookStoreWebApi
|
/BookStoreWebApp/Services/Dtos/Review.cs
| 2.59375
| 3
|
using BookStoreWebApp.DAL.Interfaces;
using FluentValidation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BookStoreWebApp.Services.Dtos
{
public class Review
{
public Guid Id { get; set; }
public string VoterName { get; set; }
public uint NumStars { get; set; }
public string Comment { get; set; }
public Guid BookId { get; set; }
}
public class ReviewValidator : AbstractValidator<Review>
{
public ReviewValidator()
{
this.RuleFor(x => x.Id).NotEqual(Guid.Empty);
this.RuleFor(x => x.VoterName).MaximumLength(50);
this.RuleFor(x => x.BookId).NotEqual(Guid.Empty);
}
}
}
|
c8299920eb9984c7c16898d8d3180d5370af1f00
|
C#
|
OneYoungMean/NeuralTank
|
/Assets/NeuralEvolutionaryBots/Examples/SelfDrivingCar/Scripts/ConsecutiveGeneration.cs
| 2.59375
| 3
|
using System.Collections;
using UnityEngine;
namespace EvolutionaryPerceptron.Examples.SelfDrivingCar
{
using EvolutionaryPerceptron.MendelMachine;
public class ConsecutiveGeneration : MendelMachine
{
[Header("Consecutive data")]
public Transform startPoint;
public float lifeTime;
[Header("Indicators")]
[SerializeField] int index;
protected override void Start()
{
base.Start();
index = 0;
StartCoroutine(InstantiateBotCoroutine(0.3f));
}
public override void NeuralBotDestroyed(Brain neuralBot)
{
base.NeuralBotDestroyed(neuralBot);
Destroy(neuralBot.gameObject);
index++;
if (index < individualsPerGeneration)
{
StartCoroutine(InstantiateBotCoroutine(0.3f));
}
else
{
index = 0; generation++;
Save();
population = Mendelization();
StartCoroutine(InstantiateBotCoroutine(1));
}
}
IEnumerator InstantiateBotCoroutine(float time)
{
yield return new WaitForSeconds(time);
InstantiateBot(population[index], lifeTime, startPoint, index);
}
}
}
|
25630011ee59635364e7c1487f3e5d87984e26fd
|
C#
|
luhan/bhxy3
|
/MoleMole/FaceEffect.cs
| 2.84375
| 3
|
namespace MoleMole
{
using System;
using UnityEngine;
public class FaceEffect
{
private MonoFaceEffect _effect;
private GameObject GetEffectByName(string name)
{
int index = 0;
int length = this._effect.items.Length;
while (index < length)
{
if (this._effect.items[index].name == name)
{
return this._effect.items[index].effect;
}
index++;
}
return null;
}
public void HideAll()
{
int index = 0;
int length = this._effect.items.Length;
while (index < length)
{
this._effect.items[index].effect.SetActive(false);
index++;
}
}
public void HideEffect(string name)
{
GameObject effectByName = this.GetEffectByName(name);
if (effectByName != null)
{
effectByName.SetActive(false);
}
}
public void Init(MonoFaceEffect effect)
{
this._effect = effect;
}
public void ShowEffect(string name)
{
GameObject effectByName = this.GetEffectByName(name);
if (effectByName != null)
{
effectByName.SetActive(true);
}
}
public void Uninit()
{
if (this._effect != null)
{
UnityEngine.Object.Destroy(this._effect.gameObject);
this._effect = null;
}
}
}
}
|
d9304d90be5848d33f1b7b0cc1798e4ce89fc37b
|
C#
|
SallyWW/Cash-Exchange-App
|
/TenmoClient/UserInterface.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using TenmoClient.APIClients;
using TenmoClient.Data;
namespace TenmoClient
{
public class UserInterface
{
private readonly ConsoleService consoleService = new ConsoleService();
private readonly AuthService authService = new AuthService();
private readonly AccountService accountService = new AccountService();
private bool quitRequested = false;
public void Start()
{
while (!quitRequested)
{
while (!authService.IsLoggedIn)
{
ShowLogInMenu();
}
// If we got here, then the user is logged in. Go ahead and show the main menu
ShowMainMenu();
}
}
private void ShowLogInMenu()
{
Console.WriteLine("Welcome to TEnmo!");
Console.WriteLine("1: Login");
Console.WriteLine("2: Register");
Console.Write("Please choose an option: ");
if (!int.TryParse(Console.ReadLine(), out int loginRegister))
{
Console.WriteLine("Invalid input. Please enter only a number.");
}
else if (loginRegister == 1)
{
HandleUserLogin();
}
else if (loginRegister == 2)
{
HandleUserRegister();
}
else
{
Console.WriteLine("Invalid selection.");
}
}
private void ShowMainMenu()
{
int menuSelection;
do
{
Console.WriteLine();
Console.WriteLine("Welcome to TEnmo! Please make a selection: ");
Console.WriteLine("1: View your current balance");
Console.WriteLine("2: View your past transfers");
Console.WriteLine("3: View your pending requests");
Console.WriteLine("4: Send TE bucks");
Console.WriteLine("5: Request TE bucks");
Console.WriteLine("6: Log in as different user");
Console.WriteLine("0: Exit");
Console.WriteLine("---------");
Console.Write("Please choose an option: ");
if (!int.TryParse(Console.ReadLine(), out menuSelection))
{
Console.WriteLine("Invalid input. Please enter only a number.");
}
else
{
switch (menuSelection)
{
case 1: // View Balance
ViewBalance();
break;
case 2: // View Past Transfers
ViewPastTransfers();
break;
case 3: // View Pending Requests
Console.WriteLine("NOT IMPLEMENTED!"); // TODO: Implement me
break;
case 4: // Send TE Bucks
SendTEBucks();
break;
case 5: // Request TE Bucks
Console.WriteLine("NOT IMPLEMENTED!"); // TODO: Implement me
break;
case 6: // Log in as someone else
Console.WriteLine();
UserService.ClearLoggedInUser(); //wipe out previous login info
return; // Leaves the menu and should return as someone else
case 0: // Quit
Console.WriteLine("Goodbye!");
quitRequested = true;
return;
default:
Console.WriteLine("That doesn't seem like a valid choice.");
break;
}
}
} while (menuSelection != 0);
}
private void HandleUserRegister()
{
bool isRegistered = false;
while (!isRegistered) //will keep looping until user is registered
{
LoginUser registerUser = consoleService.PromptForLogin();
isRegistered = authService.Register(registerUser);
}
Console.WriteLine("");
Console.WriteLine("Registration successful. You can now log in.");
}
private void HandleUserLogin()
{
while (!UserService.IsLoggedIn) //will keep looping until user is logged in
{
LoginUser loginUser = consoleService.PromptForLogin();
API_User user = authService.Login(loginUser);
if (user != null)
{
UserService.SetLogin(user);
}
}
}
private void ViewBalance()
{
decimal balance = accountService.GetBalance(UserService.UserId, UserService.Token);
Console.WriteLine($"Your current account balance is: {balance.ToString("C")}");
}
private void SendTEBucks()
{
List<API_User> users = accountService.GetUsers(UserService.Token);
Console.WriteLine("-------------------------------------------");
Console.WriteLine("Users");
Console.WriteLine("ID Name ");
Console.WriteLine("-------------------------------------------");
foreach (API_User user in users)
{
Console.WriteLine($"{user.UserId}".PadRight(12) + $"{user.Username}".PadRight(31));
}
Console.WriteLine("---------");
Console.WriteLine();
Console.WriteLine("Enter ID of user you are sending to (0 to cancel): ");
int transferToUserId = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter amount: ");
decimal amountToTransfer = Convert.ToDecimal(Console.ReadLine());
bool success = accountService.SendTransfer(UserService.Token, UserService.UserId, transferToUserId, amountToTransfer);
}
private void ViewPastTransfers()
{
List<API_TransferDetails> transfers = accountService.GetTransfers(UserService.Token);
Console.WriteLine("-------------------------------------------");
Console.WriteLine("Transfers");
Console.WriteLine("ID From/To Amount");
Console.WriteLine("-------------------------------------------");
foreach (API_TransferDetails transfer in transfers)
{
string columnOne = transfer.TransferId.ToString().PadRight(12);
string columnTwo;
if (UserService.UserId == transfer.ToUserId)
{
columnTwo = $"From: {transfer.FromUsername}".PadRight(23);
}
else
{
columnTwo = $"To: {transfer.ToUserName}".PadRight(23);
}
string columnThree = transfer.TransferAmount.ToString("C").PadLeft(7);
Console.WriteLine(columnOne + columnTwo + columnThree);
}
Console.WriteLine("---------");
Console.WriteLine("Please enter transfer ID to view details(0 to cancel): ");
int transferDetailsId = Convert.ToInt32(Console.ReadLine());
foreach (API_TransferDetails transferdetail in transfers)
{
if (transferDetailsId == transferdetail.TransferId)
{
Console.WriteLine("--------------------------------------------");
Console.WriteLine("Transfer Details");
Console.WriteLine("--------------------------------------------");
Console.WriteLine($"ID: {transferdetail.TransferId}");
Console.WriteLine($"From: {transferdetail.FromUsername}");
Console.WriteLine($"To: {transferdetail.ToUserName}");
Console.WriteLine($"Type: {transferdetail.Type}");
Console.WriteLine($"Status: {transferdetail.Status}");
Console.WriteLine($"Amount: {transferdetail.TransferAmount}");
}
}
}
}
}
|
fde310063ecf223ecbaaf604dec014edeeb644ab
|
C#
|
CougTech/CustomerLogger
|
/CustomerLogger/CSVWriter.cs
| 3.640625
| 4
|
using System.IO;
namespace CSV
{
/// <summary>
/// Handler for the logger file
/// </summary>
public class CSVWriter
{
// Members ///////////////////////////////////////////////////////////////////////////////
private string m_sLine, m_sFileName;
private FileStream m_fStream;
private StreamWriter m_sWriter;
// Constructors ///////////////////////////////////////////////////////////////////////
/// <summary>
/// Custom Constructor
/// </summary>
/// <param name="sFileName">CSV File to write to</param>
/// <param name="mode">How to initially handle file, Create will delete an existing file. Append will not.</param>
public CSVWriter(string sFileName, FileMode mode)
{
m_sLine = "";
m_sFileName = sFileName;
//If the file mode is Create
if (mode == FileMode.Create)
{
if (File.Exists(m_sFileName)) //If the file exists
File.Delete(m_sFileName); //Delete the file
}
}
// Public Functions ///////////////////////////////////////////////////////////////////
/// <summary>
/// Appends a string to the end of the current line as a new CSV cell
/// </summary>
/// <param name="sText">String to append.</param>
public void AddToCurrent(string sText)
{
if (m_sLine == "") //If the line is blank
m_sLine = sText; //Add the string to the beginnging
else //Else
m_sLine += ("," + sText); //Append the string to the end of the line as a new CSV cell
}
/// <summary>
/// Appends a string to the beginning of the current line as a new CSV cell
/// </summary>
/// <param name="sText">String to append.</param>
public void AddToStart(string sText)
{
if (m_sLine == "")
m_sLine = sText;
else
m_sLine = sText + "," + m_sLine;
}
/// <summary>
/// Opens the logger file and appends the current line. Closes the file when finished.
/// </summary>
/// <remarks>
/// The file opened is specified by m_sFileName. The line appended is m_sLine.
/// </remarks>
public void WriteLine()
{
//Create filestream and write line to the file
using (m_fStream = new FileStream(m_sFileName, FileMode.Append))
{
using (m_sWriter = new StreamWriter(m_fStream))
m_sWriter.WriteLine(m_sLine);
}
m_sLine = "";
}
}
}
|
dbebe8bab64d5ea4346f5e4344aa27c8c5fbc0a3
|
C#
|
ake698/Diary_Plus
|
/Diary/Extensions/AutoMapperExt.cs
| 2.515625
| 3
|
using AutoMapper;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Reflection;
namespace Diary.Extensions
{
public static class AutoMapperExt
{
public static void AddAutoMapperAssembly(this IServiceCollection services, string assemblyName)
{
Assembly assembly = Assembly.Load(assemblyName);
var classes = assembly.GetTypes().ToList().Where(s => !s.IsInterface && s.Name.EndsWith("Profiles", StringComparison.OrdinalIgnoreCase));
foreach (var c in classes)
{
services.AddAutoMapper(c);
}
//services.AddAutoMapper()
}
}
}
|
d1df0d396a63b07d41c7b59026c99f785ea2fc17
|
C#
|
evilz/soat-challenge
|
/src/DroneDeliverySystem/DroneDeliverySystem/Drone.cs
| 3.125
| 3
|
using System.Collections.Generic;
using System.Drawing;
namespace DroneDeliverySystem
{
public class Drone
{
public Drone(Point position, int ttl)
{
_ttl = ttl;
Position = position;
}
private int _ttl;
public Point Position { get; private set; }
public int TargetReach { get; private set; }
public bool CanMoveTo(Path target)
{
return _ttl >= target.Distance;
}
public List<Moves> Moves { get; } = new List<Moves>();
public bool IsAlive { get; set; } = true;
public void MoveToTarget(Path target)
{
Moves.AddRange(target.GetXMoves);
Moves.AddRange(target.GetYMoves);
TargetReach++;
_ttl -= target.Distance;
Position = target.Destination;
}
}
}
|
6f58e8bd634ae8757c70005ca67f0afeb0ce4865
|
C#
|
StoyanMStoyanov/SoftUni-Projects
|
/CSharp Advanced - 04.05.2015/2. MultidimensionalArrays-Sets-Dictionaries/2. Maximal sum/MaximalSum.cs
| 3.84375
| 4
|
using System;
class MaximalSum
{
static void Main()
{
string[] sizes = Console.ReadLine().Split(new string[]{" "},
StringSplitOptions.RemoveEmptyEntries);
int n = int.Parse(sizes[0]);
int m = int.Parse(sizes[1]);
int[,] matrix = new int[n,m];
FillTheMatrix(matrix);
int sizeX = 3;
int sizeY = 3;
int row = 0;
int col = 0;
int sum = 0;
int bestSum = 0;
for (int i = 0; i <= matrix.GetLength(0) - sizeX; i++)
{
for (int j = 0; j <= matrix.GetLength(1) - sizeY; j++)
{
sum = CalculateSubmatrixSum(matrix, i, j, sizeX);
if (bestSum < sum)
{
bestSum = sum;
row = i;
col = j;
}
}
}
Console.Clear();
Console.WriteLine("Sum = {0}", bestSum);
for (int i = row; i < row + 3; i++)
{
for (int j = col; j < col + 3; j++)
Console.Write("{0, 4}", matrix[i, j]);
Console.WriteLine();
}
}
private static int CalculateSubmatrixSum(int[,] matrix, int row, int col, int subMatrixLength)
{
int tempSum = 0;
for (int i = row; i < row + subMatrixLength; i++)
for (int j = col; j < col + subMatrixLength; j++)
tempSum += matrix[i, j];
return tempSum;
}
private static void FillTheMatrix(int[,] matrix)
{
for (int row = 0; row < matrix.GetLength(0); row++)
{
string[] inputRow = Console.ReadLine().Split(new string[]{" "},
StringSplitOptions.RemoveEmptyEntries);
for (int col = 0; col < matrix.GetLength(1); col++)
matrix[row, col] = int.Parse(inputRow[col]);
}
}
}
|
bbfd1925961e71f4c3a2345877f6be71d77f1165
|
C#
|
zkSNACKs/WalletWasabi
|
/WalletWasabi/Helpers/PowerSaving/WindowsPowerAvailabilityTask.cs
| 2.59375
| 3
|
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using WalletWasabi.Logging;
namespace WalletWasabi.Helpers.PowerSaving;
[SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Windows API has its own naming style. Changes would be rather detrimental here.")]
public class WindowsPowerAvailabilityTask : IPowerSavingInhibitorTask
{
private const int POWER_REQUEST_CONTEXT_VERSION = 0;
private const int POWER_REQUEST_CONTEXT_SIMPLE_STRING = 0x1;
[SuppressMessage("CodeQuality", "IDE0051:Remove unused private members", Justification = "Not used at the moment.")]
private const int POWER_REQUEST_CONTEXT_DETAILED_STRING = 0x2;
private readonly POWER_REQUEST_CONTEXT _context;
/// <summary>Handle.</summary>
private readonly IntPtr _request;
/// <remarks>Guarded by <see cref="StateLock"/>.</remarks>
private bool _isDone;
internal WindowsPowerAvailabilityTask(PowerRequestType requestType, string reason)
{
RequestType = requestType;
// Set up the diagnostic string
_context.Version = POWER_REQUEST_CONTEXT_VERSION;
_context.Flags = POWER_REQUEST_CONTEXT_SIMPLE_STRING;
_context.SimpleReasonString = reason;
_request = PowerCreateRequest(ref _context);
// Set the request
if (!PowerSetRequest(_request, requestType))
{
Logger.LogError($"Failed to set availability request (last Win32 error: {Marshal.GetLastWin32Error()}).");
throw new NotImplementedException("Failed to set the availability request. Bailing out.");
}
}
/// <summary>Availability Request Enumerations and Constants</summary>
/// <seealso href="https://superuser.com/questions/1181186/power-request-types-whats-the-difference-between-display-system-awaymode-p"/>
public enum PowerRequestType
{
/// <summary>The display remains on even if there is no user input for an extended period of time.</summary>
PowerRequestDisplayRequired = 0,
/// <summary>The system continues to run instead of entering sleep after a period of user inactivity.</summary>
PowerRequestSystemRequired = 1,
/// <summary>The system enters away mode instead of sleep in response to explicit action by the user.</summary>
/// <remarks>In away mode, the system continues to run but turns off audio and video to give the appearance of sleep.</remarks>
PowerRequestAwayModeRequired = 2,
/// <summary>The calling process continues to run instead of being suspended or terminated by process lifetime management mechanisms.</summary>
/// <remarks>When and how long the process is allowed to run depends on the operating system and power policy settings.</remarks>
PowerRequestExecutionRequired = 3
}
/// <remarks>Guards <see cref="_isDone"/>.</remarks>
private object StateLock { get; } = new();
public PowerRequestType RequestType { get; }
/// <inheritdoc/>
public bool IsDone
{
get
{
lock (StateLock)
{
return _isDone;
}
}
}
/// <summary>Creates a new power request object.</summary>
/// <seealso href="https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-powercreaterequest"/>
[DllImport("kernel32.dll")]
private static extern IntPtr PowerCreateRequest(ref POWER_REQUEST_CONTEXT Context);
/// <summary>Increments the count of power requests of the specified type for a power request object.</summary>
/// <returns>If the function succeeds, it returns a nonzero value. If the function fails, it returns zero.</returns>
/// <remarks>To get extended error information, call GetLastError.</remarks>
/// <seealso href="https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-powersetrequest"/>
[DllImport("kernel32.dll")]
private static extern bool PowerSetRequest(IntPtr PowerRequestHandle, PowerRequestType RequestType);
/// <seealso href="https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-powerclearrequest"/>
[DllImport("kernel32.dll")]
private static extern bool PowerClearRequest(IntPtr PowerRequestHandle, PowerRequestType RequestType);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
internal static extern int CloseHandle(IntPtr hObject);
/// <remarks>
/// Windows defines the POWER_REQUEST_CONTEXT structure with an internal union of <c>SimpleReasonString</c> and Detailed information.
/// <para>To avoid runtime interop issues, this version of POWER_REQUEST_CONTEXT only supports <c>SimpleReasonString</c>.</para>
/// <para>To use the detailed information, define the PowerCreateRequest function with the first parameter of type POWER_REQUEST_CONTEXT_DETAILED.</para>
/// </remarks>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct POWER_REQUEST_CONTEXT
{
public uint Version;
public uint Flags;
[MarshalAs(UnmanagedType.LPWStr)]
public string SimpleReasonString;
}
[StructLayout(LayoutKind.Sequential)]
public struct PowerRequestContextDetailedInformation
{
public IntPtr LocalizedReasonModule;
public uint LocalizedReasonId;
public uint ReasonStringCount;
[MarshalAs(UnmanagedType.LPWStr)]
public string[] ReasonStrings;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct POWER_REQUEST_CONTEXT_DETAILED
{
public uint Version;
public uint Flags;
public PowerRequestContextDetailedInformation DetailedInformation;
}
/// <param name="reason">Your reason for changing the power settings.</param>
public static WindowsPowerAvailabilityTask Create(string reason)
{
WindowsPowerAvailabilityTask task = new(PowerRequestType.PowerRequestExecutionRequired, reason);
return task;
}
/// <inheritdoc/>
public bool Prolong(TimeSpan timeSpan)
{
// Do nothing.
return true;
}
/// <seealso href="https://docs.microsoft.com/en-us/windows/win32/api/handleapi/nf-handleapi-closehandle"/>
/// <inheritdoc/>
public Task StopAsync()
{
bool isDone;
lock (StateLock)
{
isDone = _isDone;
_isDone = true;
}
if (!isDone)
{
Logger.LogTrace("Clear the power request.");
PowerClearRequest(_request, RequestType);
if (CloseHandle(_request) == 0)
{
// This should never happen.
Logger.LogError($"Failed to close handle (last Win32 error: {Marshal.GetLastWin32Error()}).");
}
}
else
{
Logger.LogTrace("Task is already stopped.");
}
return Task.CompletedTask;
}
}
|
6ff54ba4bff9a8a9bd27574169470c0c7be1629c
|
C#
|
Kousuke9000900/LeetCode
|
/RomanToInteger/RomanToInteger/Program.cs
| 4
| 4
|
using System;
using System.Collections.Generic;
namespace RomanToInteger
{
class Program
{
static void Main(string[] args)
{
String s;
int answer;
Console.WriteLine("ローマ数字を入力して下さい");
s = Console.ReadLine();
Program program = new Program();
answer = program.RomanToInt(s);
Console.WriteLine("結果は" + answer + "でした。処理を終了します。");
Console.ReadKey();
}
/// <summary>
/// ローマ数字を算用数字に変換
/// </summary>
/// <param name='s'>ローマ数字</param>
/// <returns>算用数字</returns>
public int RomanToInt(string s)
{
int answer = 0; // 変換結果
// 変換用のリストを作成(辞書型)
Dictionary<char, int> RomanToIntList = new Dictionary<char, int>();
RomanToIntList.Add('I', 1);
RomanToIntList.Add('V', 5);
RomanToIntList.Add('X', 10);
RomanToIntList.Add('L', 50);
RomanToIntList.Add('C', 100);
RomanToIntList.Add('D', 500);
RomanToIntList.Add('M', 1000);
// 引数を一文字ずつに分解
List<char> Roman = new List<char>();
foreach (char c in s)
{
Roman.Add(c);
}
// 1文字のみは計算不要
if (Roman.Count == 1)
{
answer = RomanToIntList[Roman[0]];
return answer;
}
// 加算(Iの次がVかX,Xの次がLかC,Cの次がDかMなら、符号を反転)
for (int i = 0; i < Roman.Count; i++)
{
if(i != Roman.Count - 1) // リストの最後か否か
{
if (Roman[i].Equals('I') && (Roman[i + 1].Equals('V') || Roman[i + 1].Equals('X')))
answer += RomanToIntList[Roman[i]] * -1; // 符号反転
else if (Roman[i].Equals('X') && (Roman[i + 1].Equals('L') || Roman[i + 1].Equals('C')))
{
answer += RomanToIntList[Roman[i]] * -1;
}
else if (Roman[i].Equals('C') && (Roman[i + 1].Equals('D') || Roman[i + 1].Equals('M')))
{
answer += RomanToIntList[Roman[i]] * -1;
}
else
{
answer += RomanToIntList[Roman[i]];
}
}
else
{
answer += RomanToIntList[Roman[i]];
}
}
return answer;
}
}
}
|
5cfb2f58d9c9f05fd3df34ec8d1b0d5c3313f0ab
|
C#
|
manlsc/ESC.Core
|
/Helper/CheckHelper.cs
| 3.328125
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace ESC.Core
{
/// <summary>
/// 验证帮助类
/// </summary>
public class CheckHelper
{
/// <summary>
/// 非空验证
/// </summary>
/// <param name="argument">待验证字符串</param>
/// <param name="argumentName">变量名称</param>
public static void IsNotEmpty(string argument, string argumentName)
{
if (string.IsNullOrEmpty((argument ?? string.Empty).Trim()))
{
throw new ArgumentException(argumentName + " 不能为空.", argumentName);
}
}
/// <summary>
/// 长度验证
/// </summary>
/// <param name="argument">字符串</param>
/// <param name="length">最大长度</param>
/// <param name="argumentName"></param>
public static void IsNotOutOfLength(string argument, int length, string argumentName)
{
if (argument.Trim().Length > length)
{
throw new ArgumentException(argumentName + " 长度不能大于 " + length + " 字节.", argumentName);
}
}
/// <summary>
/// 非空验证
/// </summary>
/// <param name="argument"></param>
/// <param name="argumentName"></param>
public static void IsNotNull(object argument, string argumentName)
{
if (argument == null)
{
throw new ArgumentNullException(argumentName);
}
}
/// <summary>
/// 非负数验证
/// </summary>
/// <param name="argument"></param>
/// <param name="argumentName"></param>
public static void IsNotNegative(int argument, string argumentName)
{
if (argument < 0)
{
throw new ArgumentOutOfRangeException(argumentName);
}
}
/// <summary>
/// 非负数验证
/// </summary>
/// <param name="argument"></param>
/// <param name="argumentName"></param>
public static void IsNotNegative(long argument, string argumentName)
{
if (argument < 0)
{
throw new ArgumentOutOfRangeException(argumentName);
}
}
/// <summary>
/// 非负数验证
/// </summary>
/// <param name="argument"></param>
/// <param name="argumentName"></param>
public static void IsNotNegative(float argument, string argumentName)
{
if (argument < 0)
{
throw new ArgumentOutOfRangeException(argumentName);
}
}
/// <summary>
/// 验证时间是否合法
/// </summary>
/// <param name="argument"></param>
/// <param name="argumentName"></param>
public static void IsNotInvalidDate(DateTime argument, string argumentName)
{
if (!argument.IsValid())
{
throw new ArgumentOutOfRangeException(argumentName);
}
}
/// <summary>
/// 如果小于当前时间抛出异常
/// </summary>
/// <param name="argument"></param>
/// <param name="argumentName"></param>
public static void IsNotInPast(DateTime argument, string argumentName)
{
if (argument < DateTime.UtcNow)
{
throw new ArgumentOutOfRangeException(argumentName);
}
}
/// <summary>
/// 如果大于当前时间抛出异常
/// </summary>
/// <param name="argument"></param>
/// <param name="argumentName"></param>
public static void IsNotInFuture(DateTime argument, string argumentName)
{
if (argument > DateTime.UtcNow)
{
throw new ArgumentOutOfRangeException(argumentName);
}
}
/// <summary>
/// 非空集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="argument"></param>
/// <param name="argumentName"></param>
public static void IsNotEmpty<T>(ICollection<T> argument, string argumentName)
{
IsNotNull(argument, argumentName);
if (argument.Count == 0)
{
throw new ArgumentException("集合不能为空.", argumentName);
}
}
/// <summary>
/// 区间验证
/// </summary>
/// <param name="argument"></param>
/// <param name="min"></param>
/// <param name="max"></param>
/// <param name="argumentName"></param>
public static void IsNotOutOfRange(int argument, int min, int max, string argumentName)
{
if ((argument < min) || (argument > max))
{
throw new ArgumentOutOfRangeException(argumentName, argumentName + "必须在" + min + "-" + max + "之间");
}
}
}
}
|
fc4f158f6e8984185e512b65e4afcff6b33cddb2
|
C#
|
VanchoDimitrov/ParallelProgrammingWithCSharp
|
/19.PLINQ-Introduction/Program.cs
| 3.46875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace _19.PLINQ_Introduction
{
class Program
{
static void Main(string[] args)
{
//Parallel LINQ or PLINQ is a parallel implementation of the Language-Integrated Query or LINQ pattern.
// 1. Data Source
var numbers = new List<int>();
for (int i = 0; i < 1000; i++)
{
numbers.Add(i);
}
// 2. Query
// sequential processing
var query0 = from n in numbers
select n;
//parallel processing
var query1 = from n in numbers.AsParallel()
select n;
var query2 = (from n in numbers.AsParallel()
select n).ToList();
var query3 = (from n in numbers
select n).ToList().AsParallel();
// method query
var query4 = numbers.AsParallel().AsOrdered();
// 3. Execution
foreach (var i in query4)
Console.WriteLine(i);
Console.ReadKey();
}
}
}
|
dc124308e8ef93cb53670f41bb349b7d17c607d3
|
C#
|
YHDF/WebProject
|
/Controllers/AuthController.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using System.Threading.Tasks;
using EFTechCommerce.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using WebApi.Entities;
using WebApi.Models;
namespace WebApi.Controllers
{
[ApiController]
public class AuthController : ControllerBase
{
private readonly ILogger<AuthController> _logger;
public AuthController(ILogger<AuthController> logger)
{
_logger = logger;
}
private static string GenerateToken()
{
var chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var stringChars = new char[64];
var random = new Random();
for (int i = 0; i < stringChars.Length; i++)
{
stringChars[i] = chars[random.Next(chars.Length)];
}
var finalString = new String(stringChars);
return finalString;
}
[HttpPost]
[Route("login")]
public User Login(User user)
{
UserDAO usr = new UserDAO();
User userInfo = usr.GetUser(user.Email);
string userMail = userInfo.Email;
string userPswd = userInfo.Password;
Console.WriteLine(userMail);
Console.WriteLine(user.Email);
Console.WriteLine(user.Password);
Console.WriteLine(userPswd);
string token = "";
if (
userMail == user.Email && user.Password == userPswd) // Check mail & pswd
{
token = "GeneratedToken";
usr.InsertToken (userMail, token);
}
User returneduser = new User(userMail, "", token);
return returneduser;
}
/*[HttpPost]
[Route("logout")]
public User Logout(User user)
{
UserDAO usr = new UserDAO();
usr.InsertToken(user.Email, ""); // Destroy the token
}*/
[HttpGet]
[Route("gettoken")]
public User GetToken(string email)
{
UserDAO usr = new UserDAO();
User userInfo = usr.GetUser(email);
Console.WriteLine("this is : " + userInfo.Token);
return userInfo;
}
}
}
|
4368ff290ec87fec7e563256f201728556cb78ce
|
C#
|
jerryguo255/IT722_algo
|
/PrimsMST/Program.cs
| 3
| 3
|
using Priority_Queue;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrimsMST
{
class Program
{
static void Main(string[] args)
{
//Random r = new Random();
//int num = 10;
//int weight = num;
//SimplePriorityQueue<WeightedVertex> pqlist = new SimplePriorityQueue<WeightedVertex>();
//List<WeightedVertex> Wlist = new List<WeightedVertex>();
//for (int i = 0; i < num; i++)
//{
// Wlist.Add(new WeightedVertex(i));
//}
//foreach (var item in Wlist)
//{
// Console.WriteLine(item);
//}
//pqlist.Enqueue(Wlist[2],3);
//pqlist.Enqueue(Wlist[2],1);
//pqlist.Enqueue(Wlist[5],2);
//Console.WriteLine("==============");
//while (pqlist.Count !=0)
//{
// var xxx = pqlist.Dequeue();
// Console.WriteLine(xxx);
//}
////foreach (var item in pq)
////{
//// Console.WriteLine(item);
////}
//Console.ReadLine();
////===========================
Program p = new Program();
var LoadedList = p.CreateNLoad_WeightedVertex();
Console.WriteLine(p.Cal_LeastCostViaPrimsMST(LoadedList));
Console.ReadLine();
// Console.ReadKey();
}
int Cal_LeastCostViaPrimsMST(List<WeightedVertexForPMST> LoadVList)
{
var PQ = new SimplePriorityQueue<WeightedVertexForPMST>();
PQ.Enqueue(LoadVList[0], LoadVList[0].KeyValue=0);
while (PQ.Count != 0)
{
var processingV = PQ.Dequeue();
processingV.Visited = true;
for (int i = 0; i < processingV.adjs.Count; i++)
{
var theAdj = processingV.adjs[i];
if (!theAdj.Visited)
{
var edgeWeight_ForTheAdjAndProcessingV = processingV.AdjWeightPair[theAdj.Id];
if (edgeWeight_ForTheAdjAndProcessingV < theAdj.KeyValue)
{
theAdj.KeyValue = edgeWeight_ForTheAdjAndProcessingV;
theAdj.Parent = processingV.Id;
PQ.Enqueue(theAdj, theAdj.KeyValue);
}
}
}
}
int total = 0;
foreach (var item in LoadVList)
{
total += item.KeyValue;
}
return total;
}
List<WeightedVertexForPMST> CreateNLoad_WeightedVertex()
{
// StreamReader stdin = new StreamReader("..\\..\\input.txt");
// Console.SetIn(stdin);//standard input from txt file
string input = Console.ReadLine();
string[] words = input.Split(' ');
int VertexNum = int.Parse(words[0]);//get the number of Vertex
int EdgeNum = int.Parse(words[1]); //get the number of Edge
List<WeightedVertexForPMST> WVlist = new List<WeightedVertexForPMST>();
for (int i = 1; i < VertexNum + 1; i++)
{
WVlist.Add(new WeightedVertexForPMST(i));
}//init empty vertexList
//load adjs and weight
for (int i = 0; i < EdgeNum; i++)
{
words = Console.ReadLine().Split(' ');
int vertexId = int.Parse(words[0]);
int adjID = int.Parse(words[1]);
int edgeWeight = int.Parse(words[2]);
WVlist[vertexId - 1].AddneighbourWithWeight(WVlist[adjID - 1], edgeWeight);
}
//foreach (var item in WVlist)
//{
// Console.WriteLine(item);
//}
return WVlist;
}
}
}
|
0f83c2ffdf5f35089956ff120a5b5553e11272b2
|
C#
|
definedD4/BacterySim
|
/BacterySim/Simulation/Bactery.cs
| 2.84375
| 3
|
using System;
using System.Windows.Media;
namespace BacterySim.Simulation
{
public class Bactery
{
public double Size { get; set; } = 1.0d;
public double Energy { get; set; } = 0.0d;
public double FoodAbsorbtionRatePerSize { get; set; } = 0.05d;
public double EnergyUsageRatePerSize { get; set; } = 0.005d;
public IBacteryWatch Watch { get; set; }
public void Update(TimeSpan delta, SimulationProperties properties)
{
double sec = delta.TotalSeconds;
double deltaFood = Math.Min(FoodAbsorbtionRatePerSize * Size * properties.Food * sec, properties.Food);
Energy += deltaFood;
Energy -= EnergyUsageRatePerSize * Size;
properties.Food -= deltaFood;
}
public bool CanSplit => Energy > Size * 5d;
public Tuple<Bactery, Bactery> Split()
{
return Tuple.Create(
new Bactery {Size = NewRadius(Size), Energy = NewEnergy(Energy)},
new Bactery {Size = NewRadius(Size), Energy = NewEnergy(Energy) }
);
}
private double NewRadius(double oldRadius)
{
return oldRadius + GlobalRandom.NextDouble() * 0.7d;
}
private double NewEnergy(double oldEnergy)
{
return oldEnergy / 2.0d - Size * 0.05d;
}
}
}
|
6fe6580b5beae7a9cf96bd2563f2a6a61486baa4
|
C#
|
Sarmaad/Saxx.Storyblok
|
/src/Saxx.Storyblok/StoryblokStory.cs
| 2.8125
| 3
|
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace Saxx.Storyblok
{
public class StoryblokStory<T> : StoryblokStory where T : StoryblokComponent
{
public StoryblokStory(StoryblokStory story)
{
if (story == null)
{
return;
}
Name = story.Name;
Slug = story.Slug;
FullSlug = story.FullSlug;
CreatedAt = story.CreatedAt;
PublishedAt = story.PublishedAt;
FirstPublishedAt = story.FirstPublishedAt;
Id = story.Id;
Uuid = story.Uuid;
var castContent = story.Content as T;
Content = castContent ?? throw new Exception($"A component of type \"{story.Content.GetType()}\" cannot be cast to \"{typeof(T)}\"");
}
[JsonPropertyName("content")] public new T Content { get; set; }
}
public class StoryblokStory
{
[JsonPropertyName("name")] public string Name { get; set; }
[JsonPropertyName("slug")] public string Slug { get; set; }
[JsonPropertyName("full_slug")] public string FullSlug { get; set; }
[JsonPropertyName("created_at")] public DateTime CreatedAt { get; set; }
[JsonPropertyName("published_at")] public DateTime? PublishedAt { get; set; }
[JsonPropertyName("first_published_at")]
public DateTime? FirstPublishedAt { get; set; }
[JsonPropertyName("id")] public int Id { get; set; }
[JsonPropertyName("uuid")] public Guid Uuid { get; set; }
[JsonPropertyName("content")] public StoryblokComponent Content { get; set; }
public DateTime LoadedAt { get; set; }
public override string ToString()
{
return FullSlug;
}
}
public class StoryblokStoriesContainer
{
[JsonPropertyName("stories")] public IEnumerable<StoryblokStory> Stories { get; set; }
}
public class StoryblokStoryContainer
{
[JsonPropertyName("story")] public StoryblokStory Story { get; set; }
}
}
|
5c2ca97a335baa73271450591f47698362cb6804
|
C#
|
Brian-McG/Poppel
|
/Poppel/Poppel/Order/Order.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Poppel.Domain;
namespace Poppel.Order
{
public class Order
{
private Collection<OrderItem> products = new Collection<OrderItem>();
private DateTime dateOrderPlaced;
private Customer customer;
private Employee employee;
private int orderId;
private OrderStatus orderStatus;
private decimal orderPrice;
private Delivery deliveryDetails;
public enum OrderStatus
{
open = 0, awitingPayment = 1, awaitingDelivery = 2, delivered = 3, archived = 4
};
//Etc.
#region Properties
public Delivery DeliveryDetails
{
get { return deliveryDetails; }
set { deliveryDetails = value; }
}
public decimal OrderPrice
{
get { return orderPrice; }
set { orderPrice = value; }
}
public OrderStatus CurrentOrderStatus
{
get { return orderStatus; }
set { orderStatus = value; }
}
public int OrderId
{
get { return orderId; }
set { orderId = value; }
}
public Collection<OrderItem> Products
{
get { return products; }
set { products = value; }
}
public Customer Customer
{
get { return customer; }
set { customer = value; }
}
public DateTime DateOrderPlaced
{
get { return dateOrderPlaced; }
set { dateOrderPlaced = value; }
}
public Employee Employee
{
get { return employee; }
set { employee = value; }
}
public decimal getVat()
{
return decimal.Divide(OrderPrice, 0.14m);
}
public decimal getOrderTotal()
{
return decimal.Add(OrderPrice, getVat());
}
#endregion
}
}
|
9258d2ad8e149ca4daa9e2bb4e5c209645777dd8
|
C#
|
luisflux/Project-Dollhouse
|
/Other/tools/SimsLib/SimsLib/IFF/FieldReader.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace SimsLib.IFF
{
public struct FieldEncodingData
{
public byte CompressionCode;
public byte[] FieldWidths;
public uint EncodedDataLength;
public int FieldDataCounter;
public byte[] EncodedData;
public uint ReadDataLength;
public byte BitBufferCount;
public long BitBuffer;
}
/// <summary>
/// Used to decode fields from a set of data compressed using field encoding
/// (http://simtech.sourceforge.net/tech/misc.html#fields). Original code
/// written by Propeng.
/// </summary>
public class FieldReader
{
private int ReadBits(ref FieldEncodingData FieldData, byte Width, ref long Value)
{
while (FieldData.BitBufferCount < Width)
{
if (FieldData.ReadDataLength >= FieldData.EncodedDataLength)
return 0;
FieldData.BitBuffer <<= 8;
FieldData.BitBuffer |= FieldData.EncodedData[FieldData.FieldDataCounter];
FieldData.BitBufferCount += 8;
FieldData.ReadDataLength++;
}
Value = FieldData.BitBuffer >> (FieldData.BitBufferCount - Width);
Value &= (1L << Width) - 1;
FieldData.BitBufferCount -= Width;
return 1;
}
public int DecodeField(ref FieldEncodingData Data, byte FieldType, ref long Value)
{
long Prefix = 0, Width = 0;
if(ReadBits(ref Data, 1, ref Value) == 0)
return 0;
if (Value == 0)
return 1;
if (ReadBits(ref Data, 2, ref Prefix) == 0)
return 0;
Width = Data.FieldWidths[FieldType * 4 + Prefix];
if(ReadBits(ref Data, (byte)Width, ref Value) == 0)
return 0;
Value |= -(Value & 1L << (byte)(Width - 1));
return 1;
}
}
}
|
db679816cd59a34fe0029584d11033c8477455f4
|
C#
|
sqrlmn/LA583
|
/LibraryAssistantDAL/reservationDAL.cs
| 2.90625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace LibraryAssistantDAL
{
public class ReservationDAL
{
public bool setReservationDAL(string reservationID, string rUsername, string rISBN)
{
MySqlConnection conn = new MySqlConnection("Server=libraryassistant.cwhg663yxudq.us-west-2.rds.amazonaws.com;Database=library;Uid=la583;Pwd=la583password;");
string query = "INSERT INTO reservations (reservationID, rUsername, rISBN)"; // setting database variables for book reservation
query += " VALUES (@reservationID, @rUsername, @rISBN)"; // setting arguments to database names
MySqlCommand cmd = new MySqlCommand(query, conn); // processing command
cmd.Parameters.Add(new MySqlParameter("@reservationID", reservationID));
cmd.Parameters.Add(new MySqlParameter("@rUsername", rUsername));
cmd.Parameters.Add(new MySqlParameter("@rISBN", rISBN));
conn.Open();
int rowAffected = cmd.ExecuteNonQuery(); // checking if the database set was successful
conn.Close();
if (rowAffected > 0)
{
return true;
}
else
{
return false;
}
}
public string GetUserReservationIdDAL(string keyword)
{
MySqlConnection conn = new MySqlConnection("Server=libraryassistant.cwhg663yxudq.us-west-2.rds.amazonaws.com;Database=library;Uid=la583;Pwd=la583password;");
MySqlCommand cmd = new MySqlCommand("SELECT reservationId FROM reservations WHERE username=@rusername", conn); // grabbing reservationId
cmd.Parameters.Add(new MySqlParameter("@username", keyword));
conn.Open();
string reservationID = (string)cmd.ExecuteScalar();
conn.Close();
return reservationID;
}
}
}
|
b49153664db5a36f1c4878623278b2caf232f619
|
C#
|
BeTheBase/ProjectVrij
|
/Unity_Project_Vrij/Assets/_Scripts/WaveSystem/EnemySpawner.cs
| 2.609375
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class EnemySpawner : MonoBehaviour {
public static int EnemiesAlive = 0;
public Wave[] waves;
public static bool Spawning = true;
public static int enemiesToSpawn;
public static int waveIndex = 0;
ObjectPooler objectPooler;
public List<Vector3> spawnPoints;
// Use this for initialization
void Start ()
{
objectPooler = ObjectPooler.Instance;
}
private void Update()
{
if(Input.GetKeyDown(KeyCode.Return) && waveIndex < waves.Length && enemiesToSpawn == 0 && EnemiesAlive == 0)
{
print(waveIndex);
print(waves.Length);
StartCoroutine(SpawnWave());
}
}
IEnumerator SpawnWave()
{
yield return new WaitForSeconds(1);
Wave wave = waves[waveIndex];
waveIndex++;
for (int enemyType = 0; enemyType < wave.enemyAmounts.Count; enemyType++)
{
enemiesToSpawn += wave.enemyAmounts[enemyType];
}
for (int enemyType = 0; enemyType < wave.enemyPrefabs.Count; enemyType++)
{
for (int i = 0; i < wave.enemyAmounts[enemyType]; i++)
{
Spawn(wave.enemyPrefabs[enemyType].name);
enemiesToSpawn--;
yield return new WaitForSeconds(wave.spawnRate / spawnPoints.Count);
}
}
}
void Spawn(string enemy)
{
if (Spawning == true)
{
EnemiesAlive++;
Vector3 spawnPosition = spawnPoints[Random.Range(0, spawnPoints.Count)];
objectPooler.SpawnFromPool(enemy, spawnPosition, Quaternion.identity);
}
}
}
|
0a8e525fc922fb5f77c035f4c1e0f9ae78a4a5ce
|
C#
|
khoanguyen109/datlichbaoduong
|
/vdcore/ErrorMessages.cs
| 3.453125
| 3
|
using System;
using System.Text;
namespace Vendare.Error
{
/// <summary>
///This class provides a means of building collections of custom errors.
///The class is instantiated with the max number of errors in the collection
///Call setMesage for each possible error with its message
///call setError to indicate that an error has occured
/// </summary>
public class ErrorMessages
{
/// <summary> number of messages class can hold</summary>
private int capacity = 0;
/// <summary> holds readable messages</summary>
private String[] messages = null;
/// <summary> toggle switches for individual messages</summary>
private bool[] switches;
/// <summary> Prefix which appears before each message upon calling getList()*</summary>
private String errorPrefix = "<li class=error>";
/// <summary> Suffix which appears after each message upon calling getList()</summary>
private String errorSuffix = "</li>";
/// <summary> Prefix which appears before list of messages upon calling getList()</summary>
private String errorsPrefix = "<ul class=errorList>";
/// <summary> Suffix which appears after list of messages upon calling getList()</summary>
private String errorsSuffix = "</ul>";
/// <summary> indicates whether or not there are any errors</summary>
private bool empty = true;
/// <summary>
/// Creates an error collection with the specified capacity
/// </summary>
/// <param name="capacity">Total number of possible errors</param>
public ErrorMessages(int capacity)
{
this.capacity = capacity;
messages = new String[capacity];
switches = new bool[capacity];
}
/// <summary>
/// Sets the text message for an error
/// </summary>
/// <param name="index">specifies which error to set</param>
/// <param name="message">the textual message to set</param>
public void SetMessage(System.ValueType index, String message)
{
if((int)index >= capacity)
{
capacity += 5;
String[] newMessages = new String[capacity];
bool[] newSwitches = new bool[capacity];
messages.CopyTo(newMessages,0);
switches.CopyTo(newSwitches,0);
messages = newMessages;
switches = newSwitches;
}
messages[(int)index] = message;
}
/// <summary>
/// flag that an error has occured
/// </summary>
/// <param name="index">specifies which error has occured</param>
public void SetError(System.ValueType index)
{
if((int)index < capacity)
{
switches[(int)index] = true;
empty = false;
}
}
/// <summary>
/// clear all errors in the collection
/// </summary>
public void ClearErrors()
{
for(int i=0; i < capacity; i++)
switches[i] = false;
empty = true;
}
/// <summary>
/// provide formatting for the prefix of the message.
/// This string will appear before each message upon calling GetList()
/// </summary>
/// <param name="prefix">String to assign to prefix</param>
public void SetPrefix(String prefix)
{
errorPrefix = prefix;
}
/// <summary>
/// provide formatting for the suffix of the message.
/// This string will appear after each message upon calling GetList()
/// </summary>
/// <param name="prefix">String to assign to suffix</param>
public void SetSuffix(String suffix)
{
errorSuffix = suffix;
}
/// <summary>
/// provide formatting for the prefix of the entire list of errors.
/// This string will appear before the entire list upon calling GetList()
/// </summary>
/// <param name="prefix">String to assign to prefix</param>
public void SetListPrefix(String prefix)
{
errorsPrefix = prefix;
}
/// <summary>
/// provide formatting for the suffix of the entire list of massages.
/// This string will appear after the entire list upon calling GetList()
/// </summary>
/// <param name="prefix">String to assign to suffix</param>
public void SetListSuffix(String suffix)
{
errorsSuffix = suffix;
}
/// <summary>
/// Returns true if any errors have occured
/// </summary>
/// <returns>Returns true if any errors have occured</returns>
public bool IsEmpty()
{
return empty;
}
/// <summary>
/// return a list of all errors preceeded by prefix and proceeded by suffix
/// </summary>
/// <returns>return a list of all errors</returns>
public String GetList()
{
StringBuilder list = new StringBuilder(200);
list.Append(errorsPrefix);
for(int i=0;i<capacity;i++)
{
if(switches[i])
{
list.Append(errorPrefix);
list.Append(messages[i]);
list.Append(errorSuffix);
}
}
list.Append(errorsSuffix);
return list.ToString();
}
}
}
|
0b30b396d4dbc80a3d3927ffbe22af3c207ef48c
|
C#
|
Harrimaga/LD44
|
/CottonCandy/CottonCandy/Cards/Ensnare.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CottonCandy.Cards
{
[Serializable]
class Ensnare : Card
{
public Ensnare() : base(true, "Ensnare", "Stun all units in a "+CardBalance.ENSNARE_RANGE+" tile wide diamond for "+CardBalance.ENSNARE_STUN+" turn", CardBalance.ENSNARE_COST, PurchaseMode.ENEMIES, "Cards/SilverEnemyAoECastCard")
{
}
public override bool Play()
{
return false;
}
public override bool Play(int x, int y)
{
int diamondwidth = CardBalance.ENSNARE_RANGE / 2;
int row = 0;
for (int i = diamondwidth; i >= 0; i--)
{
for (int j = -i; j <= i; j++)
{
if (x + j > 0 && x + j < Globals.grid.w && y - row > 0 && Globals.grid.GetTile(x + j, y - row).unit != null)
{
Globals.grid.GetTile(x + j, y - row).unit.Stun(CardBalance.ENSNARE_STUN);
}
}
row++;
}
row = 1;
for (int i = diamondwidth - 1; i >= 0; i--)
{
for (int j = -i; j <= i; j++)
{
if (x + j > 0 && x + j < Globals.grid.w && y + row < Globals.grid.h && Globals.grid.GetTile(x + j, y + row).unit != null)
{
Globals.grid.GetTile(x + j, y + row).unit.Stun(CardBalance.ENSNARE_STUN);
}
}
row++;
}
return true;
}
}
}
|
df43a4f90057b96f9462e8678d31b55fbc590b18
|
C#
|
GedGonz/Capacitacion-DDD
|
/DatosPRG/Repositorio/BaseRepositorio.cs
| 2.828125
| 3
|
using NegocioPRG.Contratos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq.Expressions;
using System.Data.Entity;
namespace DatosPRG.Repositorio
{
public class BaseRepositorio<T> : IBaseRepositorio<T> where T : class
{
protected readonly DbContext contexto;
protected readonly DbSet<T> Tabla;
public BaseRepositorio(DbContext contexto)
{
this.contexto = contexto;
this.Tabla = contexto.Set<T>();
}
public void add(T entidad)
{
Tabla.Add(entidad);
}
public IEnumerable<T> List(Expression<Func<T, bool>> predicado)
{
return Tabla.Where(predicado);
}
public IEnumerable<T> ListAll()
{
return Tabla.ToList();
}
}
}
|
be6a25188bb99215ed4e96dc63ab1c9cabf22615
|
C#
|
Aeromg/HumanNamesExtractor
|
/NamesExtractor/RegexExtension/RegexFunctionExecutor.cs
| 2.875
| 3
|
using System.Linq;
using System.Text.RegularExpressions;
namespace IndexerLib.RegexExtension
{
public static class RegexFunctionExecutor
{
static readonly Regex QuoteRegex = new Regex(@"(?<!\\)\$");
public static string ExecuteExpression(string expression)
{
var extracted = expression;
while (extracted != "")
{
extracted = ExtractDeepestExpression(expression);
if (extracted == "")
break;
expression = expression.Replace(extracted, ExecuteSingleExpression(extracted));
}
return expression;
}
static string ExecuteSingleExpression(string expression)
{
var funcName = expression.Substring(0, expression.IndexOf(@"$"));
var args = expression.Substring(funcName.Length + 1, expression.Length - funcName.Length - 2);
var func = RegexFunctionResolver.Resolve(funcName);
return func.Execute(args);
}
static string ExtractDeepestExpression(string expression)
{
var quotes = QuoteRegex.Matches(expression).
Cast<Match>().
Select(m => m.Index).
Reverse().
ToArray();
if (quotes.Length % 2 != 0)
return "";
var names = RegexFunctionResolver.FunctionNames.OrderBy(f => f.Length).ToArray();
for (var qId = 1; qId < quotes.Length; qId++)
{
for (int fId = 0; fId < names.Length; fId++)
{
if (names[fId].Length > quotes[qId])
break;
var nameStart = quotes[qId] - names[fId].Length;
var substr = expression.Substring(nameStart, names[fId].Length);
if (substr == names[fId])
{
var function = substr;
var args = expression.Substring(quotes[qId], quotes[qId - 1] - quotes[qId] + 1);
return function + args;
}
}
}
return "";
}
static RegexFunctionExecutor()
{
RegexFunctionResolver.RegisterFunction(typeof(InflectRegexFunction));
RegexFunctionResolver.RegisterFunction(typeof(WordRegexFunction));
}
}
}
|
b4cb1f6430a4dc6c64d452494d777324c0481282
|
C#
|
rohitadidam/Batch-19.4.2021-
|
/Module-2/ADO/HandsOnAdoUsingStoredProcedures/HandsOnAdoUsingStoredProcedures/Program.cs
| 3.359375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HandsOnAdoUsingStoredProcedures.Entities;
using HandsOnAdoUsingStoredProcedures.Repositories;
namespace HandsOnAdoUsingStoredProcedures
{
class Program
{
static void Main(string[] args)
{
try
{
ProductRepository repository = new ProductRepository();
//Product product = new Product()
//{
// Pid = 130,
// Pname = "AAA",
// Price = 10,
// Stock = 20
//};
//repository.AddProduct(product);
List<Product> products = repository.GetProducts();
foreach (var item in products)
{
Console.WriteLine("ID:{0} Name:{1} Price:{2} Stock:{3}", item.Pid, item.Pname, item.Price, item.Stock);
}
//Console.WriteLine("Enter Product Id");
//int Pid = int.Parse(Console.ReadLine());
//Product product = repository.GetProduct(Pid);
//if (product != null)
//{
// Console.WriteLine("Name:{0} Price {1}", product.Pname, product.Price);
//}
//else
// Console.WriteLine("Invalid id");
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
|
43b73a057f06ec7cd3ccb4029b30bd62a4f4bf00
|
C#
|
fredsena/Design-Patterns
|
/DesignPatterns.Tests/CoffeeShopDecoratorTests.cs
| 2.875
| 3
|
using System;
using System.Linq;
using Xunit;
using DesignPatterns.Core.Decorator.CoffeeShopDecorator.Component;
using DesignPatterns.Core.Decorator.CoffeeShopDecorator.Decorator;
namespace DesignPatterns.Tests
{
public class CoffeeShopDecoratorTests
{
[Fact]
public void Expresso_WhenInstantiated_ReturnsCorrectValues()
{
Beverage beverage = new Espresso();
Assert.Equal(nameof(Espresso), beverage.GetDescription());
Assert.Equal(1.99m, beverage.Value());
}
[Fact]
public void HouseBlend_WhenAddDecorators_ValueIsIncreased()
{
Beverage houseBlend = new HouseBlend();
decimal value = houseBlend.Value();
houseBlend = new Soy(houseBlend);
houseBlend = new Mocha(houseBlend);
Assert.NotEqual(value, houseBlend.Value());
Assert.Equal(houseBlend.Description, houseBlend.GetDescription());
}
}
}
|
727401f709df5ba0d3534116133d38ed4f0dbd52
|
C#
|
ahdde/graphite.net
|
/Graphite/CarbonConnectionPool.cs
| 2.6875
| 3
|
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.ObjectPool;
namespace ahd.Graphite
{
/// <summary>
/// Connection pool for TCP connections to carbon
/// </summary>
public class CarbonConnectionPool
{
private readonly string _hostname;
private readonly IGraphiteFormatter _formatter;
private static readonly ConcurrentDictionary<(string,ushort), ObjectPool<TcpClient>> Cache = new ConcurrentDictionary<(string,ushort), ObjectPool<TcpClient>>();
private readonly ObjectPool<TcpClient> _pool;
/// <summary>
/// Create or reuse a connection pool for the specified endpoint. If there is already an existing connection pool for the specified endpoint it is reused.
/// </summary>
/// <param name="hostname">Graphite hostname</param>
/// <param name="formatter">formatter for sending data to graphite</param>
public CarbonConnectionPool(string hostname, IGraphiteFormatter formatter)
{
_hostname = hostname;
_formatter = formatter;
_pool = Cache.GetOrAdd((hostname, _formatter.Port), CreatePool);
}
/// <summary>
/// clears all connections from all endpoints
/// </summary>
public static void ClearAllPools()
{
foreach (var entry in Cache)
{
if (Cache.TryRemove(entry.Key, out var pool))
{
var disposable = pool as IDisposable;
disposable?.Dispose();
}
}
}
/// <summary>
/// clears all connections from the current pool
/// </summary>
public void ClearPool()
{
Cache.TryRemove((_hostname, _formatter.Port), out _);
var disposable = _pool as IDisposable;
disposable?.Dispose();
}
/// <summary>
/// returns a pooled connection or creates a new connection
/// <remarks>the connection is tested before returning to the caller</remarks>
/// </summary>
/// <returns></returns>
public TcpClient Get()
{
var client = _pool.Get();
if (!client.Connected)
{
client.Dispose();
client = new TcpClient(_hostname, _formatter.Port);
}
else
{
if (!Test(client))
return Get();
}
return client;
}
/// <summary>
/// returns the connection to the pool
/// </summary>
/// <param name="client">the connection to return to the pool</param>
public void Return(TcpClient client)
{
_pool.Return(client);
}
private bool Test(TcpClient client)
{
try
{
_formatter.TestConnection(client.GetStream());
return true;
}
catch (IOException ex) when (ex.InnerException is SocketException se && CheckSocketException(se))
{
client.Dispose();
return false;
}
}
/// <summary>
/// returns a pooled connection or creates a new connection
/// <remarks>the connection is tested before returning to the caller</remarks>
/// </summary>
/// <param name="useDualStack">Use ip dual stack for sending metrics</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns></returns>
public async Task<TcpClient> GetAsync(bool useDualStack, CancellationToken cancellationToken)
{
var client = _pool.Get();
if (!client.Connected)
{
client.Dispose();
if (useDualStack)
{
client = new TcpClient(AddressFamily.InterNetworkV6) {Client = {DualMode = true}};
}
else
{
client = new TcpClient(AddressFamily.InterNetwork);
}
cancellationToken.ThrowIfCancellationRequested();
await client.ConnectAsync(_hostname, _formatter.Port).ConfigureAwait(false);
}
else
{
if (!await TestAsync(client, cancellationToken).ConfigureAwait(false))
return await GetAsync(useDualStack, cancellationToken).ConfigureAwait(false);
}
return client;
}
private async Task<bool> TestAsync(TcpClient client, CancellationToken cancellationToken)
{
try
{
await _formatter.TestConnectionAsync(client.GetStream(), cancellationToken).ConfigureAwait(false);
return true;
}
catch (IOException ex) when (ex.InnerException is SocketException se && CheckSocketException(se))
{
client.Dispose();
return false;
}
}
private bool CheckSocketException(SocketException ex)
{
if (ex is null) return false;
switch (ex.SocketErrorCode)
{
case SocketError.ConnectionAborted:
case SocketError.ConnectionReset:
case SocketError.Disconnecting:
case SocketError.NetworkReset:
case SocketError.NotConnected:
case SocketError.OperationAborted:
case SocketError.Shutdown:
return true;
default:
return false;
}
}
private ObjectPool<TcpClient> CreatePool((string, ushort) endpoint)
{
return new DefaultObjectPoolProvider().Create(new TcpClientPolicy());
}
private class TcpClientPolicy : IPooledObjectPolicy<TcpClient>
{
public TcpClient Create()
{
return new TcpClient();
}
public bool Return(TcpClient obj)
{
return obj.Connected;
}
}
}
}
|
b7d6710abe0db4fc8cabe73d02b8e1f4068de88b
|
C#
|
kevinheader/Phenix.NET7
|
/Demo_ORA/Demo.Phenix.Core.Data.Schema/Program.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using Phenix.Core.Data;
using Phenix.Core.Data.Schema;
using Phenix.Core.Reflection;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("**** 演示 Phenix.Core.Data.Schema 功能 ****");
Console.WriteLine();
Console.WriteLine("Phenix.Core.Data.Schema 命名空间里提供的类,可获取到数据库表和视图的元数据,包括字段、索引、主键、外键、子健等信息。");
Console.WriteLine("这些信息的对象,可被 JSON 序列化或反序列化, 以利于跨域使用。");
Console.WriteLine();
Console.WriteLine("不管是继承 EntityBase 还是直接操作 Database,持久化引擎都要求你在设计表结构和实体类时,遵循以下编写规范:");
Console.WriteLine("1,实体类命名法为Pascal,不管是表还是视图,它们名称里的下划线,都在映射时会自动剔除掉,比如“TPT_PROJECT_INFO”表名映射的是“TptProjectInfo”类名;");
Console.WriteLine(" 表名/视图名如带前缀,映射到类名不会被自动剔除(例外:“PH7_XXX”前缀会被自动剔除);");
Console.WriteLine("2,实体类的属性名也是Pascal规则;字段命名法是加“_”前缀的camel规则名,比如“_projectName”;");
Console.WriteLine(" 表/视图的字段名/别名如带前缀,映射到类的属性/字段时不会被剔除掉(例外:“PH7_XXX”表里的字段的前缀会被自动剔除);");
Console.WriteLine(" 表/视图的字段名/别名,命名时如不出于以下目的,请避免使用如下后缀,它们是持久层引擎的保留字:");
Console.WriteLine(" “_ID”且是长整型15位以上精度:主键/外键;如为主键,新增记录时自动填充Sequence.Default.Value;每张表都应该有且仅一个长整型15位以上精度的主键字段,外键分物理外键(组合关系)和虚拟外键(聚合关系),命名尽可能与主键相呼应;");
Console.WriteLine(" “_ORIGINATOR”且是字符串/长整型15位以上精度:新增记录时自动填充Identity.CurrentIdentity.User.Name/Id;");
Console.WriteLine(" “_ORIGINATE_TIME”且是DateTime:新增记录时自动填充当前时间;");
Console.WriteLine(" “_ORIGINATE_TEAMS”且是字符串/长整型15位以上精度:新增记录时自动填充Identity.CurrentIdentity.User.RootTeams.Name/Id;");
Console.WriteLine(" “_UPDATER”且是字符串/长整型15位以上精度:更新记录时自动填充Identity.CurrentIdentity.User.Name/Id;");
Console.WriteLine(" “_UPDATE_TIME”且是DateTime:更新记录时自动填充当前时间;");
Console.WriteLine(" “_TIMESTAMP”且是长整型15位以上精度:时间戳,更新记录时自动填充Sequence.Default.Value;时间戳可用于乐观锁模式下的数据更新,保证在分布式架构下新数据不会被脏数据覆盖(会抛出Phenix.Core.Data.Rule.OutdatedDataException);");
Console.WriteLine(" “_RU”:分库路由字段,仅在新增记录时被提交,提交后不允许修改,分库增删改查时其值被HASH路由到指定的数据库;");
Console.WriteLine(" “_WM”:水印字段,仅在新增记录时被提交,提交后不允许修改;");
Console.WriteLine(" “_FG”且是整型2位/1位精度:枚举/布尔,映射到类的属性/字段时会被自动剔除掉后缀,比如字段“PI_PROJECT_TYPE_FG”映射到类的属性名是“ProjectType”/字段名是“_projectType”,类型应该是 ProjectType 枚举;");
Console.WriteLine(" “_RU”、“_WM”可以组合“_FG”一起使用,组合时先后次序随意;");
Console.WriteLine("以上是全部的编写规范。");
Console.Write("请按任意键继续");
Console.ReadKey();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("在接下来的演示之前,请检查缺省数据库连接配置信息,以保证其连接到的是你指定的测试库。");
Console.WriteLine("数据库连接配置信息存放在 SQLite 库 Phenix.Core.db 文件的 PH7_Database 表中,配置方法见其示例记录的 Remark 字段内容。");
Console.WriteLine("缺省数据库连接串:{0}", Database.Default.ConnectionString);
Console.WriteLine("如不符,请退出程序,找到 PH7_Database 表中那条 DataSourceKey 字段值为'*'的记录,配置好后再重启本程序。");
Console.Write("如果确认准确无误,请按任意键继续");
Console.ReadKey();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("构建数据库构架对象...");
MetaData metaData = Database.Default.MetaData;
Console.WriteLine("数据库构架对象可序列化为 JSON 字符串...");
string json = Utilities.JsonSerialize(metaData);
Console.WriteLine(json);
Console.Write("请按任意键继续");
Console.ReadKey();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("JSON 字符串可反序列化为数据库构架对象...");
metaData = Utilities.JsonDeserialize<MetaData>(json);
Console.WriteLine("数据库含{0}个表、{1}个视图", metaData.Tables.Count, metaData.Views.Count);
Console.Write("请按任意键继续");
Console.ReadKey();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("罗列全部表的结构...");
foreach (KeyValuePair<string, Table> kvp in metaData.Tables)
{
Console.WriteLine("表{0}({1})主键: {2}", kvp.Key, kvp.Value.Description, Utilities.JsonSerialize(kvp.Value.PrimaryKeys));
Console.WriteLine("表{0}({1})外键: {2}", kvp.Key, kvp.Value.Description, Utilities.JsonSerialize(kvp.Value.ForeignKeys));
Console.WriteLine("表{0}({1})子键: {2}", kvp.Key, kvp.Value.Description, Utilities.JsonSerialize(kvp.Value.DetailForeignKeys));
Console.WriteLine("表{0}({1})索引: {2}", kvp.Key, kvp.Value.Description, Utilities.JsonSerialize(kvp.Value.Indexes));
Console.WriteLine("表{0}({1})字段: {2}", kvp.Key, kvp.Value.Description, Utilities.JsonSerialize(kvp.Value.Columns));
Console.WriteLine();
}
Console.Write("请按任意键继续");
Console.ReadKey();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("罗列全部视图的结构...");
foreach (KeyValuePair<string, View> kvp in metaData.Views)
{
Console.WriteLine("视图{0}({1})内容: {2}", kvp.Key, kvp.Value.Description, kvp.Value.ViewText);
Console.WriteLine("视图{0}({1})数据源: {2}", kvp.Key, kvp.Value.Description, Utilities.JsonSerialize(kvp.Value.Tables.Keys));
Console.WriteLine("视图{0}({1})字段: {2}", kvp.Key, kvp.Value.Description, Utilities.JsonSerialize(kvp.Value.Columns));
Console.WriteLine();
}
Console.Write("请按回车键结束演示");
Console.ReadLine();
}
}
}
|
2c6488a64eab67dc496acfedb888513faa1c949b
|
C#
|
JacobHelm36/Library-api
|
/Services/LibrariesService.cs
| 3.109375
| 3
|
using System;
using System.Collections.Generic;
using library.Repositories;
using library_api.Models;
// using library_api.Repositories;
namespace library.Services
{
public class LibraryService
{
private readonly LibraryRepository _repo;
public LibraryService(LibraryRepository repo)
{
_repo = repo;
}
internal IEnumerable<Library> Get()
{
return _repo.Get();
}
internal Library Get(int id)
{
Library found = _repo.Get(id);
if (found == null)
{
throw new Exception("Invalid Id");
}
return found;
}
internal Library Create(Library newLibrary)
{
Library created = _repo.Create(newLibrary);
if (created == null)
{
throw new Exception("Create request failed");
}
return created;
}
internal Library Edit(Library updatedLibrary)
{
Library original = Get(updatedLibrary.Id);
original.Name = updatedLibrary.Name;
_repo.Edit(original);
return original;
}
// internal Library Delete(int id)
// {
// Library exists = _repo.Get(id);
// if (exists == null)
// {
// throw new Exception("Invalid Id");
// }
// if (_repo.Delete(id))
// {
// // why???
// return exists;
// }
// throw new Exception("Something went wrong with deleting that item");
// }
}
}
|
30e8b534351afa919ce2e1b4ae70b732b0e502a1
|
C#
|
forki/Okanshi
|
/tests/Okanshi.Tests/BasicCounterTest.cs
| 2.75
| 3
|
using System.Linq;
using FluentAssertions;
using Xunit;
namespace Okanshi.Test
{
public class BasicCounterTest
{
[Fact]
public void Initial_value_is_zero()
{
var counter = new BasicCounter(MonitorConfig.Build("Test"));
counter.GetValue().Should().Be(0);
}
[Theory]
[InlineData(1)]
[InlineData(10)]
[InlineData(110)]
public void Incrementing_the_counters_works_as_expected(int amount)
{
var counter = new BasicCounter(MonitorConfig.Build("Test"));
counter.Increment(amount);
counter.GetValue().Should().Be(amount);
}
[Theory]
[InlineData(1)]
[InlineData(10)]
[InlineData(110)]
public void Get_and_reset_does_not_reset_the_value(int amount)
{
var counter = new BasicCounter(MonitorConfig.Build("Test"));
counter.Increment(amount);
counter.GetValueAndReset();
counter.GetValue().Should().Be(amount);
}
[Theory]
[InlineData(1)]
[InlineData(10)]
[InlineData(110)]
public void Get_and_reset_returns_the_value(int amount)
{
var counter = new BasicCounter(MonitorConfig.Build("Test"));
counter.Increment(amount);
var value = counter.GetValueAndReset();
value.Should().Be(amount);
}
[Fact]
public void Consists_of_a_single_monitor()
{
var counter = new BasicCounter(MonitorConfig.Build("Test"));
counter.GetAllMonitors().Should().HaveCount(1);
counter.GetAllMonitors().Single().Should().BeSameAs(counter);
}
}
}
|
36c234832089e377251cdb3179ecb6961a409be4
|
C#
|
GeorgiLambov/SoftwareUniversity
|
/07.Object-Oriented Programming/01.Defining-Classes-Homework/04.SoftwareUniversityLearningSystem/SoftUniLearningSystem.Data/SeniorTrainer.cs
| 2.765625
| 3
|
using System;
namespace SoftUniLearningSystem.Data
{
public class SeniorTrainer : Trainer
{
public SeniorTrainer(string fName, string lName, string id)
: base(fName, lName, id)
{
}
public void DeleteCourse(string courseName)
{
Console.WriteLine("{3}: {0} {1} - DELETE course: {2}.", this.FName, this.LName, courseName, GetType().Name);
}
}
}
|
ec0ee0f0446cb15cdd04de3997ce997f55039173
|
C#
|
Juli199696/ArgUrTMapManager
|
/ArgusLib.Controls/ProcessForm.cs
| 2.890625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
namespace ArgusLib.Controls
{
/// <summary>
/// A simple <see cref="Form"/> similar to a console window. It runs a <see cref="Process"/> and displays
/// its standard error and standard output and takes input from the user.
/// If the form is closed, the process is terminated.
/// </summary>
public partial class ProcessForm : BaseForm, IDisposable
{
Process process;
bool processExited = false;
DateTime lastOutputReceived;
List<string> buffer;
/// <summary>
/// Gets or sets a <see cref="int"/> specifying the time in milliseconds between
/// the output is refreshed.
/// The default value is 50.
/// </summary>
public int TimeBetweenOutputs { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the form should automatically close when the process exits.
/// The default is true.
/// </summary>
public bool CloseWhenProcessExits { get; set; }
/// <summary>
/// Gets a value indicating whether the underlying <see cref="Process"/> has already exited.
/// </summary>
public bool ProcessHasExited
{
get { return this.processExited; }
}
/// <summary>
/// Occurs when the underlying <see cref="Process"/> exits.
/// </summary>
public event EventHandler ProcessExited;
internal ProcessForm()
: base()
{
InitializeComponent();
this.buffer = new List<string>();
this.CloseWhenProcessExits = true;
this.lastOutputReceived = new DateTime(0);
this.TimeBetweenOutputs = 50;
}
/// <summary>
/// Creates a new <see cref="ProcessForm"/> instances which will run the <see cref="Process"/>
/// specified by <paramref name="psi"/>.
/// </summary>
/// <param name="psi">A <see cref="ProcessStartInfo"/>.</param>
/// <remarks>
/// The underlying <see cref="Process"/> will use <see cref="Process.StartInfo.RedirectStandardError"/> = true,
/// <see cref="Process.StartInfo.RedirectStandardInput"/> = true, <see cref="Process.StartInfo.RedirectStandardOutput"/>
/// and <see cref="Process.StartInfo.UseShellExecute"/> = false. Therefor some properties like <see cref="Process.StartInfo.WorkingDirectory"/>
/// or <see cref="Process.StartInfo.FileName"/> may behave differently. See <see cref="Process.StartInfo.RedirectStandardError"/>,
/// <see cref="Process.StartInfo.RedirectStandardInput"/>, <see cref="Process.StartInfo.RedirectStandardOutput"/> and
/// <see cref="Process.StartInfo.UseShellExecute"/> for more detailed information.
/// </remarks>
public ProcessForm(ProcessStartInfo psi)
: this()
{
this.Text = psi.FileName;
psi.UseShellExecute = false;
psi.RedirectStandardError = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
this.process = new Process();
this.process.StartInfo = psi;
this.process.EnableRaisingEvents = true;
this.process.ErrorDataReceived += new DataReceivedEventHandler(this.Process_OutputDataReceived);
this.process.OutputDataReceived += new DataReceivedEventHandler(this.Process_OutputDataReceived);
this.process.Exited += new EventHandler(this.process_Exited);
}
/// <summary>
/// Starts the underlying <see cref="Process"/> and shows the Formwindow.
/// Each instance of <see cref="ProcessForm"/> can only be started once.
/// </summary>
/// <param name="modal">A <see cref="Boolean"/> indicating wheter the <see cref="ProcessForm"/> should be shown as modal dialog.</param>
public void Start(bool modal)
{
if (this.processExited == true)
throw new Exception("Create a new instance, object already disposed.");
this.process.Start();
this.process.BeginErrorReadLine();
this.process.BeginOutputReadLine();
if (modal == true)
base.ShowDialog();
else
base.Show();
}
/// <summary>
/// Calls <see cref="Process.WaitForExit()"/> on the underlying <see cref="Process"/>.
/// </summary>
public void WaitForExit()
{
this.process.WaitForExit();
}
/// <summary>
/// Calls <see cref="Process.WaitForExit(int)"/> on the underlying <see cref="Process"/>.
/// </summary>
public bool WaitForExit(int ms)
{
return this.process.WaitForExit(ms);
}
/// <summary>
/// Not supported. Use <see cref="ProcessForm.Start()"/> instead.
/// </summary>
public new void Show()
{
throw new NotImplementedException("Use ProcessForm.Start() instead.");
}
/// <summary>
/// Not supported. Use <see cref="ProcessForm.Start()"/> instead.
/// </summary>
public new void ShowDialog()
{
throw new NotImplementedException("Use ProcessForm.Start() instead.");
}
void process_Exited(object sender, EventArgs e)
{
this.processExited = true;
if (this.CloseWhenProcessExits == true)
{
if (this.InvokeRequired == true)
{
Action<object> closeAction = (a) => { this.Close(); };
this.Invoke(closeAction, new object());
}
else
{
this.Close();
}
}
if (this.ProcessExited != null)
this.ProcessExited(this, EventArgs.Empty);
}
/// <summary>
/// See <see cref="Form.OnFormClosing"/>.
/// </summary>
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (this.processExited == false)
{
e.Cancel = true;
if (this.process.CloseMainWindow() == false)
this.process.Kill();
}
else
{
this.Dispose();
}
base.OnFormClosing(e);
}
private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (this.IsShown == false)
return;
//this.outputBox.InvokeOutput(e.Data);
TimeSpan interval = DateTime.Now - this.lastOutputReceived;
if (interval.TotalMilliseconds < this.TimeBetweenOutputs)
{
buffer.Add(e.Data);
}
else
{
string text = string.Empty;
for (int i = 0; i < buffer.Count; i++)
{
text += buffer[i] + Environment.NewLine;
}
text += e.Data;
this.outputBox.InvokeOutput(text);
buffer.Clear();
this.lastOutputReceived = DateTime.Now;
}
}
private void inputBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode != Keys.Enter)
return;
this.outputBox.Output(">> " + this.inputBox.Text);
this.process.StandardInput.WriteLine(this.inputBox.Text);
this.inputBox.Text = string.Empty;
}
/// <summary>
/// Calls <see cref="Component.Dispose()"/> on the underlying <see cref="Process"/>.
/// </summary>
void IDisposable.Dispose()
{
this.process.Dispose();
}
}
}
|