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
|
|---|---|---|---|---|---|---|
18d80a0c53a2724e64f82e4718c0a303785e07ae
|
C#
|
joesrinadh/AssetManagement
|
/Repository/RepositoryBase.cs
| 3.140625
| 3
|
using Infrastructure.Interface.DataAccess;
using Microsoft.EntityFrameworkCore;
using Repository.Models;
namespace Repository
{
public class RepositoryBase<TEntity> : IRepositoryBase<TEntity> where TEntity : class
{
private ASMContext _context;
public RepositoryBase(ASMContext context)
{
_context = context;
}
/// <summary>
/// Add data
/// </summary>
/// <param name="entity">Entity</param>
public void Create(TEntity entity)
{
_context.Set<TEntity>().Add(entity);
}
/// <summary>
/// Update data
/// </summary>
/// <param name="entity">Entity</param>
public void Update(TEntity entity)
{
_context.Set<TEntity>().Attach(entity);
var entry = _context.Entry(entity);
entry.State = EntityState.Modified;
}
/// <summary>
///
/// Delete data
/// </summary>
/// <param name="entity">Entity</param>
public void Delete(TEntity entity)
{
_context.Set<TEntity>().Remove(entity);
}
/// <summary>
/// Get data by id
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
public TEntity Get(int Id)
{
return _context.Set<TEntity>().Find(Id);
}
/// <summary>
/// Save changes
/// </summary>
/// <returns></returns>
public int SaveChanges()
{
return _context.SaveChanges();
}
}
}
|
1251917b9a4df30f4bb75d57076a3e0f0bfd9a71
|
C#
|
berndoJ/DungeonRPG
|
/DungeonRPG/Assets/Script/Event/InventoryChangedEventArgs.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DungeonRPG.ItemContainer;
namespace DungeonRPG.Event
{
/// <summary>
/// Event argument class for the InventoryChanged event.
/// </summary>
/// <remarks>
/// Copyright (c) 2018 by Johannes Berndorfer (berndoJ)
/// </remarks>
public class InventoryChangedEventArgs : EventArgs
{
#region Properties
/// <summary>
/// The original source slot of the event.
/// </summary>
public InventorySlot OriginalSourceSlot
{
get;
private set;
}
#endregion
#region Constructor
/// <summary>
/// Creates a new instance of this class.
/// </summary>
/// <param name="originalSourceSlot">The original source slot of the event.</param>
public InventoryChangedEventArgs(InventorySlot originalSourceSlot)
{
this.OriginalSourceSlot = originalSourceSlot;
}
#endregion
}
}
|
df0c345269aeb44550f0557e57421fa604728e57
|
C#
|
natewaddoups/SSM
|
/SsmProtocol/Core/LogFilters.cs
| 2.71875
| 3
|
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Nate Waddoups
// LogFilters.cs
///////////////////////////////////////////////////////////////////////////////
using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace NateW.Ssm
{
/// <summary>
/// Indicates what condition must be met to record rows to disk.
/// </summary>
public enum LogFilterType
{
Invalid = 0,
NeverLog,
AlwaysLog,
Defogger,
OpenLoop,
ClosedLoop,
FullThrottle,
}
/// <summary>
/// For testing purposes
/// </summary>
internal class TestLogFilter : LogFilter
{
private string requiredValue;
/// <summary>
/// Factory
/// </summary>
/// <param name="factory">Creates LogWriters on-demand</param>
/// <returns>an instance of LogFilter</returns>
public static LogFilter GetInstance(
LogWriterFactory factory,
Parameter parameter,
Conversion conversion,
string requiredValue)
{
return new TestLogFilter(factory, parameter, conversion, requiredValue);
}
private TestLogFilter(
LogWriterFactory factory,
Parameter parameter,
Conversion conversion,
string requiredValue)
: base (
factory,
parameter,
conversion)
{
this.requiredValue = requiredValue;
}
protected override bool ShouldLog(LogColumn column)
{
return column.ValueAsString == requiredValue;
}
}
/// <summary>
/// Supports AlwaysLogFilter and NeverLogFilter
/// </summary>
public class TrivialLogFilter : LogFilter
{
private bool state;
internal TrivialLogFilter(
LogWriterFactory factory,
bool state)
: base (
factory,
null,
null)
{
this.state = state;
}
protected override bool ShouldLog(LogColumn column)
{
return state;
}
}
/// <summary>
/// Always writes to the log
/// </summary>
public static class AlwaysLogFilter
{
public static LogFilter GetInstance(LogWriterFactory factory)
{
return new TrivialLogFilter(factory, true);
}
}
/// <summary>
/// Never writes to the log
/// </summary>
public static class NeverLogFilter
{
public static LogFilter GetInstance(LogWriterFactory factory)
{
return new TrivialLogFilter(factory, false);
}
}
/// <summary>
/// Defogger-controlled logging
/// </summary>
public class DefoggerLogFilter : LogFilter
{
/// <summary>
/// Constructor
/// </summary>
private DefoggerLogFilter(
LogWriterFactory factory,
Parameter parameter,
Conversion conversion)
: base(
factory,
parameter,
conversion)
{
}
/// <summary>
/// Factory
/// </summary>
public static LogFilter GetInstance(
LogWriterFactory factory,
ParameterDatabase database)
{
Parameter parameter;
Conversion conversion;
if (database.TryGetParameterById("S20", out parameter) &&
parameter.TryGetConversionByUnits("boolean", out conversion))
{
return new DefoggerLogFilter(factory, parameter, conversion);
}
else
{
return new LogFilter(factory, null, null);
}
}
/// <summary>
/// Log when defogger is on
/// </summary>
protected override bool ShouldLog(LogColumn column)
{
return string.Compare(column.ValueAsString, Conversion.BooleanTrue, StringComparison.OrdinalIgnoreCase) == 0;
}
}
/// <summary>
/// Open loop logging
/// </summary>
public class OpenLoopLogFilter : LogFilter
{
/// <summary>
/// Constructor
/// </summary>
private OpenLoopLogFilter(
LogWriterFactory factory,
Parameter parameter,
Conversion conversion)
: base(
factory,
parameter,
conversion)
{
}
/// <summary>
/// Factory
/// </summary>
public static LogFilter GetInstance(
LogWriterFactory factory,
ParameterDatabase database)
{
Parameter parameter;
Conversion conversion;
if ((database.TryGetParameterById("E3", out parameter) ||
database.TryGetParameterById("E33", out parameter)) &&
parameter.TryGetConversionByUnits("status", out conversion))
{
return new OpenLoopLogFilter(factory, parameter, conversion);
}
else
{
return new LogFilter(factory, null, null);
}
}
/// <summary>
/// Log when in open loop
/// </summary>
protected override bool ShouldLog(LogColumn column)
{
return string.Compare(column.ValueAsString, "10", StringComparison.OrdinalIgnoreCase) == 0;
}
}
/// <summary>
/// Closed loop logging
/// </summary>
public class ClosedLoopLogFilter : LogFilter
{
/// <summary>
/// Constructor
/// </summary>
private ClosedLoopLogFilter(
LogWriterFactory factory,
Parameter parameter,
Conversion conversion)
: base(
factory,
parameter,
conversion)
{
}
/// <summary>
/// Factory
/// </summary>
public static LogFilter GetInstance(
LogWriterFactory factory,
ParameterDatabase database)
{
Parameter parameter;
Conversion conversion;
if ((database.TryGetParameterById("E3", out parameter) ||
database.TryGetParameterById("E33", out parameter)) &&
parameter.TryGetConversionByUnits("status", out conversion))
{
return new ClosedLoopLogFilter(factory, parameter, conversion);
}
else
{
return new LogFilter(factory, null, null);
}
}
/// <summary>
/// Log when in closed loop
/// </summary>
protected override bool ShouldLog(LogColumn column)
{
return string.Compare(column.ValueAsString, "8", StringComparison.OrdinalIgnoreCase) == 0;
}
}
/// <summary>
/// Full throttle logging
/// </summary>
public class FullThrottleLogFilter : LogFilter
{
/// <summary>
/// Constructor
/// </summary>
private FullThrottleLogFilter(
LogWriterFactory factory,
Parameter parameter,
Conversion conversion)
: base(
factory,
parameter,
conversion)
{
}
/// <summary>
/// Factory
/// </summary>
public static LogFilter GetInstance(
LogWriterFactory factory,
ParameterDatabase database)
{
Parameter parameter;
Conversion conversion;
if (database.TryGetParameterById("P13", out parameter) &&
parameter.TryGetConversionByUnits("%", out conversion))
{
return new FullThrottleLogFilter(factory, parameter, conversion);
}
else
{
return new LogFilter(factory, null, null);
}
}
/// <summary>
/// Log when throttle is maxed out
/// </summary>
protected override bool ShouldLog(LogColumn column)
{
return (column.ValueAsDouble > 98.0d);
}
}
/// <summary>
/// Log when knock sum changes
/// </summary>
public class KnockLogFilter : LogFilter
{
/// <summary>
/// Indicates whether lastValue has been initalized from log data.
/// This is used to avoid logging a snippet every time the log profile changes.
/// </summary>
private bool initialized = false;
/// <summary>
/// Last-seen value of the Knock Sum parameter.
/// </summary>
private double lastValue;
/// <summary>
/// Constructor
/// </summary>
private KnockLogFilter(
LogWriterFactory factory,
Parameter parameter,
Conversion conversion)
: base(
factory,
parameter,
conversion)
{
}
/// <summary>
/// Factory
/// </summary>
public static LogFilter GetInstance(
LogWriterFactory factory,
ParameterDatabase database)
{
Parameter parameter;
Conversion conversion;
if (database.TryGetParameterById("E114", out parameter) &&
parameter.TryGetConversionByUnits("%", out conversion))
{
return new KnockLogFilter(factory, parameter, conversion);
}
else
{
return new LogFilter(factory, null, null);
}
}
/// <summary>
/// Log when knock sum value changes.
/// </summary>
protected override bool ShouldLog(LogColumn column)
{
if (!initialized)
{
this.lastValue = column.ValueAsDouble;
return false;
}
if (column.ValueAsDouble != this.lastValue)
{
this.lastValue = column.ValueAsDouble;
return true;
}
return false;
}
}
}
|
e2a2872c9f43ba96d9e805716ae19de569edd8a2
|
C#
|
PacktPublishing/Unity-5.x-Animation-Cookbook
|
/Assets/Chapter 07/Recipe 04/Scripts/Tired.cs
| 2.71875
| 3
|
using UnityEngine;
using System.Collections;
public class Tired : MonoBehaviour {
public float tiredLerpSpeed = 1f;
Animator anim;
float weightTarget = 0f;
float weight = 0f;
// Use this for initialization
void Start () {
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Space))
{
//When player presses space, we set a new value for the weightTarget variable.
//This value can be set to 0 or 1 depending on the current value.
//It is used to turn the additive layer on and off
if (weightTarget < 0.5f)
{
weightTarget = 1f;
}
else if (weightTarget > 0.5f)
{
weightTarget = 0f;
}
}
//Here we lerp the weight of the Additive layer (this layer's index is 1 in our controller)
weight = Mathf.Lerp(weight, weightTarget, Time.deltaTime * tiredLerpSpeed);
//We set the current weight value for the Additive layer. This turns the layer on and off smoothly.
anim.SetLayerWeight(1, weight);
}
}
|
b36792a36a726b4b3fec07f59660895a50294626
|
C#
|
Sprunth/Cubo-Cubo
|
/Cubo Cubo/GameScreen.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SFML.Graphics;
using SFML.Window;
namespace Cubo_Cubo
{
class GameScreen : Drawable
{
private readonly RenderTexture _targetTex;
private readonly Sprite _target;
private GameGrid _grid;
public GameScreen(Vector2u size, Vector2f pos)
{
_targetTex = new RenderTexture(size.X, size.Y) { Smooth = true };
_target = new Sprite() { Position = pos };
_grid = new GameGrid(new Vector2u((uint)Math.Floor(size.X/32f), (uint)Math.Floor(size.Y/32f)));
}
public void Draw(RenderTarget target, RenderStates states)
{
_targetTex.Clear(new Color(20, 20, 20));
_targetTex.Draw(_grid);
_targetTex.Display();
_target.Texture = _targetTex.Texture;
target.Draw(_target);
}
}
}
|
8a9a580ce519ef14d19b25a4cb54556af7eec563
|
C#
|
azirkande/MicroBatchingLibraryDemo
|
/BatchingLib.Tests/BatchGeneratorTest.cs
| 2.5625
| 3
|
using BatchGenerator;
using BatchingLibrary.Core.Database;
using BatchingLibrary.Core.Database.Entities;
using System;
using System.Linq;
using Xunit;
namespace BatchingLib.Tests
{
public class BatchGeneratorTest
{
private IDbContext _dbContext;
private readonly IBatchService _batcService;
public BatchGeneratorTest()
{
_dbContext = new DatabaseContext();
_batcService = new BatchService(_dbContext);
}
[Fact]
public void Should_generate_batch_when_enough_jobs_are_available()
{
_dbContext.BatchConfiguration.BatchSize = 2;
Guid job1 = Guid.NewGuid();
_dbContext.Jobs.Add(new Job
{
CreatedOn = DateTime.Now,
Data = "First",
Id = job1,
Status = ProcessStatus.Created
});
Guid job2 = Guid.NewGuid();
_dbContext.Jobs.Add(new Job
{
CreatedOn = DateTime.Now,
Data = "Second",
Id = job2,
Status = ProcessStatus.Created
});
var generator = new BatchingLibrary.BatchGenerator.BatchGenerator(_batcService, _dbContext);
generator.GenerateBatch();
var batchCreated = _dbContext.Batches.First();
Assert.Equal(ProcessStatus.Created, batchCreated.Status);
Assert.Equal(2, batchCreated.Jobs.Count());
Assert.NotNull(batchCreated.Jobs.First(j => j.Id == job1));
Assert.NotNull(batchCreated.Jobs.First(j => j.Id == job2));
}
[Fact]
public void Should_generate_batch_with_only_new_jobs()
{
Guid job3 = Guid.NewGuid();
_dbContext.Jobs.Add(new Job
{
CreatedOn = DateTime.Now,
Data = "First",
Id = job3,
Status = ProcessStatus.Completed
});
Guid job1 = Guid.NewGuid();
_dbContext.Jobs.Add(new Job
{
CreatedOn = DateTime.Now,
Data = "First",
Id = job1,
Status = ProcessStatus.Created
});
Guid job2 = Guid.NewGuid();
_dbContext.Jobs.Add(new Job
{
CreatedOn = DateTime.Now,
Data = "Second",
Id = job2,
Status = ProcessStatus.Created
});
var generator = new BatchingLibrary.BatchGenerator.BatchGenerator(_batcService, _dbContext);
generator.GenerateBatch();
var batchCreated = _dbContext.Batches.First();
Assert.Equal(ProcessStatus.Created, batchCreated.Status);
Assert.Equal(2, batchCreated.Jobs.Count());
Assert.NotNull(batchCreated.Jobs.First(j => j.Id == job1));
Assert.NotNull(batchCreated.Jobs.First(j => j.Id == job2));
}
[Fact]
public void Should_not_generate_batch_when_enough_jobs_are_not_available()
{
_dbContext.BatchConfiguration.BatchSize = 3;
_dbContext = new DatabaseContext();
_dbContext.Jobs.Add(new Job
{
CreatedOn = DateTime.Now,
Data = "First",
Id = Guid.NewGuid(),
Status = ProcessStatus.Created
});
var generator = new BatchingLibrary.BatchGenerator.BatchGenerator(_batcService, _dbContext);
generator.GenerateBatch();
Assert.Empty(_dbContext.Batches);
}
}
}
|
825a14931e5f8656090e7dd6dfc3606253e469e5
|
C#
|
Manicreator/VolumeOptions
|
/Assets/Scripts/SoundUtil.cs
| 2.75
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniRx;
/// <summary>
/// サウンドユーティリティ
/// </summary>
public static class SoundUtil
{
/// <summary>
/// ボリュームをデシベルに変換して取得
/// </summary>
/// <param name="vol">ボリューム (0.0-1.0)</param>
/// <returns>ボリューム [dB]</returns>
public static float CalcGetVolumeToDb(float vol)
{
if (vol <= 0.0f)
{
return float.MinValue;
}
else
{
return 20.0f * Mathf.Log10(Mathf.Min(vol, 1.0f));
}
}
/// <summary>
/// デシベルをボリュームに変換して取得
/// </summary>
/// <param name="dbVol">ボリューム [dB]</param>
/// <returns>ボリューム (0.0-1.0)</returns>
public static float CalcGetDbToVolume(float dbVol)
{
return Mathf.Pow(10.0f, Mathf.Min(dbVol, 0.0f) / 20.0f);
}
/// <summary>
/// ラウドネスを考慮したボリュームを計算して取得
/// </summary>
/// <remarks>
/// volLvRatioが半分のときに10dB差がつくボリュームを返す
///
/// volLvRatio volume db
/// 0.00f 0.000f -inf[dB]
/// 0.05f 0.007f -43.219[dB]
/// 0.10f 0.022f -33.219[dB]
/// 0.15f 0.043f -27.370[dB]
/// 0.20f 0.069f -23.219[dB]
/// 0.25f 0.100f -20.000[dB]
/// 0.30f 0.135f -17.370[dB]
/// 0.35f 0.175f -15.146[dB]
/// 0.40f 0.218f -13.219[dB]
/// 0.45f 0.265f -11.520[dB]
/// 0.50f 0.316f -10.000[dB]
/// 0.55f 0.370f -8.625[dB]
/// 0.60f 0.428f -7.370[dB]
/// 0.65f 0.489f -6.215[dB]
/// 0.70f 0.553f -5.146[dB]
/// 0.75f 0.620f -4.150[dB]
/// 0.80f 0.690f -3.219[dB]
/// 0.85f 0.763f -2.345[dB]
/// 0.90f 0.839f -1.520[dB]
/// 0.95f 0.918f -0.740[dB]
/// 1.00f 1.000f 0.000[dB]
/// </remarks>
/// <param name="volLvRatio">ボリュームレベル比率 (0.0-1.0)</param>
/// <returns>ラウドネスを考慮したボリューム (0.0-1.0)</returns>
public static float CalcGetVolume(float volLvRatio)
{
if (volLvRatio <= 0.0f)
{
return 0.0f;
}
else if (volLvRatio >= 1.0f)
{
return 1.0f;
}
else
{
return Mathf.Pow(10.0f, -Mathf.Log(1.0f / volLvRatio, 2.0f) / 2.0f);
}
}
/// <summary>
/// ラウドネスを考慮したボリュームを計算して取得 (AudioMixer用)
/// </summary>
/// <remarks>
/// volLvRatioが半分のときに10dB差がつくボリュームを返す
///
/// volLvRatio db
/// 0.00f -inf[dB]
/// 0.05f -43.219[dB]
/// 0.10f -33.219[dB]
/// 0.15f -27.370[dB]
/// 0.20f -23.219[dB]
/// 0.25f -20.000[dB]
/// 0.30f -17.370[dB]
/// 0.35f -15.146[dB]
/// 0.40f -13.219[dB]
/// 0.45f -11.520[dB]
/// 0.50f -10.000[dB]
/// 0.55f -8.625[dB]
/// 0.60f -7.370[dB]
/// 0.65f -6.215[dB]
/// 0.70f -5.146[dB]
/// 0.75f -4.150[dB]
/// 0.80f -3.219[dB]
/// 0.85f -2.345[dB]
/// 0.90f -1.520[dB]
/// 0.95f -0.740[dB]
/// 1.00f 0.000[dB]
/// </remarks>
/// <param name="volLvRatio">ボリュームレベル比率 (0.0-1.0)</param>
/// <returns>ラウドネスを考慮したボリューム [dB] (-80.0-0.0)</returns>
public static float CalcGetVolumeForAudioMixer(float volLvRatio)
{
if (volLvRatio <= 0.0f)
{
return -80.0f;
}
else if (volLvRatio >= 1.0f)
{
return 0.0f;
}
else
{
return -10.0f * Mathf.Log(1.0f / volLvRatio, 2.0f);
}
}
}
|
2c55b854369da0060eaaa7220271b39ae931f707
|
C#
|
NobuyukiInoue/LeetCode
|
/Problems/0100_0199/0101_Symmetric_Tree/Project_CS/Symmetric_Tree.cs
| 3.34375
| 3
|
using System;
public class Solution
{
public bool isSymmetric(TreeNode root)
{
if (root == null)
return true;
return checkSymmetric(root.left, root.right);
}
public bool checkSymmetric(TreeNode temp1, TreeNode temp2)
{
if (temp1 == null && temp2 == null)
return true;
if (temp1 == null || temp2 == null)
return false;
if (temp1.val != temp2.val)
return false;
return ( checkSymmetric(temp1.left, temp2.right) && checkSymmetric(temp1.right, temp2.left) );
}
public void Main(string args)
{
Console.WriteLine("args = " + args );
string flds = args.Replace("\"", "").Replace("[", "").Replace("]", "").Trim();
OperateTreeNode ope_t = new OperateTreeNode();
TreeNode root = ope_t.CreateTreeNode(flds);
Console.Write("root = \n" + ope_t.TreeToStaircaseString(root));
Console.WriteLine("root = " + ope_t.Tree2str(root));
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
bool result = isSymmetric(root);
sw.Stop();
Console.WriteLine("result = " + result.ToString());
Console.WriteLine("Execute time ... " + sw.ElapsedMilliseconds.ToString() + "ms\n");
}
}
|
e468e7d99b1e0d0cfecd5a80e08f28b2ea9fce12
|
C#
|
interesaaat/TorchSharp
|
/src/TorchSharp/NN/Init.cs
| 2.625
| 3
|
using System;
using System.Runtime.InteropServices;
using TorchSharp.Tensor;
namespace TorchSharp.NN
{
public static class Init
{
[DllImport("LibTorchSharp")]
private static extern void THSNN_initUniform(IntPtr src, double low, double high);
public static void Uniform(TorchTensor tensor, double low = 0, double high = 1)
{
THSNN_initUniform(tensor.Handle, low, high);
}
[DllImport("LibTorchSharp")]
private static extern void THSNN_initKaimingUniform(IntPtr src, double a);
public static void KaimingUniform(TorchTensor tensor, double a = 0)
{
THSNN_initKaimingUniform(tensor.Handle, a);
}
public static (long fanIn, long fanOut) CalculateFanInAndFanOut<T>(TorchTensor tensor)
{
var dimensions = tensor.Dimensions;
if (dimensions < 2)
{
throw new ArgumentException("Fan in and fan out can not be computed for tensor with fewer than 2 dimensions");
}
var shape = tensor.Shape;
// Linear
if (dimensions == 2)
{
return (shape[1], shape[0]);
}
else
{
var numInputFMaps = tensor.Shape[1];
var numOutputFMaps = tensor.Shape[0];
var receptiveFieldSize = tensor[0, 0].NumberOfElements;
return (numInputFMaps * receptiveFieldSize, numOutputFMaps * receptiveFieldSize);
}
}
}
}
|
0a041de69aad0c2a2e3ff5498b143d90996c6ee3
|
C#
|
MarkKhromov/SharpDX-Examples
|
/Examples/AlphaMapping/TextureArray.cs
| 2.6875
| 3
|
using System.Linq;
using SharpDX.Direct3D11;
using SharpDXExamples.Examples.Core.Helpers;
namespace SharpDXExamples.Examples.AlphaMapping {
public class TextureArray {
public ShaderResourceView[] ObjectTextures { get; private set; }
public bool Initialize(Device device, string[] fileNames) {
try {
ObjectTextures = fileNames
.Select(x => new ShaderResourceView(device, TextureLoader.LoadTexture2D(device, x)))
.ToArray()
;
} catch { return false; }
return true;
}
public void Shutdown() {
foreach(var texture in ObjectTextures) {
texture.Dispose();
}
}
}
}
|
7cd46e7f952b38c3cd8521d33208b916f3444008
|
C#
|
BlauFx/RhythmBox
|
/RhythmBox/Score/Score.cs
| 2.71875
| 3
|
using RhythmBox.Window.Animation;
namespace RhythmBox.Window.Score
{
public static class Score
{
public static int ScoreInt { get; private set; }
public static void ResetScore() => ScoreInt = 0;
public static void CalculateScore(int combo, Hit currentHit)
{
int addAmount = currentHit switch
{
Hit.Hit300 => 300,
Hit.Hit100 => 100,
Hit.Hitx => 0,
_ => 0,
};
var calcScore = (combo * addAmount);
ScoreInt += calcScore;
}
}
}
|
bf9a32dd0463b4768a9159dfb6bd69b140d29692
|
C#
|
Planke85/CSharp
|
/Class01/BonusHomework/Program.cs
| 3.03125
| 3
|
using System;
namespace BonusHomework
{
class Program
{
static void Main(string[] args)
{
Console.BackgroundColor = ConsoleColor.DarkMagenta;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(" * ");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(" *** ");
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine(" ***** ");
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(" ******* ");
Console.Beep(500, 500);
Console.WriteLine("---------------------");
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(" * ");
Console.WriteLine(" * ");
Console.WriteLine(" *** ");
Console.WriteLine(" * * * ");
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine(" * ");
Console.WriteLine(" * ");
Console.WriteLine(" * * ");
Console.WriteLine(" * * ");
Console.ResetColor();
}
}
}
|
deae46ee08d6de03645aa12e24775ff796b80b20
|
C#
|
DomhnallBoyle/agile_project
|
/CSC3045-CS2-Frontend/CSC3045-CS2/Models/Task.cs
| 2.546875
| 3
|
using RestSharp.Deserializers;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace CSC3045_CS2.Models
{
public class Task : INotifyPropertyChanged
{
[DeserializeAs(Name = "id")]
public long Id { get; set; }
[DeserializeAs(Name = "name")]
public string Name { get; set; }
[DeserializeAs(Name = "description")]
public string Description { get; set; }
[DeserializeAs(Name = "initialEstimate")]
public int InitialEstimate { get; set; }
[DeserializeAs(Name = "userStory")]
public UserStory UserStory { get; set; }
private User _assignee;
[DeserializeAs(Name = "assignee")]
public User Assignee
{
get { return _assignee; }
set
{
_assignee = value;
OnPropertyChanged();
}
}
public Task() { }
public Task(string name, string description, int initialEstimate, UserStory userStory, User assignee)
{
this.Name = name;
this.Description = description;
this.InitialEstimate = initialEstimate;
this.UserStory = userStory;
this.Assignee = assignee;
}
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
|
0c832ff1cfefedf61ad98ef97e89503c359cad15
|
C#
|
easywaldo/SampleTDD
|
/test-lib/Test1.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoFixture.NUnit3;
using NUnit.Framework;
namespace SampleTest
{
public class User
{
public User(int id)
{
if (id < 1)
throw new ArgumentOutOfRangeException();
}
}
public class MappedUser
{
protected MappedUser(int id, string name)
{
}
public static MappedUser Create()
{
return null;
}
}
[TestFixture]
public class Tests
{
[Test, AutoData]
public void UserTest(User user)
{
Assert.That(user, Is.Not.Null);
}
[Test, AutoData]
public void MappedUserTest(MappedUser user)
{
Assert.That(user, Is.Not.Null);
}
}
}
|
a1773fb598fa40cfc3d6ef0e7d394ef33471aadd
|
C#
|
rynnwang/CommonSolution
|
/Development/Beyova.Common/Model/ApiTracking/Entity/DebugInfo.cs
| 2.875
| 3
|
using System.Net;
using System.Text;
namespace Beyova.Diagnostic
{
/// <summary>
///
/// </summary>
public class DebugInfo
{
/// <summary>
/// The builder
/// </summary>
protected StringBuilder builder = new StringBuilder();
/// <summary>
/// Gets or sets the messages.
/// </summary>
/// <value>
/// The messages.
/// </value>
public string Messages
{
get { return builder.ToString(); }
set { builder = new StringBuilder(value.SafeToString()); }
}
/// <summary>
/// Gets or sets the HTTP request raw.
/// </summary>
/// <value>
/// The HTTP request raw.
/// </value>
public string HttpRequestRaw { get; set; }
/// <summary>
/// Gets or sets the HTTP response raw.
/// </summary>
/// <value>
/// The HTTP response raw.
/// </value>
public string HttpResponseRaw { get; set; }
/// <summary>
/// Writes the line.
/// </summary>
/// <param name="format">The format.</param>
/// <param name="args">The arguments.</param>
public void WriteLine(string format, params object[] args)
{
format = format == null ? string.Empty : format;
if (args.HasItem())
{
builder.AppendLineWithFormat(format, args);
}
else
{
builder.AppendLine(format);
}
}
/// <summary>
/// Writes the HTTP response raw.
/// </summary>
/// <param name="headers">The headers.</param>
/// <param name="body">The body.</param>
public void WriteHttpResponseRaw(WebHeaderCollection headers, string body)
{
StringBuilder builder = new StringBuilder(512);
builder.FillHeaders(headers);
builder.AppendLine();
builder.AppendLine(body);
this.HttpResponseRaw = builder.ToString();
}
}
}
|
5c4983f84baf2ea24e20d06cf5d6b76af33776a8
|
C#
|
Roadrunner67/nf-debugger
|
/source/nanoFramework.Tools.DebugLibrary.Shared/Extensions/DebuggerExtensions.cs
| 2.71875
| 3
|
//
// Copyright (c) 2017 The nanoFramework project contributors
// See LICENSE file in the project root for full license information.
//
using System.Threading.Tasks;
namespace nanoFramework.Tools.Debugger.Extensions
{
public static class DebuggerExtensions
{
/// <summary>
/// Check if device state is <see cref=""/>.
/// </summary>
/// <param name="debugEngine"></param>
/// <returns></returns>
public static bool IsDeviceInInitializeState(this Engine debugEngine)
{
var result = debugEngine.GetExecutionMode();
if (result != WireProtocol.Commands.DebuggingExecutionChangeConditions.State.Unknown)
{
// engine is in initialised state if it's not running a program or if the program execution is stopped (after having running one)
return ((result & (WireProtocol.Commands.DebuggingExecutionChangeConditions.State.ProgramExited | WireProtocol.Commands.DebuggingExecutionChangeConditions.State.ProgramRunning)) == WireProtocol.Commands.DebuggingExecutionChangeConditions.State.Initialize);
}
else
{
return false;
}
}
/// <summary>
/// Check if device execution state is: program exited.
/// </summary>
/// <param name="debugEngine"></param>
/// <returns></returns>
public static bool IsDeviceInExitedState(this Engine debugEngine)
{
var result = debugEngine.GetExecutionMode();
if (result != WireProtocol.Commands.DebuggingExecutionChangeConditions.State.Unknown)
{
return ((result & WireProtocol.Commands.DebuggingExecutionChangeConditions.State.ProgramExited) == WireProtocol.Commands.DebuggingExecutionChangeConditions.State.ProgramExited);
}
else
{
return false;
}
}
/// <summary>
/// Check if device execution state is: program running.
/// </summary>
/// <param name="debugEngine"></param>
/// <returns></returns>
public static bool IsDeviceInProgramRunningState(this Engine debugEngine)
{
var result = debugEngine.GetExecutionMode();
if (result != WireProtocol.Commands.DebuggingExecutionChangeConditions.State.Unknown)
{
return ((result & WireProtocol.Commands.DebuggingExecutionChangeConditions.State.ProgramRunning) == WireProtocol.Commands.DebuggingExecutionChangeConditions.State.ProgramRunning);
}
else
{
return false;
}
}
}
}
|
0fac1e48ce02df12355c8af7567af293b210055a
|
C#
|
dnsdurham/ArchitectureExamples
|
/Switchboard/ABC.DataContracts/Customer.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ABC.DataContracts
{
public class Customer
{
public string First { get; set; }
public string Last { get; set; }
public override string ToString()
{
return First + " " + Last;
}
}
}
|
48ffe8645a1ae2dd8b309f4332f56726ff2b4632
|
C#
|
AlexanderWatsonAR/etherscape--Published-
|
/Assets/Scripts/PlaySound.cs
| 2.640625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// Used for animation events.
public class PlaySound : MonoBehaviour
{
public AudioClip nextClip;
public AudioClip[] extras;
public GameObject otherAudioSource;
AudioSource audio;
public void Start()
{
audio = GetComponent<AudioSource>();
if(otherAudioSource != null)
audio = otherAudioSource.GetComponent<AudioSource>();
}
public void Play()
{
if(audio != null)
audio.Play();
}
public void PlayNextClip()
{
if (audio != null && nextClip != null)
{
audio.clip = nextClip;
Play();
}
}
public void PlayExtra(int index)
{
if (audio != null)
{
audio.clip = extras[index];
Play();
}
}
public void Volume(float volume)
{
if (audio != null)
audio.volume = volume;
}
public void Pitch(float pitch)
{
if (audio != null)
audio.pitch = pitch;
}
public void Loop(int loop)
{
if (audio == null)
return;
switch (loop)
{
case 0:
audio.loop = false;
break;
case 1:
audio.loop = true;
break;
}
}
public void Stop()
{
if (audio != null)
audio.Stop();
}
}
|
890f2b4957b0d2b41b1dc7f88e865e411f1bc1e2
|
C#
|
DanielWeidinger/Schaetzerei
|
/Schaetzerei.Persistence/UnitOfWork.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Schaetzerei.Core.Contracts;
using Schaetzerei.Core.Contracts.Repositories;
using Schaetzerei.Persistence.Repository;
namespace Schaetzerei.Persistence
{
public class UnitOfWork : IUnitOfWork
{
private readonly ApplicationDbContext _dbContext;
private bool _disposed;
/// <summary>
/// ConnectionString kommt aus den appsettings.json
/// </summary>
public UnitOfWork() : this(new ApplicationDbContext())
{
}
/// <summary>
/// ConnectionString kommt aus den appsettings.json
/// </summary>
public UnitOfWork(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
UserRepository = new UserRepository(_dbContext);
GameRepository = new GameRepository(_dbContext);
RoundRepository = new RoundRepository(_dbContext);
QuestionRepository = new QuestionRepository(_dbContext);
AnswerRepository = new AnswerRepository(_dbContext);
}
public IUserRepository UserRepository { get; }
public IGameRepository GameRepository { get; }
public IRoundRepository RoundRepository { get; }
public IQuestionRepository QuestionRepository { get; }
public IAnswerRepository AnswerRepository { get; }
public async Task DeleteDatabaseAsync()
{
await _dbContext.Database.EnsureDeletedAsync();
}
public async Task MigrateDatabaseAsync()
{
await _dbContext.Database.MigrateAsync();
}
public async Task<int> SaveChangesAsync()
{
var entities = _dbContext.ChangeTracker.Entries()
.Where(entity => entity.State == EntityState.Added
|| entity.State == EntityState.Modified)
.Select(e => e.Entity)
.ToArray(); // Geänderte Entities ermitteln
foreach (var entity in entities)
{
var validationContext = new ValidationContext(entity, null, null);
if (entity is IDatabaseValidatableObject)
{ // UnitOfWork injizieren, wenn Interface implementiert ist
validationContext.InitializeServiceProvider(serviceType => this);
}
var validationResults = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(entity, validationContext, validationResults, validateAllProperties: true);
if (!isValid)
{
var memberNames = new List<string>();
List<ValidationException> validationExceptions = new List<ValidationException>();
foreach (ValidationResult validationResult in validationResults)
{
validationExceptions.Add(new ValidationException(validationResult, null,
validationResult.MemberNames));
memberNames.AddRange(validationResult.MemberNames);
}
if (validationExceptions.Count == 1) // eine Validationexception werfen
{
throw validationExceptions.Single();
}
else // AggregateException mit allen ValidationExceptions als InnerExceptions werfen
{
throw new ValidationException($"Entity validation failed for {string.Join(", ", memberNames)}",
new AggregateException(validationExceptions));
}
}
}
return await _dbContext.SaveChangesAsync();
}
public async ValueTask DisposeAsync()
{
await DisposeAsync(true);
GC.SuppressFinalize(this);
}
protected virtual async ValueTask DisposeAsync(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
await _dbContext.DisposeAsync();
}
}
_disposed = true;
}
public void Dispose()
{
_dbContext?.Dispose();
}
public void ClearChangeTracker()
{
_dbContext.ChangeTracker.Clear();
}
public void Reload(IEntityObject entity)
{
_dbContext.Entry(entity).Reload();
}
public bool ContextHasChanges => _dbContext.ChangeTracker.HasChanges();
}
}
|
97a9c07d6c1b7dfa0aa093e12bf5d9e6f80c7082
|
C#
|
Fao2212/Caso2
|
/Model/BallBuilder.cs
| 2.859375
| 3
|
using Caso2.model;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Caso2.Model
{
class BallBuilder : IStrategy/*, IBuilder<List<Ball>>*/
{
List<Ball> listBalls;
public List<Ball> generate(int numberOfBalls)
{
return build(numberOfBalls);
}
public List<Ball> build(int numberOfBalls)
{
for (int i = 0; i < numberOfBalls; i++)
{
listBalls.Add(new Ball(90, Brushes.Gray));
}
List<Ball> newList = listBalls;
this.reset();
return newList;
}
public void reset()
{
this.listBalls = new List<Ball>();
}
}
}
|
9d32531e1a512014115db3a2d7ca2abe196c0849
|
C#
|
JoshuaTerry/NextGen
|
/DDI/DDI.Shared.Test/Extensions/MemberInfoExtensionsTests.cs
| 2.65625
| 3
|
using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using DDI.Shared.Enums;
using DDI.Shared.Helpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using DDI.Shared.Extensions;
namespace DDI.Shared.Test.Extensions
{
[TestClass]
public class MemberInfoExtensionsTests
{
private const string TESTDESCR = "Shared | Extensions";
[TestMethod, TestCategory(TESTDESCR)]
public void MemberInfoExtensions_GetAttribute()
{
MemberInfo titleProperty = typeof(MyClass).GetProperty("Title");
var defaultValueAttribute = titleProperty.GetAttribute<DefaultValueAttribute>();
Assert.IsNotNull(defaultValueAttribute, "GetAttribute found DefaultValue attribute.");
Assert.AreEqual("test", defaultValueAttribute.Value, "GetAttribute returned correct attribute.");
Assert.IsNull(titleProperty.GetAttribute<BrowsableAttribute>(), "Title does not have browsable attribute.");
}
[TestMethod, TestCategory(TESTDESCR)]
public void MemberInfoExtensions_GetAttributes()
{
MemberInfo subTitle = typeof(MyClass).GetProperty("Subtitle");
var attributes = subTitle.GetAttributes<PaintColorAttribute>().ToList();
Assert.IsNotNull(attributes, "GetAttributes returned a value.");
Assert.AreEqual(2, attributes.Count, "Subtitle has 2 attribute instances.");
CollectionAssert.AllItemsAreInstancesOfType(attributes, typeof(PaintColorAttribute));
}
[TestMethod, TestCategory(TESTDESCR)]
public void MemberInfoExtensions_IsAttributeDefined()
{
Assert.IsTrue(typeof(MemberInfoExtensionsTests).IsAttributeDefined<TestClassAttribute>(), "Test class has TestClass attribute defined.");
}
private class MyClass
{
[DefaultValue("test")]
public string Title { get; set; }
[PaintColor(ConsoleColor.Black), PaintColor(ConsoleColor.Blue)]
public string Subtitle { get; set; }
}
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
private class PaintColorAttribute : Attribute
{
public ConsoleColor Color { get; private set; }
public PaintColorAttribute(ConsoleColor color)
{
Color = color;
}
}
}
}
|
41b54363074e2941e7e9cdb48fcce7a2c245e5f9
|
C#
|
brunomlopes/ILoveLucene
|
/src/Tests/CalculatorTests.cs
| 2.703125
| 3
|
using Core.Abstractions;
using Core.Extensions;
using Plugins;
using Xunit;
namespace Tests
{
public class CalculatorTests
{
[Fact]
public void CanCalculateSimpleExpressions()
{
var action = new Calculator();
action.ActOn(new TextItem("21 + 21"));
Assert.Equal("42", action.Text);
}
[Fact]
public void CanCalculatePowerOf2Expressions()
{
var action = new Calculator();
action.ActOn(new TextItem("pow(10,2)"));
Assert.Equal("100", action.Text);
}
}
}
|
c42c720693e86b8202d5caf7add65c6af8e938ab
|
C#
|
teslax2/ZeusAssistant
|
/ZeusAssistant/Model/Messages/MessageAlarm.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ZeusAssistant.Model.Messages
{
public class MessageAlarm : Message
{
public DateTime Time { get; set; }
public double TimeConfidence { get; set; }
public int DaysEnabled { get; set; }
public MessageAlarm(IntentEnum intent, double confidence) : base(intent, confidence)
{
}
public MessageAlarm(IntentEnum intent, double confidence,DateTime time, double timeConfidence, int days, string message) : this(intent, confidence)
{
Time = time;
TimeConfidence = timeConfidence;
DaysEnabled = days;
Note = message;
}
public MessageAlarm(IntentEnum intent, double confidence, DateTime time, double timeConfidence) : this(intent, confidence)
{
Time = time;
TimeConfidence = timeConfidence;
}
}
}
|
ea0eab6bd69a0992359332ea4337565301d3e112
|
C#
|
tangxuehua/enode
|
/src/ENode/Infrastructure/Impl/DefaultTypeNameProvider.cs
| 2.640625
| 3
|
using System;
using System.Collections.Concurrent;
using System.Reflection;
namespace ENode.Infrastructure.Impl
{
public class DefaultTypeNameProvider : ITypeNameProvider, IAssemblyInitializer
{
private Assembly[] _asemblies;
private readonly ConcurrentDictionary<string, Type> _dict = new ConcurrentDictionary<string, Type>();
public Type GetType(string typeName)
{
Type t;
if (_dict.TryGetValue(typeName, out t))
{
return t;
}
foreach (var assembly in _asemblies)
{
var type = assembly.GetType(typeName);
if (type != null)
{
_dict.TryAdd(typeName, type);
return type;
}
}
return null;
}
public string GetTypeName(Type type)
{
return type.FullName;
}
public void Initialize(params Assembly[] assemblies)
{
_asemblies = assemblies;
}
}
}
|
78c097d29f1d38a81fa4090646df97b22f4334b0
|
C#
|
mdathaulla/C-Sharp-Advanced
|
/Garbage_Collector/Garbage_Collector/Program.cs
| 3.171875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GarbageCollector
{
class TestClassForGC
{
~TestClassForGC()
{
for (int i = 0; i < 50; i++)
{
Console.Write("1");
}
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine($"Memory without GC - {GC.GetTotalMemory(false) / 1024} kb"); // without GC
Console.WriteLine("");
long[] a = new long[1024 * 5]; // about 40kb
// array a is in 0 Generation
Console.WriteLine($"Generation - {GC.GetGeneration(a)}");
Console.WriteLine($"Memory without GC - {GC.GetTotalMemory(false) / 1024} kb"); // without GC
Console.WriteLine("");
byte[] b = new byte[1024 * 1024 * 100]; // about 819kb
// array b is in 2 Generation
Console.WriteLine($"Generation - {GC.GetGeneration(b)}");
Console.WriteLine($"Memory without GC - {GC.GetTotalMemory(false) / 1024} kb"); //without GC
Console.WriteLine($"Memory with GC - {GC.GetTotalMemory(true) / 1024} kb");
Console.WriteLine("");
string s = "abcdefghijkl";
Console.WriteLine($"Memory without GC - {GC.GetTotalMemory(false) / 1024} kb"); //without GC
string t = s + "1234567890";
Console.WriteLine($"Memory without GC - {GC.GetTotalMemory(false) / 1024} kb"); //without GC
t = null;
Console.WriteLine($"Memory without GC - {GC.GetTotalMemory(false) / 1024} kb"); //without GC
Console.WriteLine("");
TestClassForGC forGBCollector = new TestClassForGC();
for (int i = 0; i < 100; i++)
{
Console.Write("0");
}
GC.Collect();
// Makes the program to wait for the GB Collector finalization
GC.WaitForPendingFinalizers();
Console.ReadKey();
}
}
}
|
01dabcbe7c935514dfaaecd71846e5c9893f1b28
|
C#
|
Flydiverny/da148a_csharp
|
/Assignment2/TrashManager/WasteSchedule.cs
| 3.3125
| 3
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="WasteSchedule.cs" company="Markus Maga">
// Markus Maga
// </copyright>
// <summary>
// Defines the WasteSchedule type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace TrashManager
{
using System;
/// <summary>
/// The waste schedule.
/// </summary>
public class WasteSchedule : IStartable
{
/// <summary>
/// The start.
/// </summary>
public void Start()
{
this.WriteProgramInfo();
this.HandleMenu();
}
/// <summary>
/// Does what needs to be done for said menu choice.
/// </summary>
/// <param name="choice">
/// Action to perform.
/// </param>
private void PerformMenuChoice(int choice)
{
switch (choice)
{
case 1:
this.ShowSchedule(2);
return;
case 2:
this.ShowSchedule(4);
return;
}
}
/// <summary>
/// Prints a week schedule with specified repetition.
/// </summary>
/// <param name="repetition">
/// Repetition, for example every two weeks would be 2.
/// </param>
private void ShowSchedule(int repetition)
{
Console.WriteLine("Your bin empties the following weeks:\n\n");
const int Weeks = 52;
const int Columns = 4;
// Amount of repetitions are known, so it would make sense to use a for loop.
for (int i = repetition, column = 1; i <= Weeks; i += repetition, column++)
{
Console.Write("{0,15} {1,2}", "Week", i);
if (column == Columns)
{
Console.WriteLine();
column = 0;
}
}
Console.WriteLine("\n-----------------------------------");
}
/// <summary>
/// Loops the menu until user asks to exit.
/// </summary>
private void HandleMenu()
{
do
{
this.WriteMenu();
var choice = this.GetMenuChoice();
if (choice.Equals(0))
{
return;
}
this.PerformMenuChoice(choice);
}
while (true);
}
/// <summary>
/// Asks for a menu choice until a valid input is given.
/// </summary>
/// <returns>
/// menu choice
/// </returns>
private int GetMenuChoice()
{
var output = "Please choose a menu alternative [0-" + 2 + "]: ";
int choice;
do
{
Console.Write(output);
var input = Console.ReadLine();
int.TryParse(input, out choice);
}
while (choice < 0 || choice > 2);
Console.WriteLine("\n");
return choice;
}
/// <summary>
/// The write menu.
/// </summary>
private void WriteMenu()
{
const string StrFormat = "{0,2}. Bin No {0,2}. {1} (every {2} week)";
Console.WriteLine(StrFormat, 1, "household waste", "other");
Console.WriteLine(StrFormat, 2, "household waste", "4th");
Console.WriteLine("{0,2}. Exit the program", 0);
}
/// <summary>
/// Writes out some program info.
/// </summary>
private void WriteProgramInfo()
{
Console.WriteLine("Welcome to the Waste Schedule!!\n\n");
}
}
}
|
e6843f419b59c4df8a92cd542bda9a76719e209f
|
C#
|
GeorgiTsekov/CSharpFundamentalsMay2019
|
/FunctionalProgrammingExe/P08CustomComparator/Program.cs
| 3.421875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace P09ListOfPredicates
{
class Program
{
static void Main(string[] args)
{
int number = int.Parse(Console.ReadLine());
int[] numbers = Console.ReadLine()
.Split(" ", StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
List<int> listOfNumbers = new List<int>();
for (int i = 1; i <= number; i++)
{
bool isDivider = true;
foreach (var item in numbers)
{
if (i % item != 0)
{
isDivider = false;
}
}
if (isDivider)
{
listOfNumbers.Add(i);
}
}
Console.WriteLine(string.Join(" ", listOfNumbers));
}
}
}
|
8dba1079d2269f6f90390eeaed1403f0a2569533
|
C#
|
Borayvor/TelerikAcademy_2015_2016
|
/H08_High_Quality_Code/S19_DI_And_IoC_ContainersHomework/Dealership/Engine/Commands/Command.cs
| 2.625
| 3
|
namespace Dealership.Engine.Commands
{
using System.Collections.Generic;
using System.Linq;
using Common;
using Contracts;
using Contracts.Commands;
using Contracts.Factories;
public abstract class Command : ICommand
{
private ICommand Successor { get; set; }
public void SetSuccessor(Command successor)
{
this.Successor = successor;
}
public string Execute(
IEnumerable<string> commandAsCollection,
IVehicleFactory vehicleFactory,
IDealershipFactory dealershipFactory,
ICollection<IUser> users,
IUser[] loggedUser)
{
var commandAsList = commandAsCollection.ToList<string>();
var commandName = commandAsList[0];
if (!string.IsNullOrWhiteSpace(commandName) &&
commandName.ToLower() != Constants.RegisterUserCommandName.ToLower() &&
commandName.ToLower() != Constants.LoginCommandName.ToLower())
{
if (loggedUser[0] == null)
{
return Constants.UserNotLogged;
}
}
if (this.CanExecute(commandName))
{
return StartExecute(
commandAsList,
vehicleFactory,
dealershipFactory,
users,
loggedUser);
}
if (this.Successor != null)
{
return this.Successor.Execute(
commandAsList,
vehicleFactory,
dealershipFactory,
users,
loggedUser);
}
return string.Format(Constants.InvalidCommand, commandName);
}
protected abstract bool CanExecute(string commandName);
protected abstract string StartExecute(
IList<string> commandAsList,
IVehicleFactory vehicleFactory,
IDealershipFactory dealershipFactory,
ICollection<IUser> users,
IUser[] loggedUser);
}
}
|
28ac73ec55c1e6d2126935e21527da5ae16dffd8
|
C#
|
cleberspirlandeli/Arquitetura-de-Software
|
/OOP/03 - InterfaceVsImplementacao/Cases.cs
| 2.984375
| 3
|
namespace OOP
{
public interface IRepositorio
{
void Adicionar();
}
public class Repositorio : IRepositorio
{
//public Repositorio(int a)
//{
//}
public void Adicionar()
{
// Adiciona item
}
}
public class RepositorioFake : IRepositorio
{
public void Adicionar()
{
// Adiciona item
}
}
public class UsoImplementacao
{
public void Processo()
{
var repositorio = new Repositorio();
repositorio.Adicionar();
}
}
public class UsoAbstracao
{
private readonly IRepositorio _repositorio;
public UsoAbstracao(IRepositorio repositorio)
{
_repositorio = repositorio;
}
public void Processo()
{
_repositorio.Adicionar();
}
}
public class TesteInterfaceImplementacao
{
public TesteInterfaceImplementacao()
{
var repoImp = new UsoImplementacao();
repoImp.Processo();
var repoAbs = new UsoAbstracao(new Repositorio());
repoAbs.Processo();
var repoAbsFake = new UsoAbstracao(new RepositorioFake());
repoAbsFake.Processo();
}
}
}
|
d57b3ae7e48b9003743db1dd38f9434c83636968
|
C#
|
marklauter/graph
|
/src/Graph.Indexes/FileAdjacencyListGuid.cs
| 2.8125
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Graphs.Indexes
{
public abstract class FileAdjacencyListGuid
: AdjacencyIndex<Guid>
{
public string Path { get; }
private int size;
public override int Size => this.size;
protected FileAdjacencyListGuid(string path)
{
this.Path = !String.IsNullOrEmpty(path) ? path : "data";
if (!Directory.Exists(this.Path))
{
Directory.CreateDirectory(this.Path);
}
this.size = Directory
.EnumerateFiles(this.Path)
.Count();
}
protected string ClonePath()
{
var newPath = $"{this.Path}.clone.{Guid.NewGuid()}";
Directory.CreateDirectory(newPath);
foreach (var fileName in Directory.EnumerateFiles(this.Path))
{
File.Copy(
System.IO.Path.Combine(this.Path, fileName),
System.IO.Path.Combine(newPath, fileName));
}
return newPath;
}
public override bool Adjacent(Guid source, Guid target)
{
var fileName = System.IO.Path.Combine(this.Path, source.ToString());
return File.Exists(fileName) && FileContainsKey(fileName, target);
}
public override int Degree(Guid node)
{
var fileName = System.IO.Path.Combine(this.Path, node.ToString());
if (File.Exists(fileName))
{
using var file = new FileStream(fileName, FileMode.Open, FileAccess.Read);
using var reader = new BinaryReader(file);
return reader.ReadInt32();
}
return 0;
}
public override Guid First()
{
return this.Size > 0
? Guid.Parse(Directory.EnumerateFiles(this.Path).First())
: throw new InvalidOperationException("First is invalid on empty index.");
}
public override IEnumerable<Guid> Keys()
{
return Directory
.EnumerateFiles(this.Path)
.Select(f => Guid.Parse(System.IO.Path.GetFileName(f)));
}
public override IEnumerable<Guid> Neighbors(Guid node)
{
var fileName = System.IO.Path.Combine(this.Path, node.ToString());
using var file = new FileStream(fileName, FileMode.Open, FileAccess.Read);
using var reader = new BinaryReader(file);
var length = reader.ReadInt32();
for (var i = 0; i < length; ++i)
{
yield return new Guid(reader.ReadBytes(16));
}
}
protected static bool FileContainsKey(string fileName, Guid key)
{
using var file = new FileStream(fileName, FileMode.Open, FileAccess.Read);
using var reader = new BinaryReader(file);
var length = reader.ReadInt32();
for (var i = 0; i < length; ++i)
{
if (key == new Guid(reader.ReadBytes(16)))
{
return true;
}
}
return false;
}
protected void AddKeyToFile(string fileName, bool fileExists, Guid key)
{
if (fileExists)
{
using var file = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite);
using var reader = new BinaryReader(file);
using var writer = new BinaryWriter(file);
var length = reader.ReadInt32() + 1;
writer.Seek(0, SeekOrigin.Begin);
writer.Write(length);
writer.Seek(0, SeekOrigin.End);
writer.Write(key.ToByteArray());
}
else
{
using var file = new FileStream(fileName, FileMode.CreateNew, FileAccess.Write);
using var writer = new BinaryWriter(file);
writer.Seek(0, SeekOrigin.Begin);
writer.Write(1);
writer.Write(key.ToByteArray());
++this.size;
}
}
protected void RemoveKeyFromFile(string fileName, Guid key)
{
using var file = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite);
using var reader = new BinaryReader(file);
var length = reader.ReadInt32();
if (length - 1 == 0)
{
reader.Close();
File.Delete(fileName);
--this.size;
return;
}
var keys = new byte[length - 1][];
var deletionPoint = 0;
var index = 0;
for (var i = 0; i < length; ++i)
{
var bytes = reader.ReadBytes(16);
if (key != new Guid(bytes))
{
keys[index++] = bytes;
}
else
{
deletionPoint = i;
}
}
using var writer = new BinaryWriter(file);
writer.Seek(0, SeekOrigin.Begin);
writer.Write(length - 1);
for (var i = deletionPoint; i < length - 1; ++i)
{
var offset = i * 16 + sizeof(int);
writer.Seek(offset, SeekOrigin.Begin);
writer.Write(keys[i]);
}
}
}
}
|
297ad2510fcd1e9f2d945b769246afbdccc9f061
|
C#
|
Syrrianyl/EDDI-French
|
/DataDefinitions/TradeRating.cs
| 2.78125
| 3
|
using System.Collections.Generic;
using System.Linq;
using Utilities;
namespace EddiDataDefinitions
{
/// <summary>
/// Trade ratings
/// </summary>
public class TradeRating
{
private static readonly List<TradeRating> RATINGS = new List<TradeRating>();
public string edname { get; private set; }
public string LocalName
{
get
{
return I18N.GetString(edname) ?? edname;
}
}
public string name { get; private set; }
public int rank { get; private set; }
private TradeRating(string edname, int rank, string name)
{
this.edname = edname;
this.rank = rank;
this.name = name;
RATINGS.Add(this);
}
public static readonly TradeRating Penniless = new TradeRating("Penniless", 0, "Penniless");
public static readonly TradeRating MostlyPenniless = new TradeRating("MostlyPenniless", 1, "Mostly Penniless");
public static readonly TradeRating Peddler = new TradeRating("Peddler", 2, "Peddler");
public static readonly TradeRating Dealer = new TradeRating("Dealer", 3, "Dealer");
public static readonly TradeRating Merchant = new TradeRating("Merchant", 4, "Merchant");
public static readonly TradeRating Broker = new TradeRating("Broker", 5, "Broker");
public static readonly TradeRating Entrepreneur = new TradeRating("Entrepreneur", 6, "Entrepreneur");
public static readonly TradeRating Tycoon = new TradeRating("Tycoon", 7, "Tycoon");
public static readonly TradeRating Elite = new TradeRating("Elite", 8, "Elite");
public static TradeRating FromName(string from)
{
if (from == null)
{
return null;
}
TradeRating result = RATINGS.FirstOrDefault(v => v.name == from);
// test LocalName
if (result == null)
{
result = RATINGS.FirstOrDefault(v => v.LocalName == from);
}
if (result == null)
{
Logging.Report("Unknown Trade Rating name " + from);
}
return result;
}
public static TradeRating FromEDName(string from)
{
if (from == null)
{
return null;
}
string tidiedFrom = from.ToLowerInvariant();
TradeRating result = RATINGS.FirstOrDefault(v => v.edname.ToLowerInvariant() == tidiedFrom);
if (result == null)
{
Logging.Report("Unknown Trade Rating ED name " + from);
}
return result;
}
public static TradeRating FromRank(int from)
{
TradeRating result = RATINGS.FirstOrDefault(v => v.rank == from);
if (result == null)
{
Logging.Report("Unknown Trade Rating rank " + from);
}
return result;
}
}
}
|
4cdf802ff054e530ce8693aac3954b7f73ab04b4
|
C#
|
DrFingerClawz/OpenVP
|
/trunk/OpenVP/OpenVP.Metadata/.svn/text-base/Event.cs.svn-base
| 2.59375
| 3
|
// Event.cs created with MonoDevelop
// User: chris at 3:08 PM 11/3/2008
//
// To change standard headers go to Edit->Preferences->Coding->Standard Headers
//
using System;
using System.Reflection;
using OpenVP.Metadata.Loose;
namespace OpenVP.Metadata
{
public class Event : MetadataObject
{
[LooseSource("begin")]
public int BeginTime { get; protected set; }
[LooseSource("end")]
public int EndTime { get; protected set; }
public IChannel Source { get; private set; }
public Event(IChannel source, LooseDictionary data, int beginTime, int endTime) : base(data)
{
this.BeginTime = beginTime;
this.EndTime = endTime;
this.Source = source;
}
protected Event(IChannel source, LooseDictionary data) : base(data)
{
this.SetLoose();
this.Source = source;
}
private void SetLoose()
{
Type type = this.GetType();
foreach (MemberInfo member in type.GetMembers(BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.NonPublic)) {
FieldInfo field;
PropertyInfo property;
field = member as FieldInfo;
property = member as PropertyInfo;
if (field == null && property == null)
continue;
object[] attrs = member.GetCustomAttributes(typeof(LooseSourceAttribute), false);
LooseSourceAttribute attr;
if (attrs.Length == 0)
continue;
attr = (LooseSourceAttribute) attrs[0];
LooseObject obj = this.LooseData[attr.Path];
if (obj == null)
continue;
object val;
if (!TryConvert(field != null ? field.FieldType : property.PropertyType, obj, out val))
continue;
if (field != null)
field.SetValue(this, val);
else
property.SetValue(this, val, null);
}
}
private static bool TryConvert(Type type, LooseObject obj, out object output)
{
if (type == typeof(int)) {
output = (int) obj.ToNumber();
return true;
}
if (type == typeof(float)) {
output = obj.ToNumber();
return true;
}
if (type == typeof(string)) {
output = obj.ToString();
return true;
}
if (typeof(LooseObject).IsAssignableFrom(type)) {
output = obj;
return true;
}
output = null;
return false;
}
}
}
|
aef93d6b320669eb043dc4dbecd6fcfdf0a3da53
|
C#
|
CtrlFnAlt/Corso10157
|
/Models/ViewModel/LessonViewModel.cs
| 2.765625
| 3
|
using System;
using System.Data;
namespace Corso10157.Models.ViewModel
{
public class LessonViewModel
{
public int Id { get; set; }
public int IdCourse { get; set; }
public string Titolo { get; set; }
public TimeSpan Durata { get; set; }
public static LessonViewModel FromDataRow(DataRow dataRow)
{
var lessonViewModel = new LessonViewModel {
Id = Convert.ToInt32(dataRow["Id"]),
IdCourse = Convert.ToInt32(dataRow["IdCourse"]),
Titolo = Convert.ToString(dataRow["Titolo"]),
Durata = TimeSpan.Parse(Convert.ToString(dataRow["Durata"])),
};
return lessonViewModel;
}
}
}
|
f9bda1a8ffcd9cbd63bc7153ec2bc2a66349381d
|
C#
|
niyifalomo/mi-share-app
|
/Mi-Share.Service/UserService.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mi_Share.Model;
using Mi_Share.Data.Infrastructure;
using Mi_Share.Data.Repositories;
namespace Mi_Share.Service
{
public interface IUserService {
bool CreateUser(User user);
User GetUserByCredentials(string username, string password);
IEnumerable<User> GetUsers();
IEnumerable<UsersCollections> GetCollectionsList(int currentUserID);
User GetUserByID(int id);
}
public class UserService : IUserService
{
private readonly IUserRepository _userRepository;
private readonly ICollectionAccessRepository _collectionAccessRepository;
private readonly IItemRepository _itemRepository;
private readonly IUnitOfWork _unitOfWork;
public UserService(IUserRepository userRepository,IItemRepository itemRepository,IUnitOfWork unitOfWork, ICollectionAccessRepository collectionAccessRepository)
{
_userRepository = userRepository;
_unitOfWork = unitOfWork;
_collectionAccessRepository = collectionAccessRepository;
_itemRepository = itemRepository;
}
public bool CreateUser(User user)
{
_userRepository.Add(user);
return SaveUser() > 0 ? true : false;
}
//Get User using credentials
public User GetUserByCredentials(string username, string password)
{
var user = _userRepository.Get(x => x.UserName.ToLower() == username.ToLower() && x.Password == password);
return user;
}
public User GetUserByID(int id)
{
var user = _userRepository.GetById(id);
return user;
}
public IEnumerable<User> GetUsers()
{
var users = _userRepository.GetAll();
return users;
}
//Get Other users libraries ----Username, items and access status
public IEnumerable<UsersCollections> GetCollectionsList(int currentUserID)
{
var users = _userRepository.GetMany(x=>x.ID != currentUserID)
.GroupJoin(
_collectionAccessRepository.GetMany(x => x.Requester_ID == currentUserID),
i => i.ID,
p => p.Owner_ID,
(i, g) =>
new
{
i = i,
g = g
}
)
.SelectMany(
temp => temp.g.DefaultIfEmpty(),
(temp, p) =>
new UsersCollections
{
UserID = temp.i.ID,
FullName = temp.i.FullName,
ItemCount = _itemRepository.GetMany(x => x.Owner_ID == temp.i.ID).Count(),
Access = (p == null) ? CollectionAccessStatus.None : p.Status
}
);
return users;
}
public int SaveUser()
{
return _unitOfWork.Commit();
}
}
}
|
e783d63a524706de25fac1fa2e9b12ae6b245595
|
C#
|
dhirutech/pragmatic-cqrs-with-asp-net-core-for-spas
|
/4-cqrs-with-mediatr-and-odata/PersonsController.cs
| 2.703125
| 3
|
using MediatR;
using Microsoft.AspNet.OData;
using System;
using System.Linq;
namespace Sample
{
public class DeletePerson : IRequest
{
/// <summary>
/// Id of the person
/// </summary>
public Guid Id { get; set; }
}
public class PersonsController : ODataController
{
private readonly DataContext ctx;
public PersonsController(DataContext ctx)
{
this.ctx = ctx;
}
[EnableQuery]
public SingleResult<Person> GetPerson(Guid key)
{
return new SingleResult<Person>(ctx.Persons.Where(v => v.Id == key));
}
[EnableQuery]
public IQueryable<Person> GetPersons()
{
return ctx.Persons;
}
}
}
|
addf91e1b678e5714b92d4e3b8709106d24ee291
|
C#
|
Mdejonge/GildtAPI
|
/Model/Tag.cs
| 2.515625
| 3
|
using Newtonsoft.Json;
namespace GildtAPI.Model
{
public class Tag
{
[JsonProperty]
public int Id { get; set; }
[JsonProperty]
public string Name { get; set; }
public Tag(int id, string name)
{
Id = id;
Name = name;
}
}
}
|
4aedf530c8f42bb48b59a4f82f3ec7bb639c77a9
|
C#
|
sharkbound/csharp-projects
|
/CursorGoto/CursorGoto/Program.cs
| 3.09375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;
using System.Drawing;
using System.Threading;
namespace csharp
{
class Program
{
static void Main(string[] args)
{
Console.Title = "CursorGoto";
ConsoleKeyInfo k;
int shiftnum = 7;
int timer = 9;
bool firstloop = false;
bool interloop = true;
bool doLoop = true;
Point point = new Point();
Point gotothis = new Point();
MouseEventArgs mouse = new MouseEventArgs(MouseButtons.Left, 1, gotothis.X, gotothis.Y, 1);
MousePos(ref firstloop);
while (doLoop)
{
#region cursorJumpAsk
continueloop:
//Console.WriteLine("do u want to jump the cursor somewhere? [y/n]");
//k = Console.ReadKey();
//if (k.Key == ConsoleKey.Y)
//{
// Console.WriteLine("enter the place for the cursor to jump to...");
// Console.WriteLine("enter the first coord...");
// point.X = int.Parse(Console.ReadLine());
// Console.WriteLine("enter the second coord...");
// point.Y = int.Parse(Console.ReadLine());
// Cursor.Position = point;
//}
#endregion
#region cursor goto
set:
Console.WriteLine("do u want to set a goto point? [y/n]");
k = Console.ReadKey();
switch (k.Key)
{
case ConsoleKey.Y:
Console.WriteLine("do u want to set the goto position manually? [y/n]");
k = Console.ReadKey();
if (k.Key == ConsoleKey.Y)
{
ManualSetGotoPos(ref point, ref gotothis);
}
else
{
gotothis = ReturnMousePos(ref gotothis);
}
point = Cursor.Position;
interloop = true;
while (interloop)
{
while (Cursor.Position.Y > gotothis.Y)
{
SlowDownCursorY(ref shiftnum, ref gotothis);
point.Y -= shiftnum;
Cursor.Position = point;
Console.WriteLine("moved cursor to \tY: {0}", point.Y);
Thread.Sleep(timer);
}
while (Cursor.Position.Y < gotothis.Y)
{
SlowDownCursorY(ref shiftnum, ref gotothis);
point.Y += shiftnum;
Cursor.Position = point;
Console.WriteLine("moved cursor to \tY: {0}", point.Y);
Thread.Sleep(timer);
}
while (Cursor.Position.X > gotothis.X)
{
SlowDownCursorX(ref shiftnum, ref gotothis);
point.X -= shiftnum;
Cursor.Position = point;
Console.WriteLine("moved cursor to \tX: {0}", point.X);
Thread.Sleep(timer);
}
while (Cursor.Position.X < gotothis.X)
{
SlowDownCursorX(ref shiftnum, ref gotothis);
point.X += shiftnum;
Cursor.Position = point;
Console.WriteLine("moved cursor to \tX: {0}", point.X);
Thread.Sleep(timer);
}
if (Cursor.Position.X == gotothis.X && Cursor.Position.Y == gotothis.Y)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("i have arrived at the entered location!");
Console.ForegroundColor = ConsoleColor.White;
// OnMouseClick(mouse);
interloop = false;
}
}
break;
case ConsoleKey.N:
break;
default:
goto set;
}
#endregion
#region menu
menu:
Console.WriteLine("exit? [y/n]");
k = Console.ReadKey();
if (k.Key == ConsoleKey.Y)
{
break;
}
else if (k.Key == ConsoleKey.N)
{
goto continueloop;
}
else
{
goto menu;
}
}
#endregion
}
private static void ManualSetGotoPos(ref Point point, ref Point gotothis)
{
Console.WriteLine("enter the X to goto...");
gotothis.X = int.Parse(Console.ReadLine());
Console.WriteLine("enter the Y to goto...");
gotothis.Y = int.Parse(Console.ReadLine());
}
private static void SlowDownCursorY(ref int shiftnum, ref Point gotothis)
{
int y = Cursor.Position.Y - gotothis.Y;
if (y < 0)
{
y = gotothis.Y - Cursor.Position.Y;
}
if (y < 30)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("triggered!");
Console.ForegroundColor = ConsoleColor.White;
shiftnum = 1;
}
else
{
shiftnum = 7;
}
}
private static void SlowDownCursorX(ref int shiftnum, ref Point gotothis)
{
int x = Cursor.Position.X - gotothis.X;
if (x < 0)
{
x = gotothis.X - Cursor.Position.X;
}
if (x < 30)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("triggered!");
Console.ForegroundColor = ConsoleColor.White;
shiftnum = 1;
}
else
{
shiftnum = 7;
}
}
private static void MousePos(ref bool firstloop)
{
while (firstloop)
{
Console.WriteLine("Cursor X: {0}, Cursor Y: {1}", Cursor.Position.X, Cursor.Position.Y);
Thread.Sleep(100);
}
}
static Point ReturnMousePos(ref Point gotothis)
{
gotothis.X = Cursor.Position.X;
gotothis.Y = Cursor.Position.Y;
Console.WriteLine("move the cursor away from the current spot them press any key...");
Console.ReadKey();
return gotothis;
}
}
}
|
e5a6fb8bd7bd0ab1326018b6177556a3518bd476
|
C#
|
alesegdia/cube-wars
|
/Assets/Scripts/Tests/UtilsTest.cs
| 2.765625
| 3
|
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
namespace CubeWars
{
namespace Tests
{
public class UtilsTest
{
[Test]
public void ManhattanDistanceOrderTest()
{
int numIterations = 1000;
while (--numIterations > 0)
{
var v1 = new Vector2Int(Random.Range(10, 1000), Random.Range(10, 1000));
var v2 = new Vector2Int(Random.Range(10, 1000), Random.Range(10, 1000));
Assert.IsTrue(Utils.ManhattanDistance(v1, v2) == Utils.ManhattanDistance(v2, v1));
var val1 = Random.Range(500, 10000);
var val2 = Random.Range(500, 10000);
Assert.IsTrue(Utils.ManhattanDistance(new Vector2Int(val1, val2), new Vector2Int(val1, val2)) == 0);
Assert.IsTrue(Utils.ManhattanDistance(new Vector2Int(val2, val1), new Vector2Int(val2, val1)) == 0);
}
}
[Test]
public void ManhattanDistanceDirectCalculationTest()
{
int numIterations = 1000;
while (--numIterations > 0)
{
var v1 = Random.Range(500, 10000);
var v2 = Random.Range(500, 10000);
var r = Random.Range(500, 10000);
Assert.IsTrue(Utils.ManhattanDistance(new Vector2Int(v1, v2), new Vector2Int(v1 + r, v2)) == r);
Assert.IsTrue(Utils.ManhattanDistance(new Vector2Int(v1, v2), new Vector2Int(v1, v2 + r)) == r);
}
}
[Test]
public void ManhattanDistanceDiagonalTest()
{
int numIterations = 1000;
while (--numIterations > 0)
{
var v = Random.Range(500, 10000);
var r = Random.Range(500, 10000);
Assert.IsTrue(Utils.ManhattanDistance(new Vector2Int(v, v), new Vector2Int(v + r, v + r)) == r * 2);
Assert.IsTrue(Utils.ManhattanDistance(new Vector2Int(v, v), new Vector2Int(v - r, v - r)) == r * 2);
}
}
}
}
}
|
1559a0353d675f5e6d7832ce65ad421cb8a30d08
|
C#
|
zaz8065/worlds-best-bars-new
|
/WorldsBestBars.Services/ReviewService.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using WorldsBestBars.Services.Models;
namespace WorldsBestBars.Services
{
public class ReviewService : BaseService
{
#region Public Methods
/// <summary>
/// Gets the pending moderation.
/// </summary>
/// <param name="total">The total.</param>
/// <param name="skip">The skip.</param>
/// <param name="take">The take.</param>
/// <returns></returns>
public IEnumerable<Review> GetPendingModeration(out int total, int skip, int take)
{
using (var connection = GetConnection())
{
using (var command = connection.CreateCommand())
{
command.CommandText = "select @count = count(*) from Review where IsModerated = 0";
command.Parameters.Add(new SqlParameter("@count", SqlDbType.Int) { Direction = ParameterDirection.Output });
command.ExecuteNonQuery();
total = (int)command.Parameters["@count"].Value;
}
using (var command = connection.CreateCommand())
{
command.CommandText = @"with cte as (
select
RE.Id,
RE.BarId,
B.Name as [BarName],
RE.UserId,
U.Name as [UserName],
RE.ParentId,
RE.Title,
RE.Comment,
RE.IsActive,
RE.Created,
RE.IsModerated,
RE.UserIP,
RE.RatingId,
RA.Design,
RA.Drinks,
RA.Service,
RA.Overall,
row_number() over (order by RE.Created desc) as __RN
from
Review RE
left join Rating RA on (RE.RatingId = RA.Id)
inner join Bar B on (RE.BarId = B.Id)
left join [User] U on (RE.UserId = U.Id)
where
RE.IsModerated = 0 )
select
Id,
BarId,
BarName,
UserId,
UserName,
ParentId,
Title,
Comment,
IsActive,
Created,
IsModerated,
UserIP,
RatingId,
Design,
Drinks,
Service,
Overall
from
cte
where
__RN between @skip and (@skip + @take)";
command.Parameters.AddWithValue("@skip", skip);
command.Parameters.AddWithValue("@take", take);
using (var reader = command.ExecuteReader())
{
var result = new List<Review>();
while (reader.Read())
{
result.Add(Review.FromReader(reader));
}
return result.ToArray();
}
}
}
}
/// <summary>
/// Gets all.
/// </summary>
/// <param name="total">The total.</param>
/// <param name="skip">The skip.</param>
/// <param name="take">The take.</param>
/// <returns></returns>
public IEnumerable<Review> GetAll(out int total, int skip, int take)
{
using (var connection = GetConnection())
{
using (var command = connection.CreateCommand())
{
command.CommandText = "select @count = count(*) from Review";
command.Parameters.Add(new SqlParameter("@count", SqlDbType.Int) { Direction = ParameterDirection.Output });
command.ExecuteNonQuery();
total = (int)command.Parameters["@count"].Value;
}
using (var command = connection.CreateCommand())
{
command.CommandText = @"with cte as (
select
RE.Id,
RE.BarId,
B.Name as [BarName],
RE.UserId,
U.Name as [UserName],
RE.ParentId,
RE.Title,
RE.Comment,
RE.IsActive,
RE.Created,
RE.IsModerated,
RE.UserIP,
RE.RatingId,
RA.Design,
RA.Drinks,
RA.Service,
RA.Overall,
row_number() over (order by RE.Created desc) as __RN
from
Review RE
left join Rating RA on (RE.RatingId = RA.Id)
inner join Bar B on (RE.BarId = B.Id)
left join [User] U on (RE.UserId = U.Id) )
select
Id,
BarId,
BarName,
UserId,
UserName,
ParentId,
Title,
Comment,
IsActive,
Created,
IsModerated,
UserIP,
RatingId,
Design,
Drinks,
Service,
Overall
from
cte
where
__RN between @skip and (@skip + @take)";
command.Parameters.AddWithValue("@skip", skip);
command.Parameters.AddWithValue("@take", take);
using (var reader = command.ExecuteReader())
{
var result = new List<Review>();
while (reader.Read())
{
result.Add(Review.FromReader(reader));
}
return result.ToArray();
}
}
}
}
public void Moderate(Guid id, bool isActive)
{
using (var connection = GetConnection())
{
using (var command = connection.CreateCommand())
{
command.CommandText = "update Review set IsActive = @isActive, IsModerated = 1 where Id = @id";
command.Parameters.AddWithValue("@isActive", isActive);
command.Parameters.AddWithValue("@id", id);
command.ExecuteNonQuery();
}
}
}
#endregion
}
}
|
12806c01980c733a74fff4a1c4c410d1b1b0cc04
|
C#
|
Andranik93/Chat
|
/Client/Client.cs
| 2.90625
| 3
|
using System;
using System.Net;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Windows.Forms;
namespace Client
{
public partial class Client : Form
{
TcpClient _client;
NetworkStream _nwStream;
Thread _thread;
Boolean _listen = false;
public Client()
{
InitializeComponent();
}
private void Client_Load(object sender, EventArgs e)
{
}
private void ConnectButton_Click(object sender, EventArgs e)
{
if (this.txtRemoteIP.Text == ""|| this.txtRemoteHost.Text == ""|| this.txtRemotePort.Text == "")
return;
_client = new TcpClient();
_client.Connect(IPAddress.Parse(this.txtRemoteIP.Text), Convert.ToInt32(this.txtRemotePort.Text));
_nwStream = _client.GetStream();
if (_client.Connected)
{
_thread = new Thread(Listening);
_thread.Start();
//var nwStream = _client.GetStream();
//byte[] msg = Encoding.ASCII.GetBytes("Hi Server");
//nwStream.Write(msg, 0, msg.Length);
_listen = true;
}
}
private void Listening()
{
while (_listen)
{
if (_nwStream.DataAvailable)
{
byte[] msg = new byte[256];
_nwStream.Read(msg, 0, msg.Length);
string _msg = Encoding.ASCII.GetString(msg);
this.listMessage.Text += _msg + '\n';
}
}
}
private void SendButton_Click(object sender, EventArgs e)
{
if (_client.Connected)
{
var nwStream = _client.GetStream();
byte[] msg = Encoding.ASCII.GetBytes(this.txtSend.Text+'\n');
nwStream.Write(msg, 0, msg.Length);
//_client.Client.Send(msg);
}
}
}
}
|
b0ffc66983dd85326b54d1b6f2a2b625f76b218f
|
C#
|
danieleli/Swagger.Net
|
/Swagger.Net._Test/Factories/ParameterFactory_Test.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web.Http.Description;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using Sample.Mvc4WebApi.Models;
using Swagger.Net.Factories;
using Swagger.Net.Models;
namespace Swagger.Net._Test.Factories
{
public enum TestEnum
{
A,B,C
}
[TestClass]
public class ParameterFactory_Test
{
private ParameterFactory _factory;
public void Setup()
{
var docProvider = new XmlCommentDocumentationProvider(TestHelper.XML_DOC_PATH);
_factory = new ParameterFactory(docProvider);
}
[TestMethod]
public void GetParameterType_With_IEnumerable()
{
Setup();
var type = typeof(IEnumerable<Int32>);
var rtn = ModelFactory.GetDataType(type).Name;
Assert.AreEqual("Int32", rtn, "returned value");
}
[TestMethod]
public void GetParameterType_With_Array()
{
Setup();
var type = typeof(Int32[]);
var rtn = ModelFactory.GetDataType(type).Name;
Debug.WriteLine(rtn);
Assert.AreEqual("Int32", rtn, "returned value");
}
[TestMethod]
public void GetParameterType_With_ListT()
{
Setup();
var type = typeof(List<Int32>);
var rtn = ModelFactory.GetDataType(type).Name;
Debug.WriteLine(rtn);
Assert.AreEqual("Int32", rtn, "returned value");
}
[TestMethod]
public void CreateParameter_ReturnsWith_DataType_IsOptional_ParamName_ParamType()
{
// Arrange
Setup();
var paramSource = ApiParameterSource.FromUri;
var dataType = typeof(BlogPost);
var isOptional = true;
var paramName = "param3";
var input = TestHelper.CreateParameter(paramName, dataType, isOptional, paramSource);
// Act
dynamic rtnParam = _factory.CreateParameter(input, "");
// Assert
Assert.AreEqual(dataType.Name, rtnParam.dataType, "param source (body, uri, unknown");
Assert.AreEqual(!isOptional, rtnParam.required, "is required");
Assert.AreEqual(paramName, rtnParam.name, "param name");
Assert.AreEqual(ParamType.query.ToString(), rtnParam.paramType, "param Type");
Debug.WriteLine(JsonConvert.SerializeObject((object)rtnParam));
}
[TestMethod]
public void CreateParameter_Sets_AllowableValues()
{
// Arrange
Setup();
var paramSource = ApiParameterSource.FromUri;
var dataType = typeof(TestEnum);
var isOptional = true;
var paramName = "param3";
var input = TestHelper.CreateParameter(paramName, dataType, isOptional, paramSource);
// Act
var rtnParam = _factory.CreateParameter(input, "");
// Assert
Assert.IsInstanceOfType(rtnParam, typeof(ApiEnumParameter));
var afterCast = (ApiEnumParameter) rtnParam;
Debug.WriteLine(JsonConvert.SerializeObject((object)rtnParam));
Assert.AreEqual("A,B,C", string.Join(",",afterCast.allowableValues.values), "Allowable values");
}
[TestMethod]
public void CreateParameter_Returns_FromUri_When_ParamName_IsInRoute()
{
// Arrange
Setup();
var paramSource = ApiParameterSource.FromUri;
var dataType = typeof(BlogPost);
var isOptional = true;
var paramName = "myparam";
var input = TestHelper.CreateParameter(paramName, dataType, isOptional, paramSource);
// Act
dynamic rtnParam = _factory.CreateParameter(input, TestHelper.ROUTE_TEMPLATE);
// Assert
Assert.AreEqual(ParamType.path.ToString(), rtnParam.paramType, "param Type");
Debug.WriteLine(JsonConvert.SerializeObject((object)rtnParam));
}
[TestMethod]
public void CreateParameter_Returns_FromBody_When_ParamSouce_IsFromBody()
{
// Arrange
Setup();
var paramSource = ApiParameterSource.FromBody;
var dataType = typeof(BlogPost);
var isOptional = true;
var paramName = "myparam";
var input = TestHelper.CreateParameter(paramName, dataType, isOptional, paramSource);
// Act
dynamic rtnParam = _factory.CreateParameter(input, TestHelper.ROUTE_TEMPLATE);
// Assert
Assert.AreEqual(ParamType.body.ToString(), rtnParam.paramType, "param Type");
Debug.WriteLine(JsonConvert.SerializeObject((object)rtnParam));
}
[TestMethod]
public void CreateParameter_Returns_FromBody_When_ParamSouce_IsUnknown()
{
// Arrange
Setup();
var paramSource = ApiParameterSource.Unknown;
var dataType = typeof(BlogPost);
var isOptional = true;
var paramName = "myparam";
var input = TestHelper.CreateParameter(paramName, dataType, isOptional, paramSource);
// Act
dynamic rtnParam = _factory.CreateParameter(input, TestHelper.ROUTE_TEMPLATE);
// Assert
Assert.AreEqual(ParamType.body.ToString(), rtnParam.paramType, "param Type");
Debug.WriteLine(JsonConvert.SerializeObject((object)rtnParam));
}
[TestMethod]
public void CreateParameter_Sets_AllowableMultiple()
{
// Arrange
Setup();
var paramSource = ApiParameterSource.FromUri;
var dataType = typeof(BlogPost);
var isOptional = true;
var paramName = "param3";
var input = TestHelper.CreateParameter(paramName, dataType, isOptional, paramSource);
// Act
dynamic rtnParam = _factory.CreateParameter(input, "");
// Assert
Assert.AreEqual(false, rtnParam.allowMultiple, "Allowable values");
Debug.WriteLine(JsonConvert.SerializeObject((object)rtnParam));
}
[TestMethod]
public void IEnumerable_AllowMutiple_True()
{
// Arrange
Setup();
var paramSource = ApiParameterSource.FromUri;
var dataType = typeof(IEnumerable<Int32>);
var isOptional = true;
var paramName = "param3";
var input = TestHelper.CreateParameter(paramName, dataType, isOptional, paramSource);
// Act
dynamic rtnParam = _factory.CreateParameter(input,"fjdskf/fjdksla");
// Assert
Assert.AreEqual(true, rtnParam.allowMultiple, "Allowable values");
Debug.WriteLine(JsonConvert.SerializeObject((object)rtnParam));
}
}
}
|
eb80cca19f262201906545d74b60128881cbb7a9
|
C#
|
tudor96stani/MSCertCode
|
/Chapter1/AsyncAwait/Listing1-19.cs
| 3.09375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace AsyncAwait
{
class Listing1_19
{
static void Main(string[] args)
{
SleepAsyncB(2000).Wait();
}
static Task SleepAsyncA(int ms)
{
return Task.Run(() => Thread.Sleep(ms));
}
static Task SleepAsyncB(int ms)
{
TaskCompletionSource<bool> tcs = null;
var t = new Timer(delegate { tcs.TrySetResult(true); }, null, -1, -1);
tcs = new TaskCompletionSource<bool>(t);
t.Change(ms, -1);
return tcs.Task;
}
}
}
|
4dd617d9785c0bf7ffa7efbecffec9affedabdab
|
C#
|
anitha510/AlgorithmsCoursera
|
/TopologicalOrdering/Program.cs
| 3.96875
| 4
|
/*
Compute a topological ordering of a given directed acyclic graph (DAG) with 𝑛 vertices and 𝑚 edges.
Input Format. A graph is given in the standard format.
Constraints. 1 ≤ 𝑛 ≤ 10^5, 0 ≤ 𝑚 ≤ 10^5. The given graph is guaranteed to be acyclic.
Output Format. Output any topological ordering of its vertices. (Many DAGs have more than just one
topological ordering. You may output any of them.)
Memory Limit. 512MB.
Sample 1.
Input:
4 3
1 2
4 1
3 1
Output:
4 3 1 2
Sample 2.
Input:
4 1
3 1
Output:
2 3 1 4
Sample 3.
Input:
5 7
2 1
3 2
3 1
4 3
4 1
5 2
5 3
Output:
5 4 3 2 1
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TopologicalOrdering
{
class Node
{
internal int vertex;
internal int pre;
internal int post;
internal bool visited;
internal List<Node> neighbors = new List<Node>();
internal Node(int v)
{
vertex = v;
}
}
class Program
{
static int count = 0;
static void Explore(Node v)
{
v.visited = true;
v.pre = count++;
foreach (Node neighbor in v.neighbors)
{
if (neighbor.visited == false)
Explore(neighbor);
}
v.post = count++;
}
static void Main(string[] args)
{
var tokens = Console.ReadLine().Split(' ').Select(r => int.Parse(r)).ToArray();
int vertices = tokens[0];
int edges = tokens[1];
Node[] graph = new Node[vertices];
for (int v = 0; v < vertices; v++)
{
graph[v] = new Node(v);
}
int vertex1, vertex2;
for (int e = 1; e <= edges; e++)
{
//Read each edge
tokens = Console.ReadLine().Split(' ').Select(r => int.Parse(r)).ToArray();
vertex1 = tokens[0] - 1;
vertex2 = tokens[1] - 1;
//Add each edge to th adj list
graph[vertex1].neighbors.Add(graph[vertex2]);
}
// Do a DFS and compute post order
foreach (Node v in graph)
{
if (v.visited == false)
Explore(v);
}
StringBuilder result = new StringBuilder("");
foreach (Node node in graph.OrderByDescending(g => g.post))
result.Append((node.vertex + 1).ToString() + " ");
Console.WriteLine(result);
//Console.ReadLine();
}
}
}
|
7fdf70e2f8c2feec525bd0bdd61dd4b4800d5b13
|
C#
|
CogShift/RecurringInterval
|
/RecurringInterval/BiMonthlyInterval.cs
| 3.25
| 3
|
using System;
namespace RecurringInterval
{
internal class BiMonthlyInterval : Interval
{
/**** WARNING **
* We are making assumptions here.
* if the date is 1, move to 16th
* if the date is 2-12, add 15
* if the date is 13-15 move to last day of month
* if the date is 15, move to last day of month
* if the date is 16, move to 1st day of next month
* if the date is 17-27, add month - 15
* if the date is 28-31, move to 15th day of next month
*/
public BiMonthlyInterval(DateTime startDate) : this(startDate, startDate.Day - 1)
{
}
public BiMonthlyInterval(DateTime startDate, int endDay) : base(Period.BiMonthly)
{
EndDay = endDay;
if (EndDay == -1)
{
StrategyLastDayOfMonthAnd15th(startDate);
}
else if (EndDay == 1)
{
Strategy17To1And2To16(startDate);
}
else if (EndDay >= 2 && EndDay <= 12)
{
StrategyNextMonthMinus15(startDate, EndDay);
}
else if (EndDay >= 13 && EndDay <= 15)
{
StrategyLastDayOfMonthAnd15th(startDate, EndDay);
}
else if (EndDay == 16)
{
Strategy17To1And2To16(startDate);
}
else if (EndDay >= 17 && EndDay <= 27)
{
StrategyNextMonthMinus15(startDate, EndDay);
}
else
{
StrategyLastDayOfMonthAnd15th(startDate);
}
}
private void Strategy17To1And2To16(DateTime startDate)
{
if (startDate.Day == 1)
{
EndDate = new DateTime(startDate.Year, startDate.Month, 1);
StartDate = new DateTime(startDate.AddMonths(-1).Year, startDate.AddMonths(-1).Month, 17);
}
else if (startDate.Day <= 16)
{
EndDate = new DateTime(startDate.Year, startDate.Month, 16);
StartDate = new DateTime(startDate.Year, startDate.Month, 2);
}
else
{
EndDate = new DateTime(startDate.AddMonths(1).Year, startDate.AddMonths(1).Month, 1);
StartDate = new DateTime(startDate.Year, startDate.Month, 17);
}
}
private void StrategyNextMonthMinus15(DateTime startDate, int endDay)
{
if (endDay > 15) endDay -= 15;
if (startDate.Day <= endDay)
{
EndDate = new DateTime(startDate.Year, startDate.Month, endDay);
StartDate = new DateTime(startDate.AddMonths(-1).Year, startDate.AddMonths(-1).Month, Math.Min(endDay + 16, DateTime.DaysInMonth(startDate.AddMonths(-1).Year, startDate.AddMonths(-1).Month)));
}
else if (startDate.Day <= endDay + 15)
{
EndDate = new DateTime(startDate.Year, startDate.Month, Math.Min(endDay + 15, DateTime.DaysInMonth(startDate.Year, startDate.Month)));
StartDate = new DateTime(startDate.Year, startDate.Month, endDay + 1);
}
else
{
EndDate = new DateTime(startDate.AddMonths(1).Year, startDate.AddMonths(1).Month, endDay);
StartDate = new DateTime(startDate.Year, startDate.Month, Math.Min(endDay + 16, DateTime.DaysInMonth(startDate.Year, startDate.Month)));
}
}
private void StrategyLastDayOfMonthAnd15th(DateTime startDate, int endDate = 15)
{
if (startDate.Day <= endDate)
{
EndDate = new DateTime(startDate.Year, startDate.Month, endDate);
StartDate = new DateTime(startDate.Year, startDate.Month, 1);
}
else
{
EndDate = new DateTime(startDate.Year, startDate.Month, DateTime.DaysInMonth(startDate.Year, startDate.Month));
StartDate = new DateTime(startDate.Year, startDate.Month, endDate + 1);
}
}
//static readonly Func<DateTime, DateTime> add15 = a => a.AddDays(15);
//static readonly Func<DateTime, DateTime> sub15 = a => a.AddMonths(1).AddDays(-15);
//static readonly Func<DateTime, DateTime> mov15 = a => new DateTime(a.AddMonths(1).Year, a.AddMonths(1).Month, 15);
//static readonly IReadOnlyDictionary<int, Func<DateTime, DateTime>> dateMap = new ReadOnlyDictionary<int, Func<DateTime, DateTime>>(new Dictionary<int, Func<DateTime, DateTime>>
// {
// { 01, a => new DateTime(a.Year, a.Month,16) }, // move to 16th
// { 02, add15 }, // add 15
// { 03, add15 },
// { 04, add15 },
// { 05, add15 },
// { 06, add15 },
// { 07, add15 },
// { 08, add15 },
// { 09, add15 },
// { 10, add15 },
// { 11, add15 },
// { 12, add15 },
// { 13, add15 },
// { 14, a => new DateTime(a.Year, a.Month, DateTime.DaysInMonth(a.Year, a.Month)) }, // move to last day of month
// { 15, a => new DateTime(a.Year, a.Month, DateTime.DaysInMonth(a.Year, a.Month)) }, // move to last day of month
// { 16, a => new DateTime(a.AddMonths(1).Year, a.AddMonths(1).Month, 1) }, // 1st day of next month
// { 17, sub15 }, //add month - 15
// { 18, sub15 },
// { 19, sub15 },
// { 20, sub15 },
// { 21, sub15 },
// { 22, sub15 },
// { 23, sub15 },
// { 24, sub15 },
// { 25, sub15 },
// { 26, sub15 },
// { 27, sub15 },
// { 28, mov15 }, // move to 15th day of next month
// { 29, mov15 },
// { 30, mov15 },
// { 31, mov15 },
// });
//public BiMonthlyInterval(DateTime startDate) : base(Period.BiMonthly)
//{
// StartDate = startDate;
// var nextStartDate = dateMap[StartDate.Day](StartDate);
// EndDate = nextStartDate.AddDays(-1);
// EndDay = EndDate.Day == 1
// ? 1
// : StartDate.Day > EndDate.Day
// ? EndDate.Day
// : StartDate.Day - 1;
//}
public override Interval Next()
{
return new BiMonthlyInterval(NextStartDate(), EndDay);
}
private DateTime NextStartDate()
{
return EndDate.AddDays(1);
}
}
}
|
6f398a561c5b463697adc5fade96d4003cd9a29f
|
C#
|
galaxymacos/LeetCodeGrind
|
/Algorithm/BinaryTree.cs
| 3.140625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Messaging;
namespace Algorithm
{
public class BinaryTree
{
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x)
{
val = x;
}
}
public bool IsValidBST(TreeNode root)
{
return Recur(root, long.MinValue, long.MaxValue);
}
public bool Recur(TreeNode root, long min, long max)
{
bool leftSatisfied = false;
bool rightSatisfied = false;
if (root == null)
{
return true;
}
if (root.val <= min || root.val >= max)
{
Console.WriteLine(root);
return false;
}
if (root.left != null)
{
leftSatisfied = Recur(root.left, min, Math.Min(max, root.val));
}
else
{
leftSatisfied = true;
}
if (root.right != null)
{
rightSatisfied = Recur(root.right, Math.Max(min, root.val), max);
}
else
{
rightSatisfied = true;
}
return leftSatisfied && rightSatisfied;
}
public IList<IList<int>> LevelOrder(TreeNode root)
{
if (root == null)
{
return new List<IList<int>>();
}
IList<IList<int>> result = new List<IList<int>>();
Queue<TreeNode> queue = new Queue<TreeNode>();
queue.Enqueue(root);
while (queue.Count > 0)
{
IList<TreeNode> nodesCurrentLevel = new List<TreeNode>();
while (queue.Count > 0)
{
nodesCurrentLevel.Add(queue.Dequeue());
}
IList<int> currentLevelNum = new List<int>();
foreach (TreeNode treeNode in nodesCurrentLevel)
{
currentLevelNum.Add(treeNode.val);
if (treeNode.left != null)
{
queue.Enqueue(treeNode.left);
}
if (treeNode.right != null)
{
queue.Enqueue(treeNode.right);
}
}
result.Add(currentLevelNum);
}
return result;
}
public IList<int> InorderTraversal(TreeNode root)
{
List<int> result = new List<int>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode cur = root;
while (cur != null || stack.Count>0)
{
while (cur != null)
{
stack.Push(cur);
cur = cur.left;
}
cur = stack.Pop();
result.Add(cur.val);
cur = cur.right;
}
return result;
}
// 二叉树的锯齿形层次遍历
public IList<IList<int>> ZigzagLevelOrder(TreeNode root)
{
IList<IList<int>> result = new List<IList<int>>();
if (root == null)
{
return result;
}
bool movingRight = true;
Queue<TreeNode> queue = new Queue<TreeNode>();
queue.Enqueue(root);
while (queue.Count > 0)
{
List<TreeNode> nodeInCurLevel = new List<TreeNode>();
while (queue.Count > 0)
{
TreeNode curNode = queue.Dequeue();
nodeInCurLevel.Add(curNode);
}
if (movingRight)
{
result.Add(nodeInCurLevel.Select(a => a.val).ToList());
movingRight = false;
}
else
{
result.Add(nodeInCurLevel.Select(a=>a.val).Reverse().ToList());
movingRight = true;
}
for (int i = 0; i < nodeInCurLevel.Count; i++)
{
if (nodeInCurLevel[i].left != null)
{
queue.Enqueue(nodeInCurLevel[i].left);
}
if (nodeInCurLevel[i].right != null)
{
queue.Enqueue(nodeInCurLevel[i].right);
}
}
}
return result;
}
private Dictionary<int, int> map;
public TreeNode BuildTree(int[] preorder, int[] inorder)
{
int n = preorder.Length;
map = new Dictionary<int, int>();
for (int i = 0; i < n; i++)
{
map.Add(inorder[i],i);
}
return MyBuildTree(preorder, inorder, 0, n - 1, 0, n - 1);
}
public TreeNode MyBuildTree(int[] preorder, int[] inorder, int preorder_left, int preorder_right,
int inorder_left, int inorder_right)
{
if (preorder_left > preorder_right) {
return null;
}
int preorder_root = preorder_left;
int inorder_root = map[preorder[preorder_root]];
TreeNode root = new TreeNode(preorder[preorder_root]);
int size_left_subtree = inorder_root - inorder_left;
root.left = MyBuildTree(preorder, inorder, preorder_left + 1, preorder_left + size_left_subtree,
inorder_left, inorder_root - 1);
root.right = MyBuildTree(preorder, inorder, preorder_left + size_left_subtree + 1, preorder_right,
inorder_root + 1, inorder_right);
return root;
}
#region 填充每个节点的下一个右侧节点指针
public class Node
{
public int val;
public Node left;
public Node right;
public Node next;
}
public Node Connect(Node root) {
if (root == null)
{
return null;
}
Queue<Node> queue = new Queue<Node>();
queue.Enqueue(root);
while (queue.Count>0)
{
var nodeCurLvl = new List<Node>();
while (queue.Count > 0)
{
nodeCurLvl.Add(queue.Dequeue());
}
for (int i = 0; i < nodeCurLvl.Count; i++)
{
nodeCurLvl[i].next = i + 1 < nodeCurLvl.Count ? nodeCurLvl[i + 1] : null;
if (nodeCurLvl[i].left != null)
{
queue.Enqueue(nodeCurLvl[i].left);
}
if (nodeCurLvl[i].right != null)
{
queue.Enqueue(nodeCurLvl[i].right);
}
}
}
return root;
}
#endregion
#region 二叉搜索树中第k小的元素
public int KthSmallest(TreeNode root, int k)
{
for (int i = 0; i < k; i++)
{
TreeNode smallest = root;
TreeNode smallestParent = root;
while (smallest.left != null)
{
smallestParent = smallest;
smallest = smallest.left;
}
if (i == k - 1)
{
return smallest.val;
}
smallestParent.left = smallest.right;
}
return -1;
}
#endregion
#region 岛屿数量
private HashSet<(int, int)> landPoses;
/// <summary>
/// 给你一个由'1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。
/// 岛屿总是被水包围,并且每座岛屿只能由水平方向或竖直方向上相邻的陆地连接形成。
///
/// 此外,你可以假设该网格的四条边均被水包围。
///
/// 作者:力扣 (LeetCode)
/// 链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-medium/xvtsnm/
/// 来源:力扣(LeetCode)
/// 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
/// </summary>
/// <param name="grid"></param>
/// <returns></returns>
public int NumIslands(char[][] grid)
{
int landNum = 0;
landPoses = new HashSet<(int, int)>();
for (int i = 0; i < grid.Length; i++)
{
for (int j = 0; j < grid[0].Length; j++)
{
if (grid[i][j] == '1')
{
landPoses.Add((i, j));
}
}
}
while (landPoses.Count > 0)
{
foreach ((int, int) origin in landPoses)
{
RemoveLandByOrigin(grid, origin);
landNum++;
break;
}
}
return landNum;
}
private void RemoveLandByOrigin(char[][] grid, (int, int) origin)
{
landPoses.Remove(origin);
// Check Left
if (origin.Item2 - 1 >= 0)
{
if (landPoses.Contains((origin.Item1, origin.Item2-1)))
{
RemoveLandByOrigin(grid, (origin.Item1, origin.Item2-1));
}
}
// Check Right
if (origin.Item2 + 1 < grid[0].Length)
{
if (landPoses.Contains((origin.Item1, origin.Item2+1)))
{
RemoveLandByOrigin(grid, (origin.Item1, origin.Item2+1));
}
}
// Check Top
if (origin.Item1 - 1 >= 0)
{
if (landPoses.Contains((origin.Item1-1, origin.Item2)))
{
RemoveLandByOrigin(grid, (origin.Item1-1, origin.Item2));
}
}
// Check Bottom
if (origin.Item1 + 1 < grid.Length)
{
if (landPoses.Contains((origin.Item1+1, origin.Item2)))
{
RemoveLandByOrigin(grid, (origin.Item1+1, origin.Item2));
}
}
}
#endregion
}
}
|
4cb94acfcbc129bfb8428487ec7d69250261e4f5
|
C#
|
orangutanboy/Brainfuck-Interpreter
|
/BrainfuckInterpreter/Program.cs
| 2.984375
| 3
|
using System;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
namespace BrainfuckInterpreter
{
class Program
{
private static string _programInstructions;
[STAThread]
static void Main(string[] args)
{
Console.InputEncoding = new ASCIIEncoding();
Runner runner = new Runner();
//runner.LoadAndRun(ExamplePrograms.HelloWorld);
//runner.LoadAndRun(ExamplePrograms.LowerToUpper);
//runner.LoadAndRun(ExamplePrograms.Fibonacci);
//runner.LoadAndRun(ExamplePrograms.Rot13);
_programInstructions = ReadProgram();
runner.LoadAndRun(_programInstructions);
Console.WriteLine();
Console.WriteLine("Press any key to quit");
Console.ReadKey();
}
//Read a program from the command line, allow user to paste from clipboard
private static string ReadProgram()
{
Console.WriteLine("Enter program:");
var program = string.Empty;
do
{
var nextKey = Console.ReadKey(true);
if (nextKey.Key == ConsoleKey.V && nextKey.Modifiers == ConsoleModifiers.Control)
{
var clipBoardText = Clipboard.GetText();
Console.Write(clipBoardText);
program += clipBoardText;
}
else if (nextKey.Key == ConsoleKey.Enter)
{
Console.WriteLine();
break;
}
else
{
Console.Write(nextKey.KeyChar);
program += nextKey.KeyChar;
}
}
while (true);
return program;
}
internal static void ErrorOut(string p)
{
if (Debugger.IsAttached)
{
Debugger.Break();
}
Console.WriteLine(p);
Environment.Exit(-1);
Console.ReadLine();
}
}
}
|
810e67089fb36e8a551306837e351a5bce8e5510
|
C#
|
amandania/Senior-Project
|
/Server/Assets/Engine/Net/Packet/OutgoingPackets/SendMonsterSpawn.cs
| 2.640625
| 3
|
using DotNetty.Buffers;
using System;
using System.Text;
using UnityEngine;
/// <summary>
/// Anytime the server wants to spawn a monster it will send this packet to all clients.
/// <see cref="World.LoadMonsters"/> for call refrence
/// </summary>
public class SendMonsterSpawn : IOutGoingPackets
{
public OutGoingPackets PacketType => OutGoingPackets.SEND_MONSTER_SPAWN;
private readonly Npc m_npc;
public SendMonsterSpawn(Npc a_npc)
{
m_npc = a_npc;
}
/// <summary>
/// This function creates an array of bytes containing an id for the monster and the current position and rotation
/// </summary>
/// <returns>Buffer Message</returns>
public IByteBuffer GetPacket()
{
var buffer = Unpooled.Buffer();
String guid = m_npc.GetGuid().ToString();
int length = guid.Length;
buffer.WriteInt(length);
buffer.WriteString(guid, Encoding.Default);
string resourceName = m_npc.GetDefinition().ModelName;
buffer.WriteInt(resourceName.Length);
buffer.WriteString(resourceName, Encoding.Default);
Vector3 plrPos = m_npc.Position;
buffer.WriteFloat(plrPos.x);
buffer.WriteFloat(plrPos.y);
buffer.WriteFloat(plrPos.z);
Vector3 rotation = m_npc.Rotation;
buffer.WriteFloat(rotation.x);
buffer.WriteFloat(rotation.y);
buffer.WriteFloat(rotation.z);
//Debug.Log("Spawning other player with Session Id: {0}" + _player._Session.PlayerId);
return buffer;
}
}
|
187b39a3aab19bc4225600b90c5a2a066a8d76cb
|
C#
|
dingxinliang/TestHPYL
|
/Himall.Core/Helper/ObjectHelper.cs
| 2.734375
| 3
|
namespace Himall.Core.Helper
{
public static class ObjectHelper
{
/// <summary>
/// 深复制
/// </summary>
/// <param name="obj">待复制的对象</param>
/// <returns></returns>
public static object DeepColne(object obj)
{
var objJson = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
var objCopy = Newtonsoft.Json.JsonConvert.DeserializeObject(objJson);
return objCopy;
}
/// <summary>
/// 深复制
/// </summary>
/// <param name="obj">待复制的对象</param>
/// <returns></returns>
public static T DeepColne<T>(T t)
{
var objJson = Newtonsoft.Json.JsonConvert.SerializeObject(t);
var objCopy = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(objJson);
return objCopy;
}
}
}
|
d7765e3191b527fa3e90983b2dd9f8a4f3c8a6f5
|
C#
|
chenbojian/Axe.SimpleHttpMock
|
/src/Axe.SimpleHttpMock/IContentDeserializer.cs
| 2.515625
| 3
|
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace Axe.SimpleHttpMock
{
/// <summary>
/// Represents an HTTP content deserializer.
/// </summary>
public interface IContentDeserializer
{
/// <summary>
/// Deserialize http content to an object.
/// </summary>
/// <param name="content"><see cref="HttpContent"/> instance.</param>
/// <returns>A task with deserialized object.</returns>
[Obsolete("This method will be removed in the upcoming release. Please use DeserializeAsync<T>(HttpContent) instead.")]
Task<object> DeserializeAsync(HttpContent content);
/// <summary>
/// Deserialize http content to an object.
/// </summary>
/// <typeparam name="T">The type of the object.</typeparam>
/// <param name="content">The <see cref="HttpContent"/> instance.</param>
/// <returns>A task with deserialized object.</returns>
Task<T> DeserializeAsync<T>(HttpContent content);
/// <summary>
/// Deserialize http content to an object.
/// </summary>
/// <typeparam name="T">The type of the object.</typeparam>
/// <param name="content">The <see cref="HttpContent"/> instance.</param>
/// <param name="template">The template object.</param>
/// <returns>A task with deserialized object.</returns>
[Obsolete("This method will be removed in the upcoming release. Please use DeserializeAsync<T>(HttpContent) instead.")]
Task<T> DeserializeAsync<T>(HttpContent content, T template);
}
}
|
36dce0b77057769b89d6fc6a0856ef86f3ad16e1
|
C#
|
qipa/SOALog
|
/SOALog/FileAppender.cs
| 2.859375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Collections.Concurrent;
using System.Threading;
using System.IO;
namespace SOALog
{
class FileAppender : ICommonAppender
{
private static Stream _stream;
private int batchSize = 500;
private int flushInterval = 200;
private ConcurrentQueue<string> queue = new ConcurrentQueue<string>();
public ConcurrentQueue<string> Queue
{
get { return queue; }
}
static FileAppender()
{
string file = ConfigurationManager.AppSettings["SOALog.File.File"];
if (string.IsNullOrEmpty(file))
{
throw new LogException("缺少 SOALog.File.File 配置。 需要通过 SOALog.File.File 指定 Log 文件的 文件名 或者 相对路径 。");
}
file = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, file);
if (!File.Exists(file))
{
using(Stream s = File.Create(file))
{
}
}
_stream = File.Open(file, FileMode.Append, FileAccess.Write, FileShare.Read);
}
public void Start()
{
Thread thread = new Thread(Work);
thread.Start();
}
private void Work()
{
try
{
string msg;
while (true)
{
if (this.queue.Count == 0)
{
Thread.Sleep(this.flushInterval);
continue;
}
IList<string> list = new List<string>();
for (int i = 0; i < this.batchSize; i++)
{
if (this.queue.Count == 0)
break;
if (this.queue.TryDequeue(out msg))
{
list.Add(msg);
}
}
byte[] bytes;
foreach(string s in list)
{
bytes = Encoding.UTF8.GetBytes(s + "\r\n");
_stream.Write(bytes, 0, bytes.Length);
}
_stream.Flush();
}
}
finally
{
this.isValid = false;
}
}
private bool isValid = true;
public bool IsValid
{
get { return isValid; }
}
}
}
|
e540b239f7e3bba45475662a124458e61f7ebc9e
|
C#
|
mrskme/EdabitTest
|
/EdabitTest/Medium/FindTheBomb.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace EdabitTest.Medium
{
class FindTheBomb
{
public static string FindBomb(string sentence)
=> sentence.Contains("bomb") ? "Duck!!!" : "There is no bomb, relax.";
}
}
|
f81e52d32bddf979d2ddca2976f346997d85d063
|
C#
|
pushqrdx/Xamarine
|
/Xamarine/Xamarine/Hosting/Swan/Reflection/ExtendedTypeInfo.cs
| 2.90625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Xamarine.Hosting.Swan.Reflection
{
/// <summary>
/// Provides extended information about a type.
/// This class is mainly used to define sets of types within the Definition class
/// and it is not meant for other than querying the BasicTypesInfo dictionary.
/// </summary>
public class ExtendedTypeInfo
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ExtendedTypeInfo" /> class.
/// </summary>
/// <param name="t">The t.</param>
public ExtendedTypeInfo(Type t)
{
Type = t ?? throw new ArgumentNullException(nameof(t));
IsNullableValueType = Type.GetTypeInfo().IsGenericType && Type.GetGenericTypeDefinition() == typeof(Nullable<>);
IsValueType = t.GetTypeInfo().IsValueType;
UnderlyingType = IsNullableValueType ? new NullableConverter(Type).UnderlyingType : Type;
IsNumeric = NumericTypes.Contains(UnderlyingType);
// Extract the TryParse method info
try
{
TryParseMethodInfo = UnderlyingType.GetMethod(TryParseMethodName, new[] {typeof(string), typeof(NumberStyles), typeof(IFormatProvider), UnderlyingType.MakeByRefType()}) ??
UnderlyingType.GetMethod(TryParseMethodName, new[] {typeof(string), UnderlyingType.MakeByRefType()});
_tryParseParameters = TryParseMethodInfo?.GetParameters();
}
catch
{
// ignored
}
// Extract the ToString method Info
try
{
ToStringMethodInfo = UnderlyingType.GetMethod(ToStringMethodName, new[] {typeof(IFormatProvider)}) ?? UnderlyingType.GetMethod(ToStringMethodName, new Type[] { });
_toStringArgumentLength = ToStringMethodInfo?.GetParameters().Length ?? 0;
}
catch
{
// ignored
}
}
#endregion
#region Static Declarations
private const string TryParseMethodName = nameof(byte.TryParse);
private const string ToStringMethodName = nameof(ToString);
private static readonly Type[] NumericTypes = {typeof(byte), typeof(sbyte), typeof(decimal), typeof(double), typeof(float), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(short), typeof(ushort)};
#endregion
#region State Management
private readonly ParameterInfo[] _tryParseParameters;
private readonly int _toStringArgumentLength;
#endregion
#region Properties
/// <summary>
/// Gets the type this extended info class provides for.
/// </summary>
/// <value>
/// The type.
/// </value>
public Type Type { get; }
/// <summary>
/// Gets a value indicating whether the type is a nullable value type.
/// </summary>
/// <value>
/// <c>true</c> if this instance is nullable value type; otherwise, <c>false</c>.
/// </value>
public bool IsNullableValueType { get; }
/// <summary>
/// Gets a value indicating whether the type or underlying type is numeric.
/// </summary>
/// <value>
/// <c>true</c> if this instance is numeric; otherwise, <c>false</c>.
/// </value>
public bool IsNumeric { get; }
/// <summary>
/// Gets a value indicating whether the type is value type.
/// Nullable value types have this property set to False.
/// </summary>
public bool IsValueType { get; }
/// <summary>
/// When dealing with nullable value types, this property will
/// return the underlying value type of the nullable,
/// Otherwise it will return the same type as the Type property.
/// </summary>
/// <value>
/// The type of the underlying.
/// </value>
public Type UnderlyingType { get; }
/// <summary>
/// Gets the try parse method information. If the type does not contain
/// a suitable TryParse static method, it will return null.
/// </summary>
/// <value>
/// The try parse method information.
/// </value>
public MethodInfo TryParseMethodInfo { get; }
/// <summary>
/// Gets the ToString method info
/// It will prefer the overload containing the IFormatProvider argument.
/// </summary>
/// <value>
/// To string method information.
/// </value>
public MethodInfo ToStringMethodInfo { get; }
/// <summary>
/// Gets a value indicating whether the type contains a suitable TryParse method.
/// </summary>
/// <value>
/// <c>true</c> if this instance can parse natively; otherwise, <c>false</c>.
/// </value>
public bool CanParseNatively => TryParseMethodInfo != null;
#endregion
#region Methods
/// <summary>
/// Gets the default value of this type. For reference types it return null.
/// For value types it returns the default value.
/// </summary>
/// <returns>Default value of this type.</returns>
public object GetDefault()
{
return Type.GetTypeInfo().IsValueType ? Activator.CreateInstance(Type) : null;
}
/// <summary>
/// Tries to parse the string into an object of the type this instance represents.
/// Returns false when no suitable TryParse methods exists for the type or when parsing fails
/// for any reason. When possible, this method uses CultureInfo.InvariantCulture and NumberStyles.Any.
/// </summary>
/// <param name="s">The s.</param>
/// <param name="result">The result.</param>
/// <returns><c>true</c> if parse was converted successfully; otherwise, <c>false</c>.</returns>
public bool TryParse(string s, out object result)
{
result = GetDefault();
try
{
if (Type == typeof(string))
{
result = Convert.ChangeType(s, Type);
return true;
}
if (IsNullableValueType && string.IsNullOrEmpty(s))
{
result = GetDefault();
return true;
}
if (CanParseNatively == false)
{
result = GetDefault();
return false;
}
// Build the arguments of the TryParse method
var dynamicArguments = new List<object> {s};
for (var pi = 1; pi < _tryParseParameters.Length - 1; pi++)
{
var argInfo = _tryParseParameters[pi];
if (argInfo.ParameterType == typeof(IFormatProvider))
dynamicArguments.Add(CultureInfo.InvariantCulture);
else if (argInfo.ParameterType == typeof(NumberStyles))
dynamicArguments.Add(NumberStyles.Any);
else
dynamicArguments.Add(null);
}
dynamicArguments.Add(null);
var parseArguments = dynamicArguments.ToArray();
if ((bool) TryParseMethodInfo.Invoke(null, parseArguments) == false)
{
result = GetDefault();
return false;
}
result = parseArguments[parseArguments.Length - 1];
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Converts this instance to its string representation,
/// trying to use the CultureInfo.InvariantCulture
/// IFormat provider if the overload is available.
/// </summary>
/// <param name="instance">The instance.</param>
/// <returns>A <see cref="System.String" /> that represents the current object.</returns>
public string ToStringInvariant(object instance)
{
if (instance == null)
return string.Empty;
return _toStringArgumentLength != 1 ? instance.ToString() : ToStringMethodInfo.Invoke(instance, new object[] {CultureInfo.InvariantCulture}) as string;
}
#endregion
}
/// <summary>
/// Provides extended information about a type.
/// This class is mainly used to define sets of types within the Constants class
/// and it is not meant for other than querying the BasicTypesInfo dictionary.
/// </summary>
/// <typeparam name="T">The type of extended type infomation.</typeparam>
public class ExtendedTypeInfo<T> : ExtendedTypeInfo
{
/// <summary>
/// Initializes a new instance of the <see cref="ExtendedTypeInfo{T}" /> class.
/// </summary>
public ExtendedTypeInfo()
: base(typeof(T))
{
// placeholder
}
/// <summary>
/// Converts this instance to its string representation,
/// trying to use the CultureInfo.InvariantCulture
/// IFormat provider if the overload is available.
/// </summary>
/// <param name="instance">The instance.</param>
/// <returns>A <see cref="System.String" /> that represents the current object.</returns>
public string ToStringInvariant(T instance)
{
return base.ToStringInvariant(instance);
}
}
}
|
444ef1791d69c9ef62c7dbff1a8b43124b06275c
|
C#
|
TikTikys/Tasks
|
/10 - 2 - TaskEquals .Net Core/TaskEquals/EqualsOrGetHashCode.cs
| 3.734375
| 4
|
using System;
namespace TaskEquals
{
class EqualsOrGetHashCode
{
public static void Main()
{
Console.WriteLine("\nЗадача: Реализовать свой класс Person(ФИО, Дата рождения, Место рождения, Номер паспорта), переопределить в нём методы. GetHashCode и Equals\n");
// Создаем объекты для последующего сравнения.
Person vladimir = new Person("Пименов Владимир", new DateTime(1994, 8, 19), "Тирасполь", 6329);
Person andrei = new Person("Пименов Андрей", new DateTime(2000, 12, 14), "Тирасполь", 6699);
Person valadimirClone = new Person("Пименов Владимир", new DateTime(1994, 8, 19), "Тирасполь", 6329);
Person andreiReference = andrei;
// Используем для сравнения объектов переопределенный метод Equals()
Console.WriteLine("Equals:");
{
Console.WriteLine($"Сравнение двух разных объеков с попомощью метода Equals: vladimir | andrei");
vladimir.ToPrint(andrei);
Console.WriteLine($"Result = {vladimir.Equals(andrei)}\n");
Console.WriteLine($"Сравнение двух одинаковых объеков с попомощью метода Equals: vladimir | valadimirClone");
vladimir.ToPrint(valadimirClone);
Console.WriteLine($"Result = {vladimir.Equals(valadimirClone)}\n");
Console.WriteLine($"Сравнение двух ссылок на один объект с попомощью метода Equals: andrei | andreiReference");
andrei.ToPrint(andreiReference);
Console.WriteLine($"Result = {andrei.Equals(andreiReference)}\n");
}
// Используем для сравнения объектов переопределенный метод GetHashCode
Console.WriteLine("\n\n\nGetHashCode:");
{
Console.WriteLine($"Сравнение двух разных объеков с попомощью метода GetHashCode: vladimir | andrei");
vladimir.ToPrint(andrei);
Console.WriteLine($"Result: {vladimir.GetHashCode()} == {andrei.GetHashCode()} = {vladimir.GetHashCode() == andrei.GetHashCode()}\n");
Console.WriteLine($"Сравнение двух одинаковых объеков с попомощью метода GetHashCode: vladimir | valadimirClone");
vladimir.ToPrint(valadimirClone);
Console.WriteLine($"Result: {vladimir.GetHashCode()} == {valadimirClone.GetHashCode()} = {vladimir.GetHashCode() == valadimirClone.GetHashCode()}\n");
Console.WriteLine($"Сравнение двух ссылок на один объект с попомощью метода GetHashCode: andrei | andreiReference");
andrei.ToPrint(andreiReference);
Console.WriteLine($"Result: {andrei.GetHashCode()} == {andreiReference.GetHashCode()} = {andrei.GetHashCode() == andreiReference.GetHashCode()}\n");
}
Console.WriteLine("\nКонец задачи.\n");
Console.ReadKey();
}
}
}
|
a61e95f62b3ea624bdba30decc272bdb13bc8c22
|
C#
|
webgzf/RX-Explorer
|
/RX_Explorer/Class/IncrementalLoadingCollection.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Storage.Search;
using Windows.UI.Xaml.Data;
namespace RX_Explorer.Class
{
/// <summary>
/// 提供增量加载集合的实现
/// </summary>
/// <typeparam name="T">集合内容的类型</typeparam>
public sealed class IncrementalLoadingCollection<T> : ObservableCollection<T>, ISupportIncrementalLoading
{
public StorageItemQueryResult ItemQuery { get; private set; }
public StorageFolderQueryResult FolderQuery { get; private set; }
private uint CurrentIndex;
private Func<uint, uint, StorageItemQueryResult, Task<IEnumerable<T>>> MoreItemsNeed;
private Func<uint, uint, StorageFolderQueryResult, Task<IEnumerable<T>>> MoreFolderNeed;
private uint MaxNum;
/// <summary>
/// 初始化IncrementalLoadingCollection
/// </summary>
/// <param name="MoreItemsNeed">提供需要加载更多数据时能够调用的委托</param>
public IncrementalLoadingCollection(Func<uint, uint, StorageItemQueryResult, Task<IEnumerable<T>>> MoreItemsNeed)
{
this.MoreItemsNeed = MoreItemsNeed;
}
public IncrementalLoadingCollection(Func<uint, uint, StorageFolderQueryResult, Task<IEnumerable<T>>> MoreFolderNeed)
{
this.MoreFolderNeed = MoreFolderNeed;
}
public async Task SetStorageQueryResultAsync(StorageItemQueryResult InputQuery)
{
if (InputQuery == null)
{
throw new ArgumentNullException(nameof(InputQuery), "Parameter could not be null");
}
ItemQuery = InputQuery;
MaxNum = await ItemQuery.GetItemCountAsync();
CurrentIndex = MaxNum > 100 ? 100 : MaxNum;
if (MaxNum > 100)
{
HasMoreItems = true;
}
}
public async Task SetStorageQueryResultAsync(StorageFolderQueryResult InputQuery)
{
if (InputQuery == null)
{
throw new ArgumentNullException(nameof(InputQuery), "Parameter could not be null");
}
FolderQuery = InputQuery;
MaxNum = await FolderQuery.GetItemCountAsync();
CurrentIndex = MaxNum > 20 ? 20 : MaxNum;
if (MaxNum > 20)
{
HasMoreItems = true;
}
}
public IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
{
return AsyncInfo.Run(async (c) =>
{
if (CurrentIndex + count >= MaxNum)
{
uint ItemNeedNum = MaxNum - CurrentIndex;
if (ItemNeedNum == 0)
{
HasMoreItems = false;
return new LoadMoreItemsResult { Count = 0 };
}
else
{
IEnumerable<T> Result;
if (MoreItemsNeed == null)
{
Result = await MoreFolderNeed(CurrentIndex, ItemNeedNum, FolderQuery).ConfigureAwait(true);
}
else
{
Result = await MoreItemsNeed(CurrentIndex, ItemNeedNum, ItemQuery).ConfigureAwait(true);
}
for (int i = 0; i < Result.Count() && HasMoreItems; i++)
{
Add(Result.ElementAt(i));
}
CurrentIndex = MaxNum;
HasMoreItems = false;
return new LoadMoreItemsResult { Count = ItemNeedNum };
}
}
else
{
IEnumerable<T> Result;
if (MoreItemsNeed == null)
{
Result = await MoreFolderNeed(CurrentIndex, count, FolderQuery).ConfigureAwait(true);
}
else
{
Result = await MoreItemsNeed(CurrentIndex, count, ItemQuery).ConfigureAwait(true);
}
for (int i = 0; i < Result.Count() && HasMoreItems; i++)
{
Add(Result.ElementAt(i));
}
CurrentIndex += count;
HasMoreItems = true;
return new LoadMoreItemsResult { Count = count };
}
});
}
public bool HasMoreItems { get; set; }
}
}
|
4f591f435c361b25e5cab95c3356dfadbc02781c
|
C#
|
n1kr0/ADO_NET
|
/ADO_NET_user photo/PersonalsApp/Helpers/CompressImage.cs
| 3.21875
| 3
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PersonalsApp.Helpers
{
public static class CompressImage
{
public static Bitmap CreateImage(Bitmap originalPic, int maxWidth, int maxHeight)
{
try
{
//Розмір старого зображення
int width = originalPic.Width;
int height = originalPic.Height;
//Обчислюємо розмір нового зображення
int widthDiff = (width - maxWidth);
int heightDiff = (height - maxHeight);
//Ширину будемо залишати, міняємо висоту
bool doWidthResize = (maxWidth > 0 && width > maxWidth && widthDiff > -1 && widthDiff > heightDiff);
//Висоту залишаємо, міняємо ширину
bool doHeightResize = (maxHeight > 0 && height > maxHeight && heightDiff > -1 && heightDiff > widthDiff);
//Обчисленя розміру
if (doWidthResize || doHeightResize || (width.Equals(height)
&& widthDiff.Equals(heightDiff)))
{
int iStart;
Decimal divider;
if (doWidthResize)
{
iStart = width;
divider = Math.Abs((Decimal)iStart / maxWidth);
width = maxWidth;
height = (int)Math.Round((height / divider));
}
else
{
iStart = height;
divider = Math.Abs((Decimal)iStart / maxHeight);
height = maxHeight;
width = (int)Math.Round((width / divider));
}
}
using (Bitmap outBmp = new Bitmap(width, height, PixelFormat.Format16bppRgb555))
{
using (Graphics oGraphics = Graphics.FromImage(outBmp))
{
oGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
oGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
oGraphics.DrawImage(originalPic, 0, 0, width, height);
return new Bitmap(outBmp);
}
}
}
catch
{
return null;
}
}
}
}
|
fdb4151b85ad67baab53d23b91ed9897b87d8e69
|
C#
|
byrkalukasz/Testy_Automatyczne_Praca
|
/Functions/Autentyfication.cs
| 2.625
| 3
|
using System;
using System.IO;
namespace Eskok_autoTest
{
class Autentyfication
{
public string GetSmsPassword()
{
string tekst, SMSCode = "";
int index;
if (File.Exists("D:\\kopia.txt"))
{
File.Delete("D:\\kopia.txt");
}
File.Copy("C:\\apache-tomcat-6.0.53\\logs\\tomcat6-stdout.2019-11-29.log", "D:\\kopia.txt");
FileStream test = new FileStream("D:\\kopia.txt", FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(test);
while ((tekst = reader.ReadLine()) != null)
{
index = tekst.LastIndexOf("SMS:");
if (index >= 0)
{
SMSCode = tekst.Substring(index + 4);
}
}
return SMSCode;
}
public string ValidUserLoginSelect()
{
string[] ValidUserLoginTable = { "0655175779" };
string ValidUserLogin;
int UserNumber;
Random UserRandom = new Random();
UserNumber = UserRandom.Next(ValidUserLoginTable.Length);
ValidUserLogin = ValidUserLoginTable[UserNumber];
return ValidUserLogin;
}
public string InvalidUserLoginSelect()
{
string[] InvalidUserLoginTable = { "0425385987", "065" };
string InvalidUserLogin;
int UserNumber;
Random UserRandom = new Random();
UserNumber = UserRandom.Next(InvalidUserLoginTable.Length);
InvalidUserLogin = InvalidUserLoginTable[UserNumber];
return InvalidUserLogin;
}
}
}
|
61bc4b4cb7c5a40d7a241a5e867d241f65be42a5
|
C#
|
nizamializadeh/Hospital-Console
|
/Hospital/Hospital/hekimler.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hospital
{
class hekimler
{
public hekimler()
{
List<string> hekimler = new List<string>();
hekimler.Add("1.Dr. Oktay samilov");
hekimler.Add("2.T.e.n. Dr. Vusal Eyvazov");
hekimler.Add("3.Dr. Elxan Besirov");
foreach (string i in hekimler)
{
Console.WriteLine(i);
}
}
}
}
|
944a005b85c84db97358ebb9b4977d3b4600a39f
|
C#
|
AndreyBespamyatnov/Joyenjoy.me
|
/src/PhotoBooth.Service/Tasks/PrintTask.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using NLog;
using PhotoBooth.Models;
using PhotoBooth.Service.Helpers;
namespace PhotoBooth.Service.Tasks
{
public class PrintTask
{
static readonly Logger PrintTaskLogger = LogManager.GetLogger("PrintTaskLogger");
internal static async Task Do(CancellationToken token, int delaySeconds)
{
if (!Directory.Exists("PrintQueue"))
{
Directory.CreateDirectory("PrintQueue");
}
while (!token.IsCancellationRequested)
{
try
{
List<PrintQueue> currentBoothPrintPhotos = ContextHelper.Instance.GetCurrentBoothPrintPhotos();
if (currentBoothPrintPhotos != null && currentBoothPrintPhotos.Count > 0)
{
foreach (var currentPhotoBoothPrintElement in currentBoothPrintPhotos)
{
string localPath = String.Empty;
string blobUrl = currentPhotoBoothPrintElement.BlobPathToImage;
string guidRegex = "(.{8}-.{4}-.{4}-.{4}-.{12})";
string eventId = Regex.Matches(blobUrl, guidRegex)[0].Value;
string fileName = Path.GetFileName(blobUrl);
localPath = Path.Combine("PrintQueue", Path.GetFileName(blobUrl));
BlobHelper.Instance.DownloadPhotoFromBlob(eventId, fileName, localPath);
FilesHelper.Instance.PrintFile(localPath);
ContextHelper.Instance.RemovePrintQueueElement(currentPhotoBoothPrintElement);
FilesHelper.Instance.WaitForFile(localPath);
File.Delete(localPath); //only if print successfull and file printed
PrintTaskLogger.Info("File {0} printed", localPath);
}
}
else
{
PrintTaskLogger.Info("No photos to print");
}
}
catch (Exception ex)
{
PrintTaskLogger.Error(ex);
}
await Task.Delay(TimeSpan.FromSeconds(delaySeconds), token);
}
}
}
}
|
0f05f7f9c8cb9fe1e8f7dff40f591e5b5087ce2d
|
C#
|
hotn/Vagrant-Tray
|
/VagrantTray/Model/VagrantInstance.cs
| 2.640625
| 3
|
using System;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
using MikeWaltonWeb.VagrantTray.Business.VagrantExe.Processes;
namespace MikeWaltonWeb.VagrantTray.Model
{
[Serializable]
[XmlRoot(IsNullable = false)]
public class VagrantInstance : ICloneable<VagrantInstance>
{
private State _currentState;
[NonSerialized]
private VagrantProcess _currentProcess;
[field:NonSerialized]
public event EventHandler StateChanged;
[XmlIgnore]
public State CurrentState
{
get { return _currentState; }
set
{
_currentState = value;
if (StateChanged != null)
{
StateChanged(this, EventArgs.Empty);
}
}
}
[XmlIgnore]
public string CurrentStateString
{
get
{
return Regex.Replace(CurrentState.ToString(), "([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))", "$1 ");
}
}
[XmlElement]
public string Directory { get; set; }
public VagrantProcess CurrentProcess
{
get { return _currentProcess; }
set { _currentProcess = value; }
}
public enum State
{
Unknown,
Running,
Saved,
Poweroff,
Loading,
NotCreated
}
public VagrantInstance Clone()
{
return new VagrantInstance {CurrentState = CurrentState, Directory = Directory, CurrentProcess = CurrentProcess};
}
public override bool Equals(object obj)
{
if (!(obj.GetType() == GetType()))
{
return false;
}
return Directory == ((VagrantInstance) obj).Directory;
}
public override int GetHashCode()
{
return Directory.GetHashCode();
}
}
}
|
1afdb3fa53dee933626813f70f2dbdf3f30d45f7
|
C#
|
sandeepshakya/Inventory
|
/Inventory/Model/Models/Mapping/ProductLocationMap.cs
| 2.65625
| 3
|
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
namespace Model.Models.Mapping
{
public class ProductLocationMap : EntityTypeConfiguration<ProductLocation>
{
public ProductLocationMap()
{
// Primary Key
this.HasKey(t => t.Id);
// Properties
// Table & Column Mappings
this.ToTable("ProductLocations");
this.Property(t => t.Id).HasColumnName("Id");
this.Property(t => t.Locaton).HasColumnName("Locaton");
}
}
}
|
033517ce60ddfca4b9b544195e0c7b1290a2efe0
|
C#
|
Zaikao/TCC-TKP
|
/Controle.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TrabalhoConclusaoCurso.DAO;
namespace TrabalhoConclusaoCurso.Modelo
{
public class Controle
{
public bool tem;
public String mensagem = "";
public bool acessar (String login, String senha)
{
LoginDao loginComando = new LoginDao();
tem = loginComando.verificarLogin(login, senha);
if (!loginComando.mensagem.Equals(""))
{
this.mensagem = loginComando.mensagem;
}
return tem;
}
public String cadastrar (String email, String senha, String nome, String idade, String confimarSenha)
{
return mensagem;
}
}
}
|
e5351be55f134049ae6654320e28c7e4eed72181
|
C#
|
desairavi1101/Train-Application
|
/TrainApplicationLibrary/Classes/Reservation.cs
| 3.15625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TrainApplicationLibrary.Classes
{
public class Reservation : IReservation
{
private static int NextTrainId = 1;
private static int NextTicketNo = 1;
private List<ITrain> Trains;
private List<ITicket> Tickets;
public int AddTrain(ITrain train)
{
int id = NextTrainId++;
Train t = train as Train;
Trains.Add(t);
t.Id = id;
return id;
}
public List<ITrain> ViewTrains(string source,string destination) {
var trains = from t in Trains.OfType<Train>()
where t.Source == source && t.Destination == destination
select t;
return trains.OfType<ITrain>().ToList();
}
public int SearchTrains(string source, string destination, int noOfPassenger)
{
var trains = from t in Trains.OfType<Train>()
where t.Source == source && t.Destination == destination
select t;
foreach (Train t in trains)
{
var train = (from ticket in Tickets.OfType<Ticket>()
where ticket.TrainId == t.Id
group ticket by ticket.TrainId into g
select new {TrainId = g.Key , RemainingSeates = 200 - g.Sum(ta => ta.NoOfPassenger) }).FirstOrDefault();
if (train.RemainingSeates >= noOfPassenger)
{
return train.TrainId;
}
}
return 0;
}
public int DeleteTrain(int trainId)
{
var ticket = (from t in Tickets.OfType<Ticket>()
where t.TrainId == trainId
select t).FirstOrDefault();
if (ticket == default(Ticket))
{
return 0;
}
Trains.OfType<Train>().ToList().RemoveAll(t => t.Id == trainId);
return 1;
}
public List<ITicket> ViewAllBookedTickets()
{
return Tickets;
}
public int BookTicket(int noOfPassenger, int trainId, out int totalPrice)
{
if (trainId == 0)
{
totalPrice = 0;
return 0;
}
int ticketNo = NextTicketNo++;
ITicket ticket = new Ticket()
{
TicketNo = ticketNo,
TrainId = trainId,
NoOfPassenger = noOfPassenger
};
Tickets.Add(ticket);
totalPrice = 200 * noOfPassenger;
return ticketNo;
}
public int EditTrain(int trainId, string source, string destination)
{
var train = (from t in Trains.OfType<Train>()
where t.Id == trainId
select t).FirstOrDefault();
if (train == default(Train))
{
return 0 ;
}
train.Source = source;
train.Destination = destination;
return 1;
}
public int EditTrain(int trainId, string name, string source, string destination)
{
var train = (from t in Trains.OfType<Train>()
where t.Id == trainId
select t).FirstOrDefault();
if (train == default(Train))
{
return 0;
}
train.Source = source;
train.Destination = destination;
train.Name = name;
return 1;
}
}
}
|
36b02edc4e57abb07fd465222721ea194c5aa825
|
C#
|
karthik-palchamy/MeatWallet
|
/Core/Specifications/BaseSpecification.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
namespace Core.Specifications
{
public class BaseSpecification<T> : ISpecification<T>
{
public BaseSpecification()
{
}
//Func<T, bool>---> represents a function that takes an object of type T and returns a bool.
// It's commonly referred to as a "predicate", and is used to verify a condition on an object.
public BaseSpecification(Expression<Func<T, bool>> criteria)
{
Criteria = criteria;
}
public Expression<Func<T, bool>> Criteria { get; }
public List<Expression<Func<T, object>>> Includes {get; } = new List<Expression<Func<T, object>>>();
protected void AddInclude(Expression<Func<T, object>> includeExpression){
Includes.Add(includeExpression);
}
}
}
|
ff7025bd0cbb7631ab2a7db56c44a054afd0d96c
|
C#
|
NakovaJ/C-HomeWork
|
/HeroesJourney/HeroesJoyrneyApp/HeroesJoyrneyApp/HeroesJoyrneyEntities/HeroesJourneyModels/Player.cs
| 3.078125
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace HeroesJoyrneyApp.HeroesJoyrneyEntities.HeroesJourneyModels
{
public class Player
{
public string Email { get; set; }
public string Password { get; set; }
public string Name { get; set; }
public string Race { get; set; }
public string Type { get; set; }
public int Health { get; set; }
public int Strength { get; set; }
public int Agility { get; set; }
public Player()
{
}
public Player(string email, string password,string name)
{
Email = email;
Password = password;
Name = name;
Race = "";
Health = 0;
Strength = 0;
Agility = 0;
}
public void CreateDwarf()
{
Health += 100;
Strength += 6;
Agility += 2;
Race = "Dwarf";
}
public void CreateElf()
{
Health += 60;
Strength += 4;
Agility += 6;
Race = "Elf";
}
public void CreateHuman()
{
Health += 80;
Strength += 5;
Agility += 4;
Race = "Human";
}
public void BecomeWarrior()
{
Health += 20;
Agility -= 1;
Type = "Warrior";
}
public void BecomeRogue()
{
Health -= 20;
Agility += 1;
Type = "Rogue";
}
public void BecomeMage()
{
Health += 20;
Strength -= 1;
Type = "Mage";
}
public void PrintInfo()
{
Console.WriteLine($"{Name} ({Race}) the {Type}");
Console.WriteLine($"Health:{Health}, Strength:{Strength}, Agility: {Agility}");
}
}
}
|
7997f1ecb65b1d6f35b29a3aa19ef40f0000df2c
|
C#
|
marcsicr/littlewizard
|
/littlewizard/Assets/Scripts/SceneObjs/ItemContainer.cs
| 2.515625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class ItemContainer : MonoBehaviour{
public AudioClip openClip;
public static string TAG = "ItemContainer";
protected Animator myAnimator;
public Item[] throwItems;
private void Awake() {
myAnimator = GetComponent<Animator>();
}
public abstract void open();
public abstract Vector3 getThrowPoint();
public void throwLoot() {
SoundManager.Instance.playEffect(openClip);
StartCoroutine(throwLootCo(throwItems));
}
protected IEnumerator throwLootCo(Item[] throwItems) {
foreach (Item throwItem in throwItems) {
Vector2 end = getThrowPoint() + Random.insideUnitSphere;
StartCoroutine(throwItemCo(throwItem,end));
yield return new WaitForSeconds(0.1f);
}
}
private IEnumerator throwItemCo(Item throwItem,Vector2 throwPosition) {
Vector2 start = transform.position;
Vector2 end = throwPosition;
Vector2 middle = Bezier.computeElipticalP1(start, end);
Item itemInstance = GameObject.Instantiate(throwItem, transform.position, Quaternion.identity).GetComponent<Item>();
itemInstance.setCollectable(false);
for (float t = 0; t <= 1; t += 0.05f) {
itemInstance.transform.position = Bezier.quadraticBezierPoint(t, start, middle, end);
yield return new WaitForEndOfFrame();
}
itemInstance.setCollectable(true);
}
}
|
a181674714480e57f0c0d214e7c6dcae73048773
|
C#
|
SaturnEclipseUK/DATEXIIToolkitCS
|
/DATEXIIToolkit/Models/EventDataStore.cs
| 2.796875
| 3
|
using DATEXIIToolkit.Models.DataObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DATEXIIToolkit.Models
{
/// <summary>
/// This data store contains the Event data indexed by event ID.
/// </summary>
public class EventDataStore : DataStore
{
public EventDataStore() : base()
{
}
public override void updateData(DataObject data)
{
lock (this)
{
EventData eventData = (EventData)data;
String eventIdentifier = eventData.getEventIdentifier();
if (dataMap.ContainsKey(eventIdentifier))
{
dataMap.Remove(eventIdentifier);
dataMap.Add(eventIdentifier, eventData);
}
else {
dataMap.Add(eventIdentifier, eventData);
}
}
}
public LinkedList<EventData> getAllEventData()
{
lock (this)
{
LinkedList<EventData> returnDataObjectsList = new LinkedList<EventData>();
IList<DataObject> dataObjectList = new List<DataObject>(dataMap.Values.ToList());
foreach (EventData dataObject in dataObjectList)
{
returnDataObjectsList.AddLast(dataObject);
}
return returnDataObjectsList;
}
}
public override void removeData(String eventIdentifier)
{
lock (this)
{
if (dataMap.ContainsKey(eventIdentifier))
{
dataMap.Remove(eventIdentifier);
}
}
}
}
}
|
ba3cf2b5e3297dd9633a5cda5c0539cfab8b336d
|
C#
|
kns98/LL
|
/lltree/Program.cs
| 3.03125
| 3
|
using System;
using System.IO;
using System.Reflection;
namespace LL
{
class Program
{
static void _PrintUsage()
{
var name = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().GetModules()[0].Name);
Console.Error.WriteLine("Usage: {0} <grammarfile> <inputfile>", name);
Console.Error.WriteLine();
Console.Error.WriteLine(" <grammarfile>\tThe grammar file to use");
Console.Error.WriteLine(" <inputfile>\tThe file to parse");
}
/// <summary>
/// Usage: lltree $grammarfile $inputfile
/// </summary>
/// <param name="args">The grammar file and the input file to parse</param>
/// <returns></returns>
static int Main(string[] args)
{
if (2!=args.Length)
{
_PrintUsage();
return 1;
}
// read the ebnf document from the file.
var ebnf = EbnfDocument.ReadFrom(args[0]);
var hasErrors = false;
// here we validate the document and print any
// validation errors to the console.
foreach (var msg in ebnf.Validate(false))
{
if (EbnfErrorLevel.Error == msg.ErrorLevel)
{
hasErrors = true;
Console.Error.WriteLine(msg);
}
}
foreach (var msg in ebnf.Prepare(false))
{
if (EbnfErrorLevel.Error == msg.ErrorLevel)
{
hasErrors = true;
Console.Error.WriteLine(msg);
}
}
// even if we have errors, we keep going.
// create a CFG from the EBNF document
var cfg = ebnf.ToCfg();
// we have to prepare a CFG to be parsable by an LL(1)
// parser. This means removing left recursion, and
// factoring out first-first and first-follows conflicts
// where possible.
// here we do that, and print any errors we encounter.
foreach(var msg in cfg.PrepareLL1(false))
{
if(CfgErrorLevel.Error==msg.ErrorLevel)
{
hasErrors = true;
Console.Error.WriteLine(msg);
}
}
// if we don't have errors let's set up our parse.
if(!hasErrors)
{
// the tokenizer is created from the EBNF document becase
// it has the terminal definitions, unlike the CFG,
// see https://www.codeproject.com/Articles/5162249/How-to-Make-an-LL-1-Parser-Lesson-1
// The FileReaderEnumerable takes a filename and exposes IEnumerable<char> from
// them. Tokenizers expect IEnumerable<char> (typically a string or char array)
var tokenizer = ebnf.ToTokenizer(cfg, new FileReaderEnumerable(args[1]));
// now create our parser. and since the parser *might* return multiple parse trees
// in some cases, we keep reading until the end of document, calling ParseSubtree()
// each time to get the result back as a ParseNode tree. We then take those nodes and
// write them to the console via an implicit call to their ToString method
using (var parser = cfg.ToLL1Parser(tokenizer))
while (ParserNodeType.EndDocument != parser.NodeType)
Console.WriteLine(parser.ParseSubtree());
return 0;
}
return 1;
}
}
}
|
68c7f699824fbecd9a67c56aa955287ca4c35a53
|
C#
|
thelinuxlich/artemis_CSharp
|
/Artemis_XNA_INDEPENDENT/Utils/BagEnumerator.cs
| 2.5625
| 3
|
#region File description
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BagEnumerator.cs" company="GAMADU.COM">
// Copyright 2013 GAMADU.COM. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY GAMADU.COM 'AS IS' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GAMADU.COM OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those of the
// authors and should not be interpreted as representing official policies, either expressed
// or implied, of GAMADU.COM.
// </copyright>
// <summary>
// Class BagEnumerator.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
#endregion File description
namespace Artemis.Utils
{
#region Using statements
using global::System.Collections;
using global::System.Collections.Generic;
#endregion Using statements
/// <summary>Class BagEnumerator.</summary>
/// <typeparam name="T">The <see langword="Type"/> T.</typeparam>
internal class BagEnumerator<T> : IEnumerator<T>
{
/// <summary>The bag.</summary>
private volatile Bag<T> bag;
/// <summary>The index.</summary>
private volatile int index;
/// <summary>Initializes a new instance of the <see cref="BagEnumerator{T}"/> class.</summary>
/// <param name="bag">The bag.</param>
public BagEnumerator(Bag<T> bag)
{
this.bag = bag;
this.Reset();
}
/// <summary>Gets the current element in the collection.</summary>
/// <value>The current element.</value>
/// <returns>The current element in the collection.</returns>
T IEnumerator<T>.Current
{
get
{
return this.bag.Get(this.index);
}
}
/// <summary>Gets the current element in the collection.</summary>
/// <value>The current.</value>
/// <returns>The current element in the collection.</returns>
object IEnumerator.Current
{
get
{
return this.bag.Get(this.index);
}
}
/// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
public void Dispose()
{
this.bag = null;
}
/// <summary>Advances the enumerator to the next element of the collection.</summary>
/// <returns>true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.</returns>
public bool MoveNext()
{
return ++this.index < this.bag.Count;
}
/// <summary>Sets the enumerator to its initial position, which is before the first element in the collection.</summary>
public void Reset()
{
this.index = -1;
}
}
}
|
b69395a117c97e146142776d616dcd1e605ff213
|
C#
|
OpenDDRmobi/openddr-csharp
|
/simple/DDR-Simple-API/Exceptions/ValueException.cs
| 2.59375
| 3
|
/**
* Copyright (c) 2011-2017 OpenDDR LLC and others. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace W3c.Ddr.Exceptions
{
/// <summary>
/// This is a subclass of DDRException and is thrown when an error is detected during an attempt to retrieve the value of a Property using one of the value accessor methods of the PropertyValue class. The exception code indicates the nature of the error.
/// </summary>
public class ValueException : DDRException
{
/// <summary>
/// The value represented by the PropertyValue is incompatible with the return type of the method used to retrieve it.
/// </summary>
public static int INCOMPATIBLE_TYPES = 600;
/// <summary>
/// The property value is unknown.
/// </summary>
public static int NOT_KNOWN = 900;
/// <summary>
/// The implementation is aware of multiple values for this Property.
/// </summary>
public static int MULTIPLE_VALUES = 10000;
public ValueException()
: base()
{
}
public ValueException(int code, String message)
: base(code, message)
{
}
public ValueException(int code, Exception ex)
: base(code, ex)
{
}
}
}
|
b37aa3b8dbbee9ac5a973e4caec0a654d16c4598
|
C#
|
JamzZz/Terramon-Source-Code
|
/Razorwing.Framework/Bindables/NonNullableBindable.cs
| 2.65625
| 3
|
using System;
using Razorwing.Framework.Configuration;
namespace Razorwing.Framework.Bindables
{
public class NonNullableBindable<T> : Bindable<T>
where T : class
{
public NonNullableBindable(T defaultValue)
{
if (defaultValue == null)
throw new ArgumentNullException(nameof(defaultValue));
Value = Default = defaultValue;
}
public override T Value
{
get => base.Value;
set
{
if (value == null)
throw new ArgumentNullException(nameof(Value), $"Cannot set {nameof(Value)} of a {nameof(NonNullableBindable<T>)} to null.");
base.Value = value;
}
}
}
}
|
5eec43c21ce61a8497d5e80ced4205c9f3d1132a
|
C#
|
EricFreeman/TopDownShooter
|
/Assets/Scripts/Particles/BloodPool.cs
| 2.65625
| 3
|
using UnityEngine;
namespace Assets.Scripts.Particles
{
[RequireComponent(typeof(SpriteRenderer))]
public class BloodPool : MonoBehaviour
{
public float Speed = 3f;
private Color _color;
private Vector3 _spread;
public void Setup(Vector3 spread, Color color)
{
_color = color;
_spread = spread;
}
void Start()
{
var spriteRenderer = GetComponent<SpriteRenderer>();
spriteRenderer.color = _color;
}
void Update ()
{
transform.position = Vector3.MoveTowards(transform.position, _spread, Speed * Time.deltaTime);
if(transform.position == _spread)
Destroy(this);
}
}
}
|
e9ba7abfc48bc6c09d1189fdf261bb99098f41ca
|
C#
|
jspencersharpe/Gass-E
|
/GassE/Model/Event.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.ComponentModel;
using System.Text;
using System.Threading.Tasks;
namespace GassE.Model
{
public class Event : INotifyPropertyChanged
{
public int EventId { get; set; }
public int Odometer { get; set; }
public decimal Gallons { get; set; }
public decimal CostofFillUp { get; set; }
public string Date { get; set; }
public Event()
{
//placeholder
}
public Event(int EventOdometer, decimal EventGallons, decimal EventCostofFillUp, string EventDate)
{
this.Odometer = EventOdometer;
this.Gallons = EventGallons;
this.CostofFillUp = EventCostofFillUp;
this.Date = EventDate;
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
|
3ea5fdb9f8ab350f6530d49a0a4eea4e2eab5386
|
C#
|
PlamenTsvetkov/SoftUni-Software-Engineering
|
/CSharp-Programming-Basics/Exams/e7.Exam22-23August.2020/01.SeriesCalculator/Program.cs
| 3.515625
| 4
|
using System;
namespace _01.SeriesCalculator
{
class Program
{
static void Main(string[] args)
{
string nameSerial = Console.ReadLine();
double seasonNum = double.Parse(Console.ReadLine());
double episodsNum = double.Parse(Console.ReadLine());
double timeEpisod = double.Parse(Console.ReadLine());
double advertisingTime = timeEpisod * 0.2;
double specialEpizodTime = 10 * seasonNum;
double timeEpizodAdvertising = advertisingTime + timeEpisod;
double totalTimeAdvertising = timeEpizodAdvertising * episodsNum * seasonNum + specialEpizodTime;
Console.WriteLine($"Total time needed to watch the {nameSerial} series is {Math.Floor(totalTimeAdvertising)} minutes.");
}
}
}
|
955e4df4b82c658dd66f1aa0b60bb2d56b8c1372
|
C#
|
bramom/Bug.RS
|
/Polymorphism/OOPAnimals2/Dog.cs
| 3.359375
| 3
|
using System;
namespace OOPAnimals2
{
public class Dog : Animal
{
public Dog(string name) : base(name)
{
}
override public void DoWalk()
{
Console.WriteLine(string.Format("Dog {0} walk", Name));
}
override public void DoTalk()
{
Console.WriteLine(string.Format("Dog {0} talk: Woof!", Name));
}
}
}
|
e94b94b22d225d3175303a38d3469e2dc5e08714
|
C#
|
msarchet/pvc
|
/Pvc.Core/PvcStream.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace PvcCore
{
public class PvcStream : Stream
{
private readonly Lazy<Stream> stream;
/// <summary>
/// Arbitrary name for a stream. For streams created by pvc.Source, this will be the name
/// or relative path to the file. Don't rely on this for file name processing or detection,
/// instead use OriginalSourcePath.
/// </summary>
public string StreamName { get; private set; }
/// <summary>
/// Location on disk of the original source for this stream. Useful for plugins that need
/// to provide include paths or other similar configuration to their internals.
/// </summary>
public string OriginalSourcePath { get; private set; }
/// <summary>
/// Tags represent a way to filter streams for plugins. By default all streams created from
/// files will receive a tag of their file extension. Other tags may be applied to streams
/// by plugins during the pipe processing.
/// </summary>
public List<string> Tags { get; set; }
public PvcStream(Func<FileStream> fileStream)
: this()
{
this.stream = new Lazy<Stream>(fileStream);
}
public PvcStream(Func<MemoryStream> memoryStream)
: this()
{
this.stream = new Lazy<Stream>(memoryStream);
}
public PvcStream(Func<BufferedStream> bufferedStream)
: this()
{
this.stream = new Lazy<Stream>(bufferedStream);
}
public PvcStream(Func<NetworkStream> networkStream)
: this()
{
this.stream = new Lazy<Stream>(networkStream);
}
internal PvcStream()
{
this.Tags = new List<string>();
}
public PvcStream As(string streamName)
{
return this.As(streamName, null);
}
public PvcStream As(string streamName, string originalSourcePath)
{
this.StreamName = streamName;
this.OriginalSourcePath = originalSourcePath;
this.Tags.Add(Path.GetExtension(originalSourcePath));
return this;
}
public override bool CanRead
{
get { return this.stream.Value.CanRead; }
}
public override bool CanSeek
{
get { return this.stream.Value.CanSeek; }
}
public override bool CanWrite
{
get { return this.stream.Value.CanWrite; }
}
public override void Flush()
{
this.stream.Value.Flush();
}
public override long Length
{
get { return this.stream.Value.Length; }
}
public override long Position
{
get
{
return this.stream.Value.Position;
}
set
{
this.stream.Value.Position = value;
}
}
public override int Read(byte[] buffer, int offset, int count)
{
return this.stream.Value.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return this.Seek(offset, origin);
}
public override void SetLength(long value)
{
this.stream.Value.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
this.stream.Value.Write(buffer, offset, count);
}
/// <summary>
/// Read the contents of the stream from the beginning and return as a string. Position is
/// reset to its previous location after the read is completed.
/// </summary>
/// <returns></returns>
public override string ToString()
{
var streamPosition = this.stream.Value.Position;
this.stream.Value.Position = 0;
var result = new StreamReader(this.stream.Value).ReadToEnd();
this.stream.Value.Position = streamPosition;
return result;
}
public void ResetStreamPosition()
{
// Don't touch the stream position if we haven't actually touched it yet
if (this.stream.IsValueCreated)
this.stream.Value.Position = 0;
}
}
}
|
5d034613de981a946610a9fd217338d12b4ad9f5
|
C#
|
mmgore/SimpleTodoApp
|
/ToDoApp.Application/Commads/UpdateTodoCommandHandler.cs
| 2.546875
| 3
|
using MediatR;
using System;
using System.Threading;
using System.Threading.Tasks;
using TodoApp.Application.Exceptions;
using TodoApp.Domain.Entites;
using TodoApp.Domain.Interfaces;
namespace TodoApp.Application.Commads
{
public class UpdateTodoCommandHandler : IRequestHandler<UpdateTodoCommand, Unit>
{
private readonly IRepository<Todo> _repository;
public UpdateTodoCommandHandler(IRepository<Todo> repository)
{
_repository = repository ?? throw new ArgumentNullException(nameof(repository));
}
public async Task<Unit> Handle(UpdateTodoCommand request, CancellationToken cancellationToken)
{
var entity = await _repository.GetAsync(request.Id);
if (entity == null)
{
throw new NotFoundException(nameof(Todo), request.Id);
}
entity.Name = request.Name;
entity.Rating = request.Rating;
entity.City = request.City;
entity.ModifiedDate = DateTime.Now;
await _repository.UpdateAsync(entity);
return Unit.Value;
}
}
}
|
60f361c66da8c9ebd9fb14077b411058650d668b
|
C#
|
predator006-P/CS_AdvancedCourse
|
/NullableTypes/Program.cs
| 3.21875
| 3
|
using System;
namespace NullableTypes
{
class Program
{
static void Main(string[] args)
{
int a;
bool b = true;
DateTime? date1 = new DateTime(2020, 5, 30);
DateTime date2 = date1.GetValueOrDefault();
DateTime? date3 = date2;
DateTime? date4 = null;
DateTime date5 = date4 ?? DateTime.Now; // == (date4 != null) ? date4.GetValueOrDefault() : DateTime.Today
Console.WriteLine(date1);
Console.WriteLine(date2);
Console.WriteLine(date3);
Console.WriteLine(date5);
}
}
}
|
fb8b8e7c9e1556056e49ff9bb8ece9f9e1c4bacc
|
C#
|
nathanwoulfe/Umbraco-CMS
|
/src/Umbraco.Web.Common/ImageProcessors/CropWebProcessor.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.Globalization;
using Microsoft.Extensions.Logging;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Web;
using SixLabors.ImageSharp.Web.Commands;
using SixLabors.ImageSharp.Web.Processors;
namespace Umbraco.Cms.Web.Common.ImageProcessors
{
/// <summary>
/// Allows the cropping of images.
/// </summary>
public class CropWebProcessor : IImageWebProcessor
{
/// <summary>
/// The command constant for the crop coordinates.
/// </summary>
public const string Coordinates = "cc";
/// <inheritdoc/>
public IEnumerable<string> Commands { get; } = new[]
{
Coordinates
};
/// <inheritdoc/>
public FormattedImage Process(FormattedImage image, ILogger logger, IDictionary<string, string> commands, CommandParser parser, CultureInfo culture)
{
RectangleF? coordinates = GetCoordinates(commands, parser, culture);
if (coordinates != null)
{
// Convert the coordinates to a pixel based rectangle
int sourceWidth = image.Image.Width;
int sourceHeight = image.Image.Height;
int x = (int)MathF.Round(coordinates.Value.X * sourceWidth);
int y = (int)MathF.Round(coordinates.Value.Y * sourceHeight);
int width = (int)MathF.Round(coordinates.Value.Width * sourceWidth);
int height = (int)MathF.Round(coordinates.Value.Height * sourceHeight);
var cropRectangle = new Rectangle(x, y, width, height);
image.Image.Mutate(x => x.Crop(cropRectangle));
}
return image;
}
private static RectangleF? GetCoordinates(IDictionary<string, string> commands, CommandParser parser, CultureInfo culture)
{
float[] coordinates = parser.ParseValue<float[]>(commands.GetValueOrDefault(Coordinates), culture);
if (coordinates.Length != 4)
{
return null;
}
// The right and bottom values are actually the distance from those sides, so convert them into real coordinates
return RectangleF.FromLTRB(coordinates[0], coordinates[1], 1 - coordinates[2], 1 - coordinates[3]);
}
}
}
|
1ac5a88c632d703097fdd6fb574bd2c5c5dd5fac
|
C#
|
BrunoGoffre/Programacion-II
|
/Ejercicios/ejercicios 1 - 20/Ejercicio 18/Rectangulo.cs
| 3.234375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Geometria
{
class Rectangulo
{
float area = 0;
float perimetro = 0;
Punto Vertice1;
Punto Vertice2;
Punto Vertice3;
Punto Vertice4;
public Rectangulo(Punto Vertice1, Punto Vertice3)
{
this.perimetro = 0;
this.area = 0;
this.Vertice1 = Vertice1;
Punto aux = new Punto(Vertice3.GetX(), Vertice1.GetY());
this.Vertice2 = aux;
this.Vertice3 = Vertice3;
aux = new Punto(Vertice1.GetX(), Vertice3.GetY());
this.Vertice4 = aux;
// DistanciaPuntos = Math.Sqrt(Math.Pow(CatetoX, 2) + Math.Pow(CatetoY, 2));
}
public float GetArea()
{
if (this.area == 0)
{
float Base = this.Vertice3.GetX() - this.Vertice1.GetX();
float Altura = this.Vertice3.GetY() - this.Vertice1.GetY();
this.area = Base * Altura;
return this.area;
}
else
{
return this.area;
}
}
public float GetPerimetro()
{
if (this.perimetro == 0)
{
float Base = this.Vertice3.GetX() - this.Vertice1.GetX();
float Altura = this.Vertice3.GetY() - this.Vertice1.GetY();
this.perimetro = (Base + Altura)*2;
return this.perimetro;
}
else
{
return this.perimetro;
}
}
}
}
|
cc7cc0037c61b49d58c95d10369b2c28f3fa7481
|
C#
|
DanielN97/SoftUni_Exercises
|
/Streams, Files and Dictionaries - Exercise/ZipAndExtract/Program.cs
| 2.71875
| 3
|
using System;
using System.IO;
using System.IO.Compression;
class Program
{
static void Main(string[] args)
{
string startPath = @"../../../File";
string zipPath = @"../../../zipFile.zip";
string extractPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
}
}
|
320b2a5e77dfbdaac3de4a58c93c6dd79fa3a8b5
|
C#
|
stenli327/TelerikAcademy-
|
/Programing with C#/C# Fundamentals II/03-Methods/09.SortingArray/SortingArray.cs
| 4.3125
| 4
|
using System;
using System.Collections.Generic;
/// <summary>
/// Write a method that return the maximal element in a portion of array of integers starting at given index.
/// Using it write another method that sorts an array in ascending / descending order.
/// </summary>
class SortingArray
{
static void Main()
{
int[] elements = { 5, 67, 12, 6, 7, 78, 123, 5, 8, 3, 78, 9 };
Console.Write("Enter portion of elements: ");
int portion = int.Parse(Console.ReadLine());
Console.Write("Enter starting index: ");
int index = int.Parse(Console.ReadLine());
MaxElements(elements, portion, index);
}
private static void MaxElements(int[] elements, int portion, int index)
{
int[] arr = new int[portion];
int x = 0;
for (int i = index; i < portion + index; i++)
{
arr[x] = elements[i];
//Console.WriteLine(elements[i]);
x++;
}
Array.Sort(arr);
Console.WriteLine("Maximal element is {0} on position {1}", arr[arr.Length - 1], arr.Length - 1);
}
}
|
1a40404fa6a7c32f6e939a3c88d8d3f4847d98b0
|
C#
|
BenjaminLeonhardt/P2PServerUncloudC-
|
/P2PServerFormsGui/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;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace P2PServerFormsGui {
public partial class Form1 : Form {
public delegate void AddListItem();
public AddListItem myDelegate;
public Form1() {
InitializeComponent();
myDelegate = new AddListItem(AddListItemMethod);
peersListe.FullRowSelect = true;
}
private void AddListItemMethod() {
peersListe.Items.Clear();
foreach (Peer item in Server.Peers) {
ListViewItem newItem = new ListViewItem(item.id);
newItem.SubItems.Add(item.name);
newItem.SubItems.Add(item.ip);
newItem.SubItems.Add("Windows 10");
peersListe.Items.Add(newItem);
}
}
public Thread ListenThread { get; set; }
static byte[] buffer { get; set; }
static Socket socket;
private void start_Click(object sender, EventArgs e) {
string HostName = System.Net.Dns.GetHostName();
IPHostEntry hostInfo = Dns.GetHostEntry(HostName);
string IpAdresse = hostInfo.AddressList[hostInfo.AddressList.Length - 1].ToString();
Server server = new P2PServerFormsGui.Server(10, 1024,this);
server.Init();
server.Start(new IPEndPoint(IPAddress.Any, 5000));
//socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//socket.Bind(new IPEndPoint(IPAddress.Any, 5000));
//socket.Listen(100);
//ThreadStart start = new ThreadStart(accept);
//Thread ListenThread = new Thread(start);
//ListenThread.IsBackground = true;
//ListenThread.Start();
StatusText.Text = IpAdresse + ":5000";
StatusText.ForeColor = Color.Green;
}
public void accept() {
try {
Socket accepted = socket.Accept();
while (true) {
buffer = new byte[accepted.SendBufferSize];
int bytesRead = accepted.Receive(buffer);
byte[] formated = new byte[bytesRead];
for (int i = 0; i < bytesRead; i++) {
formated[i] = buffer[i];
}
string strData = Encoding.ASCII.GetString(formated);
Console.Write(strData + Environment.NewLine);
Thread.Sleep(50);
}
}catch(Exception ex) {
Console.WriteLine(ex.ToString());
accept();
}
}
private void peersListe_SelectedIndexChanged(object sender, EventArgs e) {
}
}
}
|
caf06d7de1c6d0cbaa9d0d9aa9d1c47f6a9e27cd
|
C#
|
RaduMemetea/CryptoDen
|
/Algorithms/Hash/SHA.cs
| 3.375
| 3
|
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
namespace Algorithms.Hash
{
public enum ShaSize
{
SHA1 = 1,
SHA256 = 256,
SHA384 = 384,
SHA512 = 512
}
class SHA
{
public static String Hash(String input, ShaSize size)
{
String output = "#";
switch (size)
{
case ShaSize.SHA1:
using(SHA1Managed sha = new SHA1Managed())
{
var hash = sha.ComputeHash(Encoding.UTF8.GetBytes(input));
var sb = new StringBuilder(hash.Length * 2);
foreach (byte b in hash)
sb.Append(b.ToString("X2"));
output = sb.ToString();
}
break;
case ShaSize.SHA256:
using (SHA256 sha = SHA256.Create())
{
var hash = sha.ComputeHash(Encoding.UTF8.GetBytes(input));
var sb = new StringBuilder(hash.Length * 2);
foreach (byte b in hash)
sb.Append(b.ToString("X2"));
output = sb.ToString();
}
break;
case ShaSize.SHA384:
using (SHA384 sha = SHA384.Create())
{
var hash = sha.ComputeHash(Encoding.UTF8.GetBytes(input));
var sb = new StringBuilder(hash.Length * 2);
foreach (byte b in hash)
sb.Append(b.ToString("X2"));
output = sb.ToString();
}
break;
case ShaSize.SHA512:
using (SHA512 sha = SHA512.Create())
{
var hash = sha.ComputeHash(Encoding.UTF8.GetBytes(input));
var sb = new StringBuilder(hash.Length * 2);
foreach (byte b in hash)
sb.Append(b.ToString("X2"));
output = sb.ToString();
}
break;
}
return output;
}
}
}
|
15018efb9479b6c0ff203e07e4b4d1a375eca76d
|
C#
|
WillCorrea/oportunidade
|
/FeedMinuto/FeedMinuto/Models/FeedNoticias.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
namespace FeedMinuto.Models
{
public class FeedNoticias
{
public FeedNoticias()
{
this.ListaFeed = new List<DadosFeed>();
this.ListaResumo = new List<ResumoFeed>();
}
public List<DadosFeed> ListaFeed { get; set; }
public List<ResumoFeed> ListaResumo { get; set; }
public FeedNoticias ObterFeedNoticias()
{
//Instancia a Classe de retono da Model
FeedNoticias retornoFeed = new FeedNoticias();
//Obtem a url do Feed localizado no web.config
string PathFeed = System.Configuration.ConfigurationManager.AppSettings["FeedMinutoURL"].ToString();
//Cria a variavel referente ao xml localizado na url em questao
using (var reader = System.Xml.XmlReader.Create(PathFeed))
{
//Efetua a leitura do feed de noticias
System.ServiceModel.Syndication.SyndicationFeed feed = System.ServiceModel.Syndication.SyndicationFeed.Load(reader);
var Palavras = new List<string>();
int QuantidadeFeeds = int.Parse(System.Configuration.ConfigurationManager.AppSettings["NumeroFeeds"].ToString());
int PalavrasResumo = int.Parse(System.Configuration.ConfigurationManager.AppSettings["NumeroPalavrasResumo"].ToString());
//Obtem os ultimos tópicos do feed de acordo com a configuracao no web.config (10)
foreach (var item in feed.Items.Take(QuantidadeFeeds).OrderByDescending(x => x.PublishDate))
{
//Obtem a lista de palavras desconsiderando as preposicoes
var ListaPalavas = ObtemPalavras(item.Summary.Text);
//Adiciona ao objeto a lista de palavras do topico
Palavras.AddRange(ListaPalavas);
//Adiciona ao objeto de retorno os feeds mais atuais
retornoFeed.ListaFeed.Add(new DadosFeed(item.Title.Text, item.PublishDate, item.Summary.Text, ListaPalavas.Count()));
}
//Faz uma consulta no objeto para quantificar as palavras utilizadas em todos os topicos
var resultado = from p in Palavras
group p by p into g
select new { palavra = g.Key, contador = g.Count() };
//Percorre o objeto de forma decrescente e obtem o numero de registros de acordo com a configuracao no web.config (10)
foreach (var registo in resultado.OrderByDescending(x => x.contador).Take(PalavrasResumo))
{
//Adiciona ao objeto de retorno o resumo das palavras mais utilizadas e quantas vezes se repetem
retornoFeed.ListaResumo.Add(new ResumoFeed(registo.palavra, registo.contador));
}
}
return retornoFeed;
}
private static string RetiraTagsHTML(string stringHtml)
{
return Regex.Replace(System.Net.WebUtility.HtmlDecode(stringHtml), "<.*?>", String.Empty);
}
private static List<string> ObtemPalavras(string texto)
{
char[] delimitadores = new char[] { ' ', '\r', '\n' };
var preposicoes = new string[] { "A", "ANTE", "APÓS", "ATÉ", "COM", "CONTRA", "DE", "DESDE", "EM", "ENTRE", "PARA", "PERANTE", "POR", "SEM", "SOB", "SOBRE", "TRÁS" };
var artigos = new string[] { "O", "A", "OS", "AS", "UM", "UMA", "UNS", "UMAS" };
texto = RetiraTagsHTML(texto);
var palavars = texto.Split(delimitadores, StringSplitOptions.RemoveEmptyEntries);
return palavars.Where(x => !preposicoes.Contains(x.ToUpper()) && !artigos.Contains(x.ToUpper())).ToList();
}
}
}
|
60d30d2ac431a6f6cf4f5cdb16feb7a3fdda4755
|
C#
|
Gorbachevaa/TAT_tasks
|
/Dev-7/Builder.cs
| 3.921875
| 4
|
using System;
namespace Dev_7
{
public enum TriangleType
{
Equaliteral,
Isosceles,
Simple
}
/// <summary>
/// Class build triangle according to rules. e.g.
/// If the sides are equal builder creates Equaliteral triangle.
/// </summary>
public class Builder
{
const double EPS = double.Epsilon;
public double SideA { get; set; }
public double SideB { get; set; }
public double SideC { get; set; }
public Builder(double[] sides)
{
SideA = sides[0];
SideB = sides[1];
SideC = sides[2];
}
/// <summary>
/// Defines which triangle's type is needed.
/// </summary>
/// <param name="sides">Triagle's sides</param>
/// <returns>/New object of Determined Type.</returns>
public Triangle Build (double[] sides)
{
switch(DetermineType())
{
case TriangleType.Equaliteral:
{
return new EqualiteralTriangle(sides);
}
case TriangleType.Isosceles:
{
return new IsosceleTriangle(sides);
}
case TriangleType.Simple:
{
return new SimpleTriangle(sides);
}
default:
{
throw new InvalidOperationException();
}
}
}
/// <summary>
/// Determines triangle's type.
/// </summary>
/// <returns>Triangle type that is enum type.</returns>
public TriangleType DetermineType()
{
TriangleType triangleType = TriangleType.Simple;
if ((Math.Abs(SideA - SideB) < EPS)
&& (Math.Abs(SideB - SideC) < EPS)
&& (Math.Abs(SideA - SideC) < EPS))
{
triangleType = TriangleType.Equaliteral;
}
else
if ((Math.Abs(SideA - SideB) < EPS)
|| (Math.Abs(SideB - SideC) < EPS)
|| (Math.Abs(SideA - SideC) < EPS))
{
triangleType = TriangleType.Isosceles;
}
return triangleType;
}
}
}
|
ae43e25346feac2676ba8d49966244110b6e2207
|
C#
|
FahimFBA/csharp-crash-course
|
/MoreIfStatements/MoreIfStatements/Program.cs
| 4.03125
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MoreIfStatements
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(MaxNum(10, 100)); // passing two values to the method named MaxNum
Console.WriteLine(MaxNumOfThree(10, 100, 1000)); // passing three values to the method named MaxNumOfThree
Console.ReadLine();
}
static int MaxNum (int a, int b)
{
int Max; // A new variable to store the Maximum value
if (a > b)
{
Max = a; // if a is bigger than b
}
else
{
Max = b; // else, b would be bigger than a
}
return Max;
}
static int MaxNumOfThree(int a, int b, int c)
{
int Max;
if (a >= b && a>= c)
{
Max = a;
}
else if (b >= c && b>= a)
{
Max = b;
}
else
{
Max = c;
}
return Max;
}
}
}
|
1a9db5cbdd0cc60c67e264dc95552adb1259c4f5
|
C#
|
imdmahajankanika/DesignPatterns
|
/MapReduce/MapReduce/main.cs
| 3.46875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace MapReduce
{
public class MainProgram
{
public static void Main(string[] args)
{
int size = 5;
// Creating a matrix of random integers as input
DataFrame df = new DataFrame();
int[,] rnd_mat = df.CreateMatrix(size, size);
// Print the generated matrix of random numbers
Console.WriteLine("Created a {0}x{1} matrix of random integers as input...", size, size);
Console.WriteLine("***************************************************");
df.DisplayMatrix(rnd_mat);
// Create tasks to be executed by threads/nodes on random data input for map and reduce procedure
GridTask[] tsk = new GridTask[rnd_mat.GetLength(0)];
Thread[] thread = new Thread[rnd_mat.GetLength(0)];
// Creating tasks for splitting and mapping procedure
for (int i = 0; i < rnd_mat.GetLength(0); i++)
{
Console.WriteLine("\nPerforming Splitting and Mapping...\n");
tsk[i] = new GridTask(df.Get_Row(i, rnd_mat));
thread[i] = new Thread(new ThreadStart(tsk[i].Execute));
thread[i].Start();
}
// Wait until all the threads are terminated
foreach (Thread t in thread)
{
t.Join();
}
// Shuffling all the results after execution of tasks by each node/thread
Console.WriteLine("\nShuffling...");
Console.WriteLine("***********************");
List<Dictionary<int, int>> res = new List<Dictionary<int, int>>();
for (int i = 0; i < rnd_mat.GetLength(0); i++)
{
res.Add(tsk[i].Shuffled_Results());
}
// Performing reduce method
Console.WriteLine("\nReducing...");
Console.WriteLine("***********************");
Dictionary<int, int> Final_Res = Reduce(res);
foreach (var item in Final_Res)
Console.WriteLine(item);
// Sorting the final result
var res_list = Final_Res.Keys.ToList();
res_list.Sort();
Console.WriteLine("\nFinal result...");
Console.WriteLine("***********************");
// Finally, emit each number and count
foreach (var item in res_list)
{
Console.WriteLine("Item : {0}, Count : {1}", item, Final_Res[item]);
}
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
public static Dictionary<int, int> Reduce(List<Dictionary<int, int>> dictionaries)
{
Dictionary<int, int> final = new Dictionary<int, int>();
foreach (Dictionary<int, int> dict in dictionaries)
{
foreach (var item in dict)
{
if (final.ContainsKey(item.Key))
final[item.Key] += item.Value;
else
final[item.Key] = item.Value;
}
}
return final;
}
}
}
|
c16b9654fe97e0028f867d2eef033b2734877b85
|
C#
|
romeroej2/ExBuddy
|
/ExBuddy/Logging/IGathererLogger.cs
| 2.515625
| 3
|
namespace ExBuddy.Logging
{
internal interface IGathererLogger
{
/// <summary>
/// Logs when there is not enough time to begin a gather
/// </summary>
void GatheringNotEnoughTime();
/// <summary>
/// Logs when the node is gone
/// </summary>
void GatheringNodeIsGone();
/// <summary>
/// Logs when the node is skipped because it is not ephemeral
/// </summary>
void GatheringNodeSkippedNotEphemeral();
}
}
|
75f849f65ac1a87b3ee06e381a9933a359ad51d7
|
C#
|
leonnybg/CSharp-ProgrammingFundamentals
|
/L11 Data Types and Variables ex1/13. Vowel or Digit/Program.cs
| 3.609375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _13.Vowel_or_Digit
{
class Program
{
static void Main(string[] args)
{
var input = Console.ReadLine();
if (input=="a"||input=="u"||input=="e"||input=="i"||input=="o"||input=="y")
{ Console.WriteLine("vowel"); }
else if (input=="0"||input=="1"||input=="2"||input=="3"||input=="4"||input=="5"||input=="6"||
input=="7"||input=="8"||input=="9")
{
Console.WriteLine("digit");
}
else
{ Console.WriteLine("other"); }
}
}
}
|
30c8b4bdf2ea2041ed4f554321589abedb2e39be
|
C#
|
nahomi16/practica
|
/Practica01/Practica01/Persona.cs
| 3.15625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Practica01
{
class Persona
{
public string nombre = "", apellido = "", color = "";
public int edad = 0;
public double peso = 0.0;
public void Nacer()
{
Console.WriteLine("Estoy Naciendo");
}
public void Crecer()
{
Console.WriteLine("estoy creciendo");
}
public void Procrear()
{
Console.WriteLine("Me estoy procreando");
}
public void Respirar()
{
Console.WriteLine("Estoy respirando");
}
public void Cantar()
{
Console.WriteLine("estoy cantando");
}
}
}
|
2166cc153386fc89a7a9a2d9529111d52d7b60be
|
C#
|
phuongkien/SAHULHotelManager
|
/SAHULHotelManager/DTO/CDepartment.cs
| 2.8125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SAHULHotelManager.DTO
{
class CDepartment
{
#region "Attribus"
private int id; // mã bộ phận
private string name; // tên bộ phận
private int departmentParentid; // mã bộ phận cha
private int number; // số nhân viên
#endregion
#region "Constructor"
public CDepartment()
{
this.id = 0;
this.name = "Unknow";
this.departmentParentid = 0;
this.number = 0;
}
public CDepartment(int id, string name, int departmantParentid, int number)
{
this.id = id;
this.name = name;
this.departmentParentid = departmantParentid;
this.number = number;
}
#endregion
#region "Method"
public string ShowInFors()
{
return "\n ID: " + id + "\n Name: " + name + "\n Department Parent ID: " + departmentParentid + "\n Number: " + number;
}
#endregion
}
}
|
29359a835fe1808867aaa8657b3c61b0dc171ed7
|
C#
|
KeRNeLith/QuikGraph
|
/src/QuikGraph/Interfaces/Edges/IUndirectedEdge.cs
| 2.65625
| 3
|
namespace QuikGraph
{
/// <summary>
/// Represents an undirected edge.
/// </summary>
/// <remarks>
/// Invariant: source must be less or equal to target (using the default comparer).
/// </remarks>
/// <typeparam name="TVertex">Vertex type.</typeparam>
public interface IUndirectedEdge<out TVertex> : IEdge<TVertex>
{
}
}
|
d05d2fff2b18eaab4abbd01fd01d2054f18a701b
|
C#
|
laceywalkerr/TreeHouseC-
|
/CSharp/MethodReturnValues.cs
| 4.03125
| 4
|
using System;
using System.Threading;
class Program
{
static void Ask(string question)
{
Console.WriteLine(question);
string answer = Console.ReadLine();
//Console.Readline will return the users responce when the question is prompted, and then gets assigned to the "answer" variable.
Console.WriteLine(answer);
}
static double Add(double first, double second)
{
return first + second;
}
static double Subtract(double first, double second)
{
return first - second;
}
static void Main(string[] args)
{
Console.WriteLine("Welcome to the cat food store!");
Ask("How many cans are you ordering?");
// Just gonna use a console writeline to throw a space between the kind of code I'm calling back, makes it easier to read.
Console.WriteLine("-----------------");
double total = Add(3, 5);
Console.WriteLine(total);
double remaining = Subtract(21.3, 7.1);
Console.WriteLine(remaining);
Console.WriteLine("----You could also do this and return the same info-----");
Console.WriteLine(Add(3, 5));
Console.WriteLine(Subtract(21.3, 7.1));
}
}
|
af33440893c62bf528fb0fb91157eb52808b9365
|
C#
|
killjoyelite/VP-end-of-semester-project
|
/WindowsService1/Service1.cs
| 2.609375
| 3
|
using System;
using System.Management;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Globalization;
using System.Threading;
namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
private ManualResetEvent _shutdownEvent = new ManualResetEvent(false);
private Thread _thread;
public Service1()
{
InitializeComponent();
}
//public void OnDebug()
//{
// OnStart(null);
//}
public static string driveList()
{
//IList<String> DriveList = new List<String>();
string dname = "";
foreach (DriveInfo driveInfo in DriveInfo.GetDrives())
{
if (driveInfo.DriveType == DriveType.Removable)
{
dname = driveInfo.RootDirectory.FullName;
//DriveList.Add(driveInfo.RootDirectory.FullName);
}
}
//foreach (string driveName in DriveList)
//{
// Console.WriteLine(driveName);
//}
//Console.WriteLine(dname);
return dname;
}
public static void Copy(string sourceDirectory, string targetDirectory)
{
DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);
DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);
CopyAll(diSource, diTarget);
}
public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
//DateTime dt = DateTime.Now;
//var culture = new CultureInfo("en-GB");
//string transferLogPath = @"C:\Users\SMile\Documents\Visual Studio 2010\Projects\WindowsService1\VP-end-of-semester-project\WindowsService1\bin\Release\TransferLog.txt";
Directory.CreateDirectory(target.FullName);
// Copy each file into the new directory.
//Console.WriteLine(@"Copying {0} --> {1}", fi.FullName, target.FullName);
try
{
//using (StreamWriter sw = File.AppendText(transferLogPath))
//{
foreach (FileInfo fi in source.GetFiles())
{
//sw.WriteLine(@"Copying {0} --> {1}", fi.FullName, target.FullName);
fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);
}
//sw.WriteLine("---------------------" + dt.ToString(culture) + "---------------------\n");
//}
}
catch (Exception)
{
throw;
}
// Copy each subdirectory using recursion.
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
private void WorkerThreadFunc()
{
//using (StreamWriter sw = File.AppendText("C:/Users/SMile/Documents/Visual Studio 2010/Projects/WindowsService1/VP-end-of-semester-project/WindowsService1/bin/Release/OnThreadStart.txt"))
//{
// sw.WriteLine("Thread Started\n");
// sw.WriteLine("\n");
//}
string sourceDirectory = "";
string targetDirectory = @"C:\Users\SMile\Desktop\Auto backup";
while (!_shutdownEvent.WaitOne(0))
{
do
{
sourceDirectory = "";
sourceDirectory = driveList();
} while (sourceDirectory == "") ;
//using (StreamWriter sw = File.AppendText("C:/Users/SMile/Documents/Visual Studio 2010/Projects/WindowsService1/VP-end-of-semester-project/WindowsService1/bin/Release/OnNonEmptyPath.txt"))
//{
// sw.WriteLine("Non Empty Path\n");
// sw.WriteLine("\n");
//}
try
{
Copy(sourceDirectory, targetDirectory);
}
catch (Exception )
{
//using (StreamWriter sw = File.AppendText(errorPath))
//{
//sw.WriteLine(dt.ToString(culture) + " - " + e.Message + "\n");
//sw.WriteLine("\n");
//}
//File.AppendAllText(@"C:\Users\SMile\Documents\Visual Studio 2010\Projects\WindowsService1\WindowsService1\bin\Release\ErrorLog.txt", "Device not found");
}
//using (StreamWriter sw = File.AppendText("C:/Users/SMile/Documents/Visual Studio 2010/Projects/WindowsService1/VP-end-of-semester-project/WindowsService1/bin/Release/CopyCompletePath.txt"))
//{
// sw.WriteLine("Copy Done\n");
// sw.WriteLine("\n");
//}
//Thread.Sleep(5000);
}
//using (StreamWriter sw = File.AppendText("C:/Users/SMile/Documents/Visual Studio 2010/Projects/WindowsService1/VP-end-of-semester-project/WindowsService1/bin/Release/ThreadEnd.txt"))
//{
// sw.WriteLine("Thread Ended\n");
// sw.WriteLine("\n");
//}
}
protected override void OnStart(string[] args)
{
DateTime dt = DateTime.Now;
var culture = new CultureInfo("en-GB");
//string startPath = @"C:\Users\SMile\Documents\Visual Studio 2010\Projects\WindowsService1\VP-end-of-semester-project\WindowsService1\bin\Release\OnStart.txt";
//string errorPath = @"C:\Users\SMile\Documents\Visual Studio 2010\Projects\WindowsService1\VP-end-of-semester-project\WindowsService1\bin\Release\ErrorLog.txt";
//System.IO.File.Create(AppDomain.CurrentDomain.BaseDirectory + "OnStart.txt");
_thread = new Thread(WorkerThreadFunc);
_thread.Name = "My Worker Thread";
_thread.IsBackground = true;
_thread.Start();
//try
//{
//using (StreamWriter sw = File.AppendText(startPath))
//{
// sw.WriteLine(dt.ToString(culture) + " - Backup Service Started\n");
// sw.WriteLine("\n");
//}
//}
//catch (Exception e)
//{
// //using (StreamWriter sw = File.AppendText(errorPath))
// //{
// // sw.WriteLine(dt.ToString(culture) + " - " + e.Message);
// // sw.WriteLine("\n");
// //}
//}
//try
//{
// Copy(sourceDirectory, targetDirectory);
//}
//catch (Exception e)
//{
// using (StreamWriter sw = File.AppendText(errorPath))
// {
// sw.WriteLine(dt.ToString(culture) + " - " + e.Message + "\n");
// //sw.WriteLine("\n");
// }
// //File.AppendAllText(@"C:\Users\SMile\Documents\Visual Studio 2010\Projects\WindowsService1\WindowsService1\bin\Release\ErrorLog.txt", "Device not found");
//}
////Console.WriteLine("Total files copied: \n");
////Console.WriteLine();
//OnStart(null);
using (StreamWriter sw = File.AppendText("C:/Users/SMile/Desktop/BackupLog.txt"))
{
sw.WriteLine(dt.ToString(culture) + " - " + "Backup Service Started\n");
sw.WriteLine("\n");
}
}
protected override void OnStop()
{
DateTime dt = DateTime.Now;
var culture = new CultureInfo("en-GB");
_shutdownEvent.Set();
if (!_thread.Join(3000))
{ // give the thread 3 seconds to stop
_thread.Abort();
}
using (StreamWriter sw = File.AppendText("C:/Users/SMile/Desktop/BackupLog.txt"))
{
sw.WriteLine(dt.ToString(culture) + " - " + "Backup Service Stopped\n");
sw.WriteLine("\n");
}
//string stopPath = @"C:\Users\SMile\Documents\Visual Studio 2010\Projects\WindowsService1\VP-end-of-semester-project\WindowsService1\bin\Release\OnStop.txt";
//System.IO.File.Create(AppDomain.CurrentDomain.BaseDirectory + "OnStop.txt");
//try
//{
// using (StreamWriter sw = File.AppendText(stopPath))
// {
// sw.WriteLine(localDate.ToString(culture) + " - Backup Service Stopped\n");
// //sw.WriteLine("\n");
// }
//}
//catch (Exception)
//{
// throw;
//}
}
}
}
|
943edbb325fea833aa95fd83530099460acd3198
|
C#
|
ischool-desktop/K12.Data
|
/Permrec/ParentRecord.cs
| 2.71875
| 3
|
using System.Xml;
namespace K12.Data
{
/// <summary>
/// 家長及監護人資訊
/// </summary>
public class ParentRecord
{
/// <summary>
/// 預設建構式
/// </summary>
public ParentRecord()
{
Father = new Father();
Mother = new Mother();
Custodian = new Custodian();
}
/// <summary>
/// XML參數建構式
/// <![CDATA[
/// ]]>
/// </summary>
/// <param name="data"></param>
public ParentRecord(XmlElement data)
{
Load(data);
}
/// <summary>
/// 從XML載入設定值
/// <![CDATA[
/// ]]>
/// </summary>
/// <param name="data"></param>
public void Load(XmlElement data)
{
Father = new Father(data);
Mother = new Mother(data);
Custodian = new Custodian(data);
RefStudentID = data.GetAttribute("RefStudentID");
}
/// <summary>
/// 所屬學生編號
/// </summary>
[Field(Caption = "學生編號", EntityName = "Student", EntityCaption = "學生",IsEntityPrimaryKey=true)]
public string RefStudentID { get; set; }
/// <summary>
/// 所屬學生記錄物件
/// </summary>
public StudentRecord Student
{
get
{
return !string.IsNullOrEmpty(RefStudentID)?K12.Data.Student.SelectByID(RefStudentID):null;
}
}
/// <summary>
/// 父親資訊
/// </summary>
public Father Father { get; set; }
/// <summary>
/// 父親最高學歷,此為唯讀屬性,要修改請使用Father.EducationDegree屬性。
/// </summary>
[Field(Caption = "父親最高學歷", EntityName = "Parent", EntityCaption = "家長及監護人")]
public string FatherEducationDegree { get { return Father.EducationDegree; } }
/// <summary>
/// 父親身份證字號,此為唯讀屬性,要修改請使用Father.IDNumber屬性。
/// </summary>
[Field(Caption = "父親身份證字號", EntityName = "Parent", EntityCaption = "家長及監護人")]
public string FatherIDNumber { get { return Father.IDNumber; } }
/// <summary>
/// 父親工作,此為唯讀屬性,要修改請使用Father.Job屬性。
/// </summary>
[Field(Caption = "父親工作", EntityName = "Parent", EntityCaption = "家長及監護人")]
public string FatherJob { get { return Father.Job; } }
/// <summary>
/// 父親存歿,此為唯讀屬性,要修改請使用Father.Living屬性。
/// </summary>
[Field(Caption = "父親存歿", EntityName = "Parent", EntityCaption = "家長及監護人")]
public string FatherLiving { get { return Father.Living; } }
/// <summary>
/// 父親姓名,此為唯讀屬性,要修改請使用Father.Name屬性。
/// </summary>
[Field(Caption = "父親姓名", EntityName = "Parent", EntityCaption = "家長及監護人")]
public string FatherName { get { return Father.Name; } }
/// <summary>
/// 父親國籍,此為唯讀屬性,要修改請使用Father.Nationality屬性。
/// </summary>
[Field(Caption = "父親國籍", EntityName = "Parent", EntityCaption = "家長及監護人")]
public string FatherNationality { get { return Father.Nationality; } }
/// <summary>
/// 父親電話,此為唯讀屬性,要修改請使用Father.Phone屬性。
/// </summary>
[Field(Caption = "父親電話", EntityName = "Parent", EntityCaption = "家長及監護人")]
public string FatherPhone { get { return Father.Phone; } }
/// <summary>
/// 父親電子郵件,此為唯讀屬性,要修改請使用Father.EMail屬性。
/// </summary>
[Field(Caption = "父親電子郵件", EntityName = "Parent", EntityCaption = "家長及監護人")]
public string FatherEMail { get { return Father.EMail; } }
/// <summary>
/// 母親資訊
/// </summary>
public Mother Mother { get; set; }
/// <summary>
/// 母親最高學歷,此為唯讀屬性,要修改請使用Mother.EducationDegree屬性。
/// </summary>
[Field(Caption = "母親電話", EntityName = "Parent", EntityCaption = "家長及監護人")]
public string MotherEducationDegree { get { return Mother.EducationDegree; } }
/// <summary>
/// 母親身份證字號,此為唯讀屬性,要修改請使用Mother.IDNumber屬性。
/// </summary>
[Field(Caption = "母親身份證字號", EntityName = "Parent", EntityCaption = "家長及監護人")]
public string MotherIDNumber { get { return Mother.IDNumber; } }
/// <summary>
/// 母親工作,此為唯讀屬性,要修改請使用Mother.Job屬性。
/// </summary>
[Field(Caption = "母親工作", EntityName = "Parent", EntityCaption = "家長及監護人")]
public string MotherJob { get { return Mother.Job; } }
/// <summary>
/// 母親存歿,此為唯讀屬性,要修改請使用Mother.Living屬性。
/// </summary>
[Field(Caption = "母親存歿", EntityName = "Parent", EntityCaption = "家長及監護人")]
public string MotherLiving { get { return Mother.Living; } }
/// <summary>
/// 母親姓名,此為唯讀屬性,要修改請使用Mother.Name屬性。
/// </summary>
[Field(Caption = "母親姓名", EntityName = "Parent", EntityCaption = "家長及監護人")]
public string MotherName { get { return Mother.Name; } }
/// <summary>
/// 母親國籍,此為唯讀屬性,要修改請使用Mother.Nationality屬性。
/// </summary>
[Field(Caption = "母親國籍", EntityName = "Parent", EntityCaption = "家長及監護人")]
public string MotherNationality { get { return Mother.Nationality; } }
/// <summary>
/// 母親電話,此為唯讀屬性,要修改請使用Mother.Phone屬性。
/// </summary>
[Field(Caption = "母親電話", EntityName = "Parent", EntityCaption = "家長及監護人")]
public string MotherPhone { get { return Mother.Phone; } }
/// <summary>
/// 母親電子郵件,此為唯讀屬性,要修改請使用Mother.EMail屬性。
/// </summary>
[Field(Caption = "母親電子郵件", EntityName = "Parent", EntityCaption = "家長及監護人")]
public string MotherEMail { get { return Mother.EMail; } }
/// <summary>
/// 監護人資訊
/// </summary>
public Custodian Custodian { get; set; }
/// <summary>
/// 監護人最高學歷,此為唯讀屬性,要修改請使用Custodian.EducationDegree屬性。
/// </summary>
[Field(Caption = "監護人最高學歷", EntityName = "Parent", EntityCaption = "家長及監護人")]
public string CustodianEducationDegree { get { return Custodian.EducationDegree; } }
/// <summary>
/// 監護人身份證字號,此為唯讀屬性,要修改請使用Custodian.IDNumber屬性。
/// </summary>
[Field(Caption = "監護人身份證字號", EntityName = "Parent", EntityCaption = "家長及監護人")]
public string CustodianIDNumber { get { return Custodian.IDNumber; } }
/// <summary>
/// 監護人工作,此為唯讀屬性,要修改請使用Custodian.Job屬性。
/// </summary>
[Field(Caption = "監護人工作", EntityName = "Parent", EntityCaption = "家長及監護人")]
public string CustodianJob { get { return Custodian.Job; } }
/// <summary>
/// 監護人稱謂,此為唯讀屬性,要修改請使用Custodian.Relationship屬性。
/// </summary>
[Field(Caption = "監護人稱謂", EntityName = "Parent", EntityCaption = "家長及監護人")]
public string CustodianRelationship { get { return Custodian.Relationship; } }
/// <summary>
/// 監護人姓名,此為唯讀屬性,要修改請使用Custodian.Name屬性。
/// </summary>
[Field(Caption = "監護人姓名", EntityName = "Parent", EntityCaption = "家長及監護人")]
public string CustodianName { get { return Custodian.Name; } }
/// <summary>
/// 監護人國籍,此為唯讀屬性,要修改請使用Custodian.Nationality屬性。
/// </summary>
[Field(Caption = "監護人國籍", EntityName = "Parent", EntityCaption = "家長及監護人")]
public string CustodianNationality { get { return Custodian.Nationality; } }
/// <summary>
/// 監護人電話,此為唯讀屬性,要修改請使用Custodian.Phone屬性。
/// </summary>
[Field(Caption = "監護人電話", EntityName = "Parent", EntityCaption = "家長及監護人")]
public string CustodianPhone { get { return Custodian.Phone; } }
/// <summary>
/// 監護人電子郵件,此為唯讀屬性,要修改請使用Custodian.EMail屬性。
/// </summary>
[Field(Caption = "監護人電子郵件", EntityName = "Parent", EntityCaption = "家長及監護人")]
public string CustodianEMail { get { return Custodian.EMail; } }
}
/// <summary>
/// 父親、母親及監護人所共同繼承的類別
/// </summary>
public abstract class ParentBase
{
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 工作
/// </summary>
public string Job { get; set; }
/// <summary>
/// 最高學歷
/// </summary>
public string EducationDegree { get; set; }
/// <summary>
/// 國籍
/// </summary>
public string Nationality { get; set; }
/// <summary>
/// 身分證號
/// </summary>
public string IDNumber { get; set; }
/// <summary>
/// 電話
/// </summary>
public string Phone { get; set; }
/// <summary>
/// 電子郵件
/// </summary>
public string EMail { get; set; }
/// <summary>
/// 公司名稱
/// </summary>
public string CompanyName { get; set; }
/// <summary>
/// 公司職稱
/// </summary>
public string CompanyTitle { get; set; }
/// <summary>
/// 公司分類,與Job欄位意義相同,但若要仔細使用Company相關欄位
/// </summary>
public string CompanyCategory { get; set; }
/// <summary>
/// 手機
/// </summary>
public string CellPhone { get; set; }
/// <summary>
/// 住家電話
/// </summary>
public string HomePhone { get; set; }
/// <summary>
/// 辦公室電話
/// </summary>
public string CompanyPhone { get; set; }
/// <summary>
/// 地址郵遞區號
/// </summary>
public string AddressZipCode { get; set; }
/// <summary>
/// 地址縣市
/// </summary>
public string AddressCounty { get; set; }
/// <summary>
/// 地址鄉鎮市區
/// </summary>
public string AddressTown { get; set; }
/// <summary>
/// 地址村里
/// </summary>
public string AddressDistrict { get; set; }
/// <summary>
/// 地址鄰
/// </summary>
public string AddressArea { get; set; }
/// <summary>
/// 地址其他
/// </summary>
public string AddressDetail { get; set; }
/// <summary>
/// 地址經度
/// </summary>
public string AddressLongitude { get; set; }
/// <summary>
/// 地址緯度
/// </summary>
public string AddressLatitude { get; set; }
}
/// <summary>
/// 父親資訊
/// </summary>
public class Father : ParentBase
{
/// <summary>
/// 無參數建構式
/// </summary>
internal Father()
{
}
/// <summary>
/// XML參數建構式
/// </summary>
/// <param name="data"></param>
internal Father(XmlElement data)
{
Load(data);
}
/// <summary>
/// 依XML載入設定值
/// </summary>
/// <param name="data"></param>
public void Load(XmlElement data)
{
XmlHelper xdata = new XmlHelper(data);
Name = xdata.GetString("FatherName");
Nationality = xdata.GetString("FatherNationality");
IDNumber = xdata.GetString("FatherIDNumber");
Living = xdata.GetString("FatherLiving");
EducationDegree = xdata.GetString("FatherOtherInfo/FatherEducationDegree");
Job = xdata.GetString("FatherOtherInfo/FatherJob");
Phone = xdata.GetString("FatherOtherInfo/Phone");
EMail = xdata.GetString("FatherOtherInfo/EMail");
CompanyName = xdata.GetString("FatherOtherInfo/Company/Name");
CompanyTitle = xdata.GetString("FatherOtherInfo/Company/Title");
CompanyCategory = xdata.GetString("FatherOtherInfo/Company/Category");
CellPhone = xdata.GetString("FatherOtherInfo/PhoneList/Phone[@Title='手機']");
HomePhone = xdata.GetString("FatherOtherInfo/PhoneList/Phone[@Title='住家電話']");
CompanyPhone = xdata.GetString("FatherOtherInfo/PhoneList/Phone[@Title='辦公室電話']");
AddressZipCode = xdata.GetString("FatherOtherInfo/AddressList/Address/ZipCode");
AddressCounty = xdata.GetString("FatherOtherInfo/AddressList/Address/County");
AddressTown = xdata.GetString("FatherOtherInfo/AddressList/Address/Town");
AddressDistrict = xdata.GetString("FatherOtherInfo/AddressList/Address/District");
AddressArea = xdata.GetString("FatherOtherInfo/AddressList/Address/Area");
AddressDetail = xdata.GetString("FatherOtherInfo/AddressList/Address/Detail");
AddressLongitude = xdata.GetString("FatherOtherInfo/AddressList/Address/Longitude");
AddressLatitude = xdata.GetString("FatherOtherInfo/AddressList/Address/Latitude");
}
/// <summary>
/// 輸出成XML
/// </summary>
/// <returns></returns>
public XmlElement ToXml()
{
XmlDataDocument xmldoc = new XmlDataDocument();
xmldoc.Load("");
return null;
}
/// <summary>
/// 存歿
/// </summary>
public string Living { get; set; }
}
/// <summary>
/// 母親資訊
/// </summary>
public class Mother : ParentBase
{
/// <summary>
/// 無參數建構式
/// </summary>
internal Mother()
{
}
/// <summary>
/// XML參數建構式
/// </summary>
/// <param name="data"></param>
internal Mother(XmlElement data)
{
XmlHelper xdata = new XmlHelper(data);
Name = xdata.GetString("MotherName");
Nationality = xdata.GetString("MotherNationality");
IDNumber = xdata.GetString("MotherIDNumber");
Living = xdata.GetString("MotherLiving");
EducationDegree = xdata.GetString("MotherOtherInfo/MotherEducationDegree");
Job = xdata.GetString("MotherOtherInfo/MotherJob");
Phone = xdata.GetString("MotherOtherInfo/Phone");
EMail = xdata.GetString("MotherOtherInfo/EMail");
CompanyName = xdata.GetString("MotherOtherInfo/Company/Name");
CompanyTitle = xdata.GetString("MotherOtherInfo/Company/Title");
CompanyCategory = xdata.GetString("MotherOtherInfo/Company/Category");
CellPhone = xdata.GetString("MotherOtherInfo/PhoneList/Phone[@Title='手機']");
HomePhone = xdata.GetString("MotherOtherInfo/PhoneList/Phone[@Title='住家電話']");
CompanyPhone = xdata.GetString("MotherOtherInfo/PhoneList/Phone[@Title='辦公室電話']");
AddressZipCode = xdata.GetString("MotherOtherInfo/AddressList/Address/ZipCode");
AddressCounty = xdata.GetString("MotherOtherInfo/AddressList/Address/County");
AddressTown = xdata.GetString("MotherOtherInfo/AddressList/Address/Town");
AddressArea = xdata.GetString("MotherOtherInfo/AddressList/Address/Area");
AddressDistrict = xdata.GetString("MotherOtherInfo/AddressList/Address/District");
AddressDetail = xdata.GetString("MotherOtherInfo/AddressList/Address/Detail");
AddressLongitude = xdata.GetString("MotherOtherInfo/AddressList/Address/Longitude");
AddressLatitude = xdata.GetString("MotherOtherInfo/AddressList/Address/Latitude");
}
/// <summary>
/// 存歿,型態需要改為boolean
/// </summary>
public string Living { get; set; }
}
/// <summary>
/// 監護人資訊
/// </summary>
public class Custodian : ParentBase
{
/// <summary>
/// 無參數建構式
/// </summary>
internal Custodian()
{
}
/// <summary>
/// XML參數建構式
/// </summary>
/// <param name="data"></param>
internal Custodian(XmlElement data)
{
XmlHelper xdata = new XmlHelper(data);
Name = xdata.GetString("CustodianName");
Nationality = xdata.GetString("CustodianNationality");
IDNumber = xdata.GetString("CustodianIDNumber");
Relationship = xdata.GetString("CustodianRelationship");
EducationDegree = xdata.GetString("CustodianOtherInfo/EducationDegree");
Job = xdata.GetString("CustodianOtherInfo/Job");
Phone = xdata.GetString("CustodianOtherInfo/Phone");
EMail = xdata.GetString("CustodianOtherInfo/EMail");
CompanyName = xdata.GetString("CustodianOtherInfo/Company/Name");
CompanyTitle = xdata.GetString("CustodianOtherInfo/Company/Title");
CompanyCategory = xdata.GetString("CustodianOtherInfo/Company/Category");
CellPhone = xdata.GetString("CustodianOtherInfo/PhoneList/Phone[@Title='手機']");
HomePhone = xdata.GetString("CustodianOtherInfo/PhoneList/Phone[@Title='住家電話']");
CompanyPhone = xdata.GetString("CustodianOtherInfo/PhoneList/Phone[@Title='辦公室電話']");
AddressZipCode = xdata.GetString("CustodianOtherInfo/AddressList/Address/ZipCode");
AddressCounty = xdata.GetString("CustodianOtherInfo/AddressList/Address/County");
AddressTown = xdata.GetString("CustodianOtherInfo/AddressList/Address/Town");
AddressArea = xdata.GetString("CustodianOtherInfo/AddressList/Address/Area");
AddressDistrict = xdata.GetString("CustodianOtherInfo/AddressList/Address/District");
AddressDetail = xdata.GetString("CustodianOtherInfo/AddressList/Address/Detail");
AddressLongitude = xdata.GetString("CustodianOtherInfo/AddressList/Address/Longitude");
AddressLatitude = xdata.GetString("CustodianOtherInfo/AddressList/Address/Latitude");
}
/// <summary>
/// 稱謂
/// </summary>
public string Relationship { get; set; }
}
}
|
78d687bd54e95571cb04755b07c6b9b8a5dcb950
|
C#
|
dsheehan23/WindowsFormC--DungeonGame
|
/Dungeon_Sheehan/Dungeon_Sheehan/Player.cs
| 3.34375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dungeon_Sheehan
{
public class Player
{
public Player(string NAME)
{
this.Name = NAME;
this.treasure_list = new List<Treasure>();
}
string Name { get; set; }
private List<Treasure> treasure_list = new List<Treasure>();
public double GetTotalTreasureAmount()
{
double total = 0;
foreach (var i in treasure_list)
{
total += i.TreasureAmount;
}
return total;
}
public string DisplayTreasure_List()
{
string treasure = "";
foreach (var element in this.treasure_list)
{
treasure += string.Format("{0} ", element.TreasureName);
}
return treasure;
}
public void SetTreasure_List(Treasure item)
{
treasure_list.Add(item);
}
public void DeleteTreasureList()
{
treasure_list.Clear();
}
public override string ToString()
{
return string.Format(this.Name);
}
}
}
|
740b16dc13962f2e23357877e592ba12f3b9d3a1
|
C#
|
NightOwl888/MvcSiteMapProvider_FluentApiDemo1
|
/src/MvcSiteMapProvider_FluentApiDemo1/_FluentSiteMapNodeProviders/SemanticSiteMapNodeProviderWithoutDynamicNodeProviders.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MvcSiteMapProvider;
using MvcSiteMapProvider.Builder;
using MvcSiteMapProvider.Builder.Fluent;
namespace MvcSiteMapProvider_FluentApiDemo1._FluentSiteMapNodeProviders
{
public class SemanticSiteMapNodeProviderWithoutDynamicNodeProviders
: ISiteMapNodeProvider
{
#region ISiteMapNodeProvider Members
public IEnumerable<ISiteMapNodeToParentRelation> GetSiteMapNodes(ISiteMapNodeHelper helper)
{
// Try the API! Let us know if there is something we can do to make it better.
// This is the same sample as the MvcMusicStore demo, and shows how you can
// mark up the API semantically as a replacement for XML. This example doesn't
// use Dynamic Node Providers as we are evaluating whether it makes sense to
// support them. This would be how the semantic provider would look when used
// in conjunction with the DynamicSiteMapNodeProvider.cs sample.
// Note that the base node of this tree doesn't necessarily have to be the home page.
// You can specify .WithParentKey(string) to indicate that this branch is descending from
// any node defined in any other node source (XML, .NET Attributes, IDynamicNodeProivder,
// ISiteMapNodeBuilder).
// Be sure to try adding nodes yourself to see if you can suggest ways to make this
// more intuitive, easier to read, or easier to write.
return helper.RegisterNode()
.MatchingRoute(x => x.WithController("Home").WithAction("Index"))
.WithDisplayValues(x => x.WithTitle("$resources:SiteMapLocalizations,HomeTitle").WithDescription("This is the home page"))
.WithSeoValues(x => x.WithSiteMaps(y => y.WithChangeFrequency(ChangeFrequency.Always).WithUpdatePriority(UpdatePriority.Normal).WithLastModifiedDate(DateTime.Parse("2002-05-30T09:00:00"))))
.WithChildNodes(homeChildren =>
{
homeChildren.RegisterNode()
.MatchingRoute(x => x.WithController("Store").WithAction("Index"))
.WithDisplayValues(x => x.WithTitle("$resources:SiteMapLocalizations,BrowseGenresTitle"))
.WithChildNodes(genreChildren =>
{
genreChildren.RegisterNode()
.MatchingRoute(x => x.WithController("Store").WithAction("Browse").WithValue("id", "Jazz").WithValue("someOtherParameter", "whatever2"))
.WithDisplayValues(x => x.WithTitle("Jazz 4"))
.WithSeoValues(x => x.WithCanonicalKey("ABC123"));
genreChildren.RegisterNode()
.MatchingRoute(x => x.WithController("Store").WithAction("Browse").WithValue("id", "Jazz").WithValue("someParameter", "hello"))
.WithDisplayValues(x => x.WithTitle("Jazz 2"))
.WithSeoValues(x => x.WithCanonicalUrl("/Store/Browse/Jazz").WithMetaRobotsValues(MetaRobots.NoIndex | MetaRobots.NoFollow | MetaRobots.NoOpenDirectoryProject))
.WithKey("ABC123");
genreChildren.RegisterNode()
.MatchingRoute(x => x.WithController("Store").WithAction("Browse").WithValue("id", "Jazz").WithValue("someParameter", "goodbye"))
.WithDisplayValues(x => x.WithTitle("Jazz 5"))
.WithSeoValues(x => x.WithMetaRobotsValues(MetaRobots.NoIndex | MetaRobots.NoFollow | MetaRobots.NoOpenDirectoryProject | MetaRobots.NoYahooDirectory));
genreChildren.RegisterNode()
.MatchingUrl("~//Store/Browse/Jazz?someParameter=goodbye3") // NOTE: It is not valid to apply route values to a URL based node // TODO: Add inheritable route values.
.WithDisplayValues(x => x.WithTitle("Jazz 6"))
.WithInheritableRouteValues(x => x.WithController("Store").WithAction("Browse").WithValues(new Dictionary<string, object> { { "id", "Jazz" }, { "someOtherParameter", "whatever" } }))
.WithSeoValues(x => x.WithMetaRobotsValues(MetaRobots.NoIndex | MetaRobots.NoFollow | MetaRobots.NoOpenDirectoryProject | MetaRobots.NoYahooDirectory));
});
homeChildren.RegisterNode()
.MatchingRoute(x => x.WithController("ShoppingCart").WithAction("Index"))
.WithDisplayValues(x => x.WithTitle("$resources:SiteMapLocalizations,ReviewCartTitle"));
homeChildren.RegisterNode()
.AsGroupingNodeTitled("$resources:SiteMapLocalizations,CheckoutTitle")
.WithKey("Checkout")
.WithInheritableRouteValues(x => x.WithController("Checkout"));
homeChildren.RegisterNode()
.AsGroupingNodeTitled("$resources:SiteMapLocalizations,AccountTitle")
.WithInheritableRouteValues(x => x.WithController("Account"))
.WithChildNodes(accountChildren =>
{
accountChildren.RegisterNode()
.MatchingRoute(x => x.WithAction("LogOn"))
.WithDisplayValues(x => x.WithTitle("$resources:SiteMapLocalizations,LogOnTitle").WithVisibilityProvider("MvcMusicStore.Code.NonAuthenticatedVisibilityProvider, Mvc Music Store"));
accountChildren.RegisterNode()
.MatchingRoute(x => x.WithAction("LogOff"))
.WithDisplayValues(x => x.WithTitle("$resources:SiteMapLocalizations,LogOffTitle").WithVisibilityProvider("MvcMusicStore.Code.AuthenticatedVisibilityProvider, Mvc Music Store"));
accountChildren.RegisterNode()
.MatchingRoute(x => x.WithAction("Register"))
.WithDisplayValues(x => x.WithTitle("$resources:SiteMapLocalizations,RegisterTitle").WithVisibilityProvider("MvcMusicStore.Code.NonAuthenticatedVisibilityProvider, Mvc Music Store"));
accountChildren.RegisterNode()
.MatchingRoute(x => x.WithAction("ChangePassword"))
.WithDisplayValues(x => x.WithTitle("$resources:SiteMapLocalizations,ChangePasswordTitle").WithVisibilityProvider("MvcMusicStore.Code.AuthenticatedVisibilityProvider, Mvc Music Store"));
accountChildren.RegisterNode()
.MatchingRoute(x => x.WithController("Store").WithAction("Browse").WithValue("id", "Jazz").WithValue("someOtherParameter", "whatever"))
.WithDisplayValues(x => x.WithTitle("Jazz 3").WithVisibilityProvider("MvcMusicStore.Code.AuthenticatedVisibilityProvider, Mvc Music Store"))
.WithSeoValues(x => x.WithCanonicalUrl("http://www.whatever.com/Store/Browse/Jazz"));
});
homeChildren.RegisterNode()
.MatchingRoute(x => x.WithArea("Admin").WithController("Home").WithAction("Index"))
.WithDisplayValues(x => x.WithTitle("$resources:SiteMapLocalizations,AdministrationTitle").WithVisibility("SiteMapPathHelper,!*").WithVisibilityProvider("MvcSiteMapProvider.FilteredSiteMapNodeVisibilityProvider, MvcSiteMapProvider"))
.WithChildNodes(adminChildren =>
{
adminChildren.RegisterNode()
.MatchingRoute(x => x.WithArea("Admin").WithController("StoreManager").WithAction("Index"))
.WithDisplayValues(x => x.WithTitle("$resources:SiteMapLocalizations,StoreManagerTitle"))
.WithChildNodes(storeManagerChildren =>
{
storeManagerChildren.RegisterNode()
.MatchingRoute(x => x.WithAction("Create"))
.WithDisplayValues(x => x.WithTitle("$resources:SiteMapLocalizations,CreateAlbumTitle"));
storeManagerChildren.RegisterNode()
.MatchingRoute(x => x.WithAction("Edit"))
.WithDisplayValues(x => x.WithTitle("$resources:SiteMapLocalizations,EditAlbumTitle"));
storeManagerChildren.RegisterNode()
.MatchingRoute(x => x.WithAction("Delete"))
.WithDisplayValues(x => x.WithTitle("$resources:SiteMapLocalizations,DeleteAlbumTitle"));
});
});
homeChildren.RegisterNode()
.MatchingRoute(x => x.WithAction("SiteMap"))
.WithDisplayValues(x => x.WithTitle("$resources:SiteMapLocalizations,SitemapTitle"))
.WithUrlResolutionValues(x => x.WithUrlResolver("MvcMusicStore.Code.UpperCaseSiteMapNodeUrlResolver, Mvc Music Store"));
homeChildren.RegisterNode()
.MatchingUrl("http://www.microsoft.com/")
.WithDisplayValues(x => x.WithTitle("Microsoft"))
.WithKey("Microsoft");
})
.ToList();
}
#endregion
}
}
|
c97c3e8244bece489d51ca651008bad9d542df80
|
C#
|
GoginashviliBidzina/Booth.Management
|
/Booth.Application/Queries/Product/ProductListingQuery.cs
| 2.65625
| 3
|
using System.Linq;
using FluentValidation;
using System.Threading.Tasks;
using System.Collections.Generic;
using FluentValidation.Attributes;
using Microsoft.EntityFrameworkCore;
using Booth.Application.Infrastructure;
using Booth.Domain.ProductManagement.ReadModels;
namespace Booth.Application.Queries.Product
{
[Validator(typeof(ProductListingQueryValidator))]
public class ProductListingQuery : Query<ProductListingQueryResult>
{
public int BoothId { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public decimal MinPrice { get; set; }
public decimal MaxPrice { get; set; }
public int PageSize { get; set; }
public int PageIndex { get; set; }
public async override Task<QueryExecutionResult<ProductListingQueryResult>> ExecuteAsync()
{
var products = await _db.Set<ProductReadModel>()
.Where(product =>
(string.IsNullOrWhiteSpace(Name) ? true : product.Name.Contains(Name)) &&
(string.IsNullOrWhiteSpace(Code) ? true : product.Code.Contains(Code)) &&
(MinPrice < MaxPrice && MinPrice > 0 && MaxPrice > 0 ? true : product.Price < MaxPrice && product.Price > MinPrice)
)
.Skip(PageSize * PageIndex)
.Take(PageSize)
.ToListAsync();
var listing = products.Select(product => new ProductListing(product.Id,
product.AggregateRootId,
product.Code,
product.Name,
product.Description,
product.Price,
product.SupplierId,
product.PhotoUrl,
product.PhotoWidth,
product.PhotoHeight));
var result = new ProductListingQueryResult(listing.Count() < PageSize,
products.Count(),
listing);
return await OkAsync(result);
}
}
internal class ProductListingQueryValidator : AbstractValidator<ProductListingQuery>
{
public ProductListingQueryValidator()
{
RuleFor(product => product.BoothId)
.GreaterThan(0)
.WithMessage("BoothId should be greater than zero.");
}
}
public class ProductListing
{
public int Id { get; set; }
public int AggregateRootId { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public int SupplierId { get; set; }
public string PhotoUrl { get; set; }
public int PhotoWidth { get; set; }
public int PhotoHeight { get; set; }
public ProductListing(int id,
int aggregateRootId,
string code,
string name,
string description,
decimal price,
int supplierId,
string photoUrl,
int photoWidth,
int photoHeight)
{
Id = id;
AggregateRootId = aggregateRootId;
Name = name;
Code = code;
Description = description;
Price = price;
SupplierId = supplierId;
PhotoUrl = photoUrl;
PhotoWidth = photoWidth;
PhotoHeight = photoHeight;
}
}
public class ProductListingQueryResult
{
public bool IsLastPage { get; set; }
public int TotalCount { get; set; }
public IEnumerable<ProductListing> ProductListing { get; set; }
public ProductListingQueryResult(bool isLastPage,
int totalCount,
IEnumerable<ProductListing> productListing)
{
IsLastPage = isLastPage;
TotalCount = totalCount;
ProductListing = productListing;
}
}
}
|
d318b70c39a182fde2b8efd1093964fc4af191ce
|
C#
|
discord-net/Discord.Net
|
/src/Discord.Net.Core/Entities/Activities/SpotifyGame.cs
| 2.9375
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Discord
{
/// <summary>
/// A user's activity for listening to a song on Spotify.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class SpotifyGame : Game
{
/// <summary>
/// Gets the song's artist(s).
/// </summary>
/// <returns>
/// A collection of string containing all artists featured in the track (e.g. <c>Avicii</c>; <c>Rita Ora</c>).
/// </returns>
public IReadOnlyCollection<string> Artists { get; internal set; }
/// <summary>
/// Gets the Spotify album title of the song.
/// </summary>
/// <returns>
/// A string containing the name of the album (e.g. <c>AVĪCI (01)</c>).
/// </returns>
public string AlbumTitle { get; internal set; }
/// <summary>
/// Gets the track title of the song.
/// </summary>
/// <returns>
/// A string containing the name of the song (e.g. <c>Lonely Together (feat. Rita Ora)</c>).
/// </returns>
public string TrackTitle { get; internal set; }
/// <summary>
/// Gets the date when the track started playing.
/// </summary>
/// <returns>
/// A <see cref="DateTimeOffset"/> containing the start timestamp of the song.
/// </returns>
public DateTimeOffset? StartedAt { get; internal set; }
/// <summary>
/// Gets the date when the track ends.
/// </summary>
/// <returns>
/// A <see cref="DateTimeOffset"/> containing the finish timestamp of the song.
/// </returns>
public DateTimeOffset? EndsAt { get; internal set; }
/// <summary>
/// Gets the duration of the song.
/// </summary>
/// <returns>
/// A <see cref="TimeSpan"/> containing the duration of the song.
/// </returns>
public TimeSpan? Duration { get; internal set; }
/// <summary>
/// Gets the elapsed duration of the song.
/// </summary>
/// <returns>
/// A <see cref="TimeSpan"/> containing the elapsed duration of the song.
/// </returns>
public TimeSpan? Elapsed => DateTimeOffset.UtcNow - StartedAt;
/// <summary>
/// Gets the remaining duration of the song.
/// </summary>
/// <returns>
/// A <see cref="TimeSpan"/> containing the remaining duration of the song.
/// </returns>
public TimeSpan? Remaining => EndsAt - DateTimeOffset.UtcNow;
/// <summary>
/// Gets the track ID of the song.
/// </summary>
/// <returns>
/// A string containing the Spotify ID of the track (e.g. <c>7DoN0sCGIT9IcLrtBDm4f0</c>).
/// </returns>
public string TrackId { get; internal set; }
/// <summary>
/// Gets the session ID of the song.
/// </summary>
/// <remarks>
/// The purpose of this property is currently unknown.
/// </remarks>
/// <returns>
/// A string containing the session ID.
/// </returns>
public string SessionId { get; internal set; }
/// <summary>
/// Gets the URL of the album art.
/// </summary>
/// <returns>
/// A URL pointing to the album art of the track (e.g.
/// <c>https://i.scdn.co/image/ba2fd8823d42802c2f8738db0b33a4597f2f39e7</c>).
/// </returns>
public string AlbumArtUrl { get; internal set; }
/// <summary>
/// Gets the direct Spotify URL of the track.
/// </summary>
/// <returns>
/// A URL pointing directly to the track on Spotify. (e.g.
/// <c>https://open.spotify.com/track/7DoN0sCGIT9IcLrtBDm4f0</c>).
/// </returns>
public string TrackUrl { get; internal set; }
internal SpotifyGame() { }
/// <summary>
/// Gets the full information of the song.
/// </summary>
/// <returns>
/// A string containing the full information of the song (e.g.
/// <c>Avicii, Rita Ora - Lonely Together (feat. Rita Ora) (3:08)</c>
/// </returns>
public override string ToString() => $"{string.Join(", ", Artists)} - {TrackTitle} ({Duration})";
private string DebuggerDisplay => $"{Name} (Spotify)";
}
}
|
cee7a7eef1a23ca5d3aabc84b13f42d696d67d26
|
C#
|
vsk1705/Personal-Projects
|
/Sudoku Solver .NET Console Application/SudokuSolverApp/Strategies/SimpleMarkUpStrategy.cs
| 3.5
| 4
|
using SudokuSolverApp.Data;
using System;
using System.Linq;
namespace SudokuSolverApp.Strategies
{
class SimpleMarkUpStrategy : IStrategy
{
private readonly SudokuMapper _sudokuMapper;
public SimpleMarkUpStrategy(SudokuMapper sudokuMapper)
{
this._sudokuMapper = sudokuMapper;
}
public int[,] Solve(int[,] SudokuMatrix)
{
for(int row = 0; row < SudokuMatrix.GetLength(0); row++)
{
for (int col = 0; col < SudokuMatrix.GetLength(1); col++)
{
if (SudokuMatrix[row, col] == 0 || SudokuMatrix[row, col].ToString().Length > 1)
{
var possibilityInRowAndCol = GetPossibilityInRowAndCol(SudokuMatrix, row, col);
var possibilityInBlock = GetPossibilityInBlock(SudokuMatrix, row, col);
SudokuMatrix[row, col] = GetIntersectionOfPossibilities(possibilityInRowAndCol, possibilityInBlock);
}
}
}
return SudokuMatrix;
}
private int GetPossibilityInRowAndCol(int[,] sudokuMatrix, int givenRow, int givenCol)
{
int[] possibilities = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (int col = 0; col < sudokuMatrix.GetLength(1); col++)
if (IsValidElement(sudokuMatrix[givenRow, col]))
possibilities[sudokuMatrix[givenRow, col] - 1] = 0;
for (int row = 0; row < sudokuMatrix.GetLength(0); row++)
if (IsValidElement(sudokuMatrix[row, givenCol]))
possibilities[sudokuMatrix[row, givenCol] - 1] = 0;
return Convert.ToInt32(String.Join(string.Empty, possibilities.Select(p => p).Where(p => p != 0)));
}
private int GetPossibilityInBlock(int[,] sudokuMatrix, int givenRow, int givenCol)
{
int[] possibilities = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var sudokuMap = _sudokuMapper.Find(givenRow, givenCol);
for (int row = sudokuMap.StartRow; row <= sudokuMap.StartRow + 2; row++)
{
for (int col = sudokuMap.StartCol; col <= sudokuMap.StartCol + 2; col++)
{
if (IsValidElement(sudokuMatrix[row, col])) possibilities[sudokuMatrix[row, col] - 1] = 0;
}
}
return Convert.ToInt32(String.Join(string.Empty, possibilities.Select(p => p).Where(p => p != 0)));
}
private bool IsValidElement(int cellElement) // Helper Method
{
if (cellElement != 0 && cellElement.ToString().Length == 1)
return true;
return false;
}
private int GetIntersectionOfPossibilities(int possibilityInRowAndCol, int possibilityInBlock)
{
var possibilityInRowAndColArray = possibilityInRowAndCol.ToString().ToCharArray();
var possibilityInBlockArray = possibilityInBlock.ToString().ToCharArray();
var possibilityIntersectionArray = possibilityInRowAndColArray.Intersect(possibilityInBlockArray);
return Convert.ToInt32(string.Join(string.Empty, possibilityIntersectionArray));
}
}
}
|