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
|
|---|---|---|---|---|---|---|
dd681b2a7fac2f2d127880c44041972aedb8a227
|
C#
|
EWSoftware/PDI
|
/Source/EWSPDI/RecurFrequency.cs
| 2.53125
| 3
|
//===============================================================================================================
// System : Personal Data Interchange Classes
// File : RecurFrequency.cs
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : 10/22/2014
// Note : Copyright 2003-2014, Eric Woodruff, All rights reserved
// Compiler: Microsoft Visual C#
//
// This file contains the recurrence frequency enumerated type
//
// This code is published under the Microsoft Public License (Ms-PL). A copy of the license should be
// distributed with the code and can be found at the project website: https://github.com/EWSoftware/PDI.
// This notice, the author's name, and all copyright notices must remain intact in all applications,
// documentation, and source files.
//
// Date Who Comments
// ==============================================================================================================
// 08/12/2004 EFW Created the code
//===============================================================================================================
using System;
namespace EWSoftware.PDI
{
/// <summary>
/// This enumerated type defines the recurrence frequency
/// </summary>
[Serializable]
public enum RecurFrequency
{
/// <summary>Recurrence pattern is undefined and returns no dates</summary>
Undefined,
/// <summary>Yearly recurrence</summary>
Yearly,
/// <summary>Monthly recurrence</summary>
Monthly,
/// <summary>Weekly recurrence</summary>
Weekly,
/// <summary>Daily recurrence</summary>
Daily,
/// <summary>Hourly recurrence</summary>
Hourly,
/// <summary>Minutely recurrence</summary>
Minutely,
/// <summary>Secondly recurrence</summary>
Secondly
}
}
|
d92bcca52e43f4e3a956ce66edda0c9810bdc58c
|
C#
|
Susuo/rtilabs
|
/files/asobiba/omegarti_v3_src/CodeBox.cs
| 2.796875
| 3
|
/*
* Copyright (c) Daisuke OKAJIMA All rights reserved.
*
* $Id$
*/
using System;
using System.Windows.Forms;
namespace Zanetti.Forms
{
/// <summary>
/// CodeBox ̊Tv̐łB
/// </summary>
internal class CodeBox : TextBox
{
public event EventHandler CodeComplete;
private int _code;
public int StockCode {
get {
return _code;
}
set {
_code = value;
this.Text = value.ToString();
Select(1, 0);
}
}
protected override bool IsInputChar(char ch) {
return IsInterestingChar(ch);
}
protected override bool ProcessDialogChar(char ch) {
if(IsInterestingChar(ch))
return false;
else
return true;
}
private bool IsInterestingChar(char ch) {
return ('0'<=ch && ch<='9') || (int)ch==8 || ch=='\n';
}
protected override void OnKeyPress(KeyPressEventArgs args) {
base.OnKeyPress(args);
char ch = args.KeyChar;
if('0'<=ch && ch<='9') {
if(this.Text.Length==3) {
_code = Int32.Parse(this.Text + ch);
if(CodeComplete!=null) CodeComplete(this, args);
}
}
else if(ch=='\n') {
_code = Int32.Parse(this.Text);
if(CodeComplete!=null) CodeComplete(this, args);
}
}
}
}
|
a6942c4d4ea01d2121663f2e987e81683152254f
|
C#
|
emote-project/Scenario2
|
/Code/Thalamus/Example Modules/ThalamusSpeechClient/WindowsSpeechEngine.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Speech.Synthesis;
using System.Speech.Synthesis.TtsEngine;
namespace ThalamusSpeechClient
{
public class WindowsSpeechEngine : SpeechEngine
{
public WindowsSpeechEngine() : base(SpeechEngineType.Windows) { }
private SpeechSynthesizer tts = null;
private Dictionary<Prompt, string> ids = new Dictionary<Prompt, string>();
private Dictionary<int, float> visemes = new Dictionary<int, float>();
public override void Setup()
{
SetupVisemes();
}
public override void Start(SpeechClient server)
{
base.Start(server);
tts = new SpeechSynthesizer();
bool voiceExists = false;
foreach (InstalledVoice v in tts.GetInstalledVoices())
{
Console.WriteLine("WindowsTTS: Found '" + v.VoiceInfo.Name + "' voice.");
if (v.VoiceInfo.Name == voice) voiceExists = true;
}
if (voiceExists) tts.SelectVoice(Properties.Settings.Default.Voice);
tts.VisemeReached += new EventHandler<VisemeReachedEventArgs>(ProcessViseme);
tts.PhonemeReached += new EventHandler<PhonemeReachedEventArgs>(ProcessPhonem);
tts.SpeakCompleted += new EventHandler<SpeakCompletedEventArgs>(Ended);
tts.SpeakStarted += new EventHandler<SpeakStartedEventArgs>(Started);
tts.BookmarkReached += new EventHandler<BookmarkReachedEventArgs>(Bookmark);
tts.Rate = Properties.Settings.Default.SpeechRate;
Console.WriteLine("Started WindowsTTS speech engine.");
}
private void SetupVisemes()
{
visemes = new Dictionary<int, float>();
// closed
visemes.Add(0, 0); //silence
visemes.Add(21, 0); //p, b, m
// almost closed
visemes.Add(18, 0.1f); //f, v
visemes.Add(7, 0.1f); //w, uw
// slight open
visemes.Add(14, 0.3f); //l
visemes.Add(15, 0.3f); //s, z
visemes.Add(16, 0.3f); //sh, ch, jh, zh
visemes.Add(17, 0.3f); //th, dh
visemes.Add(19, 0.3f); //d, t, n
// mid open
visemes.Add(8, 0.5f); //ow
visemes.Add(13, 0.5f); //r
visemes.Add(20, 0.5f); //k, g, ng
// almost wide open
visemes.Add(1, 0.7f); //ae, ax, ah
visemes.Add(2, 0.7f); //aa
visemes.Add(3, 0.7f); //ao
visemes.Add(9, 0.7f); //aw
visemes.Add(12, 0.7f); //h
visemes.Add(10, 0.7f); //oy
visemes.Add(11, 0.7f); //ay
// wide open
visemes.Add(4, 1.0f); //ey, eh, uh
visemes.Add(5, 1.0f); //er
visemes.Add(6, 1.0f); //y, iy, ih, ix
}
private float VisemeToPercent(int viseme)
{
if (visemes.ContainsKey(viseme)) return visemes[viseme];
else return 0;
}
#region private windows TTS events
private void ProcessPhonem(object sender, PhonemeReachedEventArgs args)
{
//Console.WriteLine(args.Phoneme);
}
private void ProcessViseme(object sender, VisemeReachedEventArgs args)
{
SpeechClient.SpeechPublisher.Viseme(args.Viseme, args.NextViseme, VisemeToPercent(args.Viseme), VisemeToPercent(args.NextViseme));
}
private void Started(object sender, SpeakStartedEventArgs args)
{
if (ids.ContainsKey(args.Prompt))
{
Started(ids[args.Prompt]);
}
else
{
Started();
}
}
private void Ended(object sender, SpeakCompletedEventArgs args)
{
if (ids.ContainsKey(args.Prompt))
{
Ended(ids[args.Prompt]);
ids.Remove(args.Prompt);
}
else
{
Ended();
}
}
private void Bookmark(object sender, BookmarkReachedEventArgs args)
{
Bookmark(args.Bookmark);
}
#endregion
public override void CancelCurrentSpeech()
{
tts.SpeakAsyncCancelAll();
}
internal override void Stop()
{
tts.SpeakAsyncCancelAll();
}
public override void Speak(SpeechClient.Speech speech)
{
try
{
PromptBuilder p = new PromptBuilder();
p.StartStyle(new PromptStyle(PromptEmphasis.None));
for (int i = 0; i < speech.Text.Length; i++)
{
if (speech.Bookmarks == null || speech.Bookmarks.Length < i + 1)
{
string s = "";
for (; i < speech.Text.Length; i++) s += speech.Text[i] + " ";
p.AppendText(s);
break;
}
else
{
p.AppendText(speech.Text[i]);
p.AppendBookmark(speech.Bookmarks[i]);
}
}
p.Culture = tts.Voice.Culture;
p.EndStyle();
if (speech.Id != "") ids.Add(tts.SpeakAsync(p), speech.Id);
else tts.SpeakAsync(p);
}
catch (Exception e)
{
Console.WriteLine("WindowsTTS Failed: " + e.Message);
}
}
}
}
|
3a9b3b201e855aa27bd466740d5ff795720a10b6
|
C#
|
Nicoleyuan/Why-do-not-you-study-from-now-on
|
/.net/src/TestIndexer.cs
| 3.5
| 4
|
//TestIndexer.cs -- 索引器;Property与自动Property
using System;
using System.Collections.Generic;
namespace ByPoints.Indexer
{
//第1个类:Student
public class Student
{
//三个私有字段(属性)
private int id;
private string name;
private int age;
//另外有一个属性由编译器提供,被自动属性Political操纵
//属性courses:放多门课程被该生修的课程的名字,
// 后面提供索引器来操纵它
private List<string> courses = new List<string>();
//两个相互重载的构造函数:
public Student(int id)
{
this.id = id;
}
public Student(int id, string name, int age)
{
this.id = id;
this.name = name;
this.age = age;
}
//三个操纵字段的Property
//▼操纵字段id的只读Property: ID
public int ID
{
get
{
return id;
}
}
//▼操纵字段name的Property: Name
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
//▼操纵字段age的Property: Age
public int Age
{
get
{
return age;
}
set
{
age = (value >= 12 && value <= 40) ? value : -1;
} //-1是个醒目的非法值
}
//自动Property
public string Political
{ //编译器自动维护有关字段
set;
get;
}
//索引器
public string this[int index]
{
set
{
if (index > courses.Count + 1 || index < 0)
{
Console.WriteLine("设置学生 {0} 的课程时位置超出范围!", name);
}
else if (index == courses.Count + 1)
{
courses.Add(value);
}
else
{
courses.Insert(index, value);
}
}
get
{
if (index >= courses.Count + 1 || index < 0)
{
Console.WriteLine("访问学生{0}的课程时位置超出范围!", name);
return "N/A";
}
else
{
return courses[index];
}
}
}
//需要将对象当作字符串使用的场合,
// 会(自动)调用对象.ToString()
public override string ToString()
{
String s = string.Format(
"======== ID:{0,3} Name:{1,2} Age:{2,2} Political:{3} ========\n",
id, name, age, Political);
s += "{";
foreach (string c in courses)
{
s += string.Format(" {0} ", c);
}
s += "}\n";
return s;
}
}
//第2个类:Class
public class Class
{ //班级类
//只读字段 numberOfStudents:准备在构造函数中赋值
private readonly int numberOfStudents;
//字段 students: 存放班级中同学信息,索引器访问其中的元素
private Student[] students;
//构造函数
public Class(Student[] stuArray)
{
//数组对象Length Property:存放元素个数
students = stuArray;
numberOfStudents = students.Length; //为只读字段赋值
}
//只读Property,访问学生个数
public int NumberOfStudents
{
get
{
return numberOfStudents;
}
}
//【索引器】: 访问班级中的学生
public Student this[int index]
{
get
{
if (index >= 0 && index < numberOfStudents)
return students[index];
else
{
Console.WriteLine("Error:您要访问的学生索引超出范围");
return null;
}
}
set
{
if (index >= 0 && index < numberOfStudents)
students[index] = value;
else
{
Console.WriteLine("Error:设置学生 {0} 时索引超出范围",
value.Name); //((Student)value).Name);
}
}
} //索引器定义结束
public override string ToString()
{
string classStudents = "";
for (int i = 0; i < numberOfStudents; i++)
classStudents += this[i]; // += this[i].ToString();
return classStudents;
}
}
//第3个类:TestIndexer
public class TestIndexer
{
public static void Test()
{
Student[] stuArr = new Student[8];
Class cc = new Class(stuArr);
//访问索引器
cc[0] = new Student(101); //索引器:set
cc[0].Name = "伊尹"; //索引器:get 及 Property:set
cc[0].Age = 23; //索引器:get 及 Property:set
cc[1] = new Student(102, "比干", 19); //索引器:set
cc[2] = new Student(103, "曹操", 23); //索引器:set
cc[3] = new Student(104, "夫差", 22); //索引器:set
cc[4] = new Student(105, "管仲", 19); //索引器:set
cc[5] = new Student(106, "吴起", 17); //索引器:set
cc[6] = new Student(107, "孙权", 22); //索引器:set
cc[7] = new Student(108, "颜渊", 21); //索引器:set
cc[8] = new Student(109, "赵括", 23); //索引器:set--发现越界
cc[5].Political = "党员";
cc[5][0] = "高等数学";
cc[5][1] = "离散数学";
cc[5][2] = "大学英语I";
cc[5][3] = "数据结构";
cc[5][9] = "SQL Server数据库应用";
Console.WriteLine(cc); //cc.ToString()
for (int i = 0; i < cc.NumberOfStudents; i++)
{
//Console.Write(cc[i]); //①索引器:get; ②Student对象.ToString()
Console.Write("{0,4}", cc[i].Name); //索引器:get 及 Property:get
}
Console.WriteLine();
}
}
}
|
9ed83c0bc1490557f7cf1883301f2b0198e7e466
|
C#
|
329277920/Snail.Collector
|
/Snail.Collector.Storage/DB/StorageModel/BaseModel.cs
| 2.53125
| 3
|
using Newtonsoft.Json.Linq;
using Snail.Collector.Core.Storage.DB;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Dapper.SqlMapper;
namespace Snail.Collector.Storage.DB.StorageModel
{
public abstract class BaseModel : IDynamicParameters
{
/// <summary>
/// 获取当前实体
/// </summary>
protected object Entity { get; private set; }
public BaseModel(object entity)
{
this.Entity = entity;
}
/// <summary>
/// 添加Sql执行参数
/// </summary>
/// <param name="command"></param>
/// <param name="identity"></param>
public virtual void AddParameters(IDbCommand command, Identity identity)
{
foreach (var property in JsonParser.GetProperties(this.Entity))
{
if (command.Parameters.Contains(property.Name))
{
continue;
}
var parameter = command.CreateParameter();
parameter.ParameterName = property.Name;
parameter.Value = GetValue(property);
command.Parameters.Add(parameter);
}
}
protected virtual object GetValue(JProperty property)
{
if (property.Value is JValue)
{
if (((JValue)property.Value).Type == JTokenType.Date)
{
return DateTime.Parse(property.Value.ToString()).ToString("s");
}
}
return property.Value;
}
}
}
|
cab1075567de9e1cc56701b29c7bbb17272fccd4
|
C#
|
tdong503/Bridge
|
/Bridge/Program.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using Bridge.CardTypeHandler;
using Bridge.Model;
using Microsoft.Extensions.DependencyInjection;
namespace Bridge
{
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
public ServiceProvider SetDI()
{
//set DI
var serviceProvider = new ServiceCollection()
.AddTransient<Compare>()
.AddTransient<HighCard>()
.AddTransient<Pair>()
.AddTransient<TwoPair>()
.AddTransient<ThreeOfAKind>()
.AddTransient<Straight>()
.AddTransient<Flush>()
.AddTransient<FullHouse>()
.AddTransient<FourOfAKind>()
.AddTransient<StraightFlush>()
.AddTransient(factory =>
{
ICardType Accesor(CardTypes key)
{
switch (key)
{
case CardTypes.StraightFlush:
return factory.GetService<StraightFlush>();
case CardTypes.FourOfAKind:
return factory.GetService<FourOfAKind>();
case CardTypes.FullHouse:
return factory.GetService<FullHouse>();
case CardTypes.Flush:
return factory.GetService<Flush>();
case CardTypes.Straight:
return factory.GetService<Straight>();
case CardTypes.ThreeOfAKind:
return factory.GetService<ThreeOfAKind>();
case CardTypes.TwoPair:
return factory.GetService<TwoPair>();
case CardTypes.Pair:
return factory.GetService<Pair>();
default:
return factory.GetService<HighCard>();
}
}
return (Func<CardTypes, ICardType>) Accesor;
})
.BuildServiceProvider();
return serviceProvider;
}
public string CompareHandCards(string handCardA, string handCardB)
{
var serviceProvider = SetDI();
var cardListA = Common.ConvertCardStringToList(handCardA);
var cardListB = Common.ConvertCardStringToList(handCardB);
var bridge = serviceProvider.GetService<Compare>();
var blackGroup = new HandCard(GroupTypes.Black, cardListA, bridge.DistinguishCardTypes(cardListA));
var whiteGroup = new HandCard(GroupTypes.White, cardListB, bridge.DistinguishCardTypes(cardListB));
return bridge.CompareWith(blackGroup, whiteGroup);
}
}
}
|
0566055fa773bf47a2f10808bac935410bb2fe14
|
C#
|
Measurity/MonoGame.Extended
|
/Source/MonoGame.Extended/RenderTarget2DExtensions.cs
| 2.625
| 3
|
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace MonoGame.Extended
{
public static class RenderTarget2DExtensions
{
public static IDisposable BeginDraw(this RenderTarget2D renderTarget, GraphicsDevice graphicsDevice, Color backgroundColor)
{
return new RenderTargetOperation(renderTarget, graphicsDevice, backgroundColor);
}
private class RenderTargetOperation : IDisposable
{
private readonly GraphicsDevice _graphicsDevice;
private readonly Viewport _viewport;
private readonly RenderTargetUsage _previousRenderTargetUsage;
public RenderTargetOperation(RenderTarget2D renderTarget, GraphicsDevice graphicsDevice, Color backgroundColor)
{
_graphicsDevice = graphicsDevice;
_viewport = _graphicsDevice.Viewport;
_previousRenderTargetUsage = _graphicsDevice.PresentationParameters.RenderTargetUsage;
_graphicsDevice.PresentationParameters.RenderTargetUsage = RenderTargetUsage.PreserveContents;
_graphicsDevice.SetRenderTarget(renderTarget);
_graphicsDevice.Clear(backgroundColor);
}
public void Dispose()
{
_graphicsDevice.SetRenderTarget(null);
_graphicsDevice.PresentationParameters.RenderTargetUsage = _previousRenderTargetUsage;
_graphicsDevice.Viewport = _viewport;
}
}
}
}
|
1858ace7bf8f764eaad32fa8f7ad757abaf6ef2f
|
C#
|
soethan/AlgorithmsExamples
|
/AlgorithmsExamples/BubbleSort.cs
| 3.890625
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlgorithmsExamples
{
/// <summary>
/// On Each Pass
/// Compare each array item to it’s right neighbor
/// If the right neighbor is smaller then Swap right and left
/// Repeat for the remaining array items
/// Perform subsequent passes until no swaps are performed
/// Worst Case: O(n^2)
/// Best Case: O(n)
/// Space Requirement: O(n)
/// </summary>
public class BubbleSort: ISort
{
// 5 4 3 2 1
public void Sort(int[] numbers)
{
bool swapped;
do
{
swapped = false;
for (int i = 1; i < numbers.Length; i++)
{
//left > right ==> swap
if (numbers[i - 1] > numbers[i])
{
var temp = numbers[i];
numbers[i] = numbers[i - 1];
numbers[i - 1] = temp;
swapped = true;
}
}
} while (swapped);
}
}
}
|
657618e86fdfa71d0f9e0324e6b30f4158b6d068
|
C#
|
nishi-yuki/VmplayerUtility
|
/MonoTest/BatchLancherMaker.cs
| 2.515625
| 3
|
using System.IO;
using VmplayerUtilityCore;
using File = System.IO.File;
namespace MonoTest
{
class BatchLancherMaker : ILauncherMaker
{
const string batchFileExtension = @".bat";
public void MakeLauncher(string command, string args, string launcherPath)
{
string filePath = Path.ChangeExtension(
launcherPath, batchFileExtension);
string cmdLine = string.Format("\"{0}\" {1}", command, args);
using (StreamWriter s = File.CreateText(filePath))
{
s.WriteLine(cmdLine);
}
}
}
}
|
c700c93ab62138290e2ce920cab91c1977267c62
|
C#
|
kennh/ninjasamurai
|
/wizard.cs
| 3.546875
| 4
|
using System;
using System.Collections.Generic;
namespace ConsoleApplication
{
// Wizard should have a default health of 50 and intelligence of 25
// Wizard should have a method called heal, which when invoked, heals the Wizard by 10 * intelligence
// Wizard should have a method called fireball, which when invoked, decreases the health of whichever object it attacked by some random integer between 20 and 50
public class Wizard : Human
{
public Wizard(string name, int str,int dex, int intel = 25, int hp = 50) : base(name, str, intel, dex, hp)
{
}
public void heal()
{
intelligence *= 10;
}
public void fireball(Human obj)
{
// (obj);
Random rand = new Random();
obj.health -= rand.Next(20,50);
System.Console.WriteLine(obj.health);
}
}
}
|
ae984b317a912b3deb7bb185e4101ccf199b85b3
|
C#
|
matelopez2012/ServicesGo
|
/ServicesGo/Business_Layer/Controllers/ControladorasCuenta/ControladorActualizarCuenta.cs
| 2.71875
| 3
|
using ServicesGo.Business_Layer.Models;
using ServicesGo.Persistence_Layer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ServicesGo.Business_Layer.Controllers.ControladorasCuenta
{
public class ControladorActualizarCuenta
{
// Instancia del contexto que permitirá mapear la base de datos
private HomeServicesContext DataBaseMap = new HomeServicesContext();
// Consulta si existe la cuenta en la base de datos y la retorna
// null en caso de que no exista
public Cuenta BuscarCuenta(string nombreUsuario)
{
var consultaCuenta = from st in DataBaseMap.Cuentas
where st.NombreUsuario == nombreUsuario
select st;
return consultaCuenta.FirstOrDefault();
}
// Método para actualizar el rol de un usuario
public bool ActualizarRol(string nombreUsuario, string rol)
{
if (BuscarCuenta(nombreUsuario) != null)
{
// Si la cuenta existe la guarda
var cuenta = BuscarCuenta(nombreUsuario);
//Y cambia su rol
cuenta.Rol = rol;
DataBaseMap.SaveChanges();
return true;
}
return false;
}
}
}
|
024b55b0ecf8a726c173bae0fdf791b14cd06064
|
C#
|
babizhu/dafeiji_client
|
/Assets/script/sound/Sound.cs
| 2.765625
| 3
|
using UnityEngine;
using System.Collections;
/**
* 控制整个游戏的声音系统
*/
public class Sound {
/**
* 游戏是否静音
*/
private bool isSilence;
public bool Silence
{
get { return isSilence; }
set { isSilence = value; }
}
private static Sound m_instance = null;
private Sound()
{
}
public static Sound getInstance()
{
if (m_instance == null)
{
m_instance = new Sound();
}
return m_instance;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
/**
* 播放声音
*/
public void play(AudioClip clip)
{
if (!Silence && clip != null )
{
AudioSource.PlayClipAtPoint(clip, new Vector3());
}
}
}
|
aca0f094bcab621fbba0407acf2ef741668eaf25
|
C#
|
IreNox/tiki1
|
/Components/Elements/Events/DoWhatIWantEvent.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TikiEngine.Elements.Graphics;
using Microsoft.Xna.Framework;
using TikiEngine.Elements.Trigger;
namespace TikiEngine.Elements.Events
{
public class DoWhatIWantEvent : GameEvent
{
#region Vars
private Action<GameTime> _doWhatIWant;
#endregion
#region Init
public DoWhatIWantEvent(GameTrigger trigger, Action<GameTime> doWhatIWant, bool unique)
: base(trigger)
{
_doWhatIWant = doWhatIWant;
this.unique = unique;
}
#endregion
#region Member
public override void Update(GameTime gameTime)
{
trigger.Update(gameTime);
if (trigger.Triggered())
{
_doWhatIWant(gameTime);
}
base.Update(gameTime);
}
#endregion
#region Properties
public Action<GameTime> DoWhatIWant
{
get { return _doWhatIWant; }
set { _doWhatIWant = value; }
}
#endregion
}
}
|
767c6c64692360c668f7f84838d7def8131149b9
|
C#
|
nguyendinhandp/econhom3
|
/ecoNhom3/Controllers/NhaCungCapsController.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using ecoNhom3.Models;
namespace ecoNhom3.Controllers
{
public class NhaCungCapsController : Controller
{
private readonly MyDbContext _context;
public NhaCungCapsController(MyDbContext context)
{
_context = context;
}
public IActionResult Index()
{
var n = _context.NhaCungCaps.ToList();
return View(n);
}
public IActionResult Details()
{
return View();
}
// PUT: api/NhaCungCaps/5
public async Task<IActionResult> Edit(int id, NhaCungCap nhaCungCap)
{
if (id != nhaCungCap.MaNcc)
{
return BadRequest();
}
_context.Entry(nhaCungCap).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!NhaCungCapExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
[HttpPost]
public async Task<ActionResult<NhaCungCap>> Create (NhaCungCap nhaCungCap)
{
_context.NhaCungCaps.Add(nhaCungCap);
await _context.SaveChangesAsync();
return CreatedAtAction("GetNhaCungCap", new { id = nhaCungCap.MaNcc }, nhaCungCap);
}
public async Task<ActionResult<NhaCungCap>> Delete(int id)
{
var nhaCungCap = await _context.NhaCungCaps.FindAsync(id);
if (nhaCungCap == null)
{
return NotFound();
}
_context.NhaCungCaps.Remove(nhaCungCap);
await _context.SaveChangesAsync();
return nhaCungCap;
}
private bool NhaCungCapExists(int id)
{
return _context.NhaCungCaps.Any(e => e.MaNcc == id);
}
}
}
|
7763550ccc93ac320d480810cc2e5a548b24a041
|
C#
|
kleopatra999/Aspose.Pdf-for-.NET
|
/Examples/CSharp/AsposePdfGenerator/Headings/SystemBullets.cs
| 3.109375
| 3
|
using System;
using System.IO;
using Aspose.Pdf;
namespace Aspose.Pdf.Examples.CSharp.AsposePdfGenerator.Headings
{
public class SystemBullets
{
public static void Run()
{
// ExStart:SystemBullets
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdfGenerator_Headings();
// Instntiate the Pdf object by calling its empty constructor
Aspose.Pdf.Generator.Pdf pdf1 = new Aspose.Pdf.Generator.Pdf();
// Create the section in the Pdf object
Aspose.Pdf.Generator.Section sec1 = pdf1.Sections.Add();
/*
* Create 1st heading in the Pdf object's section with level=1. Then create
* a text segment and add it in the heading. Set its UserLabel="Bullet1" to
* use system defined bullet. After setting all properties, add heading into
* the paragraphs collection of the section
*/
Aspose.Pdf.Generator.Heading heading1 = new Aspose.Pdf.Generator.Heading(pdf1, sec1, 1);
Aspose.Pdf.Generator.Segment segment1 = new Aspose.Pdf.Generator.Segment(heading1);
heading1.Segments.Add(segment1);
segment1.Content = "Bullet1";
heading1.UserLabel = "Bullet1";
sec1.Paragraphs.Add(heading1);
/*
* Create 2nd heading in the Pdf object's section with level=2. Then create
* a text segment and add it in the heading. Set its UserLabel="Bullet2" to
* use system defined bullet. After setting all properties, add heading into
* the paragraphs collection of the section
*/
Aspose.Pdf.Generator.Heading heading2 = new Aspose.Pdf.Generator.Heading(pdf1, sec1, 2);
Aspose.Pdf.Generator.Segment segment2 = new Aspose.Pdf.Generator.Segment(heading2);
heading2.Segments.Add(segment2);
segment2.Content = "Bullet2";
heading2.UserLabel = "Bullet2";
sec1.Paragraphs.Add(heading2);
/*
* Create 3rd heading in the Pdf object's section with level=3. Then create
* a text segment and add it in the heading. Set its UserLabel="Bullet3" to
* use system defined bullet. After setting all properties, add heading into
* the paragraphs collection of the section
*/
Aspose.Pdf.Generator.Heading heading3 = new Aspose.Pdf.Generator.Heading(pdf1, sec1, 3);
Aspose.Pdf.Generator.Segment segment3 = new Aspose.Pdf.Generator.Segment(heading3);
heading3.Segments.Add(segment3);
segment3.Content = "Bullet3";
heading3.UserLabel = "Bullet3";
sec1.Paragraphs.Add(heading3);
pdf1.Save(dataDir + "SystemBullets_out.pdf");
// ExEnd:SystemBullets
}
}
}
|
7d9098373c49f298333e6c3ab8b38d6aa43dfb58
|
C#
|
shendongnian/download4
|
/first_version_download2/5811-306406-486312-2.cs
| 3.421875
| 3
|
public delegate bool ItemFilterDelegate(MyItem item);
public IEnumerable<MyItem> FilterItems(ItemFilterDelegate filter)
{
var result = new List<MyItem>();
foreach(MyItem item in AllItems)
{
if(filter(item))
result.Add(item);
}
return item;
}
public IEnumerable<MyItem> FilterByName(string name)
{
return FilterItems(item => item.Name == name);
}
|
598a918af1371008e8563073558efc6596694a86
|
C#
|
shendongnian/download4
|
/code1/120781-55692375-195878993-4.cs
| 2.78125
| 3
|
public static string GetCommonPrefixParallel ( IList<string> strings )
{
var stringsCount = strings.Count;
if( stringsCount == 0 )
return null;
if( stringsCount == 1 )
return strings[0];
var firstStr = strings[0];
var finalList = new List<string>();
var myLock = new object();
Parallel.For( 1, stringsCount,
() => new StringBuilder( firstStr ),
( i, loop, localSb ) =>
{
var sbLen = localSb.Length;
var str = strings[i];
var strLen = str.Length;
if( sbLen > strLen )
localSb.Length = sbLen = strLen;
for( int j = 0; j < sbLen; j++ )
{
if( localSb[j] != str[j] )
{
localSb.Length = j;
break;
}
}
return localSb;
},
( localSb ) =>
{
lock( myLock )
{
finalList.Add( localSb.ToString() );
}
} );
return GetCommonPrefix( finalList );
}
|
af435d45b8419b649fc9515723b2b05c8beb1490
|
C#
|
khoiquyenvn/DetectPropertyChange
|
/ConsoleApp1/Extension.cs
| 3.25
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Linq;
namespace ConsoleApp1
{
static class Extentions
{
public static List<Variance> DetailedCompare<T>(T val1, T val2)
{
List<Variance> variances = new List<Variance>();
CompareField(val1, val2, variances);
ComparePros(val1, val2, variances);
return variances;
}
private static void CompareField<T>(T val1, T val2, List<Variance> variances)
{
FieldInfo[] fi = val1.GetType().GetFields();
foreach (FieldInfo f in fi)
{
Variance v = new Variance();
v.Prop = f.Name;
v.valA = f.GetValue(val1);
v.valB = f.GetValue(val2);
if (!v.valA.Equals(v.valB))
variances.Add(v);
}
}
private static void ComparePros<T>(T val1, T val2, List<Variance> variances)
{
PropertyInfo[] pi = val1.GetType().GetProperties();
foreach (PropertyInfo p in pi)
{
Variance v = new Variance();
v.Prop = p.Name;
if (p.PropertyType.Namespace == "System.Collections.Generic")
{
dynamic lst1 = p.GetValue(val1);
dynamic lst2 = p.GetValue(val2);
if (lst1 != null && lst2 != null)
{
var notExistInList2 = ((IEnumerable<dynamic>)lst1).Except((IEnumerable<dynamic>)lst2).ToList();
var notExistInList1 = ((IEnumerable<dynamic>)lst2).Except((IEnumerable<dynamic>)lst1).ToList();
if (notExistInList1.Any() || notExistInList2.Any())
{
v.valA = lst1;
v.valB = lst2;
v.DeleteItems = notExistInList2;
v.ModifyItems = notExistInList1;
variances.Add(v);
}
}
}
else
{
v.valA = p.GetValue(val1);
v.valB = p.GetValue(val2);
if (!v.valA.Equals(v.valB))
variances.Add(v);
}
}
}
}
class Variance
{
public string Prop { get; set; }
public dynamic valA { get; set; }
public dynamic valB { get; set; }
public dynamic DeleteItems { get; set; }
public dynamic ModifyItems { get; set; }
}
}
|
43b08a23dcff3c24db579c1090eecce05218470c
|
C#
|
AugustFrank/OrchidSecure
|
/OrchidSecure/OrchidSecure/Models/Address/Address.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace OrchidSecure.Models.Address
{
public class Address
{
private int id;
private string address;
private int zipcode;
public Address() { }
public Address(int pId, string pAddress, int pZipcode)
{
this.id = pId;
this.address = pAddress;
this.zipcode = pZipcode;
}
public void setId(int pId)
{
this.id = pId;
}
public int getId()
{
return this.id;
}
public void setAddress(string pAddress)
{
this.address = pAddress;
}
public string getAddress()
{
return this.address;
}
public void setZipcode(int pZipcode)
{
this.zipcode = pZipcode;
}
public int getZipcode()
{
return this.zipcode;
}
}
}
|
a1b7453ce4100006e184536491382425ef318507
|
C#
|
BMGDigitalTech/abhilash-projects
|
/dataIFD/dataIFD/Program.cs
| 3.671875
| 4
|
using System;
namespace dataIFD
{
class Program
{
static void Main(string[] args)
{
int inum1 = 54;
int inum2 = 51;
int isum = inum1 + inum2;
double d1 = 3.51;
double d2 = 5.65;
double dsum = d1 + d2;
float f1 = 5.51F;
float f2 = 6.52F;
float fsum = f1 + f2;
Console.WriteLine("Sum of integers " + inum1 + " and " + inum2 + " is " + isum);
Console.WriteLine("Sum of double " + d1 + " and " + d2 + " is " + dsum);
Console.WriteLine("Sum of float " + f1 + " and " + f2 + " is " + fsum);
Console.Read();
}
}
}
|
fb6412d95a0590a6fae1386379a86273813b8b3d
|
C#
|
vknez95/GreedKataGame
|
/Utility/IListExtensions.cs
| 2.859375
| 3
|
using System;
using System.Collections.Generic;
namespace GreedKataGame.Utility
{
public static class IListExtensions
{
public static void AddIfNotNull<T>(this IList<T> source, T value)
{
if (value != null)
{
source.Add(value);
}
}
}
}
|
f4dd9c53b7bb81ba05625dd05c4ad39d80dc4de5
|
C#
|
richrd77/EFCrud
|
/EFCrud/EFCrud/Controllers/WeatherForecastController.cs
| 2.75
| 3
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EFCrud.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private readonly ILogger<WeatherForecastController> _logger;
private readonly MyDBContext dbContext;
public WeatherForecastController(ILogger<WeatherForecastController> logger, MyDBContext context)
{
_logger = logger;
this.dbContext = context;
}
[HttpGet]
public List<Employee> Get()
{
return dbContext.Employees.ToList();
}
[HttpPost]
public bool Post( [FromBody] Employee newEmployee)
{
var newEmp = new Employee();
newEmp.FirstName = newEmployee.FirstName;
dbContext.Employees.Add(newEmp);
dbContext.SaveChanges();
return true;
}
[HttpDelete]
public bool Delete([FromBody] int deleteId)
{
var foundEmployee = dbContext.Employees.Find(deleteId);
dbContext.Employees.Remove(foundEmployee);
dbContext.SaveChanges();
return true;
}
}
}
|
e42dbd3cc8125df5cad9d160d904691e86e33222
|
C#
|
TatoSoftware/SudokuAnalyzer
|
/App_Code/clsSK.cs
| 2.953125
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml;
// This class is the workhorse of the Soduku solving engine and is the only interface to the various techniques
// that are used to solved a puzzle. Think of it as pure Sudoku solving and nothing to do with the user interface
public class clsSK
{
const int MAXITERATIONS = 9999999;
// rows are 0 to 8, columns are 0 to 8
//9 elements addressed by 0 to 8
int[, ,] mSK = new int[10, 10, 10];
clsStats myStats = new clsStats();
int mNoOfChanges;
public int gCurrentMethod;
const string COJO_METHOD_COLORING = "COLO";
const string COJO_METHOD_COJOINS = "COJO";
//returned as property
string mReasonCode;
bool mbIsPuzzleValid;
bool mUseBruteForce = true;
bool mUseNishio = true;
int mIterationCnt;
bool mbIsPuzzleSolved;
//
public string ReasonCode
{
get { return mReasonCode; }
}
public bool IsPuzzleValid
{
get { return mbIsPuzzleValid; }
}
public bool IsPuzzleSolved
{
get { return mbIsPuzzleSolved; }
}
public int IterationCount
{
set { mIterationCnt = value; }
}
public bool UseBruteForce
{
set { mUseBruteForce = value; }
}
public bool UseNishio
{
set { mUseNishio = value; }
}
public void LoadFromXML(ref XmlDocument XML_IC)
{
//
clsSolnSets mySolnSets = new clsSolnSets();
mSK.Initialize();
ConvertXMLtoArray(ref XML_IC);
mbIsPuzzleValid = mySolnSets.IsThisCaseValid(mSK);
//this object only used for this purpose
//tell front end case is invalid, ie something wrong with user input.
mbIsPuzzleSolved = false;
if (mbIsPuzzleValid)
{
mReasonCode = "VALIDINPUT";
if (sIsSolved() == "Yes")
{
mbIsPuzzleSolved = true;
//new feature to simplify front end
}
}
else
{
mReasonCode = "INVALIDINPUT";
}
}
public void LoadFromArray(int[, ,] skArg)
{
// nisho has already prepared the array, just copy it to this object
short r = 0;
short c = 0;
short p = 0;
clsSolnSets mySolnSets = new clsSolnSets();
mSK.Initialize();
for (r = 0; r <= 8; r++)
{
for (c = 0; c <= 8; c++)
{
for (p = 1; p <= 9; p++)
{
mSK[r, c, p] = skArg[r, c, p];
}
}
}
mbIsPuzzleValid = mySolnSets.IsThisCaseValid(mSK);
//this object only used for this purpose
//tell front end case is invalid, ie something wrong with user input.
if (mbIsPuzzleValid)
{
mReasonCode = "VALIDINPUT";
}
else
{
mReasonCode = "INVALIDINPUT";
}
}
public void SolveIT()
{
//
//based on the number of iterations to perform, count set via a property
//
do
{
mNoOfChanges = 0;
NewIteration();
mIterationCnt = mIterationCnt - 1;
} while (!(mNoOfChanges == 0 | mIterationCnt == 0));
}
public XmlDocument GetXMLResults()
{
//
//gather all info and return to front end via an xml document/string
//
//<cell>3 4 157<\cell> 2 values for r 3 col 4
//<cell>8 8 9<\cell> 1 value for cell on bottom right
//<stats>xx nnnn<\stats> eg xw 0024 24 cells changed via x-wing method
//<solved>yes or no<\solved>
//<changes>0000<\changes> total changes made this iteration
//<reason>Invalid User Input<\reason> reason why puzzle invalid, (user input error or >1 solution
// or reason why brute force analysis stopped
//<valid>yes or no<\valid>
XmlDocument XML_CS = new XmlDocument();
XmlElement elem = null;
XmlNode root = null;
string sPlist = null;
string sValue = null;
int r = 0;
int c = 0;
int p = 0;
XML_CS.LoadXml("<case caseid ='none' source='cdf' level='none' hardest='none' reason='none' casename='none' casedef='none' casesolution='none'> </case>");
root = XML_CS.DocumentElement;
//clone the text boxes to a integer array
for (r = 0; r <= 8; r++)
{
for (c = 0; c <= 8; c++)
{
sPlist = "";
for (p = 1; p <= 9; p++)
{
if (mSK[r, c, p] == 1)
{
sPlist = sPlist + p;
//build list of possibles
}
}
//new format for xml_cs is 'r c 12345' not 'xx 12345'
sValue = Convert.ToString(r) + " " + Convert.ToString(c) + " " + sPlist; //csNote
//Create a new node.
elem = XML_CS.CreateElement("cell");
elem.InnerText = sValue;
//Add the node to the document.
root.AppendChild(elem);
}
}
myStats.GetXMLStats(ref XML_CS); //append statistics
//
//total changes, create node and append to document
//
sValue = String.Format("{0:0000}", mNoOfChanges);
elem = XML_CS.CreateElement("changes");
elem.InnerText = sValue;
root.AppendChild(elem);
//
// solved or not flag, create node and append to document
//
sValue = sIsSolved();
elem = XML_CS.CreateElement("status");
elem.InnerText = sValue;
root.AppendChild(elem);
//
// case valid or not flag, create node and append to document
//
//tranform to text
if (mbIsPuzzleValid)
{
sValue = "Yes";
}
else
{
sValue = "No";
}
elem = XML_CS.CreateElement("valid");
elem.InnerText = sValue;
root.AppendChild(elem);
//
// reason why puzzle is not valid create node and append to document
//
sValue = mReasonCode;
elem = XML_CS.CreateElement("reason");
elem.InnerText = sValue;
root.AppendChild(elem);
//all done return the document
return XML_CS;
}
private void ConvertXMLtoArray(ref XmlDocument XML_IC)
{
int r = 0;
int c = 0;
int p = 0;
string sValue = null;
string sCandidates = null;
string sP = null;
int[,] intCells = new int[9,9];
intCells.Initialize();
//
XmlNodeList elemList = XML_IC.GetElementsByTagName("cell");
int i = 0;
//
//each cell is represented by the form "r c 12357" set r,c p values to 12357
//
for (i = 0; i <= elemList.Count - 1; i++)
{
sValue = elemList[i].InnerXml;
r = Convert.ToInt16(sValue.Substring(0, 1)); //csNote
c = Convert.ToInt16(sValue.Substring(2, 1));
sCandidates = sValue.Substring(4);
//to end of string
for (p = 1; p <= 9; p++)
{
sP = Convert.ToString(p);
if (sCandidates.Contains(sP))
{
mSK[r, c, p] = 1;
intCells[r, c] = 1; //csNote new feature, if no cell specified default to all p values
}
}
}
// if in xml the cell is not specified or blank default it to 123456789
for (r = 0; r <= 8; r++)
{
for (c = 0; c <= 8; c++)
{
if (intCells[r, c] == 0)
{
for (p = 1; p <= 9; p++)
{
mSK[r, c, p] = 1;
} //next p
}
} //next col
} //next row
}
public void NewIteration()
{
// Methods to convert/test
// Solution Sets - work in progress
// solve one iteration of the puzzle, solve once really means just one iteration, not 1,2,4,8 as before
//
clsSolnSets mySolnSets = default(clsSolnSets);
clsNineByNine myNineByNine = default(clsNineByNine);
clsColoring myColoring = default(clsColoring);
clsGordonian myGordonian = default(clsGordonian);
clsNishio myNishio = default(clsNishio);
clsBrute myBrute = default(clsBrute);
int iOldChangeCnt = 0;
int p = 0;
//
//solve all row, column or box's (solution sets) independently
//
mySolnSets = new clsSolnSets();
iOldChangeCnt = mNoOfChanges;
mySolnSets.NewIteration(ref mSK, mIterationCnt);
mNoOfChanges = mNoOfChanges + mySolnSets.ChangeCount;
if (mySolnSets.ChangeCount > 0)
{
myStats.UpdateStats("NS", mySolnSets.NakedSingles);
myStats.UpdateStats("HS", mySolnSets.HiddenSingles);
myStats.UpdateStats("NP", mySolnSets.NakedPairs);
myStats.UpdateStats("NT", mySolnSets.NakedTriples);
myStats.UpdateStats("NQ", mySolnSets.NakedQuads);
myStats.UpdateStats("HP", mySolnSets.HiddenPairs);
myStats.UpdateStats("LB", mySolnSets.LockedBoxes);
myStats.UpdateStats("LR", mySolnSets.LockedRows);
myStats.UpdateStats("LC", mySolnSets.LockedCols);
myStats.UpdateStats("HT", mySolnSets.HiddenTriples);
myStats.UpdateStats("HQ", mySolnSets.HiddenQuads);
}
mySolnSets = null;
//for clarity in single stepping, don't change too much at once
if (mNoOfChanges > iOldChangeCnt) return;
//
// look for Gordonian Rectangles
//
iOldChangeCnt = mNoOfChanges;
myGordonian = new clsGordonian();
myGordonian.Gordonian(ref mSK);
switch (myGordonian.Method)
{
case "GRNP":
myStats.UpdateStats("GR", myGordonian.ChangeCount);
break;
case "GROS":
myStats.UpdateStats("GO", myGordonian.ChangeCount);
break;
case "GRPP":
myStats.UpdateStats("GP", myGordonian.ChangeCount);
break;
}
mNoOfChanges = mNoOfChanges + myGordonian.ChangeCount;
myGordonian = null;
if (mNoOfChanges > iOldChangeCnt) return; //for clarity in single stepping, don't change too much at once
//
// X-wing Look at the entire matrix
//
iOldChangeCnt = mNoOfChanges;
for (p = 1; p <= 9; p++)
{
myNineByNine = new clsNineByNine();
var _with3 = myNineByNine;
_with3.pValue = p;
_with3.BuildMatrix(ref mSK);
_with3.Xwing(ref mSK);
myStats.UpdateStats("XW", _with3.ChangeCount);
mNoOfChanges = mNoOfChanges + _with3.ChangeCount;
myNineByNine = null;
}
//for clarity in single stepping, don't change too much at once
if (mNoOfChanges > iOldChangeCnt) return;
//
// SwordFish - look at entire matrix
//
iOldChangeCnt = mNoOfChanges;
for (p = 1; p <= 9; p++)
{
myNineByNine = new clsNineByNine();
var _with4 = myNineByNine;
_with4.pValue = p;
_with4.BuildMatrix(ref mSK);
_with4.SwordFish(ref mSK);
myStats.UpdateStats("SW", _with4.ChangeCount);
mNoOfChanges = mNoOfChanges + _with4.ChangeCount;
myNineByNine = null;
}
if (mNoOfChanges > iOldChangeCnt) return; //for clarity in single stepping, don't change too much at once
//
// Coloring, look at entire matrix, one p value only look for a chain of co-jointed pairs
//
iOldChangeCnt = mNoOfChanges;
for (p = 1; p <= 9; p++)
{
myColoring = new clsColoring();
var _with5 = myColoring;
_with5.pValue = p;
_with5.BuildMatrix(ref mSK);
_with5.COJOChains(ref mSK);
if (myColoring.Method == COJO_METHOD_COJOINS)
{
myStats.UpdateStats("CJ", myColoring.ChangeCount);
//will be one or the other
}
else if (myColoring.Method == COJO_METHOD_COLORING)
{
myStats.UpdateStats("CO", myColoring.ChangeCount);
//but not both
}
mNoOfChanges = mNoOfChanges + _with5.ChangeCount;
//only solve for 1 p value for clarity in single stepping
if (myColoring.ChangeCount != 0) break;
myColoring = null;
}
if (mNoOfChanges > iOldChangeCnt) return; //for clarity in single stepping, don't change too much at once
//
// Now try Nishio, looking for naked pairs and guessing as to which one is correct
//
if (mUseNishio)
{
myNishio = new clsNishio();
myNishio.TryNishio(ref mSK);
mNoOfChanges = mNoOfChanges + myNishio.ChangeCount;
myStats.UpdateStats("NI", myNishio.ChangeCount);
myNishio = null;
}
if (mNoOfChanges > iOldChangeCnt) return; //for clarity in single stepping, don't change too much at once
//
//now try brute force (if requested) if all known methods have failed
//note Nishio will create another instance of clsSK.. very cool
//
if (mUseBruteForce)
{
if (mNoOfChanges == 0 & sIsSolved() == "No")
{
myBrute = new clsBrute();
myBrute.Analyze(ref mSK);
if (myBrute.IsSolveable)
{
mbIsPuzzleValid = true;
mReasonCode = myBrute.ReasonCode;
//one solution, found by brute force
myStats.UpdateStats("BF", myBrute.NoOfChanges);
mNoOfChanges = mNoOfChanges + myBrute.NoOfChanges;
}
else
{
mbIsPuzzleValid = false;
mReasonCode = myBrute.ReasonCode;
//probably more than 1 solution
}
}
}
}
//xxxx
public string sIsSolved()
{
string functionReturnValue = null;
//
// Need to check all solution sets
// each and every one must contain the numbers 1..9
//
int r = 0;
int c = 0;
int p = 0;
int pTotals = 0;
int[] pCnts = new int[10];
//make sure we have 9 occurances of every number 1..9
int[,] miniSK = new int[9, 9];
//copy of grid looking at only scalars
int iNoOfPValues = 0;
int iPValue = 0;
//define the top left corner of each box in the mini grid
int[,] iBoxMap = { { 0, 0 }, { 0, 3 }, { 0, 6 }, { 3, 0 }, { 3, 3 }, { 3, 6 }, { 6, 0 }, { 6, 3 }, { 6, 6 } };
int iBox = 0;
pCnts.Initialize();
functionReturnValue = "Yes";
pTotals = 0;
//make a copy of the grid with only solved p values
for (r = 0; r <= 8; r++)
{
for (c = 0; c <= 8; c++)
{
iNoOfPValues = 0;
for (p = 1; p <= 9; p++)
{
if (mSK[r, c, p] == 1)
{
iNoOfPValues = iNoOfPValues + 1;
iPValue = p;
pTotals = pTotals + p;
}
}
if (iNoOfPValues == 1)
{
miniSK[r, c] = iPValue;
//clone grid to with only p values
}
else
{
functionReturnValue = "No";
return functionReturnValue;
//still choices to make therefore unsolved
}
}
}
//simple (original) test only proves puzzle is not valid, not the inverse.
if (pTotals != 405)
{
functionReturnValue = "No";
return functionReturnValue;
}
//
//
//make sure 1 2 3 4 5 6 7 8 9 in every row
//
for (r = 0; r <= 8; r++)
{
for (p = 1; p <= 9; p++)
{
pCnts[p] = 0;
//array.initialize did not work at run time
}
for (c = 0; c <= 8; c++)
{
pCnts[miniSK[r, c]] = pCnts[miniSK[r, c]] + 1;
}
for (p = 1; p <= 9; p++)
{
if (pCnts[p] != 1)
{
functionReturnValue = "No";
return functionReturnValue;
}
}
}
//make sure 1 2 3 4 5 6 7 8 9 in every column
for (c = 0; c <= 8; c++)
{
for (p = 1; p <= 9; p++)
{
pCnts[p] = 0;
//array.initialize did not work at run time
}
for (r = 0; r <= 8; r++)
{
pCnts[miniSK[r, c]] = pCnts[miniSK[r, c]] + 1;
}
for (p = 1; p <= 9; p++)
{
if (pCnts[p] != 1)
{
functionReturnValue = "No";
return functionReturnValue;
}
}
}
//
//still not good enough, need to check every box
//
for (iBox = 0; iBox <= 8; iBox++)
{
for (p = 1; p <= 9; p++)
{
pCnts[p] = 0;
}
for (r = iBoxMap[iBox, 0]; r <= iBoxMap[iBox, 0] + 2; r++)
{
for (c = iBoxMap[iBox, 1]; c <= iBoxMap[iBox, 1] + 2; c++)
{
pCnts[miniSK[r, c]] = pCnts[miniSK[r, c]] + 1;
}
}
for (p = 1; p <= 9; p++)
{
if (pCnts[p] != 1)
{
functionReturnValue = "No";
return functionReturnValue;
}
}
}
return functionReturnValue;
}
//xxxx
//=====
public string sGetPCount(int viP)
//
// returns the number of times the passed p value occurs in the grid
// eg a=sGetPCount("8") returns 3 if there are 3 8's in the grid which have been solved
// a=sGetPCount("2") returns 0 if there are no 2's solved in the grid
//
{
string sfunctionReturnValue = null;
//
// Need to check all solution sets
// each and every one must contain the numbers 1..9
//
int r = 0;
int c = 0;
int p = 0;
int ipCnts = 0;
bool bIsPaCandidate = false;
int iSolvedPCnt = 0;
for (r = 0; r <= 8; r++)
{
for (c = 0; c <= 8; c++)
{
bIsPaCandidate = false;
ipCnts = 0;
for (p = 1; p <= 9; p++) //check all the candidates
{
if (mSK[r, c, p] == 1) {ipCnts = ipCnts + 1;}
if (mSK[r, c, viP] == 1) { bIsPaCandidate = true; }
}
if (ipCnts == 1 && bIsPaCandidate) {iSolvedPCnt = iSolvedPCnt + 1;}
}
}
sfunctionReturnValue = Convert.ToString(iSolvedPCnt);
return sfunctionReturnValue;
}
//=====
private void myDebug(string sMess)
{
//Redirect all Output Window text to the Immediate Window" checked under the menu Tools > Options > Debugging > General.
//System.Diagnostics.Debug.WriteLine(sMess);
}
}
|
1d08bf181fb749bb441c92e79dfd0b47e1167bf4
|
C#
|
NikolayKertev/SoftUni-Fundamentals
|
/Exercises/03_Methods/08_Factoriel Divider/Program.cs
| 3.96875
| 4
|
using System;
namespace Factoriel_Divider
{
class Program
{
static void Main(string[] args)
{
decimal a = int.Parse(Console.ReadLine());
decimal b = int.Parse(Console.ReadLine());
decimal facA = facSum(a);
decimal facB = facSum(b);
decimal output = factorielDivider(facA, facB);
Console.WriteLine($"{output:f2}");
}
private static decimal factorielDivider(decimal x, decimal y)
{
return x / y;
}
private static decimal facSum(decimal x)
{
decimal counter = x;
decimal sumFac = 1;
for (int i = 1; i <= x; i++)
{
sumFac *= counter;
counter--;
}
return sumFac;
}
}
}
|
b23e6a86e546354747daf808eb0d38e4045d1312
|
C#
|
alexbasic/Lototron
|
/Lototron/Program.cs
| 3.28125
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace SimLoto
{
partial class Program
{
static void Main(string[] args)
{
while (true)
{
Console.Clear();
ConsoleExtension.WriteLine(ConsoleColor.Yellow, "========= Лото 5 из 15 =========\r\n");
ConsoleExtension.WriteLine(ConsoleColor.Red, "Натренируй удачу!\r\n");
Console.WriteLine("Начинаем новый розыгрыш.\r\n");
bool isWin = false;
bool runGame = true;
var ticketNumber = 0;
var loto = new Loto();
while (!isWin && runGame)
{
var ticket = InputNumbers(5);
ticketNumber++;
isWin = loto.GuessNumbers(ticket);
if (isWin)
{
ConsoleExtension.WriteLine(ConsoleColor.Red, "=========================");
ConsoleExtension.WriteLine(ConsoleColor.Yellow, "Bingo!!!");
ConsoleExtension.WriteLine(ConsoleColor.Green, "ВЫ ВЫИГРАЛИ !!!");
Console.Write("Номера: /");
foreach (var item in ticket) { Console.Write("{0}, ", item); }
Console.WriteLine("/");
ConsoleExtension.WriteLine(ConsoleColor.Blue, "=========================\r\n");
ConsoleExtension.WriteLine(ConsoleColor.White, "Для продолжения нажми любую клавишу.");
Console.ReadKey();
break;
}
else if (loto.CountIntersects(ticket) == 3)
{
ConsoleExtension.WriteLine(ConsoleColor.Yellow, "=========================");
ConsoleExtension.WriteLine(ConsoleColor.Yellow, "Маленький выигрыш");
ConsoleExtension.WriteLine(ConsoleColor.Yellow, "Совпали три");
ConsoleExtension.WriteLine(ConsoleColor.Yellow, "=========================\r\n");
}
else
{
Console.WriteLine("Билет не выиграл...");
}
runGame = ConsoleExtension.BooleanQuestion("\r\nПопробуй другой билет! (Да/Нет)", ConsoleColor.Yellow);
Console.WriteLine("\r\n");
}
}
Console.ReadLine();
}
static IEnumerable<int> InputNumbers(int count)
{
Console.WriteLine("Введи 5 чисел.");
var sequece = new List<int>();
var isNumber = false;
var isNotUniq = false;
for (var i = 0; i < count; i++)
{
var number = 0;
do
{
Console.Write("Число {0} >", i + 1);
isNumber = int.TryParse(Console.ReadLine(), out number);
isNotUniq = sequece.Contains(number);
if (isNotUniq) Console.WriteLine("Это число уже введено!");
} while (!isNumber || isNotUniq);
sequece.Add(number);
}
return sequece;
}
}
}
|
a28590e8a64274113520986ebf57455c28cc008e
|
C#
|
MCVitzz/Lamp
|
/Lamp/Rendering/Buffers/VAO.cs
| 2.515625
| 3
|
using Lamp.Models;
using OpenTK.Graphics.OpenGL4;
namespace Lamp.Rendering.Buffers
{
public class VAO
{
private readonly int Id;
public VBO Vbo;
public BufferLayout Layout;
public IBO Ibo;
protected int Size;
public VAO()
{
Id = GL.GenVertexArray();
}
public VAO(ModelData model, BufferLayout layout) : this()
{
Allocate(model);
BindAll();
SetPointers(layout);
EnablePointers();
}
public void Allocate(ModelData model)
{
Vbo = new VBO();
Ibo = new IBO();
Vbo.Bind();
Ibo.Bind();
Vbo.Allocate(model.Vertices);
Ibo.Allocate(model.Indices);
Size = model.Indices.Length;
}
public void Draw()
{
GL.Enable(EnableCap.DepthTest);
BindAll();
GL.DrawElements(PrimitiveType.Triangles, Size, DrawElementsType.UnsignedShort, 0);
}
public void SetPointers(BufferLayout layout)
{
Layout = layout;
BindAll();
int i = 0;
foreach(BufferElement element in layout.GetElements())
{
GL.VertexAttribPointer(
i,
element.type.GetElements(),
element.type.GetDataType(),
element.normalized,
layout.GetStride(),
element.offset);
i++;
}
}
public void EnablePointers()
{
for(int i = 0; i < Layout.GetElements().Count; i++)
{
GL.EnableVertexAttribArray(i);
}
}
public void DisablePointers()
{
for (int i = 0; i < Layout.GetElements().Count; i++)
{
GL.DisableVertexAttribArray(i);
}
}
public virtual void BindAll()
{
Bind();
Vbo.Bind();
Ibo.Bind();
}
public void Bind()
{
GL.BindVertexArray(Id);
}
public void Unbind()
{
GL.BindVertexArray(0);
}
public void Destroy()
{
GL.DeleteVertexArray(Id);
Vbo.Destroy();
Ibo.Destroy();
}
}
}
|
6ef97b0d74988e0b53a50b585bd4786934aec8c1
|
C#
|
redplane/iConfess
|
/A-SOURCE_CODE/A-SERVICE/Administration/Notification/Models/CloudBasicQueue.cs
| 2.609375
| 3
|
namespace NotificationManagement.Models
{
public class CloudBasicQueue
{
#region Properties
/// <summary>
/// Name of queue which is used for exchanging messages.
/// </summary>
public string Exchange = "account-registration";
/// <summary>
/// Kind of queue which is used for broadcasting information.
/// </summary>
public string KindOfQueue = "fanout";
/// <summary>
/// If set when creating a new exchange, the exchange will be marked as durable. Durable exchanges remain active when a server restarts. Non-durable exchanges (transient exchanges) are purged if/when a server restarts.
/// The server MUST support both durable and transient exchanges.
/// </summary>
public bool Durable = true;
/// <summary>
/// If set, the exchange is deleted when all queues have finished using it.
/// The server SHOULD allow for a reasonable delay between the point when it determines that an exchange is not being used(or no longer used), and the point when it deletes the exchange.At the least it must allow a client to create an exchange and then bind a queue to it, with a small but non-zero delay between these two actions.
/// The server MUST ignore the auto-delete field if the exchange already exists.
/// </summary>
public bool AutoDelete = false;
/// <summary>
/// Whether acknowlege message should be sent to queue and a message has been consumed or not.
/// </summary>
public bool AutoAcknowledge = true;
/// <summary>
/// Name of queue.
/// </summary>
public string Name = "q-account-regisration";
/// <summary>
/// Specifies the routing key for the binding.
/// The routing key is used for routing messages depending on the exchange configuration. Not all exchanges use a routing key - refer to the specific exchange documentation.
/// </summary>
public string RoutingKey = "";
/// <summary>
/// If the no-local field is set the server will not send messages to the connection that published them.
/// </summary>
public bool IsNoLocal = false;
/// <summary>
/// Exclusive queues may only be accessed by the current connection, and are deleted when that connection closes. Passive declaration of an exclusive queue by other connections are not allowed.
/// </summary>
public bool IsExclusive = false;
/// <summary>
/// Specifies the identifier for the consumer.
/// The consumer tag is local to a channel, so two clients can use the same consumer tags. If this field is empty the server will generate a unique tag.
/// </summary>
public string ConsumerTag = "";
#endregion
}
}
|
5ae200de910d498df05d58b10748b414e949b6b7
|
C#
|
YouriPeusen/SimonSaysApp
|
/SimonSaysApp/Model/Game/NormalGame.cs
| 2.9375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SimonSaysApp.Model.Game
{
class NormalGame : Game
{
private readonly string _gameLevel;
private TimeSpan _gameOverTime;
private double _sequenceSpeed;
private List<int> _lightIds;
private List<int> _lightSequence;
public NormalGame(TimeSpan gameOverTime, double sequenceSpeed, List<int> lightIds, List<int> lightSequence)
{
_gameLevel = "Normal";
_gameOverTime = gameOverTime;
_sequenceSpeed = sequenceSpeed;
_lightIds = lightIds;
_lightSequence = lightSequence;
}
public override string GameLevel
{
get { return _gameLevel; }
}
public override TimeSpan GameOverTime
{
get { return _gameOverTime; }
set { _gameOverTime = value; }
}
public override double SequenceSpeed
{
get { return _sequenceSpeed; }
set { _sequenceSpeed = value; }
}
public override List<int> LightIds
{
get { return _lightIds; }
set { _lightIds = value; }
}
public override List<int> LightSequence
{
get { return _lightSequence; }
set { _lightSequence = value; }
}
}
}
|
8c07b6cb00d60527d300c1c1c418ce85d1f42809
|
C#
|
avjgit/notes7
|
/csharp/yelllowbook-threads.cs
| 3.546875
| 4
|
// http://www.robmiles.com/c-yellow-book/ 5.4 Threads and Threading
using System;
using System.Threading;
class Threading
{
static private void busyLoop()
{
Console.WriteLine(DateTime.Now);
long count;
for (count = 0; count < 10000000000; count++)
{
}
}
static void Main()
{
// Threading.busyLoop();
ThreadStart busyLoopMethod = new ThreadStart(busyLoop);
Thread t1 = new Thread(busyLoopMethod);
t1.Start();
busyLoop();
Console.ReadLine();
}
}
|
f0418795575d41f527629e49a31aed5d7344f9ee
|
C#
|
cleytonferrari/PadraoDeRepositorio
|
/TISelvagem/TISelvagem.RepositorioMongo/AlunoRepositorioMongo.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using MongoDB.Bson;
using MongoDB.Driver.Builders;
using MongoDB.Driver.Linq;
using TISelvagem.Dominio;
using TISelvagem.Dominio.Contratos;
namespace TISelvagem.RepositorioMongo
{
public class AlunoRepositorioMongo : IRepositorio<Aluno>
{
private readonly Contexto<AlunoDTO> contexto;
public AlunoRepositorioMongo()
{
contexto = new Contexto<AlunoDTO>();
}
public Aluno Salvar(Aluno entidade)
{
var alunoDto = GetAlunoDto(entidade);
contexto.Collection.Save(alunoDto);
return GetAluno(alunoDto);
}
public Aluno Alterar(Aluno entidade)
{
var alunoDto = GetAlunoDto(entidade);
contexto.Collection.Save(alunoDto);
return GetAluno(alunoDto);
}
public void Excluir(Aluno entidade)
{
contexto.Collection.Remove(Query.EQ("_id", new ObjectId(entidade.Id)));
}
public Aluno Buscar(string id)
{
var alunoDto = contexto.Collection.AsQueryable().FirstOrDefault(x => x.Id == id);
return GetAluno(alunoDto);
}
public IEnumerable<Aluno> BuscarTodos()
{
var listaDto = contexto.Collection.AsQueryable().ToList();
foreach (var alunoDTO in listaDto)
{
var aluno = GetAluno(alunoDTO);
yield return aluno;
}
}
public IEnumerable<Aluno> BuscarPorFiltro(Func<Aluno, bool> filtro)
{
throw new NotImplementedException();
}
private static AlunoDTO GetAlunoDto(Aluno entidade)
{
var alunoDto = new AlunoDTO
{
Id = entidade.Id,
Nome = entidade.Nome,
Mae = entidade.Mae,
DataNascimento = entidade.DataNascimento
};
return alunoDto;
}
private static Aluno GetAluno(AlunoDTO entidade)
{
var aluno = new Aluno
{
Id = entidade.Id,
Nome = entidade.Nome,
Mae = entidade.Mae,
DataNascimento = entidade.DataNascimento
};
return aluno;
}
}
}
|
9f571a8ad3c654c5caadaf5506cbaf059532cb4f
|
C#
|
snegdaholoda/cSharp
|
/DZ 9 Serialization. Attribute/DZ9/DZ9/Entities/Casino.cs
| 2.734375
| 3
|
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
using System.Xml.Serialization;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
namespace geiko.DZ9.Entities
{
/// <summary>
/// This class represents a casino - an array of playing tables.
/// </summary>
class Casino : ICasino
{
/// <summary>
/// This method allows player to select a table and serialize data.
/// </summary>
/// <param name="myPurse">It is money($) in purse of player.</param>
public void SelectTable(double myPurse)
{
while (true)
{
Console.WriteLine("\n\nWhat table whould you like to play at?");
Console.WriteLine("\nPlease, set table's number\n\n Alt+F(1-10) or esc to quit.");
ConsoleKeyInfo cki = Console.ReadKey();
if ((cki.Modifiers & ConsoleModifiers.Alt) != 0)
{
try
{
switch (cki.Key)
{
#region cases
case ConsoleKey.F1:
NewtonJson_Serialize(1, ref myPurse);
// JS_Serialize(1, ref myPurse);
// SoapSerialize(1, ref myPurse);
// JsonSerialize(1, ref myPurse);
// XmlSerialize(1, ref myPurse);
// BinaryFormatMemoryStreamSerialize(1, ref myPurse);
// BinaryFormatFileStreamSerialize( 1, ref myPurse );
break;
case ConsoleKey.F2:
NewtonJson_Serialize(1, ref myPurse);
// JS_Serialize(2, ref myPurse);
// SoapSerialize(2, ref myPurse);
// JsonSerialize(2, ref myPurse);
// XmlSerialize(2, ref myPurse);
// BinaryFormatMemoryStreamSerialize(2, ref myPurse);
// BinaryFormatFileStreamSerialize(2, ref myPurse);
break;
case ConsoleKey.F3:
NewtonJson_Serialize(3, ref myPurse);
// JS_Serialize(3, ref myPurse);
// SoapSerialize(3, ref myPurse);
// JsonSerialize(3, ref myPurse);
// XmlSerialize(3, ref myPurse);
// BinaryFormatMemoryStreamSerialize(3, ref myPurse);
// BinaryFormatFileStreamSerialize(3, ref myPurse);
break;
case ConsoleKey.F4:
NewtonJson_Serialize(4, ref myPurse);
// JS_Serialize(4, ref myPurse);
// SoapSerialize(4, ref myPurse);
// JsonSerialize(4, ref myPurse);
// XmlSerialize(4, ref myPurse);
// BinaryFormatMemoryStreamSerialize(4, ref myPurse);
// BinaryFormatFileStreamSerialize(4, ref myPurse);
break;
case ConsoleKey.F5:
NewtonJson_Serialize(5, ref myPurse);
// JS_Serialize(5, ref myPurse);
// SoapSerialize(5, ref myPurse);
// JsonSerialize(5, ref myPurse);
// XmlSerialize(5, ref myPurse);
// BinaryFormatMemoryStreamSerialize(5, ref myPurse);
// BinaryFormatFileStreamSerialize(5, ref myPurse);
break;
case ConsoleKey.F6:
NewtonJson_Serialize(6, ref myPurse);
// JS_Serialize(6, ref myPurse);
// SoapSerialize(6, ref myPurse);
// JsonSerialize(6, ref myPurse);
// XmlSerialize(6, ref myPurse);
// BinaryFormatMemoryStreamSerialize(6, ref myPurse);
// BinaryFormatFileStreamSerialize(6, ref myPurse);
break;
case ConsoleKey.F7:
NewtonJson_Serialize(7, ref myPurse);
// JS_Serialize(7, ref myPurse);
// SoapSerialize(7, ref myPurse);
// JsonSerialize(7, ref myPurse);
// XmlSerialize(7, ref myPurse);
// BinaryFormatMemoryStreamSerialize(7, ref myPurse);
// BinaryFormatFileStreamSerialize(7, ref myPurse);
break;
case ConsoleKey.F8:
NewtonJson_Serialize(8, ref myPurse);
// JS_Serialize(8, ref myPurse);
// SoapSerialize(8, ref myPurse);
// JsonSerialize(8, ref myPurse);
// XmlSerialize(8, ref myPurse);
// BinaryFormatMemoryStreamSerialize(8, ref myPurse);
// BinaryFormatFileStreamSerialize(8, ref myPurse);
break;
case ConsoleKey.F9:
NewtonJson_Serialize(9, ref myPurse);
// JS_Serialize(9, ref myPurse);
// SoapSerialize(9, ref myPurse);
// JsonSerialize(9, ref myPurse);
// XmlSerialize(9, ref myPurse);
// BinaryFormatMemoryStreamSerialize(9, ref myPurse);
// BinaryFormatFileStreamSerialize(9, ref myPurse);
break;
case ConsoleKey.F10:
NewtonJson_Serialize(10, ref myPurse);
// JS_Serialize(10, ref myPurse);
// SoapSerialize(10, ref myPurse);
// JsonSerialize(10, ref myPurse);
// XmlSerialize(10, ref myPurse);
// BinaryFormatMemoryStreamSerialize(10, ref myPurse);
// BinaryFormatFileStreamSerialize(10, ref myPurse);
break;
default:
Console.WriteLine("\nIt is irrelevant table number! Try again.");
Console.ReadKey();
break;
#endregion
}
}
catch ( SystemException e )
{
Console.WriteLine("{0} Exception caught.", e);
}
}
if (cki.Key == ConsoleKey.Escape)
return;
}
}
/// <summary>
/// This method serializes object graphs to Memory stream in binary format.
/// </summary>
/// <param name="tableNumber">Number of the table.</param>
/// <param name="myPurse">Money in the purse of player.</param>
private void BinaryFormatMemoryStreamSerialize(int tableNumber, ref double myPurse)
{
MemoryStream MS = new MemoryStream();
BinaryFormatter BF = new BinaryFormatter();
if (MS.Length != 0)
{
MS.Seek(0, SeekOrigin.Begin);
ITable table = (Table)BF.Deserialize(MS);
MS.Close();
table.UserMenu(ref myPurse, tableNumber);
}
else
{
ITable table = new Table();
table.UserMenu(ref myPurse, tableNumber);
BF.Serialize(MS, table);
MS.Close();
}
}
/// <summary>
/// This method serializes object graphs to File stream in binary format.
/// </summary>
/// <param name="tableNumber">Number of the table.</param>
/// <param name="myPurse">Money in the purse of player.</param>
private void BinaryFormatFileStreamSerialize(int tableNumber, ref double myPurse)
{
string temp = "table" + tableNumber.ToString() + ".dat";
BinaryFormatter BF = new BinaryFormatter();
if (File.Exists(temp) == true)
{
FileStream FS = new FileStream(temp, FileMode.OpenOrCreate, FileAccess.ReadWrite);
FS.Seek(0, SeekOrigin.Begin);
ITable table = (Table)BF.Deserialize(FS);
FS.Close();
table.UserMenu(ref myPurse, tableNumber);
}
else
{
ITable table = new Table();
table.UserMenu(ref myPurse, tableNumber);
FileStream FS = new FileStream(temp, FileMode.OpenOrCreate, FileAccess.ReadWrite);
BF.Serialize(FS, table);
FS.Close();
}
}
/// <summary>
/// This method serializes object graphs to File stream in Soap format.
/// </summary>
/// <param name="tableNumber">Number of the table.</param>
/// <param name="myPurse">Money in the purse of player.</param>
private void SoapSerialize(int tableNumber, ref double myPurse)
{
string temp = "table_Soap_" + tableNumber.ToString() + ".xml";
SoapFormatter SoapForm = new SoapFormatter();
if (File.Exists(temp))
{
FileStream fs = new FileStream(temp, FileMode.OpenOrCreate);
fs.Seek(0, SeekOrigin.Begin);
ITable table = (Table)SoapForm.Deserialize(fs);
fs.Close();
table.UserMenu(ref myPurse, tableNumber);
}
else
{
ITable table = new Table();
table.UserMenu(ref myPurse, tableNumber);
FileStream fs = new FileStream(temp, FileMode.OpenOrCreate);
SoapForm.Serialize(fs, table);
fs.Close();
}
}
/// <summary>
/// This method serializes object's public info to file stream in Xml format.
/// </summary>
/// <param name="tableNumber">Number of the table.</param>
/// <param name="myPurse">Money in the purse of player.</param>
private void XmlSerialize(int tableNumber, ref double myPurse)
{
string temp = "table" + tableNumber.ToString() + ".xml";
if (File.Exists(temp))
{
Stream streamout = new FileStream(temp, FileMode.Open, FileAccess.Read);
XmlSerializer deserializer = new XmlSerializer(typeof(Table));
ITable table = (Table)deserializer.Deserialize(streamout);
table.UserMenu(ref myPurse, tableNumber);
streamout.Close();
}
else
{
ITable table = new Table();
table.UserMenu(ref myPurse, tableNumber);
StreamWriter writer = new StreamWriter(temp);
XmlSerializer serializer = new XmlSerializer(typeof(Table));
serializer.Serialize(writer, table);
writer.Close();
}
}
/// <summary>
/// This method serializes object info to file stream in Json format.
/// </summary>
/// <param name="tableNumber">Number of the table.</param>
/// <param name="myPurse">Money in the purse of player.</param>
private void JsonSerialize(int tableNumber, ref double myPurse)
{
string temp = "table" + tableNumber.ToString() + ".json";
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Table));
if (File.Exists(temp))
{
FileStream fs = new FileStream(temp, FileMode.OpenOrCreate);
ITable table = (Table)jsonSerializer.ReadObject(fs);
fs.Close();
table.UserMenu(ref myPurse, tableNumber);
}
else
{
ITable table = new Table();
table.UserMenu(ref myPurse, tableNumber);
FileStream fs = new FileStream(temp, FileMode.OpenOrCreate);
jsonSerializer.WriteObject(fs, table);
fs.Close();
}
}
/// <summary>
/// This method serializes object info to file stream in Json format with JavaScript Serializer.
/// </summary>
/// <param name="tableNumber">Number of the table.</param>
/// <param name="myPurse">Money in the purse of player.</param>
private void JS_Serialize(int tableNumber, ref double myPurse)
{
string temp = "table_JS_" + tableNumber.ToString() + ".json";
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
if (File.Exists(temp))
{
string json = File.ReadAllText(temp);
ITable table = jsSerializer.Deserialize<Table>(json);
table.UserMenu(ref myPurse, tableNumber);
}
else
{
ITable table = new Table();
table.UserMenu(ref myPurse, tableNumber);
string json = jsSerializer.Serialize( table );
File.WriteAllText(temp, json);
}
}
/// <summary>
/// This method serializes object info to file stream in Json format with Json.NET Serializer.
/// </summary>
/// <param name="tableNumber">Number of the table.</param>
/// <param name="myPurse">Money in the purse of player.</param>
private void NewtonJson_Serialize(int tableNumber, ref double myPurse)
{
string temp = "table_NewtonJson_" + tableNumber.ToString() + ".json";
if (File.Exists(temp))
{
string json = File.ReadAllText(temp);
ITable table = JsonConvert.DeserializeObject<Table>(json);
table.UserMenu(ref myPurse, tableNumber);
}
else
{
ITable table = new Table();
table.UserMenu(ref myPurse, tableNumber);
string json = JsonConvert.SerializeObject( table, Formatting.Indented );
File.WriteAllText(temp, json);
}
}
}
}
|
6022c71f6b5f545a78b5a8bb311bcaaf437f1f0c
|
C#
|
niralprj/Italy-Software-Engineer-Challenge
|
/PokemonItaly/Middlewares/Excecption/ExceptionMiddleware.cs
| 3.03125
| 3
|
using Microsoft.AspNetCore.Http;
using PokemonItaly.API.Models;
using System;
using System.Net;
using System.Threading.Tasks;
namespace PokemonItaly.API.Middlewares.Excecption
{
/// <summary>
/// Custom middleware class to handle exception globally
/// </summary>
public class ExceptionMiddleware
{
#region Declaration
private readonly RequestDelegate _next;
#endregion
#region Constructor
public ExceptionMiddleware(RequestDelegate requestDelegate)
{
_next = requestDelegate;
}
#endregion
#region Invoker
public async Task InvokeAsync(HttpContext httpContext)
{
try
{
await _next(httpContext);
}
catch (Exception ex)
{
await HandleExceptionAsync(httpContext, ex);
}
}
#endregion
private Task HandleExceptionAsync(HttpContext httpContext, Exception ex)
{
httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
httpContext.Response.ContentType = "application/json";
return httpContext.Response.WriteAsync(new ErrorDetails()
{
StatusCode = httpContext.Response.StatusCode,
Message = ex.Message
}.ToString());
}
}
}
|
95ad98f190d9bfd3ec939d927846ad93a3af9cee
|
C#
|
OpenLocalizationTestOrg/ECMA2YamlTestRepo2
|
/fulldocset/add/codesnippet/CSharp/e-system.windows.forms.d_38_1.cs
| 3.15625
| 3
|
// Create an instance of the 'CaptionVisibleChanged' EventHandler.
private void CallCaptionVisibleChanged()
{
myDataGrid.CaptionVisibleChanged +=
new EventHandler(Grid_CaptionVisibleChanged);
}
// Set the 'CaptionVisible' property on click of a button.
private void myButton_Click(object sender, EventArgs e)
{
if (myDataGrid.CaptionVisible == true)
myDataGrid.CaptionVisible = false;
else
myDataGrid.CaptionVisible = true;
}
// Raise the event when 'CaptionVisible' property is changed.
private void Grid_CaptionVisibleChanged(object sender, EventArgs e)
{
// String variable used to show message.
string myString = "CaptionVisibleChanged event raised, caption is";
// Get the state of 'CaptionVisible' property.
bool myBool = myDataGrid.CaptionVisible;
// Create appropriate alert message.
myString += (myBool ? " " : " not ") + "visible";
// Show information about caption of DataGrid.
MessageBox.Show(myString, "Caption information");
}
|
9fffd3235d7fdc42d5a060a1c3cd0660eb21f22b
|
C#
|
ledferoz/Parcial
|
/Inventario/Inventario/frmConsultarCliente.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Linq;
namespace Inventario
{
public partial class frmConsultarCliente : Form
{
public frmConsultarCliente()
{
InitializeComponent();
}
int indice;
private void frmConsultarCliente_Load(object sender, EventArgs e)
{
consultar();
}
public void consultar()
{
ParcialDataContext objConexion = new ParcialDataContext();
var consulta = from c in objConexion.Clientes select c;
dgvClientes.DataSource = consulta.ToList();
}
private void dgvClientes_CellClick(object sender, DataGridViewCellEventArgs e)
{
indice = dgvClientes.CurrentRow.Index;
txtId.Text = dgvClientes.Rows[indice].Cells[0].Value.ToString();
txtNombre.Text = dgvClientes.Rows[indice].Cells[1].Value.ToString();
txtApellido.Text = dgvClientes.Rows[indice].Cells[2].Value.ToString();
txtDireccion.Text = dgvClientes.Rows[indice].Cells[3].Value.ToString();
txtTelefono.Text = dgvClientes.Rows[indice].Cells[4].Value.ToString();
}
private void btnActualizar_Click(object sender, EventArgs e)
{
try
{
if (!txtId.Text.Equals(""))
{
ParcialDataContext objConexion = new ParcialDataContext();
objConexion.actualizarCliente(int.Parse(txtId.Text), txtNombre.Text, txtApellido.Text, txtDireccion.Text, txtTelefono.Text);
MessageBox.Show("Se ha actualizado exitosamente el cliente", "Actualización Cliente");
consultar();
}
else
{
MessageBox.Show("Se debe seleccionar un cliente","Error");
}
}
catch (Exception ex)
{
MessageBox.Show("No se ha actualizado exitosamente el cliente "+ex.Message, "Actualización Cliente");
}
}
}
}
|
85804c4a9736bd0198a7de689fcb84f386a4f898
|
C#
|
wes977/Lily-Systems-
|
/back-end/LS_APIs/LS_APIs/SchedulePrint/SchedulePrint.cs
| 3.109375
| 3
|
/*
File Name : SchedulePrint.cs
Date : March 15, 2017
Description : Gets the appropriate information in a datetable thats needed to create a downloadable schedule.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
namespace LS_APIs.SchedulePrinter
{
///-------------------------------------------------------------------------------------------------
/// <summary> A schedule print. </summary>
///
/// <remarks> Wesley, 2017-04-17. </remarks>
///-------------------------------------------------------------------------------------------------
public class SchedulePrint
{
///-------------------------------------------------------------------------------------------------
/// <summary> Gets the schedule body information. </summary>
///
/// <remarks> Wesley, 2017-04-17. </remarks>
///
/// <param name="scheduleId"> Id of schedule. </param>
///
/// <returns> DataTable - table of schedule information for schedule id. </returns>
///-------------------------------------------------------------------------------------------------
public DataTable GetSchedule(string scheduleId)
{
DataTable dt = new DataTable();
string command = "SELECT c.firstName + ' ' + c.lastName AS Name, " +
"CONVERT(varchar(15), CAST(a.startTime AS Date), 100) AS Date, " +
"CONVERT(varchar(15), CAST(a.startTime AS TIME), 100) AS 'Start Time', " +
"CONVERT(varchar(15), CAST(a.endTime AS TIME), 100) AS 'End Time', " +
"DATEDIFF(hh, a.startTime, a.endTime) AS 'Length (hrs)' " +
"FROM Shift_Info a INNER JOIN Employee_Info b " +
"ON a.employee_id = b.employee_id INNER JOIN Person_Info c " +
"ON b.person_id = c.person_id " +
//scheduleId is not coming directly from a user input field, but from
//another method call and is validated first. Sql Injection is less of
//a risk.
"WHERE b.store_id = '" + scheduleId + "'";
LS_APIs.DAL.ModularDAL dal = new DAL.ModularDAL();
dt = dal.Select(command);
return dt;
}
///-------------------------------------------------------------------------------------------------
/// <summary>
/// Gets the schedule header information, ie company name and address that appears above the
/// schedule to give it information about what the schedule is about and for.
/// </summary>
///
/// <remarks> Wesley, 2017-04-17. </remarks>
///
/// <param name="scheduleID"> Id of schedule. </param>
///
/// <returns>
/// DateTable - table containing information about the company the schedule is for.
/// </returns>
///-------------------------------------------------------------------------------------------------
public DataTable GetScheduleHeader(string scheduleID)
{
DataTable dt = new DataTable();
string command = "SELECT b.companyName AS 'Company Name', " +
"a.storeAddress + ', ' + a.city + ', ' + a.country AS Address, " +
"a.storePhone AS 'Phone #' " +
"FROM Store_Info a INNER JOIN Company_Info b " +
"ON a.company_id = b.company_id " +
//scheduleId is not coming directly from a user input field, but from
//another method call and is validated first. Sql Injection is less of
//a risk.
"WHERE a.store_id = '" + scheduleID + "'";
LS_APIs.DAL.ModularDAL dal = new DAL.ModularDAL();
dt = dal.Select(command);
return dt;
}
}
}
|
91ad1ae90aa0ebd80ad50494f486efb1b938a446
|
C#
|
Dzavialov/OOP2_lab2
|
/lab2_ind_2/Form1.cs
| 2.640625
| 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 lab2_ind_2
{
public partial class Form1 : Form
{
delegate void dlg(object sender, EventArgs e);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (this.Opacity == 0.5)
{
this.Opacity = 1;
}
else
{
this.Opacity = 0.5;
}
}
private void button2_Click(object sender, EventArgs e)
{
if(this.BackColor == Color.Gray)
{
this.BackColor = Color.Yellow;
}
else
{
this.BackColor = Color.Gray;
}
}
private void button3_Click(object sender, EventArgs e)
{
MessageBox.Show("Hellow World");
}
private void button4_Click(object sender, EventArgs e)
{
MessageBox.Show("Я супермегакнопка,\nі цього мене не позбавиш!");
dlg[] btn = new dlg[] { button1_Click, button2_Click, button3_Click };
if (checkBox1.Checked == true)
{
btn[0](sender, e);
}
if(checkBox2.Checked == true)
{
btn[1](sender, e);
}
if(checkBox3.Checked == true)
{
btn[2](sender, e);
}
}
}
}
|
a8df4caf7950d248adba8bb535a638268da9639d
|
C#
|
pratapladhani/PratapContactList
|
/PratapContactList/ContactList/Models/Contact.cs
| 2.53125
| 3
|
using System;
namespace ContactList.Models
{
public class Contact
{
/// <summary>
/// The ID of the contact.
/// </summary>
public int Id { get; set; }
/// <summary>
/// The Contact's full name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// The Contact's Phone number.
/// </summary>
public string Phone { get; set; }
/// <summary>
/// The Contact's Alternative Phone number.
/// </summary>
public string Phone2 { get; set; }
/// <summary>
/// The Contact's Company Name.
/// </summary>
public string Company { get; set; }
/// <summary>
/// The Contact's email address.
/// </summary>
public string Email { get; set; }
/// <summary>
/// The Contact's Title.
/// </summary>
public string Title { get; set; }
/// <summary>
/// The Contact's Image URL.
/// </summary>
public string ImageURL { get; set; }
/// <summary>
/// The Contact's address.
/// </summary>
public string Address { get; set; }
}
}
|
ca60fd6d7dd76ef04305028087864bca66ec83e5
|
C#
|
DenysGoncharov/ProfDZ5
|
/HomeWorkPr13/ConsoleApp2/Program.cs
| 3.359375
| 3
|
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static void MyTask1()
{
Console.WriteLine("MyTask1: is start");
for (int i = 0; i < 80; i++)
{
Thread.Sleep(10);
Console.Write("+");
}
Console.WriteLine("MyTask1: is over");
}
static void MyTask2()
{
Console.WriteLine("MyTask2: is start");
for (int i = 0; i < 80; i++)
{
Thread.Sleep(10);
Console.Write("-");
}
Console.WriteLine("MyTask2: is over");
}
static void Main()
{
Console.OutputEncoding = Encoding.Unicode;
Console.WriteLine("main thread is start.");
ParallelOptions options = new ParallelOptions();
// Выделить определенное количество процессорных ядер.
//options.MaxDegreeOfParallelism = Environment.ProcessorCount > 2
// ? Environment.ProcessorCount - 1 : 1;
options.MaxDegreeOfParallelism = 2;
Console.WriteLine("Number of logical CPU cores CPU:" + Environment.ProcessorCount);
Console.ReadKey();
// Выполнить параллельно два метода.
Parallel.Invoke(options, MyTask1, MyTask2);
// ВНИМАНИЕ!???
// Выполнение метода Main() приостанавливается,
// пока не произойдет завершение задач.
Console.WriteLine("main thread is over.");
// Delay
Console.ReadKey();
}
}
}
|
a0b5dd4c7ad50eadbf6f3d5246c5f2c4ccba55c5
|
C#
|
windcalm/Fly.IM
|
/Src/Fly.Handler/Channels/Channel.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Fly.Handler.Channels
{
public class Channel
{
private static readonly Random Random = new Random();
private readonly IClient _client;
private int _readTimeoutTranscationLevel;
private int _writeTimeoutTranscationLevel;
private const byte MajorVersion = 2;
private const byte MinorVersion = 1;
/// <summary>
/// 当前通道id
/// </summary>
public int Id { get; private set; }
/// <summary>
/// 通道是否关闭了
/// </summary>
public bool IsClosed { get; protected set; }
public event EventHandler Closed;
/// <summary>
/// 远端信息,对server来说,这个意味着客户端,对client来说,这个意味是服务端
/// </summary>
public HostInfo Remote { get; }
/// <summary>
/// 本端信息,对server来着,这个意味着服务端,对client来说,这个意味着客户端
/// </summary>
public HostInfo Local { get; }
/// <summary>
/// 发送和接受的总数据量
/// </summary>
public long DataTransfered { get; private set; }
public Channel(int channelId, IClient client)
{
Id = channelId;
_client = client;
Remote = _client.Remote;
Local = _client.Local;
}
internal void UpdateChannelId(int channelId)
{
Id = channelId;
}
protected void ReadHeader(int timeout = 0)
{
}
protected async Task ReadHeaderAsync(int timeout = 0)
{
}
protected void WriteHeader(int timeout = 0)
{
}
protected async Task WriteHeaderAsync(int timeout = 0)
{
}
public void Close()
{
_client.Disconnect();
IsClosed = true;
OnClosed();
}
protected virtual void OnClosed()
{
Closed?.Invoke(this,EventArgs.Empty);
}
public override string ToString()
{
return $"{Remote}<->{Local}";
}
private class ReadTimeoutTranscation : IDisposable
{
private readonly Channel _channel;
public ReadTimeoutTranscation(Channel channel, int timeout)
{
_channel = channel;
if (_channel._readTimeoutTranscationLevel == 0)
{
try
{
_channel._client.ReadTimeout = timeout;
}
catch
{
//ignore
}
}
_channel._readTimeoutTranscationLevel++;
}
public void Dispose()
{
_channel._readTimeoutTranscationLevel--;
if (_channel._readTimeoutTranscationLevel == 0)
{
try
{
_channel._client.ReadTimeout = 0;
}
catch
{
//ignore
}
}
}
}
private class WriteTimeoutTranscation : IDisposable
{
private readonly Channel _channel;
public WriteTimeoutTranscation(Channel channel, int timeout)
{
_channel = channel;
if (_channel._writeTimeoutTranscationLevel == 0)
{
try
{
_channel._client.SendTimeout = timeout;
}
catch
{
//ignore
}
}
_channel._writeTimeoutTranscationLevel++;
}
public void Dispose()
{
_channel._writeTimeoutTranscationLevel--;
if (_channel._writeTimeoutTranscationLevel == 0)
{
try
{
_channel._client.SendTimeout = 0;
}
catch
{
//ignore
}
}
}
}
}
}
|
9baa887ee1d5172114ae63bab957a7fed290652a
|
C#
|
maddxyz/ZZ2_WEBProject
|
/DAL & API/ApiGOT/Controllers/TerritoryController.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using EntitiesLayer.DTOs;
using BusinessLayer;
namespace ApiGOT.Controllers
{
public class TerritoryController : ApiController
{
public IHttpActionResult GetAllTerritorys()
{
List<TerritoryDTO> Territorys = new List<TerritoryDTO>();
foreach (var Territory in GameManager.Instance.GetTerritorys())
{
Territorys.Add(Territory);
}
return Ok(Territorys);
}
public IHttpActionResult GetTerritoryById(int id)
{
TerritoryDTO Territory = GameManager.Instance.GetTerritoryById(id);
if (Territory.Id == -1)
return NotFound();
else
return Ok(Territory);
}
public IHttpActionResult PostTerritory([FromBody] TerritoryDTO Territory)
{
GameManager.Instance.AddTerritory(Territory);
return Ok();
}
public IHttpActionResult PutTerritory([FromBody] TerritoryDTO Territory)
{
GameManager.Instance.EditTerritory(Territory);
return Ok();
}
public IHttpActionResult DeleteTerritory(int id)
{
GameManager.Instance.DeleteTerritory(id);
return Ok();
}
}
}
|
57cb3f09c9e6564277a2e7e71f4ee86bb35fa0ea
|
C#
|
A-Hoernchen/Game1
|
/Game1/Controls/Icon.cs
| 2.71875
| 3
|
using System;
using Game1.Components;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
namespace Game1.Controls
{
/// <summary>
/// Icon Control
/// </summary>
internal class Icon : Control
{
/// <summary>
/// Die zu anzeigende Textur.
/// </summary>
public string Texture { get; set; }
public Icon(ScreenComponent manager)
: base(manager)
{
}
public override void Draw(SpriteBatch spriteBatch, Point offset)
{
if (!string.IsNullOrEmpty(Texture))
{
Texture2D texture = Manager.GetIcon(Texture);
spriteBatch.Draw(texture, new Rectangle(offset.X + Position.X, offset.Y + Position.Y, Position.Width, Position.Height), Color.White);
}
}
}
}
|
3116da00aa008734df61d049a3b93ad2b6f9bbc5
|
C#
|
callumlawson/Sellout
|
/Assets/Framework/Entities/EntityManager.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.Reflection;
using Assets.Framework.States;
using Assets.Framework.Util;
using JetBrains.Annotations;
namespace Assets.Framework.Entities
{
public class EntityManager
{
private readonly Bag<Entity> entities = new Bag<Entity>();
private readonly Dictionary<Type, Bag<IState>> statesByType = new Dictionary<Type, Bag<IState>>();
private int nextAvailableId;
//TODO: Premature optimisation is the devil's work... This to be replaced by init time refelection.
private readonly MethodInfo addStateMethod = typeof(EntityManager).GetMethod("AddState");
private readonly MethodInfo getStateMethod = typeof(EntityManager).GetMethod("GetState", new[] { typeof(Entity) });
public Entity BuildEntity(IEnumerable<IState> states)
{
var entity = CreateEmptyEntity();
foreach (var state in states)
{
var genericAdd = addStateMethod.MakeGenericMethod(state.GetType());
genericAdd.Invoke(this, new object[] { entity, state });
if (state is PrefabState)
{
var prefabState = state as PrefabState;
var prefabToSpawn = AssetLoader.LoadAsset(prefabState.PrefabName);
var go = SimplePool.Spawn(prefabToSpawn);
if (go.GetComponent<EntityIdComponent>() == null)
{
go.AddComponent<EntityIdComponent>();
}
go.GetComponent<EntityIdComponent>().EntityId = entity.EntityId;
entity.GameObject = go;
}
}
return entity;
}
public Entity GetEntity(int entityId)
{
return entities[entityId];
}
public void DeleteEntity(Entity entity)
{
if (entity.GameObject != null)
{
entity.GameObject.GetComponent<EntityIdComponent>().EntityId = -1;
SimplePool.Despawn(entity.GameObject);
}
RemoveStatesForEntity(entity);
entities[entity.EntityId] = null;
}
[UsedImplicitly]
public void AddState<T>([NotNull] Entity entity, [NotNull] IState state) where T : IState
{
Bag<IState> componentsOfType;
var listInitialized = statesByType.TryGetValue(typeof(T), out componentsOfType);
if (!listInitialized)
{
componentsOfType = new Bag<IState>();
statesByType.Add(typeof(T), componentsOfType);
}
componentsOfType.Set(entity.EntityId, state);
}
//For debug only!
public List<IState> GetStates(Entity entity)
{
var results = new List<IState>();
foreach (var states in statesByType.Values)
{
if (states.Get(entity.EntityId) != null)
{
results.Add(states.Get(entity.EntityId));
}
}
return results;
}
public IState GetState([NotNull] Entity entity, Type stateType)
{
var genericAdd = getStateMethod.MakeGenericMethod(stateType);
return (IState) genericAdd.Invoke(this, new object[] { entity });
}
public T GetState<T>([NotNull] Entity entity)
{
Bag<IState> statesOfType;
var hasType = statesByType.TryGetValue(typeof(T), out statesOfType);
if (hasType)
{
return (T)statesOfType.Get(entity.EntityId);
}
return default(T);
}
public IEnumerable<Entity> GetEntitiesWithState<T>() where T : IState
{
var results = new List<Entity>();
foreach (var entity in entities)
{
if (entity.HasState<T>())
{
results.Add(entity);
}
}
return results;
}
private Entity CreateEmptyEntity()
{
var entityId = nextAvailableId;
nextAvailableId++;
var entity = new Entity(this, entityId);
entities.Set(entityId, entity);
return entity;
}
private void RemoveStatesForEntity([NotNull] Entity entity)
{
foreach (var stateBag in statesByType.Values)
{
if (stateBag.Get(entity.EntityId) != null)
{
stateBag.Set(entity.EntityId, null);
}
}
}
}
}
|
feaff7c7e38b5df8c324132549c417507ab0ae37
|
C#
|
soakes84/WarriorGame
|
/WarriorGame/Equipment/Weapon.cs
| 3.234375
| 3
|
using System;
using WarriorGame.Enum;
namespace WarriorGame.Equipment
{
class Weapon
{
private int GOOD_GUY_DAMAGE = 25;
private int BAD_GUY_DAMAGE = 23;
static Random rng = new Random();
private int damage;
public int Damage
{
get
{
return damage;
}
}
public Weapon(Faction faction)
{
switch (faction)
{
case Faction.King:
damage = GOOD_GUY_DAMAGE;
break;
case Faction.BadGuy:
damage = BAD_GUY_DAMAGE;
break;
}
}
public Weapon(Faction faction, int damage)
{
var attackPower = damage;
switch (faction)
{
case Faction.Knight:
damage = rng.Next(0, attackPower);
break;
case Faction.BadGuy:
damage = rng.Next(0, attackPower);
break;
}
}
}
}
|
726c59277e575e46bf4e06d82713b3b5dee72963
|
C#
|
SamsonMychael/FoodOrdering
|
/FoodOrdering/FoodOrdering/ViewModel/TotalCartVM.cs
| 2.96875
| 3
|
using FoodOrdering.Model;
using FoodOrdering.ViewModel.Helpers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Text;
namespace FoodOrdering.ViewModel
{
public class TotalCartVM : INotifyPropertyChanged
{
private ObservableCollection<Category> categories;
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<Category> Categories
{
get { return categories; }
set
{
categories = value;
OnPropertyChanged("Categories");
}
}
private double totalCost;
public double TotalCost
{
get { return totalCost; }
set {
totalCost = value;
OnPropertyChanged("TotalCost");
}
}
public TotalCartVM()
{
Categories = new ObservableCollection<Category>();
}
public async void ReadCollections1()
{
var category = await DataBaseHelpers.ReadDate();
categories.Clear();
foreach (var s in category)
{
categories.Add(s);
TotalCost += (s.Price * s.Quantity);
}
}
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
|
a786fe557a67dbf196e63816b20d0232accd7ed8
|
C#
|
shendongnian/download4
|
/code2/304039-6331421-13760697-4.cs
| 2.75
| 3
|
public bool IsValid<T>(T propertyvalue)
{
Type fieldType = Nullable.GetUnderlyingType(typeof(T));
if (object.ReferenceEquals(fieldType, typeof(bool))) {
return true;
}
return false;
}
|
0b3c84f81a19cafcb4976da8b7761aa1d38c1fd8
|
C#
|
s19911/cw3
|
/WebApplication1/WebApplication1/Controllers/StudentsController.cs
| 2.890625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Cwiczenie3.Models;
//using Cwiczenie3.Serivices;
using Cwiczenie3.DAL;
using Microsoft.AspNetCore.Mvc;
using System.Data.SqlClient;
using Cwiczenie3.Services;
namespace Cwiczenie3.Controllers
{
[ApiController]
[Route("api/students")]
public class StudentsController : ControllerBase
{
private IDbService _dbService;
public StudentsController(IDbService service)
{
_dbService = service;
}
//ja zaczełam jeszcze raz z wykładu bo się pogubiłam (nie działało mi dobrze)
[HttpGet("{id}")]
public IActionResult GetStudentId(int id)
{
using (SqlConnection con = new SqlConnection("Data Source=db-mssql;Initial Catalog=s19562;Integrated Security=True"))
using (SqlCommand com = new SqlCommand())
{
com.Connection = con;
com.CommandText = $"select * from Student where Student.IndexNumber={id}";
con.Open();
var dr = com.ExecuteReader();
dr.Read();
string idd = dr["IdEnrollment"].ToString();
dr.Close();
com.CommandText = $"select * from Enrollment where Enrollment.IdEnrollment={idd}";
dr = com.ExecuteReader();
var st = new List<string>();
dr.Read();
return Ok(dr["IdEnrollment"].ToString());
dr.Close();
}
}
//2. QueryString
[HttpGet]
public IActionResult GetStudents(string orderBy)
{
//return Ok(_dbService.GetStudents
using (SqlConnection con = new SqlConnection("Data Source=db-mssql;Initial Catalog=s19562;Integrated Security=True"))
using (SqlCommand com = new SqlCommand())
{
com.Connection = con;
com.CommandText = "select * from Student";
con.Open();
var dr = com.ExecuteReader();
var st = new List<string>();
while (dr.Read())
{
if (dr["LastName"] == DBNull.Value)
{
}
Console.WriteLine(dr["LastName"].ToString());
st.Add(dr["LastName"].ToString());
}
return Ok(st);
}
}
[HttpGet("{id}/semester")]
public IActionResult GetSemester(int id)
{
String st = "";
using (var con = new SqlConnection("Data Source=db-mssql;Initial Catalog=s19562;Integrated Security=True"))
using (var com = new SqlCommand())
{
com.Connection = con;
com.CommandText = "select Semester from enrollment join student on enrollment.Idenrollment=student.Idenrollment where student.IndexNumber=@id";
com.Parameters.AddWithValue("id", "s" + id.ToString());
con.Open();
var dr = com.ExecuteReader();
while (dr.Read())
{
st += st + dr["Semester"] + "\r\n";
}
}
return Ok(st);
}
[HttpGet("{id}")]
public IActionResult GetStudentWpis(String id)
{
using (SqlConnection con = new SqlConnection("Data Source=db-mssql;Initial Catalog=s19562;Integrated Security=True"))
using (SqlCommand com = new SqlCommand())
{
com.Connection = con;
com.CommandText = "select * from Student where Student.IndexNumber=@id";
com.Parameters.AddWithValue("id", id);
con.Open();
var dr = com.ExecuteReader();
dr.Read();
string ajdi = dr["IdEnrollment"].ToString();
return Ok(dr[0].ToString() + "," +dr[1] + "," +dr[2]);
}
}
//[FromRoute], [FromBody], [FromQuery]
//1. URL segment
[HttpGet("{id}")]
public IActionResult GetStudent([FromRoute]int id) //action method
{
if(id <= _dbService.GetStudents().Count())
{
return Ok(_dbService.GetStudents().Where(student =>
student.IdStudent == id));
}
else
return NotFound("Student was not found");
}
//3. Body - cialo zadan
[HttpPost]
public IActionResult CreateStudent([FromBody]Student student)
{
student.IndexNumber = $"s{new Random().Next(1, 20000)}";
//...
return Ok(student); //JSON
}
/*[HttpPut("{id}")]
public IActionResult PutStudent([FromRoute]int id , [FromBody]Student student)
{
student.IdStudent = id;
return Ok(student + "Aktualizacja zakonczona");
}*/
[HttpPut("{id}")]
public IActionResult PutStudent([FromRoute]int id)
{
return Ok("Aktualizacja zakonczona");
}
[HttpDelete("{id}")]
public IActionResult DeleteStudent([FromRoute]int id)
{
return Ok("Usuwanie ukonczone");
}
[HttpPost]
public IActionResult EnrollmentsController(Student s)
{
IStudentsDbService service = new ServerDbService();
return null;
}
}
}
|
ceec3a723c500da96e2799710831ee2b2a6b2755
|
C#
|
archangelmichael/TelerikAcademyCSharpPart1
|
/C Sharp Part 1 Homework/6. Loops/14.SpiralNumbers/SpiralNumbers.cs
| 4
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpiralNumbers
{
class SpiralNumbers
{
static void Main(string[] args)
{
/* * Write a program that reads a positive integer number N (N < 20)
* from console and outputs in the console the numbers 1 ... N numbers arranged as a spiral. */
Console.WriteLine("Enter number N: ");
int size = int.Parse(Console.ReadLine());
if (size <= 0 || size >= 20)
{
Console.WriteLine("Invalid Input!");
return;
}
int[,] spiralMatrix = new int[size, size];
int start = 0;
int end = size;
int count = 1;
while (end - start >= 1)
{
for (int p = start; p < end; p++)
{
spiralMatrix[start, p] = count;
count++;
}
for (int q = start + 1; q < end; q++)
{
spiralMatrix[q, end - 1] = count;
count++;
}
for (int r = end - 2; r >= start; r--)
{
spiralMatrix[end - 1, r] = count;
count++;
}
for (int s = end - 2; s >= start + 1; s--)
{
spiralMatrix[s, start] = count;
count++;
}
start = start + 1;
end = end - 1;
}
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (j == size - 1)
{
Console.Write(spiralMatrix[i, j]);
}
else
{
Console.Write(spiralMatrix[i, j] + "\t");
}
}
Console.WriteLine();
}
}
}
}
|
71a48033f9f85810a53a4b1b164e9e939dc6d705
|
C#
|
manuel2258/timed
|
/Assets/src/level/initializing/ElementInitializer.cs
| 2.5625
| 3
|
using System;
using src.element;
using src.level.parsing;
using UnityEngine;
namespace src.level.initializing {
public class ElementInitializer {
private readonly ElementType _elementType;
private readonly Vector2 _position;
private readonly float _angle;
public readonly int Id;
public ElementInitializer(ElementType elementType, int id, Vector2 position, float angle) {
_elementType = elementType;
_position = position;
_angle = angle;
Id = id;
}
public GameObject initialize() {
var currentGameObject = getGameObject();
setTransform(currentGameObject);
callSetupScript(currentGameObject);
return currentGameObject;
}
protected virtual GameObject getGameObject() {
switch (_elementType) {
case ElementType.Wall:
return ElementPrefabStorage.Instance.getWall();
case ElementType.ColliderBody:
return ElementPrefabStorage.Instance.getColliderBody();
default:
throw new Exception("ElementInitialized used for effector or trigger!");
}
}
protected virtual void setTransform(GameObject currentGameObject) {
currentGameObject.transform.position = _position;
currentGameObject.transform.rotation = Quaternion.Euler(0,0,_angle);
currentGameObject.transform.parent = LevelManager.Instance.LevelRoot;
}
protected virtual void callSetupScript(GameObject currentGameObject) { }
}
}
|
6b71ba765dfe99ae954ff2b37926a2e4f7d3f07e
|
C#
|
sergiobd01/OMSCampaings
|
/OMSService.WSCustomer/Business/DALBase.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using OMSService.WSCustomer.Models;
using OMSService.WSCustomer.Payload;
namespace OMSService.WSCustomer.Business
{
public class DALBase
{
protected static string ConnectionString
{
get
{
return ConfigurationManager.ConnectionStrings["APIConectionString"].ConnectionString;
}
}
protected static SqlConnection GetDbConnection()
{
return new SqlConnection(ConnectionString);
}
protected static SqlCommand GetDbCommand(string sqlQuery)
{
SqlCommand command = new SqlCommand();
command.Connection = GetDbConnection();
command.CommandType = CommandType.Text;
command.CommandText = sqlQuery;
return command;
}
#region getProcedures
// GetDbSprocCommand
protected static SqlCommand GetDbSprocCommand(string sprocName)
{
SqlCommand command = new SqlCommand(sprocName);
command.Connection = GetDbConnection();
command.CommandType = CommandType.StoredProcedure;
return command;
}
#endregion
#region CreateNullparameters
protected static SqlParameter CreateNullParameter(string name, SqlDbType paramType)
{
SqlCommand parameter = new SqlCommand();
var p = parameter.CreateParameter();
p.SqlDbType = paramType;
p.ParameterName = name;
p.Value = null;
p.Direction = ParameterDirection.Input;
return p;
}
#endregion
protected static SqlParameter CreateINParameter(string name, SqlDbType paramType)
{
SqlParameter parameter = new SqlParameter();
parameter.SqlDbType = paramType;
parameter.ParameterName = name;
parameter.Direction = ParameterDirection.Input;
return parameter;
}
/// <summary>
/// Create long parameter
/// </summary>
/// <param name="name">Parameters name.</param>
/// <param name="value">parameters value.</param>
/// <returns>SqlParameter</returns>
protected static SqlParameter CreateParameter(string name, long value)
{
SqlParameter parameter = new SqlParameter();
if (value == CommonBase.Int_NullValue)
{
// If value is null then create a null parameter
return CreateNullParameter(name, SqlDbType.Int);
}
else
{
parameter = CreateINParameter(name, SqlDbType.Int);
parameter.Value = value;
return parameter;
}
}
#region CreateParameter
/// <summary>
/// Create string parameter
/// </summary>
/// <param name="name">Parameters name.</param>
/// <param name="value">parameters value.</param>
/// <returns>SqlParameter</returns>
protected static SqlParameter CreateParameter(string name, string value)
{
SqlParameter parameter = new SqlParameter();
if (value == CommonBase.String_NullValue)
{
// If value is null then create a null parameter
return CreateNullParameter(name, SqlDbType.VarChar);
}
else
{
parameter = CreateINParameter(name, SqlDbType.VarChar);
parameter.Value = value;
return parameter;
}
}
/// <summary>
/// Create IN parameter
/// </summary>
/// <param name="name">Parameters name.</param>
/// <param name="value">parameters value.</param>
/// <returns>SqlParameter</returns>
protected static SqlParameter CreateParameter(string name, int value)
{
SqlParameter parameter = new SqlParameter();
if (value == CommonBase.Int_NullValue)
{
// If value is null then create a null parameter
return CreateNullParameter(name, SqlDbType.Int);
}
else
{
parameter = CreateINParameter(name, SqlDbType.Int);
parameter.Value = value;
return parameter;
}
}
#endregion CreateParameter
#region Singleton
protected static List<Customer> GetCustomer(ref SqlCommand command) //where T : CommonBase
{
List<Customer> dtoList = new List<Customer>();
try
{
command.Connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Customer item = new Customer();
if (reader["idCustomer"].ToString() != "") item.idCustomer = (long)reader["idCustomer"];
if (reader["idCategory"].ToString() != "") item.idCategory = (long)reader["idCategory"];
item.email = reader["email"].ToString();
item.userName = reader["userName"].ToString();
if (reader["idCard"].ToString() != "") item.idCard = (long)reader["idCard"];
item.first_name = reader["first_name"].ToString();
item.last_name = reader["last_name"].ToString();
item.phone_number = reader["phone_number"].ToString();
item.address = reader["address"].ToString();
item.country = reader["country"].ToString();
item.numberDoc = reader["numberDoc"].ToString();
item.TypeDoc = reader["TypeDoc"].ToString();
item.city = reader["city"].ToString();
if (reader["idUser"].ToString() != "") item.idUser = (long)reader["idUser"];
if (reader["modificationDate"].ToString() != "") item.modificationDate = (DateTime)reader["modificationDate"];
dtoList.Add(item);
}
reader.Close();
}
catch (SqlException oEx)
{
throw oEx;
}
finally
{
command.Connection.Close();
command.Connection.Dispose();
}
return dtoList;
}
protected static List<RespCustomerProduct> CustomerProduct(ref SqlCommand command)
{
List<RespCustomerProduct> dtoList = new List<RespCustomerProduct>();
try
{
command.Connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
RespCustomerProduct item = new RespCustomerProduct();
if (reader["idCustomer"].ToString() != "") item.idCustomer = (long)reader["idCustomer"];
item.email = reader["email"].ToString();
item.first_name = reader["first_name"].ToString();
item.last_name = reader["last_name"].ToString();
if (reader["idProduct"].ToString() != "") item.idProduct = (long)reader["idProduct"];
item.name = reader["name"].ToString();
dtoList.Add(item);
}
reader.Close();
}
catch (SqlException oEx)
{
throw oEx;
}
finally
{
command.Connection.Close();
command.Connection.Dispose();
}
return dtoList;
}
protected static List<RespTopCustomer> TopCustomer(ref SqlCommand command)
{
List<RespTopCustomer> dtoList = new List<RespTopCustomer>();
try
{
command.Connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
RespTopCustomer item = new RespTopCustomer();
if (reader["idCustomer"].ToString() != "") item.idCustomer = (long)reader["idCustomer"];
item.first_name = reader["first_name"].ToString();
item.last_name = reader["last_name"].ToString();
if (reader["Acumulado"].ToString() != "") item.Acumulado = (decimal)reader["Acumulado"];
dtoList.Add(item);
}
reader.Close();
}
catch (SqlException oEx)
{
throw oEx;
}
finally
{
command.Connection.Close();
command.Connection.Dispose();
}
return dtoList;
}
#endregion
protected static void ExecuteNonQuery(SqlCommand command)
{
try
{
command.Connection.Open();
command.ExecuteNonQuery();
command.Connection.Close();
}
catch (Exception e)
{
if (command.Connection.State == ConnectionState.Open)
command.Connection.Close();
throw e;
}
}
}
}
|
b352fd19f4772a9790e8a196c45ea085d592b4e3
|
C#
|
mad5226/PracticeSeleniumFramework
|
/SeleniumFramework/Properties/Configuration.cs
| 2.5625
| 3
|
using System;
namespace SeleniumFramework.Properties
{
public static class Configuration
{
public static string baseURL = "http://www.todorvachev.com";
public static class Credentials
{
public static class Valid
{
public static string username = "Clayton";
public static string password = "12345";
public static string repeatPassword = "12345";
}
public static class Invalid
{
public static string usernameLessThanFive = "Clay";
public static string usernameMoreThanTweleve = "ClaytonAdamss";
public static string password = "12345";
public static string wrongPassword = "12345678";
public static string repeatPassword = "12345";
}
}
}
}
|
4d99c86051e1ae54eba11ab12c2c23842985b54d
|
C#
|
Doug-Murphy/C-Sharp-Project-Cleaner
|
/StaticContentFileRemover.cs
| 2.84375
| 3
|
using System.Collections.Generic;
using System.Xml;
namespace CsprojCleaner
{
public class StaticContentFileRemover : IFileRemover
{
private readonly string _fileExtension;
public StaticContentFileRemover(string fileExtension)
{
_fileExtension = fileExtension;
}
public void CleanUpFiles(XmlDocument parsedXml)
{
var nodes = GetContentIncludes(parsedXml);
foreach (var nodeToDelete in nodes)
{
if (nodeToDelete.ParentNode == null)
{
continue;
}
nodeToDelete.ParentNode.RemoveChild(nodeToDelete);
}
}
private List<XmlNode> GetContentIncludes(XmlDocument parsedXml)
{
var results = new List<XmlNode>();
foreach (XmlNode item in parsedXml.SelectNodes("Project/ItemGroup/Content"))
{
if (item.Attributes?["Include"] == null)
{
continue;
}
var includeAttributeValue = item.Attributes["Include"].Value;
if (includeAttributeValue.EndsWithIgnoreCase($".{_fileExtension}"))
{
results.Add(item);
}
}
return results;
}
}
}
|
fd4dd3c337a6d96c3ad3ee3c16ff60f5cc45c8f2
|
C#
|
cashwu/ProjectTestSession02_AutoFixture
|
/AutoFixtureSample/UnitTest1.cs
| 3.265625
| 3
|
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Ploeh.AutoFixture;
using System.Collections.Generic;
using System.Linq;
namespace AutoFixtureSample
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
// 使用 AutoFixture 建立 String
var fixture = new Fixture();
var actual = fixture.Create<string>();
actual.Should().NotBeNullOrEmpty();
}
[TestMethod]
public void TestMethod2()
{
// 使用 AutoFixture 建立 String
// 設定 Inject 給予預設值
var fixture = new Fixture();
fixture.Inject("cash");
var actual = fixture.Create<string>();
actual.Should().NotBeNullOrEmpty();
actual.Should().StartWith("cash");
}
[TestMethod]
public void TestMethod3()
{
// 使用 AutoFixture 建立 String
// 使用 Create 方法並給予 Seed 參數
var fixture = new Fixture();
var seed = "cash";
var actual = fixture.Create<string>(seed);
actual.Should().NotBeNullOrEmpty();
actual.Should().StartWith("cash");
}
[TestMethod]
public void TestMethod4()
{
// 使用 AutoFixture 建立 String Collection
var fixture = new Fixture();
var actual = fixture.CreateMany<string>();
actual.Count().Should().BeGreaterThan(1);
}
[TestMethod]
public void TestMethod5()
{
// 使用 AutoFixture 建立 String Collection
// 使用 Inject 給予預設值
var fixture = new Fixture();
var actual = fixture.CreateMany<string>(10);
actual.Count().Should().Be(10);
}
[TestMethod]
public void TestMethod6()
{
// 使用 AutoFixture 建立 String Collection
// 使用 CreateMany 方法並給予 Seed
var fixture = new Fixture();
fixture.Inject("cash");
var actual = fixture.CreateMany<string>();
actual.Any().Should().BeTrue();
actual.All(x => x.StartsWith("cash")).Should().BeTrue();
}
[TestMethod]
public void TestMethod7()
{
// 使用 AutoFixture 建立 String Collection
// 使用 CreateMany 方法並給予 Count 參數,讓 Collection 裡有 10 個 String
var fixture = new Fixture();
var actual = fixture.CreateMany<string>(10);
actual.Count().Should().Be(10);
}
[TestMethod]
public void TestMethod8()
{
// 使用 AutoFixture 建立 String Collection
// 使用 AddManyTo 方法
var collection = new List<string>();
var fixture = new Fixture();
fixture.AddManyTo(collection);
collection.Any().Should().BeTrue();
}
[TestMethod]
public void TestMethod9()
{
// 使用 AutoFixture 建立 String Collection
// 使用 AddManyTo 方法,使用 repeatCount 參數,讓 Collection 裡有 10 個 String
var collection = new List<string>();
var fixture = new Fixture();
fixture.AddManyTo(collection, 10);
collection.Count.Should().Be(10);
}
}
}
|
16926360663ec5ace5471ea8e125d3e2240a093d
|
C#
|
MMaxam/Workfolder
|
/CarsRUs/CarsRUs/AppDevAssignment/FrmSearch.cs
| 2.78125
| 3
|
using AppDevAssignment.Classes;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AppDevAssignment
{
public partial class frmSearch : Form
{
public frmSearch()
{
InitializeComponent();
}
static string myConString = ConfigurationManager.ConnectionStrings["Hire"].ConnectionString;
DataTable dt = new DataTable("Hire");
DataSet ds = new DataSet();
MainClass mc = new MainClass();
private void frmSearch_Load(object sender, EventArgs e)
{
//Code populates datagrid table with the Hire database
this.carTableAdapter.Fill(this.hireDataSet.Car);
DataTable dt = mc.Select();
dgvCarList.DataSource = dt;
//Code populates all combo boxes with the appropriate combo box items
cboField.Items.Add("Make");
cboField.Items.Add("EngineSize");
cboField.Items.Add("RentalPerDay");
cboField.Items.Add("Available");
cboOperator.Items.Add("=");
cboOperator.Items.Add("<");
cboOperator.Items.Add(">");
cboOperator.Items.Add("<=");
cboOperator.Items.Add(">=");
}
private void btnRun_Click(object sender, EventArgs e)
{ //Code uses the options selected in the combo boxes and the text in the text box to filter through the database to display data that the user wants to see
ds.Reset();
if (cboField.Text != "" && cboOperator.Text != "" && txtValue.Text != "")
{
string Field = cboField.Text.ToString();
string Operator = cboOperator.Text.ToString();
string Value = txtValue.Text;
string search = Field + " " + Operator + " '" + Value + "'";
using (SqlConnection con = new SqlConnection(myConString))
{
try
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM Car WHERE " + @search;
SqlDataAdapter sqlData = new SqlDataAdapter(cmd);
sqlData.Fill(ds);
dgvCarList.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error updating data", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
con.Close();
}
}
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
var result = MessageBox.Show("Are you sure you want to leave?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
this.Close();
frmCars cars = new frmCars();
cars.Show();
}
}
}
}
|
f82b6ef85336641ffc2ac8b831a03d9788d32cc7
|
C#
|
andriusstatkevicius/IMDB_Storage
|
/IMDB_Storage.Data/IMDB_StorageDBContext.cs
| 2.578125
| 3
|
using IMDB_Storage.Core;
using Microsoft.EntityFrameworkCore;
namespace IMDB_Storage.Data
{
public class IMDB_StorageDBContext : DbContext
{
public IMDB_StorageDBContext(DbContextOptions<IMDB_StorageDBContext> options)
: base(options) { }
// This is the type that I want to tell EF that I want to query for Movie in the DB
// But I also want to be able to insert, update and delete
public DbSet<Movie> Movies { get; set; }
}
}
|
f548c070adc5fd0e44fc161f06edb43e2729ce72
|
C#
|
Thunkar/Complejos
|
/Complejos/Model/BinomicForm.cs
| 3.140625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Complejos
{
class BinomicForm: INotifyPropertyChanged
{
private double x;
private double y;
public double X {
get {
return this.x;
}
set {
this.x = value;
NotifyPropertyChanged("X");
}
}
public double Y
{
get
{
return this.y;
}
set
{
this.y = value;
NotifyPropertyChanged("Y");
}
}
public BinomicForm(double x, double y)
{
this.x = x;
this.y = y;
}
public BinomicForm()
{
this.x = 0.0;
this.y = 0.0;
}
public double Module()
{
return Math.Sqrt(this.X * this.X + this.Y * this.Y);
}
public double Arg()
{
double Arg = Math.Atan2(this.Y, this.X);
return Arg;
}
public void convertFromExp(ExpForm ze)
{
this.X = ze.RealPart();
this.Y = ze.ImPart();
}
public String toString()
{
return this.x + " + i" + this.y;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
|
db084f7101a3f4e04d9d523edcaa31823b8e90bb
|
C#
|
thadmuchnok64/Firebenders-Final
|
/Hold The Fort/Assets/Scripts/Container.cs
| 2.546875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Container : MonoBehaviour
{
[SerializeField] InventorySlot[] slots;
[SerializeField] SoundMaster SM;
[SerializeField] AudioClip click;
public bool insertItem(Item item)
{
bool foundMin = false;
InventorySlot a = null;
foreach (InventorySlot slot in slots)
{
Item x = slot.GetComponent<Item>();
if (x == null && !foundMin)
{
foundMin = true;
a = slot;
}
else if (x!=null&&x.itemID == item.itemID && x.isStackable)
{
slot.addItem(item);
if (SoundMaster.soundOn)
SM.PlaySound(click);
return true;
}
}
if (foundMin)
{
a.InsertItem(item);
if (SoundMaster.soundOn)
SM.PlaySound(click);
return true;
}
else
{
return false;
}
}
public bool CheckIfContainsID(int ID)
{
foreach(InventorySlot slot in slots)
{
Item x = slot.GetComponent<Item>();
if (x!=null&&x.itemID == ID)
{
return true;
}
}
return false;
}
}
|
7388c9896622e45dc2866c1d4cde0141884b93e0
|
C#
|
shyoutarou/Exam-70-483_Gerenciar_fluxo
|
/Exemplos/2_Gerencia_multi/Monitor Example/Monitor Example/Program.cs
| 3.359375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Monitor_Example
{
class PingPong
{
public void ping(bool running)
{
lock (this)
{
if (!running)
{
//ball halts.
Monitor.Pulse(this); // notify any waiting threads
return;
}
Console.Write("Ping ");
Monitor.Pulse(this); // let pong() run
Monitor.Wait(this); // wait for pong() to complete
}
}
public void pong(bool running)
{
lock (this)
{
if (!running)
{
//ball halts.
Monitor.Pulse(this); // notify any waiting threads
return;
}
Console.WriteLine("Pong ");
Monitor.Pulse(this); // let ping() run
Monitor.Wait(this); // wait for ping() to complete
}
}
}
class MyThread
{
public Thread thread;
PingPong pingpongObject;
//construct a new thread.
public MyThread(string name, PingPong pp)
{
thread = new Thread(new ThreadStart(this.run));
pingpongObject = pp;
thread.Name = name;
thread.Start();
}
//Begin execution of new thread.
void run()
{
if (thread.Name == "Ping")
{
for (int i = 0; i < 5; i++)
pingpongObject.ping(true);
pingpongObject.ping(false);
}
else
{
for (int i = 0; i < 5; i++)
pingpongObject.pong(true);
pingpongObject.pong(false);
}
}
}
class Program
{
static void Main(string[] args)
{
PingPong pp = new PingPong();
Console.WriteLine("The Ball is dropped... \n");
MyThread mythread1 = new MyThread("Ping", pp);
MyThread mythread2 = new MyThread("Pong", pp);
mythread1.thread.Join();
mythread2.thread.Join();
Console.WriteLine("\nThe Ball Stops Bouncing.");
Nonatomic_Erro();
Atomic_Monitor();
Console.Read();
}
static void Nonatomic_Erro()
{
int num = 0;
int length = 500000;
//Run on separate thread of threadpool
Task tsk = Task.Run(() =>
{
for (int i = 0; i < length; i++)
{
num = num + 1;
}
});
//Run on Main Thread
for (int i = 0; i < length; i++)
{
num = num - 1;
}
tsk.Wait();
Console.WriteLine(num); //-6674 OU o OU 655
}
static void Atomic_Monitor()
{
int num = 0;
int length = 500000;
object _lock = new object();
//Run on separate thread of threadpool
Task tsk = Task.Run(() =>
{
for (int i = 0; i < length; i++)
{
//lock the block of code
Monitor.Enter(_lock);
try
{
num = num + 1;
}
finally
{
//unlock the locked code
Monitor.Exit(_lock);
}
}
});
//Run on Main Thread
for (int i = 0; i < length; i++)
{
//lock the block of code
Monitor.Enter(_lock);
num = num - 1;
//unlock the locked code
Monitor.Exit(_lock);
}
tsk.Wait();
Console.WriteLine(num); //0
}
}
}
|
46ce2d834579c30a8b5da118fa4f9e9506860b94
|
C#
|
grecojoao/Pratice
|
/Test/HackerRank/Sorting/FraudulentActivityNotificationsTests.cs
| 2.765625
| 3
|
using HackerRank.Sorting;
using NUnit.Framework;
namespace Test.HackerRank.Sorting
{
public class FraudulentActivityNotificationsTests
{
[Test]
public void ActivityNotifications01()
{
var expenditure = new int[]
{
2, 3, 4, 2, 3, 6, 8, 4, 5
};
var result = 2;
Assert.AreEqual(result, FraudulentActivityNotifications.ActivityNotifications(expenditure, 5));
}
[Test]
public void ActivityNotifications02()
{
var expenditure = new int[]
{
10, 20, 30, 40, 50
};
var result = 1;
Assert.AreEqual(result, FraudulentActivityNotifications.ActivityNotifications(expenditure, 3));
}
}
}
|
45713e5f106d1ae5308cdfff7e8fed3a88780cd0
|
C#
|
Grzesiaczek/Brain
|
/Brain/Charting/ChartedNeuron.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace Brain
{
class ChartedNeuron : Layer
{
Neuron neuron;
Series series;
Brush fontColor;
Color background;
Color light;
Pen border;
Pen active;
Pen inactive;
Rectangle rect;
Rectangle normal;
Rectangle pushed;
static Color[] palette = { Color.Red, Color.Purple, Color.Orchid, Color.BlueViolet, Color.Goldenrod, Color.DarkGreen, Color.Maroon, Color.Navy,
Color.HotPink, Color.Firebrick, Color.Crimson, Color.Indigo, Color.Khaki, Color.Lavender};
static int index = 0;
bool visible;
public ChartedNeuron(Neuron neuron)
{
this.neuron = neuron;
visible = false;
series = new Series();
series.Name = neuron.Name;
series.ChartType = SeriesChartType.Line;
MouseClick += new MouseEventHandler(click);
MouseDoubleClick += new MouseEventHandler(click);
MouseEnter += new EventHandler(mouseOn);
MouseLeave += new EventHandler(mouseOff);
Height = 20;
Width = 60;
normal = new Rectangle(-1, -1, Width, Height);
pushed = new Rectangle(0, 0, Width, Height);
active = new Pen(Brushes.Azure, 2);
inactive = new Pen(Brushes.Purple, 2);
}
public override void show()
{
series.Points.Clear();
series.Points.AddXY(0, 0);
series.Color = palette[index];
series.BorderWidth = 2;
light = palette[index];
visible = false;
index = (index + 1) % palette.Length;
background = SystemColors.ActiveBorder;
fontColor = Brushes.DarkSlateBlue;
border = inactive;
rect = normal;
double x = 0;
foreach(NeuronData data in neuron.Activity)
{
if (data.Impulse == 0)
{
if(data.Initial == 0)
{
series.Points.AddXY(++x, data.Value);
continue;
}
double basis = data.Value / data.Initial;
for (int i = 1; i < 5; i++)
{
double factor = 0.2 * i;
series.Points.AddXY(x + factor, data.Initial * Math.Pow(basis, factor));
}
series.Points.AddXY(++x, data.Value);
}
else
{
double diff = data.Value - data.Initial;
for (int i = 1; i < 5; i++)
{
double factor = 0.2 * i;
series.Points.AddXY(x + factor, data.Initial + factor * diff);
}
if (data.Value < -0.9 * Constant.Beta)
series.Points.AddXY(++x - 0.04, data.Value * 0.96);
else
series.Points.AddXY(++x, data.Value);
}
}
base.show();
}
public override void hide()
{
hideNeuron(series, null);
base.hide();
}
void click(object sender, EventArgs e)
{
if (visible)
{
background = SystemColors.ActiveBorder;
fontColor = Brushes.DarkSlateBlue;
rect = normal;
visible = false;
hideNeuron(series, null);
}
else
{
background = light;
fontColor = Brushes.AliceBlue;
rect = pushed;
visible = true;
showNeuron(series, null);
}
}
protected override void tick(object sender, EventArgs e)
{
Graphics g = buffer.Graphics;
g.Clear(background);
g.DrawRectangle(border, rect);
g.DrawString(neuron.Word, SystemFonts.DialogFont, fontColor, rect, Constant.Format);
buffer.Render(graphics);
}
void mouseOn(object sender, EventArgs e)
{
series.BorderWidth = 4;
border = active;
}
void mouseOff(object sender, EventArgs e)
{
series.BorderWidth = 2;
border = inactive;
}
public event EventHandler showNeuron;
public event EventHandler hideNeuron;
}
}
|
8acf08e39cee082b12168b8aa3eedd7c7ea6766e
|
C#
|
rafaleals/teste-api-caminhoneiro
|
/API_JSL/API_JSL/Controllers/CaminhoesController.cs
| 2.625
| 3
|
using API_JSL.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace API_JSL.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CaminhoesController : ControllerBase
{
private readonly JSL_Context _context;
public CaminhoesController(JSL_Context context) => _context = context;
// GET: api/Caminhoes
[HttpGet]
public IEnumerable<Caminhao> GetCaminhao() => _context.Caminhao;
// GET: api/Caminhoes/5
[HttpGet("{id}")]
public async Task<IActionResult> GetCaminhao([FromRoute] int id)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
var caminhao = await _context.Caminhao.FindAsync(id);
if (caminhao == null)
return NotFound();
return Ok(caminhao);
}
// PUT: api/Caminhoes/5
[HttpPut("{id}")]
public async Task<IActionResult> PutCaminhao([FromRoute] int id, [FromBody] Caminhao caminhao)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
if (id != caminhao.IdCaminhao)
return BadRequest();
_context.Entry(caminhao).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!CaminhaoExists(id))
return NotFound();
else
throw;
}
return NoContent();
}
// POST: api/Caminhoes
[HttpPost]
public async Task<IActionResult> PostCaminhao([FromBody] Caminhao caminhao)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
_context.Caminhao.Add(caminhao);
await _context.SaveChangesAsync();
return CreatedAtAction("GetCaminhao", new { id = caminhao.IdCaminhao }, caminhao);
}
// DELETE: api/Caminhoes/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteCaminhao([FromRoute] int id)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
var caminhao = await _context.Caminhao.FindAsync(id);
if (caminhao == null)
return NotFound();
_context.Caminhao.Remove(caminhao);
await _context.SaveChangesAsync();
return Ok(caminhao);
}
private bool CaminhaoExists(int id) => _context.Caminhao.Any(e => e.IdCaminhao == id);
}
}
|
c6f55a6515211625bf16b1dfc00a6ba0e3c41843
|
C#
|
AldiyarUaliev/University-Information-System
|
/ASP-NET-Project-Assignment/UniversityInformationSystem.Services/StudentsService.cs
| 2.6875
| 3
|
namespace UniversityInformationSystem.Services
{
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using Contracts;
using Data.Contracts;
using Data.Mocks.Repositories;
using Models.EntityModels.Users;
using Models.ViewModels.Student;
public class StudentsService : Service, IStudentsService
{
public StudentsService(IUisDataContext dbContext)
: base(dbContext)
{
}
// Constructor for unit testing
public StudentsService(IUisDataContext dbContext, MockedStudentsRepository mockedStudentsRepository)
: base(dbContext)
{
this.StudentRepository = mockedStudentsRepository;
this.SeedStudents();
}
public Student GetStudentByUsername(string username)
{
return this.StudentRepository
.All()
.Single(s => s.IdentityUser.UserName == username);
}
public StudentProfileViewModel GetStudentProfileViewModel(string username)
{
Student studentEntity = this.GetStudentByUsername(username);
return Mapper.Map<StudentProfileViewModel>(studentEntity);
}
public int? GetStudentId(string username)
{
Student studentEntity = this.StudentRepository
.All()
.SingleOrDefault(s => s.IdentityUser.UserName == username);
return studentEntity?.Id;
}
public IEnumerable<string> GetAllStudentUsernames()
{
return this.StudentRepository
.All()
.Select(s => s.IdentityUser.UserName);
}
}
}
|
4882d16d1543c50882a51ded0298d4da175c37db
|
C#
|
oliverbooth/X10D
|
/X10D.Unity/src/WaitForFrames.cs
| 3.1875
| 3
|
using System.Collections;
namespace X10D.Unity;
/// <summary>
/// Represents a yield instruction that waits for a specific number of frames.
/// </summary>
public struct WaitForFrames : IEnumerator
{
private readonly int _frameCount;
private int _frameIndex;
/// <summary>
/// Initializes a new instance of the <see cref="WaitForFrames" /> struct.
/// </summary>
/// <param name="frameCount">The frame count.</param>
public WaitForFrames(int frameCount)
{
_frameCount = frameCount;
_frameIndex = 0;
}
/// <inheritdoc />
public object Current
{
get => _frameCount;
}
/// <inheritdoc />
public bool MoveNext()
{
return ++_frameIndex <= _frameCount;
}
/// <inheritdoc />
public void Reset()
{
_frameIndex = 0;
}
}
|
18a4570923ad3a2567142c963cfb2080d1bfba68
|
C#
|
fdbva/ADSL20M3.Mvc2
|
/Infrastructure.Data/UoW/UnitOfWork.cs
| 2.671875
| 3
|
using System;
using System.Threading.Tasks;
using Data.Infrastructure.Context;
using Domain.Model.Interfaces.UoW;
namespace Infrastructure.Data.UoW
{
public class UnitOfWork : IUnitOfWork, IDisposable
{
private readonly BibliotecaContext _bibliotecaContext;
private bool _disposed;
public UnitOfWork(
BibliotecaContext bibliotecaContext)
{
_bibliotecaContext = bibliotecaContext;
}
public void BeginTransaction()
{
_disposed = false;
}
public void Commit()
{
_bibliotecaContext.SaveChanges();
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
_bibliotecaContext.Dispose();
}
}
_disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
|
4eb60002d985aedac13bedd4f8098dba6547539d
|
C#
|
HumanGamer/GenericNotifier
|
/GenericNotifier/InternetNotifier.cs
| 2.9375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace GenericNotifier
{
public class InternetNotifier : NotificationService
{
private readonly WebClient _web;
private bool _isConnected;
public InternetNotifier()
{
Interval = 1000;
_isConnected = false;
_web = new WebClient();
}
public override void Update()
{
string text = _web.DownloadString("http://www.msftconnecttest.com/connecttest.txt");
if (!_isConnected && text == "Microsoft Connect Test")
{
SendNotification("Internet Connected!");
_isConnected = true;
} else if (_isConnected && text != "Microsoft Connect Test")
{
SendNotification("Internet Disconnected!");
_isConnected = false;
}
}
}
}
|
e865e91b870c2472c9f60305b452010bf34d7e89
|
C#
|
Augustojf98/Biblioteca
|
/Biblioteca.Entidades/Libro.cs
| 3.015625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Biblioteca.Entidades
{
[DataContract]
public class Libro
{
private int _id;
private string _titulo;
private string _autor;
private int _edicion;
private string _editorial;
private int _paginas;
private string _tema;
[DataMember]
public int Id
{
get
{
return this._id;
}
set
{
this._id = value;
}
}
[DataMember]
public string Titulo
{
get
{
return this._titulo;
}
set
{
this._titulo = value;
}
}
[DataMember]
public string Autor
{
get
{
return this._autor;
}
set
{
this._autor = value;
}
}
[DataMember]
public int Edicion
{
get
{
return this._edicion;
}
set
{
this._edicion = value;
}
}
[DataMember]
public string Editorial
{
get
{
return this._editorial;
}
set
{
this._editorial = value;
}
}
[DataMember]
public int Paginas
{
get
{
return this._paginas;
}
set
{
this._paginas = value;
}
}
[DataMember]
public string Tema
{
get
{
return this._tema;
}
set
{
this._tema = value;
}
}
public Libro(int id, string titulo, string autor, int edicion, string editorial,int paginas, string tema)
{
this._id = id;
this._titulo = titulo;
this._autor = autor;
this._edicion = edicion;
this._editorial = editorial;
this._paginas = paginas;
this._tema = tema;
}
public override string ToString()
{
return string.Format("Titulo: {0} | Autor: {1} | Editorial: {2} | Páginas: {3} | Edición: {4}", _titulo?.ToUpper(), _autor?.ToUpper(), _editorial, _paginas.ToString(), _edicion.ToString());
}
}
}
|
01a8b844d63e8402c1da25766bd56fcd87fc48de
|
C#
|
1907931256/MasterProject
|
/BarrelLib/TwistProfile.cs
| 2.8125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FileIOLib;
namespace BarrelLib
{
/// <summary>
/// contains barrel twist dat as array of twistValue types
/// </summary>
public class TwistProfile
{
public enum TwistType
{
Uniform,
Progressive
}
public enum DirectionEnum
{
RIGHT_HAND=0,
LEFT_HAND=1
}
public int DirectionSign {
get
{
if (Direction == DirectionEnum.LEFT_HAND)
return 1;
else
return -1;
}
}
public DirectionEnum Direction { get; set; }
TwistType _type;
List<GeometryLib.PointCyl> _twist;
public static string Name = "Twist_Profile";
public static string EndName = "End_Twist";
public double ThetaRadAt(double z)
{
double theta = 0;
switch(_type)
{
case TwistType.Uniform:
theta= ThetaRadforconstantTwist(z);
break;
case TwistType.Progressive:
theta= ThetaRadAtForNonConstant(z);
break;
}
return theta;
}
double ThetaRadforconstantTwist(double z)
{
double th =_twistDirection * Math.PI * 2 * (z / _inchPerRev);
//th %= (Math.PI * 2);
//if (th < 0)
// th += (Math.PI * 2);
return th;
}
/// <summary>
/// return theta for a given z value
/// </summary>
/// <param name="z"></param>
/// <returns></returns>
double ThetaRadAtForNonConstant(double z)
{
var tw0 = new GeometryLib.PointCyl();
var tw1 = new GeometryLib.PointCyl();
double theta = 0;
bool zFound = false;
for (int i = 0; i < _twist.Count - 1; i++)
{
if ((z >= _twist[i].Z) && (z <= _twist[i + 1].Z))
{
tw0 = _twist[i];
tw1 = _twist[i + 1];
zFound = true;
}
if (zFound)
break;
}
if (zFound)
{
if ((tw1.Z - tw0.Z) < float.Epsilon)
{
theta = tw1.ThetaRad;
}
else
{
theta = (z - tw0.Z) * (tw1.ThetaRad - tw0.ThetaRad) / (tw1.Z - tw0.Z) + tw0.ThetaRad;
}
}
return theta;
}
public List<string> ToStringList()
{
List<string> file = new List<string>();
file.Add(TwistProfile.Name);//0
file.Add(_type.ToString());//1
file.Add("z theta");//2
file.Add("inch degrees");//3
foreach (GeometryLib.PointCyl tw in _twist)
{
StringBuilder stb = new StringBuilder();
stb.Append(tw.Z);
stb.Append(FileIO.Splitter);
stb.Append(tw.ThetaRad);
file.Add(stb.ToString());
}
file.Add(TwistProfile.EndName);
return file;
}
void OpenTXT(string fileName)
{
List<string> file = FileIO.ReadDataTextFile(fileName);
_twist = new List<GeometryLib.PointCyl>();
if (file.Count >= 2)
{
string[] splitter = FileIO.Splitter;
if (file[0].Trim() == TwistProfile.Name)
{
TwistType tempEnum = TwistType.Progressive;
if (Enum.TryParse<TwistType>(file[1], true, out tempEnum))
_type = tempEnum;
else
_type = TwistType.Progressive;
for (int i = 4; i < file.Count; i++)
{
string[] splitLine = file[i].Split(splitter, StringSplitOptions.RemoveEmptyEntries);
var twist = new GeometryLib.PointCyl();
if (splitLine.Length > 1)
{
double result = 0;
if (double.TryParse(splitLine[0].Trim(), out result))
{
twist.Z = result;
}
result = 0;
if (double.TryParse(splitLine[1].Trim(), out result))
{
twist.ThetaRad= result;
}
_twist.Add(twist);
}
}
}
}
}
double _inchPerRev;
int _twistDirection;
void Build155mm()
{
_type = TwistType.Uniform;
_inchPerRev = 122;
_twistDirection = -1;
}
void Build25mm()
{
_type = TwistType.Progressive;
_inchPerRev = 40;
_twistDirection = -1;
}
void Build762mm()
{
_type = TwistType.Uniform;
_inchPerRev = 12;
_twistDirection = -1;
}
void Build50Cal()
{
_type = TwistType.Uniform;
_inchPerRev = 15;
_twistDirection = -1;
}
void Build50mm()
{
}
void Build30mm()
{
}
void Init()
{
if (Name == "50Cal")
Build50Cal();
if (Name == "155mm")
Build155mm();
if (Name == "25mm")
Build25mm();
if (Name == "7.62mm")
Build762mm();
if (Name == "50mm")
Build50mm();
if (Name == "30mm")
Build30mm();
}
public TwistProfile(Barrel barrel)
{
Init();
}
}
}
|
5b3dfbb81be2bb10b3e79c224502af0d769fa866
|
C#
|
megarage9000/RedSky-GameJam-2019
|
/Assets/SCripts/Collsion/BaseScript.cs
| 2.625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class BaseScript : MonoBehaviour
{
public Slider energyBar;
public Text status;
public float energy;
float currentEnergy;
public bool dead;
// Start is called before the first frame update
void Awake()
{
dead = false;
energy = 200f;
currentEnergy = energy;
energyBar.value = currentEnergy;
}
void Update()
{
checkIfDead();
}
void hubToPlayer(Collider2D coll)
{
if (coll.gameObject.tag == "Player")
{
var player = coll.gameObject.GetComponent<TankCollision>();
//donate
if (Input.GetKey(KeyCode.E))
{
Debug.Log("donate");
if (player.energy <= player.energyChange || currentEnergy >= energy)
{
setStatus("Health too low/Base health too high.");
}
else
{
setStatus("Donating...");
player.decreaseEnergy(2);
currentEnergy += player.energyChange * 2 * Time.deltaTime;
updateBar();
}
}
//heal
else if (Input.GetKey(KeyCode.F))
{
Debug.Log("heal");
if (player.energy >= player.energyMax || currentEnergy <= player.energyChange)
{
setStatus("Health too high/Base health too low");
}
else
{
setStatus("Healing...");
player.regainEnergy(player.energyChange * 2 * Time.deltaTime);
currentEnergy -= player.energyChange * 2 * Time.deltaTime;
updateBar();
}
}
else
{
setStatus("Press F to Heal, or Press E to Donate Energy.");
}
}
}
void OnTriggerEnter2D(Collider2D coll)
{
hubToPlayer(coll);
}
void OnTriggerStay2D(Collider2D coll)
{
hubToPlayer(coll);
}
void OnTriggerExit2D(Collider2D coll)
{
if(coll.gameObject.tag == "Player")
{
setStatus(" ");
}
}
void updateBar()
{
energyBar.value = (currentEnergy/energy) * 100;
}
//Bullets
void OnCollisionEnter2D(Collision2D coll)
{
if(coll.gameObject.tag == "Projectile")
{
Destroy(coll.gameObject);
}
}
void setStatus(string s)
{
status.text = s;
}
//Enemy
void OnCollisionStay2D(Collision2D coll)
{
if (coll.gameObject.layer == 12)
{
currentEnergy -= coll.gameObject.GetComponent<EnemyCollision>().damage * Time.deltaTime;
updateBar();
}
}
void checkIfDead()
{
if(currentEnergy <= 0)
{
dead = true;
}
}
}
|
6970a5da1d350530fd383c5be0908caa0280f389
|
C#
|
commercetools/commercetools-dotnet-core-sdk
|
/commercetools.Sdk/commercetools.Sdk.Linq/Query/Converters/BinaryLogicalPredicateVisitorConverter.cs
| 2.8125
| 3
|
using System.Linq.Expressions;
using commercetools.Sdk.Linq.Query.Visitors;
namespace commercetools.Sdk.Linq.Query.Converters
{
// | ||
// & &&
public class BinaryLogicalPredicateVisitorConverter : IQueryPredicateVisitorConverter
{
public int Priority { get; } = 4;
public bool CanConvert(Expression expression)
{
return Mapping.LogicalOperators.ContainsKey(expression.NodeType);
}
public IPredicateVisitor Convert(Expression expression, IPredicateVisitorFactory predicateVisitorFactory)
{
BinaryExpression binaryExpression = expression as BinaryExpression;
if (binaryExpression == null)
{
return null;
}
string operatorSign = Mapping.GetOperator(expression.NodeType, Mapping.LogicalOperators);
IPredicateVisitor predicateVisitorLeft = predicateVisitorFactory.Create(binaryExpression.Left);
IPredicateVisitor predicateVisitorRight = predicateVisitorFactory.Create(binaryExpression.Right);
// c => c.Parent.Id == "some id" || c.Parent.Id == "some other id"
if (CanCombinePredicateVisitors(predicateVisitorLeft, predicateVisitorRight))
{
return CombinePredicateVisitors(predicateVisitorLeft, operatorSign, predicateVisitorRight);
}
return new BinaryPredicateVisitor(predicateVisitorLeft, operatorSign, predicateVisitorRight);
}
private static bool CanCombinePredicateVisitors(IPredicateVisitor left, IPredicateVisitor right)
{
return HasSameParents(left, right);
}
private static bool HasSameParents(IPredicateVisitor left, IPredicateVisitor right)
{
bool result = false;
while (left is ContainerPredicateVisitor containerLeft && right is ContainerPredicateVisitor containerRight)
{
result = ArePropertiesEqual(containerLeft, containerRight);
left = containerLeft.Inner;
right = containerRight.Inner;
}
return result;
}
private static bool ArePropertiesEqual(ContainerPredicateVisitor left, ContainerPredicateVisitor right)
{
ConstantPredicateVisitor constantLeft = left.Parent as ConstantPredicateVisitor;
ConstantPredicateVisitor constantRight = right.Parent as ConstantPredicateVisitor;
if (constantLeft != null && constantRight != null)
{
return constantLeft.Constant == constantRight.Constant;
}
return false;
}
private static IPredicateVisitor CombinePredicateVisitors(IPredicateVisitor left, string operatorSign, IPredicateVisitor right)
{
IPredicateVisitor innerLeft = left;
IPredicateVisitor innerRight = right;
ContainerPredicateVisitor container = null;
while (innerLeft is ContainerPredicateVisitor containerLeft && innerRight is ContainerPredicateVisitor containerRight)
{
innerLeft = containerLeft.Inner;
innerRight = containerRight.Inner;
container = new ContainerPredicateVisitor(containerLeft.Parent, container);
}
if (innerLeft is BinaryPredicateVisitor binaryLeft && innerRight is BinaryPredicateVisitor binaryRight)
{
BinaryPredicateVisitor binaryPredicateVisitor = new BinaryPredicateVisitor(innerLeft, operatorSign, innerRight);
return CombinePredicates(container, binaryPredicateVisitor);
}
return null;
}
// When there is more than one property accessor, the last accessor needs to be taken out and added to the binary logical predicate.
// property(property(property operator value)
private static IPredicateVisitor CombinePredicates(IPredicateVisitor left, IPredicateVisitor right)
{
var containerLeft = (ContainerPredicateVisitor)left;
IPredicateVisitor parent = containerLeft;
if (parent == null)
{
return new ContainerPredicateVisitor(right, left);
}
IPredicateVisitor innerContainer = right;
ContainerPredicateVisitor combinedContainer = null;
while (parent != null)
{
if (CanBeCombined(parent))
{
var container = (ContainerPredicateVisitor)parent;
innerContainer = new ContainerPredicateVisitor(innerContainer, container.Inner);
combinedContainer = new ContainerPredicateVisitor(innerContainer, container.Parent);
parent = container.Parent;
}
}
return combinedContainer;
}
private static bool CanBeCombined(IPredicateVisitor left)
{
return left is ContainerPredicateVisitor;
}
}
}
|
d0731837da636b2fe1ae1bdffe2635f9976ff0a7
|
C#
|
Entropia-dev/Generando-Entropia
|
/Entidades/Clientes.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entidades
{
public class Clientes
{
//escribo todos los campos que va a tener la entidad.
String Correo_Cli;
String Nombre;
String Apellido;
String Fecha_Nac;
String Metodo_captacion;
String Dni;
String Direccion;
String Usuario_Cli;
String sexo;
//declaro un constructor vacio.
public Clientes() { }
// declaro los sets y los gets.
public void set_sexo(String Nuevo_sexo)
{
this.sexo = Nuevo_sexo;
}
public String get_sexo()
{
return sexo;
}
public void set_Fecha_Nac(String Nuevo_Fecha_Nac)
{
this.Fecha_Nac = Nuevo_Fecha_Nac;
}
public String get_Fecha_Nac()
{
return Fecha_Nac;
}
public void set_Usuario_Cli(String Nuevo_Usuario_Cli)
{
this.Usuario_Cli = Nuevo_Usuario_Cli;
}
public String get_Usuario_Cli()
{
return Usuario_Cli;
}
public void set_Metodo_captacion(String Nuevo_Metodo_captacion)
{
this.Metodo_captacion = Nuevo_Metodo_captacion;
}
public String get_Metodo_captacion()
{
return Metodo_captacion;
}
public void set_Direccion(String Nuevo_Direccion)
{
this.Direccion = Nuevo_Direccion;
}
public String get_Direccion()
{
return Direccion;
}
public void set_Apellido(String Nuevo_Direccion)
{
this.Apellido = Nuevo_Direccion;
}
public String get_Apellido()
{
return Apellido;
}
public String get_Nombre()
{
return Nombre;
}
public void set_Nombre(String Nuevo_Nombre)
{
this.Nombre = Nuevo_Nombre;
}
public String get_Dni()
{
return Dni;
}
public void set_Dni(String Nuevo_Dni)
{
this.Dni = Nuevo_Dni;
}
public void set_email_cuenta(string nuevo_email)
{
this.Correo_Cli = nuevo_email;
}
public string get_email_cuenta()
{
return Correo_Cli;
}
}
}
|
b50b08694adb2f46b4b93e96a4a2bf97c63cb3c1
|
C#
|
GabrielGui13/PEOO_2020
|
/Lista 2/Exercicio 0.7/Program.cs
| 3.546875
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercicio_7
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Digite os coeficientes a, b e c de uma equação do II grau");
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
int c = int.Parse(Console.ReadLine());
double bp = (-b + Math.Sqrt(Math.Pow(b, 2) - 4*a*c)) / (2*a);
double bn = (-b - Math.Sqrt(Math.Pow(b, 2) - 4*a*c)) / (2*a);
if ((bp % 1 == 0) && (bn % 1 == 0)) Console.WriteLine($"As raizes são {bp} e {bn}");
else Console.WriteLine("Impossível Calcular");
Console.ReadKey();
}
}
}
|
11f6d3fa466defa76e60a3a07889319bc3f8b569
|
C#
|
Packo0/SoftUniProgrammingFundamentals
|
/exercise/t05_DataTypesAndVariablesMoreExercises/p13_DecryptingMessage/p13_DecryptingMessage.cs
| 3.453125
| 3
|
using System;
namespace p13_DecryptingMessage
{
class p13_DecryptingMessage
{
static void Main(string[] args)
{
int key = int.Parse(Console.ReadLine());
int n = int.Parse(Console.ReadLine());
string message = string.Empty;
for (int i = 0; i < n; i++)
{
char current = char.Parse(Console.ReadLine());
message += (char)(current + key);
}
Console.WriteLine(message);
}
}
}
|
e7cbd6dc8f2c37da64e352326820631d7c8549a2
|
C#
|
Morebis-GIT/CI
|
/xggameplanAPI/src/domain/ImagineCommunications.GamePlan.Domain.Generic/Helpers/EnumerableCastHelper.cs
| 2.90625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace ImagineCommunications.GamePlan.Domain.Generic.Helpers
{
public static class EnumerableCastHelper
{
private static readonly MethodInfo CastGenericMethodInfo =
typeof(EnumerableCastHelper).GetMethod(nameof(Cast), BindingFlags.Static | BindingFlags.NonPublic)
?.GetGenericMethodDefinition();
private static object Cast<TResult>(IEnumerable<object> data)
{
return data.Cast<TResult>().ToArray();
}
public static object CastToArray(IEnumerable<object> data, Type toType)
{
return CastGenericMethodInfo.MakeGenericMethod(toType).Invoke(null, new object[] {data});
}
}
}
|
d28572b42df17f3613c742785a48c9ded291fc3d
|
C#
|
Vengarioth/XAMLTools
|
/src/XAMLTools/Scanner/StringSampler.cs
| 3
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace XAMLTools.Scanner
{
class StringSampler : ISampler
{
public DocumentState State { get; set; }
private string content;
private int position = 0;
public StringSampler(string content)
{
this.content = content;
}
public void Next()
{
position++;
}
public bool ReadCharacter(out char character)
{
if (position >= content.Length)
{
character = Char.MinValue;
return false;
}
character = content[position];
return true;
}
public bool PeekAhead(out char character)
{
var nextPosition = position + 1;
if (nextPosition >= content.Length)
{
character = Char.MinValue;
return false;
}
character = content[nextPosition];
return true;
}
}
}
|
3f324cef898afe226b80851a558ca8ffa4e2fdaf
|
C#
|
NazarOnischenko/FactoryMethod
|
/FactoryMethod/Program.cs
| 3.171875
| 3
|
using System;
using System.Text;
namespace FactoryMethod
{
class Program
{
static void Main(string[] args)
{
Console.InputEncoding = Encoding.Unicode;
Console.OutputEncoding = Encoding.Unicode;
Deliver deliver = new DeliverOfFood("Олександр Сочинський");
Product product = deliver.ToDeliver();
deliver = new DeliverOfAppliances("Василь Гензерук");
product = deliver.ToDeliver();
deliver = new DeliverOfClothing("Максим Марущак");
product = deliver.ToDeliver();
deliver = new DeliverOfFurniture("Назар Колвеліс");
product = deliver.ToDeliver();
}
}
}
|
46d5bb442e27abc4eaba258378b73dd501e306be
|
C#
|
ERGeorgiev/TrAIngle
|
/TrAIngle Unmodified/Assets/Scripts/EdsLibrary/Extensions/MathfExt.cs
| 2.75
| 3
|
using UnityEngine;
namespace Extensions
{
public class MathfExt
{
public static Vector2 RadianToVector2(float radian)
{
return new Vector2(Mathf.Cos(radian), Mathf.Sin(radian));
}
public static Vector2 DegreeToVector2(float degree)
{
return RadianToVector2(degree * Mathf.Deg2Rad);
}
}
}
|
5f331b3708bfcfc992db844c8d8f3d5980caef3a
|
C#
|
omccully/FutScript-cs
|
/FutScriptFunctions/Screen/ColorDetection.cs
| 3.53125
| 4
|
using System;
using System.Drawing;
using System.Diagnostics;
using System.Threading;
namespace FutScriptFunctions.Screen
{
// TODO: make code generator to generate method overloads for
// methods that accept Point or Rectangle objects for coordinates.
public static class ColorDetection
{
/// <summary>
/// Extension for Bitmap class
/// </summary>
/// <param name="bmp">A Bitmap image</param>
/// <param name="checker">Color rules. <see cref="ColorRule"/></param>
/// <returns></returns>
public static bool IncludesColor(this Bitmap bmp, ColorChecker checker)
{
Point loc = bmp.LocationOfColor(checker);
return (loc.X != -1) && (loc.Y != -1);
}
/// <summary>
/// Finds a location of a given color within a Bitmap image.
/// </summary>
/// <param name="bmp">A Bitmap image</param>
/// <param name="checker">Color rules. <see cref="ColorRule"/></param>
/// <returns>Returns Point representing coordinates, or (-1, -1) if not found.</returns>
public static Point LocationOfColor(this Bitmap bmp, ColorChecker checker)
{
// TODO: Update this implementation to increment y and x by about y/10 and x/10, respectively.
// This will greatly improve the efficiency of the algorithm, since similar colors are normally
// grouped together on a computer screen.
// Be careful to ensure that all coordinates are checked (do proper testing on this).
for (int y = 0; y < bmp.Height; y++)
{
for (int x = 0; x < bmp.Width; x++)
{
if (checker(bmp.GetPixel(x, y)))
{
return new Point(x, y);
}
}
}
return new Point(-1, -1); // color not found
}
/// <summary>
/// Checks if two images have at least <paramref name="PixelRequirement"/> number of pixels
/// that are different based on <paramref name="comparer"/>
/// </summary>
/// <param name="image_a"></param>
/// <param name="image_b"></param>
/// <param name="PixelRequirement"></param>
/// <param name="comparer"></param>
/// <returns></returns>
public static bool BitmapsHaveNumberOfPixelsDifferent(Bitmap image_a, Bitmap image_b, int PixelRequirement, ColorComparer comparer = null)
{
if (image_a.Size != image_b.Size)
{
throw new ArgumentException("image_a and image_b must be the same size.");
}
int different_pixels_found = 0;
for (int y = 0; y <= image_a.Height; y++)
{
for (int x = 0; x <= image_a.Width; x++)
{
// check if latest (x,y) pixel is "different" from the original
if (!comparer(image_a.GetPixel(x, y), image_b.GetPixel(x, y)))
{
// this pixel is different from the original
different_pixels_found++;
if (different_pixels_found >= PixelRequirement)
{
// success! enough pixel changes were found.
return true;
}
}
}
}
return false;
}
}
}
|
d7f2c6525a93d8620dd8a4c3ab227249521dfec1
|
C#
|
chloe-zen/yamldotnet
|
/YamlDotNet.RepresentationModel/Serialization/ObjectConverter.cs
| 3.140625
| 3
|
using System;
using System.ComponentModel;
using System.Globalization;
namespace YamlDotNet.RepresentationModel.Serialization
{
/// <summary>
/// Performs type conversions.
/// </summary>
public static class ObjectConverter
{
/// <summary>
/// Attempts to convert the specified value to another type using various approaches.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
/// <remarks>
/// The conversion is first attempted by ditect casting.
/// If it fails, the it attempts to use the <see cref="IConvertible"/> interface.
/// If it still fails, it tries to use the <see cref="TypeConverter"/> of the value's type, and then the <see cref="TypeConverter"/> of the <typeparamref name="TTo"/> type.
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="value"/> is null.</exception>
/// <exception cref="InvalidCastException">The value cannot be converted to the specified type.</exception>
public static TTo Convert<TFrom, TTo>(TFrom value)
{
return (TTo)Convert(value, typeof(TTo));
}
/// <summary>
/// Attempts to convert the specified value to another type using various approaches.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="to">To.</param>
/// <returns></returns>
/// <remarks>
/// The conversion is first attempted by ditect casting.
/// If it fails, it tries to use the <see cref="TypeConverter" /> of the value's type, and then the <see cref="TypeConverter" /> of the <paramref name="to" /> type.
/// If it still fails, the it attempts to use the <see cref="IConvertible"/> interface.
/// </remarks>
/// <exception cref="ArgumentNullException">Either <paramref name="value"/> or <paramref name="to"/> are null.</exception>
/// <exception cref="InvalidCastException">The value cannot be converted to the specified type.</exception>
public static object Convert(object value, Type to)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (to == null)
{
throw new ArgumentNullException("to");
}
Type from = value.GetType();
if (from == to || to.IsAssignableFrom(from))
{
return value;
}
TypeConverter resultTypeConverter = TypeDescriptor.GetConverter(from);
if (resultTypeConverter != null && resultTypeConverter.CanConvertTo(to))
{
return resultTypeConverter.ConvertTo(value, to);
}
TypeConverter expectedTypeConverter = TypeDescriptor.GetConverter(to);
if (expectedTypeConverter != null && expectedTypeConverter.CanConvertFrom(from))
{
return expectedTypeConverter.ConvertFrom(value);
}
if (typeof(IConvertible).IsAssignableFrom(from))
{
return System.Convert.ChangeType(value, to, CultureInfo.InvariantCulture);
}
throw new InvalidCastException(string.Format(CultureInfo.InvariantCulture, "Cannot convert from type '{0}' to type '{1}'.", from.FullName, to.FullName));
}
}
}
|
0b1e907c3428d07786707a05060c557489c18a0d
|
C#
|
dotnet/runtime
|
/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyDirectoryServerCollection.cs
| 2.75
| 3
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
namespace System.DirectoryServices.ActiveDirectory
{
public class ReadOnlyDirectoryServerCollection : ReadOnlyCollectionBase
{
internal ReadOnlyDirectoryServerCollection() { }
internal ReadOnlyDirectoryServerCollection(ArrayList values)
{
if (values != null)
{
for (int i = 0; i < values.Count; i++)
{
Add((DirectoryServer)values[i]!);
}
}
}
public DirectoryServer this[int index] => (DirectoryServer)InnerList[index]!;
public bool Contains(DirectoryServer directoryServer)
{
if (directoryServer == null)
throw new ArgumentNullException(nameof(directoryServer));
for (int i = 0; i < InnerList.Count; i++)
{
DirectoryServer tmp = (DirectoryServer)InnerList[i]!;
if (Utils.Compare(tmp.Name, directoryServer.Name) == 0)
{
return true;
}
}
return false;
}
public int IndexOf(DirectoryServer directoryServer)
{
if (directoryServer == null)
throw new ArgumentNullException(nameof(directoryServer));
for (int i = 0; i < InnerList.Count; i++)
{
DirectoryServer tmp = (DirectoryServer)InnerList[i]!;
if (Utils.Compare(tmp.Name, directoryServer.Name) == 0)
{
return i;
}
}
return -1;
}
public void CopyTo(DirectoryServer[] directoryServers, int index)
{
InnerList.CopyTo(directoryServers, index);
}
internal int Add(DirectoryServer server) => InnerList.Add(server);
internal void AddRange(ICollection servers) => InnerList.AddRange(servers);
internal void Clear() => InnerList.Clear();
}
}
|
f78c65aa4bd223e675463a9059148d8ec9abb9f7
|
C#
|
twyblade64/Sacred-Cellar
|
/Assets/Scripts/Tools/Runtime/PersistanceManager.cs
| 2.578125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
/// <summary>
/// Singleton used to save and load data between play sessions
/// </summary>
public class PersistanceManager : MonoBehaviour {
// Default data used when no data found
public GameDataScriptableObject defaultGameData;
// Current data after beign loaded
public GameDataScriptableObject currentGameData;
// Player progress
public int playerCoins;
public float playerHealth;
public bool playerAlive = false;
public int playerScore;
public int controlScheme = 0;
public string lastLevelScene;
public int currentLevel;
// Player stats
public int playerStatHealth;
public int playerStatLuck;
public int playerStatStrength;
public int playerStatTenacity;
public int playerStatSpeed;
private static PersistanceManager instance;
/// <summary>
/// Singleton creation logic
/// </summary>
void Awake() {
if (instance == null) {
instance = this;
DontDestroyOnLoad(this.gameObject);
} else if (instance != this) {
Destroy(this.gameObject);
}
LoadGameData();
}
/// <summary>
/// Singleton access
/// </summary>
/// <returns>The singleton instance</returns>
public static PersistanceManager GetInstance() {
return instance;
}
/// <summary>
/// Obtain the max score achieved by the player
/// </summary>
/// <returns>The max score achieved by the player</returns>
public int GetMaxScore() {
return currentGameData.maxScore;
}
/// <summary>
/// Try to set-up a new max score
/// </summary>
/// <param name="newValue">A new max-score</param>
public void UpdateMaxScore(int newValue) {
if (newValue > currentGameData.maxScore) {
currentGameData.maxScore = newValue;
SaveGameData();
}
}
/// <summary>
/// Add a value to the current player score
/// </summary>
/// <param name="val">The value to add</param>
public void AddPlayerScore(int val) {
playerScore += val;
}
/// <summary>
/// Get the current player score
/// </summary>
/// <returns>The player score</returns>
public int GetPlayerScore() {
return playerScore;
}
/// <summary>
/// Update the max-score and set the player score to 0
/// </summary>
public void ResetPlayerScore() {
UpdateMaxScore(playerScore);
playerScore = 0;
}
/// <summary>
/// Save current persistance data to disk
/// </summary>
public void SaveGameData() {
Debug.Log("Saving game data...");
BinaryFormatter bf = new BinaryFormatter();
FileStream fs = File.Create(Application.persistentDataPath + "/gamedata.dat");
bf.Serialize(fs, new GameDataSerializableWrapper(currentGameData));
fs.Close();
Debug.Log("Game data saved!");
}
/// <summary>
/// Load save data from disk or create one if it doesn't exists
/// </summary>
public void LoadGameData() {
Debug.Log("Loading game data...");
if (File.Exists(Application.persistentDataPath + "/gamedata.dat")) {
BinaryFormatter bf = new BinaryFormatter();
FileStream fs = File.OpenRead(Application.persistentDataPath + "/gamedata.dat");
GameDataSerializableWrapper gdsw = (GameDataSerializableWrapper)bf.Deserialize(fs);
currentGameData = gdsw.BuildGameData();
fs.Close();
Debug.Log("Game data loaded!");
return;
}
Debug.Log("No save file found!");
CreateGameData();
SaveGameData();
}
/// <summary>
/// Create default game data
/// </summary>
/// <returns>Default game data</returns>
public GameDataScriptableObject CreateGameData() {
currentGameData = UnityEngine.Object.Instantiate<GameDataScriptableObject>(defaultGameData);
return currentGameData;
}
/// <summary>
/// Reset game data to default
/// </summary>
public void ResetGameData() {
CreateGameData();
SaveGameData();
}
/// <summary>
/// Serializable representation of the game data
/// </summary>
[System.Serializable]
internal class GameDataSerializableWrapper {
public int deathCount;
public int maxWave;
public int maxScore;
public GameDataSerializableWrapper(GameDataScriptableObject gameData) {
deathCount = gameData.deathCount;
maxWave = gameData.maxWave;
maxScore = gameData.maxScore;
}
public GameDataScriptableObject BuildGameData() {
GameDataScriptableObject gd = ScriptableObject.CreateInstance<GameDataScriptableObject>();
gd.deathCount = deathCount;
gd.maxScore = maxScore;
gd.maxWave = maxWave;
return gd;
}
}
/// <summary>
/// Set the player stats to 0
/// </summary>
public void ResetPlayerStats() {
playerStatHealth = 0;
playerCoins = 0;
playerStatLuck = 0;
playerStatStrength = 0;
playerStatTenacity = 0;
playerStatSpeed = 0;
}
}
|
193558188fcfe491638c52b8a26aeba9dc728598
|
C#
|
microsoft/Partner-Center-DotNet-Samples
|
/sdk/SdkSamples/DevicesDeployment/DeleteDevice.cs
| 2.5625
| 3
|
// -----------------------------------------------------------------------
// <copyright file="DeleteDevice.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.DevicesDeployment
{
/// <summary>
/// Deletes a device.
/// </summary>
public class DeleteDevice : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="DeleteDevice"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public DeleteDevice(IScenarioContext context) : base("Deletes a device", context)
{
}
/// <summary>
/// Executes the delete device scenario.
/// </summary>
protected override void RunScenario()
{
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the customer to delete a device");
string selectedDeviceBatchId = this.ObtainDeviceBatchId("Enter the ID of the Device batch to retrieve the devices of");
string selectedDeviceId = this.ObtainDeviceId("Enter the ID of the device to delete");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.WriteObject(selectedDeviceId, "Device to be deleted");
this.Context.ConsoleHelper.StartProgress("Deleting device");
partnerOperations.Customers.ById(selectedCustomerId).DeviceBatches.ById(selectedDeviceBatchId).Devices.ById(selectedDeviceId).Delete();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.Success("Deleted the device successfully!");
}
}
}
|
f806ce35e552916adda607b7c0e60bb3525fcc6d
|
C#
|
mikkokok/HeatedIdon
|
/Helpers/Impl/TimeConverter.cs
| 2.9375
| 3
|
using System;
using System.Globalization;
namespace HeatedIdon.Helpers.Impl
{
public static class TimeConverter
{
private static readonly CultureInfo _cultureInfo = new CultureInfo("fi-FI");
public static string GetCurrentTimeAsString()
{
return GetCurrentTime().ToShortTimeString();
}
public static DateTime GetCurrentTime()
{
return TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow,
TimeZoneInfo.FindSystemTimeZoneById("FLE Standard Time"));
}
public static string ConverToString(DateTime time)
{
return time.ToString(_cultureInfo);
}
}
}
|
f966f537e71ae66711c375bfe907097b964004af
|
C#
|
MislavLesin/internship-7-architecture
|
/DUMP7Architecture.Presentation/Actions/Reports/ReportCategories.cs
| 2.9375
| 3
|
using DUMP7Architecture.Domain.Repositories;
using DUMP7Architecture.Presentation.Abstractions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DUMP7Architecture.Presentation.Actions.Reports
{
public class ReportCategories : IAction
{
private readonly CategoryRepository _categoryRepository;
public int MenuIndex { get; set; }
public string Label { get; set; } = "Show All Categories";
public ReportCategories(CategoryRepository categoryRepository)
{
_categoryRepository = categoryRepository;
}
public void Call()
{
Console.Clear();
var categories = _categoryRepository.GetAll();
if(categories.Count() == 0)
Console.WriteLine("No categories yet!");
else
{
foreach (var category in categories)
{
Console.WriteLine(category.ToString());
Console.WriteLine("\n");
}
}
Console.ReadKey();
Console.Clear();
}
}
}
|
64aa5a3f9c12355c9c46c965612334567342271f
|
C#
|
FranckyLandry/Plagiarism
|
/ForGitHupb/LargeAttempt/TheBank/TheBank/Bank.cs
| 3.296875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TheBank
{
class Bank
{
public List<Account> accounts;
private String name;
public Bank(String Name)
{
this.name = Name;
accounts = new List<Account>();
}
public void AddAccount(Account account)
{
accounts.Add(account);
}
public Account FindAccountInfo(String Name)
{
foreach (Account acc in accounts)
{
if (acc.Name == Name)
{
return acc;
}
}
return null;
}
public bool ApplyForCreditCard(String Name)
{
foreach (Account acc in accounts)
{
if (acc.Name == Name)
{
if (acc.State.GetType().Name == "GoldState")
{
return true;
}
}
}
return false;
}
public String PayInterestAccount(String Name)
{
foreach (Account acc in accounts)
{
if (acc.Name == Name)
{
acc.State.CalculateInterest();
return "Interest has been paid" + ", new balance is : " + acc.Balance.ToString("0.00");
}
}
return "";
}
}
}
|
a6e2a7c2ca54fdd23c1ed30c5d5917450aae967f
|
C#
|
tavisca-dshrivastav/TraineeTrainerCrud-Web-Api-Project-
|
/TraineeTrainerModel/Services/CredentialService.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TraineeTrainerModel.Services;
using TraineeTrainerModel.Dal;
using TraineeTrainerModel.Models;
namespace TraineeTrainerModel.Services
{
public class CredentialService
{
private UserCredentialsDal _credentialsDal;
public CredentialService(UserCredentialsDal credentialsDal)
{
_credentialsDal = credentialsDal;
}
public UserCredential Authenticate(string username, string password)
{
var credential = _credentialsDal.Get(username);
if (credential.PasswordHash.Equals(password))
return credential;
return null;
}
public bool Exist(string username) => !_credentialsDal.Exist(username);
}
}
|
16eb71cc79a502100a223830bd74d39c442aa16c
|
C#
|
QaitQQ/PC2
|
/SiteApi/IntegrationSiteApi/ApiBase/Post/AbstractPOSTBase.cs
| 2.546875
| 3
|
using System;
using System.IO;
using System.Net;
namespace SiteApi.IntegrationSiteApi.ApiBase.Post
{
public class AbstractPOSTBase : BaseV1Api
{
public AbstractPOSTBase(string Token, string SiteUrl) : base(Token, SiteUrl)
{
Method = "POST";
}
internal void pPost(string PostUrl, string JsonPostMessage)
{
HttpWebRequest httpWebRequest = GetRequest(PostUrl);
HttpWebResponse httpResponse = null;
//попытка отправить
try
{
using (StreamWriter streamWriter = new(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(JsonPostMessage);
}
httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
}
catch (Exception e)
{
result = e.Message;
}
//попытка принять
try
{
using StreamReader streamReader = new(httpResponse.GetResponseStream());
result = streamReader.ReadToEnd();
}
catch (Exception e)
{
result = e.Message;
}
}
}
}
|
587fd9f49ae3fb634b7f7401b7bc99030d0d30f5
|
C#
|
MartinIvanov90/trainingPurposes
|
/OOP Part 2/OopPartTwo/Resources/Matrix.cs
| 3.28125
| 3
|
using System;
using System.Linq.Expressions;
namespace OopPartTwo.Resources
{
public class Matrix<T>
where T : struct, IEquatable<T>, IComparable<T>
{
private readonly int rowSpan;
private readonly int colSpan;
private T[,] matrix;
public T this[int row, int col]
{
get
{
if (row < 0 || col < 0 || row >= this.matrix.GetLength(0) || col >= this.matrix.GetLength(1))
{
throw new ArgumentOutOfRangeException("row and col must be in the range of the Matrix!");
}
return matrix[row, col];
}
set
{
if (row < 0 || col < 0 || row >= this.matrix.GetLength(0) || col >= this.matrix.GetLength(1))
{
throw new ArgumentOutOfRangeException("Matrix out of range!");
}
matrix[row, col] = value;
}
}
public int RowSpan
{
get
{
return this.rowSpan;
}
}
public int ColSpan
{
get
{
return this.colSpan;
}
}
public Matrix(int rowSpan, int colSpan)
{
this.rowSpan = rowSpan;
this.colSpan = colSpan;
this.matrix = new T[rowSpan, colSpan];
}
public static Matrix<T> matrixAGenerator()
{
Matrix<T> result = new Matrix<T>(5, 5);
int cnt = 0;
for (int i = 0; i < result.RowSpan; i++)
{
for (int j = 0; j < result.ColSpan; j++)
{
result[i, j] = (dynamic)cnt;
cnt++;
}
}
return result;
}
public static Matrix<T> matrixBGenerator()
{
Matrix<T> result = new Matrix<T>(5, 5);
int cnt = 24;
for (int i = 0; i < result.RowSpan; i++)
{
for (int j = 0; j < result.ColSpan; j++)
{
result[i, j] = (dynamic)cnt;
cnt--;
}
}
return result;
}
public static Matrix<T> operator +(Matrix<T> matrixA, Matrix<T> matrixB)
{
if (matrixA.RowSpan != matrixB.RowSpan || matrixA.ColSpan != matrixB.ColSpan)
{
throw new InvalidOperationException($"Matrices have different rows and/or cols!");
}
Matrix<T> result = new Matrix<T>(matrixA.RowSpan, matrixB.ColSpan);
try
{
for (int i = 0; i < matrixA.RowSpan; i++)
{
for (int j = 0; j < matrixA.ColSpan; j++)
{
result[i, j] = (dynamic)matrixA[i, j] + (dynamic)matrixB[i, j] + (dynamic)0.5;
}
}
}
catch (ArgumentException ex)
{
throw new ArgumentException($"dynamic misfired :)");
}
return result;
}
public static Matrix<T> operator -(Matrix<T> matrixA, Matrix<T> matrixB)
{
if (matrixA.RowSpan != matrixB.RowSpan || matrixA.ColSpan != matrixB.ColSpan)
{
throw new InvalidOperationException($"Matrices have different rows and/or cols!");
}
Matrix<T> result = new Matrix<T>(matrixA.RowSpan, matrixB.ColSpan);
try
{
for (int i = 0; i < matrixA.RowSpan; i++)
{
for (int j = 0; j < matrixA.ColSpan; j++)
{
result[i, j] = (dynamic)matrixA[i, j] - (dynamic)matrixB[i, j] + (dynamic)0.5;
}
}
}
catch (ArgumentException ex)
{
throw new ArgumentException($"dynamic misfired :)");
}
return result;
}
public static Matrix<T> operator *(Matrix<T> matrixA, Matrix<T> matrixB)
{
if (matrixA.RowSpan != matrixB.RowSpan || matrixA.ColSpan != matrixB.ColSpan)
{
throw new InvalidOperationException($"Matrices have different rows and/or cols!");
}
Matrix<T> result = new Matrix<T>(matrixA.RowSpan, matrixB.ColSpan);
try
{
for (int i = 0; i < matrixA.RowSpan; i++)
{
for (int j = 0; j < matrixA.ColSpan; j++)
{
result[i, j] = (dynamic)matrixA[i, j] * (dynamic)matrixB[i, j] + (dynamic)0.5;
}
}
}
catch (ArgumentException ex)
{
throw new ArgumentException($"dynamic misfired :)");
}
return result;
}
public static bool operator true(Matrix<T> matrixComp)
{
if (matrixComp.RowSpan == matrixComp.ColSpan)
{
return true;
}
else
{
return false;
}
}
public static bool operator false(Matrix<T> matrixComp)
{
if (matrixComp.RowSpan > matrixComp.ColSpan || matrixComp.RowSpan < matrixComp.ColSpan)
{
return true;
}
else
{
return false;
}
}
public override string ToString()
{
string entity = "";
for (int i = 0; i < this.rowSpan; i++)
{
for (int j = 0; j < this.colSpan; j++)
{
entity += Convert.ToString(matrix[i, j]) + " ";
}
entity += "\n";
}
return entity;
}
}
}
|
4219bb047d53161513dd4ffd685e97d8eb283f9d
|
C#
|
saggett/ReligionsTree
|
/TreeBrowser/TreeBrowser.SilverlightLib/Controls/Tooltip/ToolTipTimer.cs
| 2.96875
| 3
|
using System;
using System.Windows.Threading;
namespace Silverlight.Controls
{
internal sealed class ToolTipTimer : DispatcherTimer
{
/// <summary>
/// This event occurs when the timer has stopped.
/// </summary>
public event EventHandler Stopped;
public ToolTipTimer(int maximumTicks, int initialDelay)
{
InitialDelay = initialDelay;
MaximumTicks = maximumTicks < 1 ? 1 : maximumTicks;
Interval = new TimeSpan(0, 0, 1);
Tick += OnTick;
}
/// <summary>
/// Stops the ToolTipTimer.
/// </summary>
public new void Stop()
{
base.Stop();
if (Stopped != null)
Stopped(this, System.EventArgs.Empty);
}
/// <summary>
/// Resets the ToolTipTimer and starts it.
/// </summary>
public void StartAndReset()
{
CurrentTick = 0;
Start();
}
/// <summary>
/// Stops the ToolTipTimer and resets its tick count.
/// </summary>
public void StopAndReset()
{
Stop();
CurrentTick = 0;
}
/// <summary>
/// Resets the tick count of the ToolTipTimer.
/// </summary>
public void Reset()
{
if(IsEnabled)
Stop();
CurrentTick = 0;
}
/// <summary>
/// Gets the maximum number of seconds for this timer.
/// When the maximum number of ticks is hit, the timer will stop itself.
/// </summary>
/// <remarks>The minimum number of seconds is 1.</remarks>
public int MaximumTicks { get; private set; }
/// <summary>
/// Gets the initial delay for this timer in seconds.
/// When the maximum number of ticks is hit, the timer will stop itself.
/// </summary>
/// <remarks>The default delay is 0 seconds.</remarks>
public int InitialDelay { get; private set; }
/// <summary>
/// Gets the current tick of the ToolTipTimer.
/// </summary>
public int CurrentTick { get; private set; }
private void OnTick(object sender, System.EventArgs e)
{
CurrentTick++;
if(CurrentTick == MaximumTicks + InitialDelay)
Stop();
}
}
}
|
8fd3a506f88fa69ee9e71cbeb3d5ebb406d36575
|
C#
|
rfilgueras/Underwater-Creatures
|
/Player.cs
| 3.53125
| 4
|
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using static System.Console;
namespace CreaturesOfTheSea
{
class Player
{
public string Name;
public int Score;
public Player()
{
}
public Creature Choose(List<Creature> creatures)
{
//Utility.WriteText("Which creature would you like to interact with?");
//int index = 1;
//foreach (var boy in creatures)
//{
// Utility.WriteText($"{index}) {boy.Name}", ConsoleColor.Green);
// index++;
//}
//int choice = Utility.GetUserInputRange(creatures.Count);
//using LINQ to select Names from creatures list.
List<string> options = creatures.Select(creature => creature.Name).ToList();
int choice = Utility.ShowMenu("Which creature would you like to interact with?", options);
Creature selectedCreature = creatures[choice - 1];
Utility.WriteText($"You have chosen {selectedCreature.Name}. It swims up to you.");
return selectedCreature;
}
}
}
|
ba7ac046fcaa72275e53b43a1b40bbb4d99f21aa
|
C#
|
Martinkarv/SnakeGame
|
/Point/Program.cs
| 3.140625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace Point
{
class Point
{
public int x;
public int y;
public string symbol;
public Point(int _x, int _y, string _symbol)
{
x = _x;
y = _y;
symbol = _symbol;
}
public Point(Point _p)
{
x = _p.x;
y = _p.y;
symbol = _p.symbol;
}
public void Draw()
{
Console.SetCursorPosition(x, y);
Console.Write(symbol);
}
public void Clear()
{
symbol = " ";
Draw();
}
public void MovePoint(int offset, Direction direction)
{
if(direction == Direction.RIGHT)
{
x = x + offset;
}
else if(direction == Direction.LEFT)
{
x = x - offset;
}
else if(direction == Direction.UP)
{
y = y - offset;
}
else if(direction == Direction.DOWN)
{
y = y + offset;
}
}
public bool IsHit(Point point)
{
return point.x == x && point.y == y;
}
}
class Program
{
static void Main(string[] args)
{
/* Point p1 = new Point(26, 19, "*");
p1.Draw();
Point p3 = new Point(25, 19, "*");
p3.Draw();
Point p4 = new Point(24, 19, "*");
p4.Draw();
Point p5 = new Point(23, 19, "*");
p5.Draw();
Point p6 = new Point(22, 19, "*");
p6.Draw();
*/
/*
for (int i = 22; i < 5; i++)
{
Point newPoint = new Point(i, 5, "*");
newPoint.Draw();
}
Point p2 = new Point(29, 19, "<><");
p2.Draw();
*/
Start:
/* TimerCallback callback = new TimerCallback(Tick);
Console.WriteLine("Creating timer: {0}\n",
DateTime.Now.ToString("h:mm:ss"));
Timer stateTimer = new Timer(callback, null, 0, 1000);
*/
int score = 0;
int speed = 150;
Console.ForegroundColor = ConsoleColor.Cyan;
Console.SetWindowSize(100, 50);
Console.SetBufferSize(100, 50);
Walls walls = new Walls(80, 25);
walls.DrawWalls();
/* HorizontalLine topLine = new HorizontalLine(0, 78, 0, "_");
topLine.DrawFigure();
HorizontalLine hrLine = new HorizontalLine(0, 78, 24, "_");
hrLine.DrawFigure();
VerticalLine leftLine = new VerticalLine(1, 24, 0, "|");
leftLine.DrawFigure();
VerticalLine vrLine = new VerticalLine(1, 24, 78, "|");
vrLine.DrawFigure();
*/
Point tail = new Point(6, 5, "*");
Snake snake = new Snake(tail, 4, Direction.RIGHT);
snake.DrawFigure();
Toit toit = new Toit(80, 25, "$");
Point food = toit.CaterFood();
food.Draw();
while (true)
{
if (walls.IsHitByFigure(snake))
{
Console.Beep();
break;
}
if (snake.Eat(food))
{
food = toit.CaterFood();
food.Draw();
speed -= 5;
score++;
}
else
{
snake.MoveSnake();
}
Thread.Sleep(speed);
if (Console.KeyAvailable)
{
ConsoleKeyInfo key = Console.ReadKey();
snake.ReadUserKey(key.Key);
}
}
WriteGameOver();
WriteScore(score);
PlayAgain();
var info = Console.ReadKey();
if (info.Key == ConsoleKey.Enter)
{
Console.Clear();
goto Start;
}
Console.ReadLine();
}
/* private static void Tick(object state)
{
Console.WriteLine("Tick: {0}", DateTime.Now.ToString("h:mm:ss"));
}
*/
public static void Draw(int x, int y, string symbol)
{
Console.SetCursorPosition(x, y);
Console.Write(symbol);
}
public static void WriteGameOver()
{
Console.Clear();
int xOffset = 35;
int yOffset = 8;
Console.ForegroundColor = ConsoleColor.Cyan;
Console.SetCursorPosition(xOffset, yOffset++);
ShowMessage("---------", xOffset, yOffset++);
ShowMessage("GAME OVER", xOffset, yOffset++);
ShowMessage("---------", xOffset, yOffset++);
}
public static void ShowMessage(string text, int xOffset, int yOffset)
{
Console.SetCursorPosition(xOffset, yOffset);
Console.WriteLine(text);
}
public static void WriteScore(int score)
{
int xOffset = 35;
int yOffset = 12;
Console.ForegroundColor = ConsoleColor.Cyan;
Console.SetCursorPosition(xOffset, yOffset);
Console.WriteLine($"Your SCORE:{score}");
}
public static void PlayAgain()
{
int xOffset = 29;
int yOffset = 14;
Console.SetCursorPosition(xOffset, yOffset);
Console.WriteLine("To play again press ENTER");
}
}
}
|
2eac3a67516ee6ed5871c21c1755bb2e5b30af4c
|
C#
|
opendata-heilbronn/victron-data-adapter
|
/src/VictronDataAdapter/ConfigValidator.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace VictronDataAdapter
{
public static class ConfigValidator
{
public static IList<string> ValidateConfig<TConfig>(this IServiceProvider provider)
where TConfig : class, new()
{
var options = provider.GetService<IOptions<TConfig>>();
return ValidateConfig<TConfig>(options.Value);
}
private static IList<string> ValidateConfig<TConfig>(TConfig config)
{
var context = new ValidationContext(config, serviceProvider: null, items: null);
var results = new List<ValidationResult>();
Validator.TryValidateObject(config, context, results, true);
var messages = new List<string>();
foreach (var validationResult in results)
{
messages.Add(validationResult.ErrorMessage);
}
return messages;
}
}
}
|
a20f28a074c8af49fa5869a451d7cb07fd9cb8b2
|
C#
|
Obelixx/TelerikAcademy
|
/OOP/4.OOP_Principles-Part1/2.Students_and_workers/TestProgram.cs
| 3.109375
| 3
|
namespace _2.Students_and_workers
{
using System;
using System.Collections.Generic;
using Students_and_workers.Models;
using Students_and_workers.Extensions;
class TestProgram
{
static void Main()
{
var students = new List<Student>();
students.Add(new Student("Ivan", "Ivanov", 4));
students.Add(new Student("Stoyan", "Ivanov", 4));
students.Add(new Student("Pepi", "Petrov", 3));
students.Add(new Student("Petyr", "Dimitrov", 4));
students.Add(new Student("Dimityr", "Asenov", 6));
students.Add(new Student("Asen", "Stoyanov", 5));
students.Add(new Student("Drago", "Draganov", 6));
students.Add(new Student("Koko", "Lambov", 3));
students.Add(new Student("Lambi", "Stanoev", 2));
students.Add(new Student("Stanoi", "Sholov", 2));
students = students.SortedByGrade();
foreach (var stud in students)
{
Console.WriteLine(stud);
}
Console.WriteLine("---");
var workers = new List<Worker>();
workers.Add(new Worker("Ivan", "Ivanov", 400));
workers.Add(new Worker("Stoyan", "Ivanov", 400));
workers.Add(new Worker("Pepi", "Petrov", 300));
workers.Add(new Worker("Petyr", "Dimitrov", 400));
workers.Add(new Worker("Dimityr", "Asenov", 600));
workers.Add(new Worker("Asen", "Stoyanov", 500));
workers.Add(new Worker("Drago", "Draganov", 600));
workers.Add(new Worker("Koko", "Lambov", 300));
workers.Add(new Worker("Lambi", "Stanoev", 200));
workers.Add(new Worker("Stanoi", "Sholov", 200));
workers = workers.SortedByMoneyPerHour();
foreach (var worker in workers)
{
Console.WriteLine(worker);
}
Console.WriteLine("---");
var humans = new List<Human>();
humans.AddRange(students);
humans.AddRange(humans);
humans = humans.SortedByfirstNameAndLastName();
foreach (var human in humans)
{
Console.WriteLine(human);
}
Console.WriteLine("---");
}
}
}
|
9a2d5bfe693a06892b6aa6a5dfbd1457d25a3a94
|
C#
|
NewellClark/SUnit
|
/Solutions/SUnit/SUnit/Assertions/Defaults.cs
| 2.921875
| 3
|
using SUnit.Constraints;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace SUnit.Assertions
{
/// <summary>
/// The return value of <see cref="That{T}.Is"/>.
/// </summary>
/// <typeparam name="T">The type of the value that is under test.</typeparam>
public interface IIsExpression<T> : IIsExpression<T, IIsExpression<T>, ValueTest<T>> { }
/// <summary>
/// The type that lets you say <see cref="Is"/>.
/// </summary>
/// <typeparam name="T">The type of the value under test.</typeparam>
public class That<T>
{
internal That(T actual)
: this(new BasicValueExpression<T>(actual, c => c)) { }
internal That(IValueExpression<T> expression)
{
Debug.Assert(expression != null);
this.Expression = expression;
}
protected private IValueExpression<T> Expression { get; }
/// <summary>
/// Contains methods for performing assertions on the value under test.
/// </summary>
public IIsExpression<T> Is => new BasicIsExpression<T>(Expression);
}
internal class BasicValueTest<T> : ValueTest<T>
{
internal BasicValueTest(T actual, IConstraint<T> constraint)
: base(actual, constraint) { }
private protected override That<T> ApplyModifier(T actual, ConstraintModifier<T> modifier)
{
var expression = new BasicValueExpression<T>(actual, modifier);
return new That<T>(expression);
}
}
internal class BasicValueExpression<T>
: ValueExpression<T, IValueExpression<T>, ValueTest<T>>
{
internal BasicValueExpression(T actual, ConstraintModifier<T> modifier)
: base(actual, modifier) { }
protected private override ValueTest<T> ApplyConstraint(T actual, IConstraint<T> constraint)
{
return new BasicValueTest<T>(actual, constraint);
}
protected private override IValueExpression<T> ApplyModifier(T actual, ConstraintModifier<T> modifier)
{
return new BasicValueExpression<T>(actual, modifier);
}
}
internal class BasicIsExpression<T> : IIsExpression<T>
{
private readonly IValueExpression<T> expression;
internal BasicIsExpression(IValueExpression<T> expression)
{
Debug.Assert(expression != null);
this.expression = expression;
}
public IIsExpression<T> ApplyModifier(ConstraintModifier<T> modifier)
{
return new BasicIsExpression<T>(expression.ApplyModifier(modifier));
}
public ValueTest<T> ApplyConstraint(IConstraint<T> constraint)
{
return expression.ApplyConstraint(constraint);
}
}
}
|
42c551d349c0ccda6a8f8d6ef79d382206a6ac95
|
C#
|
SoftUni/Web-Services-and-Cloud
|
/6. Unit-Testing-and-Mocking/CustomGenericList/GenericList.cs
| 3.671875
| 4
|
using System;
namespace CustomGenericList
{
// TODO: Finish testing, still bugs to fix
public class GenericList<T> where T : IComparable<T>
{
private T[] arr;
private int count;
public GenericList()
{
this.arr = new T[16];
this.Count = 0;
}
public GenericList(int capacity)
{
this.arr = new T[capacity];
this.Count = 0;
}
public int Count
{
get { return this.count; }
set { this.count = value; }
}
public int Capacity
{
get { return this.arr.Length; }
}
public T this[int index]
{
get
{
CheckIndex(index);
return this.arr[index];
}
}
public void Add(T value)
{
if (Count == Capacity)
{
Array.Resize(ref arr, arr.Length * 2);
}
arr[Count] = value;
Count++;
}
public void InsertAt(T value, int index)
{
CheckIndex(index);
T[] buffer = new T[Capacity + 1];
for (int i = 0, position = 0; i < arr.Length - 1; position++)
{
if (position == index)
{
buffer[position] = value;
continue;
}
else
{
buffer[position] = arr[i];
i++;
}
}
arr = buffer;
Count++;
}
public void Remove(T value)
{
RemoveAt(Find(value));
}
public void RemoveAt(int index)
{
CheckIndex(index);
T[] buffer = new T[Capacity];
for (int i = 0, position = 0; i < arr.Length; i++, position++)
{
if (i == index)
{
position--;
continue;
}
else
{
buffer[position] = arr[i];
}
}
arr = buffer;
Count--;
}
public void Clear()
{
Array.Clear(arr, 0, arr.Length);
Count = 0;
}
public int Find(T element)
{
for (int i = 0; i < this.Count; i++)
{
if (this.arr[i].Equals(element))
{
return i;
}
}
return -1;
}
public void CheckIndex(int index)
{
if ((index < 0) || (index >= Count))
{
throw new IndexOutOfRangeException("Index must be in range [0, count]");
}
}
public T Min()
{
T min = arr[0];
for (int i = 1; i < Count; i++)
{
T listItem = arr[i];
if (listItem.CompareTo(min) < 0)
{
min = arr[i];
}
}
return min;
}
public T Max()
{
T max = arr[0];
for (int i = 1; i < Count; i++)
{
T listItem = arr[i];
if (listItem.CompareTo(max) > 0)
{
max = arr[i];
}
}
return max;
}
public override string ToString()
{
string str = "";
for (int index = 0; index < Count; index++)
{
str += string.Format("[{0}] = {1}\n", index, arr[index]);
}
return str;
}
}
}
|
cc704643131b58c5dbaeb5dc0270a2e5d154ff84
|
C#
|
mirmostafa/OldLibrary
|
/SharedProjects/CoreLib/Helpers/EnumerableHelper.Async.cs
| 2.828125
| 3
|
using System;
using System.Collections.Generic;
using Mohammad.Threading;
namespace Mohammad.Helpers
{
partial class EnumerableHelper
{
[Obsolete]
public static void ForEachAsync<TSource>(this IEnumerable<TSource> source, Action<TSource> actor)
{
ForEachAsync(source, actor, null);
}
[Obsolete]
public static void ForEachAsync<TSource>(this IEnumerable<TSource> source, Action<TSource> actor, Action ended)
{
ForEachAsync(source, actor, true, ended);
}
[Obsolete]
public static void ForEachAsync<TSource>(this IEnumerable<TSource> source, Action<TSource> actor, bool join, Action ended)
{
ForEachAsync(source, actor, 2, @join, ended);
}
[Obsolete]
public static void ForEachAsync<TSource>(this IEnumerable<TSource> source, Action<TSource> actor, int threadCount)
{
ForEachAsync(source, actor, threadCount, true, null);
}
[Obsolete]
public static void ForEachAsync<TSource>(this IEnumerable<TSource> source, Action<TSource> actor, int threadCount, bool join, Action ended)
{
Async.ForEach(source, actor, threadCount, @join, ended);
}
}
}
|
dfcca812bc174c20304afee33e4307bb16334d57
|
C#
|
alnicolaou96/NewVirtualPetShelter
|
/VirtualPetShelter/Program.cs
| 3.59375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VirtualPetShelter
{
class Program
{
static void Main(string[] args)
{
string VolunteerOrAdopt;
do
{
Console.WriteLine("Welcome to my shelter!");
Console.WriteLine("are you here to adopt or volunteer?");
VolunteerOrAdopt = Console.ReadLine().ToLower();
Console.Clear();
}
while ((VolunteerOrAdopt != "volunteer")&&(VolunteerOrAdopt!="adopt"));
//breaks the loop when the user appropriately answers the prompt
if (VolunteerOrAdopt == "adopt")
{
Console.WriteLine("Which pet would you like to adopt?");
Console.WriteLine("Animal 1");
Console.WriteLine("Animal 2");
Console.WriteLine("Animal 3");
Console.WriteLine("Animal 4");
}
else if (VolunteerOrAdopt == "volunteer")
{
Console.WriteLine("Which job would you like to take on first?");
Console.WriteLine("Clean cages");
Console.WriteLine("Feed animals");
Console.WriteLine("Walk animals");
}
}
}
}
|
840100b70a2b7b80a39ca3580a61c5e59d4c702c
|
C#
|
shendongnian/download4
|
/code2/263617-5333634-11398759-2.cs
| 2.859375
| 3
|
private static instanceLock = new object();
private static _refreshing = true;
public static PageData Instance
{
get
{
if (_refreshing)
{
lock (instanceLock)
{
if (_refreshing)
{
m_Instance = new PageData();
refreshing = false; //now allow next refreshes.
}
}
}
return m_Instance;
}
}
public void ReSync()
{
if (!_refreshing)
lock (instanceLock)
{
if (!_refreshing)
{
_refreshing = true; //don't allow refresh until singleton is called.
}
}
}
|
d6d2bde09698321199cae2f85a3f6d85645afd74
|
C#
|
THplusplus/AdventOfCode2020
|
/AoC06/Program.cs
| 3.25
| 3
|
using System.Linq;
using static System.Console;
using static System.IO.File;
string[] groups = ReadAllText("input.txt").Split("\r\n\r\n");
char[][] anyoneAnswers = groups.Select(g => g.ToCharArray().Except(new[] { '\r', '\n' }).ToArray()).Distinct().ToArray();
char[][] everyoneAnswers = groups
.Select(g =>
g.Split("\r\n")
.Select(g => g.ToCharArray().Distinct().ToArray())
.Aggregate(
(g1, g2) => g1.Intersect(g2).ToArray()
)
)
.ToArray();
/* Part 1 */
WriteLine("Part 1: " + anyoneAnswers.Sum(a => a.Count()));
/* Part 2 */
WriteLine("Part 2: " + everyoneAnswers.Sum(a => a.Count()));
|
e84e3429dce1709a68c37e89a2990c78cb9467e3
|
C#
|
YashDengre/Practice_C-Sharp
|
/CSharpe Learning and Practice/Generics.cs
| 3.453125
| 3
|
using System;
using System.Collections.Generic;
namespace SimpleGenerics
{
//we can declare delegates any where
delegate T GenericDelegateNumberChage<T>(T number);
/// <summary>
///
/// </summary>
public class Generics<TKey, TValue>
{
public TKey Key { get; set; }
public TValue Value { get; set; }
public Dictionary<TKey, TValue> Items { get; set; }
}
public class GenricsMethod
{
public void ShowMessage<T>(T Message, T Description)
{
Console.WriteLine($"Message : {Message} {Environment.NewLine} Description : {Description}");
}
}
public class Nullable<T>
{
private object _value;
public Nullable()
{
}
public Nullable(T value)
{
_value = value;
}
public bool IsNull
{
get { return _value == null; }
}
public T GetValueORDefault()
{
if (IsNull)
return default(T);
return (T)_value;
}
}
public class GenerericDelegate
{
public int NumberCH(int number)
{
number += 10;
return number;
}
public float NumberCHF(float number)
{
number += 10;
return number;
}
public void Calling()
{
GenericDelegateNumberChage<int> NumberChange = new GenericDelegateNumberChage<int>(NumberCH);
Console.WriteLine("Number is chanegd + " + NumberChange(10));
GenericDelegateNumberChage<float> NumberChangeF = new GenericDelegateNumberChage<float>(NumberCHF);
Console.WriteLine("Number is chanegd + " + NumberChangeF(120));
//anonymous methods /fucntions
//two types:
//Lambda Expressions and methods it self
//it has to use with delegates only
GenericDelegateNumberChage<int> ALambda = x => x * x;
Console.WriteLine("Anonymous Lambda Expression:" + ALambda(10));
GenericDelegateNumberChage<int> AMethod = delegate (int data) { return data * 10; };
Console.WriteLine("Anonymous Method :" + AMethod(100));
}
}
// we use where to add constraints :
/*
* Where T : IComparable
* Where T : Generics (Custom Class Name)
* Where T : struct (value type)
* where T : class (ref type)
* where T : new() (default constructor)
*/
}
|
b8019fc3895834f54dbc227680ec742b1e0e5bc6
|
C#
|
Chris1415/Hach.Library
|
/Hach.Library/Hach.Library/Services/Mail/IMailService.cs
| 2.71875
| 3
|
using Hach.Library.Repositories;
namespace Hach.Library.Services.Mail
{
/// <summary>
/// General Mail Service
/// </summary>
/// <author>
/// Christian Hahn, Okt-2016
/// </author>
public interface IMailService
{
#region Properties
/// <summary>
/// Mail Repository
/// </summary>
IMailRepository MailRepository { get; }
#endregion
#region Interface
/// <summary>
/// Sends a Mail
/// </summary>
/// <param name="subject">Subject</param>
/// <param name="body">Body</param>
/// <param name="to">To</param>
/// <param name="sendEmptyMail">Flag to determine if the mail shall be send even if its empty</param>
/// <returns>true if the mail sending was successfull, otherwise false</returns>
bool SendMail(string subject, string body, string to, bool sendEmptyMail = true);
/// <summary>
/// Sends a Mail
/// </summary>
/// <param name="subject">Subject</param>
/// <param name="to">To</param>
/// <param name="identifier">The identifier of the composed mail</param>
/// <param name="sendEmptyMail">Flag to determine if the mail shall be send even if its empty</param>
/// <returns>true if the mail sending was successfull, otherwise false</returns>
bool SendComposedMail(string subject, string to, string identifier, bool sendEmptyMail = true);
/// <summary>
/// Adds an Entry to the built mail and caches it
/// </summary>
void AddMailEntry(string entry, string identifier);
/// <summary>
/// Get the Mail Body for a speciic mail identified by the identifier
/// </summary>
/// <param name="identifier">the mail identifier</param>
/// <returns>Body of the mail</returns>
string GetMailBody(string identifier);
#endregion
}
}
|
921e555d59daa973e390931443d39fc6af876ad5
|
C#
|
tkh-tegus/Charades
|
/Charades/Utils/Utilitaire.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace Charades.Utils
{
public static class Utilitaire
{
public readonly static List<string> ALPHABET = new List<string> { "A", "Z", "E", "R", "T", "Y", "U", "I", "O", "P", "Q", "S", "D", "F", "G", "H", "J", "K", "L", "M", "W", "X", "C", "V", "B", "N" };
public static List<string> ToList_OUF(this string param)
{
List<string> retrun_var = new List<string>();
if (!string.IsNullOrWhiteSpace(param))
{
for (int i = 0; i < param.Length; i++)
{
retrun_var.Add(param[i].ToString());
}
}
return retrun_var;
}
public static List<string> ReplaceWidthWhiteSpace(this List<string> param, string e)
{
for(int i = 0; i < param.Count; i++)
{
if (param[i].Equals(e))
{
param[i] = "";
break;
}
}
return param;
}
public static List<string> GetListKeyboard(this string param, string aide)
{
Java.Util.Random rnd = new Java.Util.Random();
List<string> return_var = param.ToList_OUF();
for(int i = param.Length; i < 12; i++)
{
int element = rnd.NextInt(ALPHABET.Count);
return_var.Add(ALPHABET[element]);
}
for (int i = 0; i < aide.Length; i++)
{
return_var.ReplaceWidthWhiteSpace(aide[i].ToString());
}
return return_var;
}
}
}
|