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
|
|---|---|---|---|---|---|---|
903c114eec2f48fefa7a694f792d6d29560fff90
|
C#
|
Azadehkhojandi/RazorEngineTest
|
/Infrastructure/DynamicTemplate.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RazorEngine.Templating;
using System.Reflection;
using System.IO;
namespace Infrastructure
{
public static class DynamicTemplate
{
public static string GiveCshtml<T>(T model,string templateName="GeneralInformation")
{
using (var service = new TemplateService())
{
var layoutTemplate = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("Infrastructure.Templates._Layout.cshtml")).ReadToEnd();
var page = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(string.Format("Infrastructure.Templates.{0}.cshtml", templateName))).ReadToEnd();
service.Compile(layoutTemplate, typeof(T), "_Layout");
return service.Parse(page, model);
}
}
}
}
|
1cb2d12d3605f345e1be0eeab1636c2a311b0d89
|
C#
|
shendongnian/download4
|
/first_version_download2/118665-8287732-18535447-2.cs
| 3.140625
| 3
|
try
{
throw new Derived1();
}
catch (Exceptionz)
{
Console.WriteLine("Caught Derived 1");
}
try
{
throw new Derived2();
}
catch (Exceptionz)
{
Console.WriteLine("Caught Derived 2");
}
|
d512b263048576cc203f76eed675c02d56bc3cf2
|
C#
|
mingw46/FixedBookingsAPI
|
/FixedBookings.Service.API/Mappings/BookingMappings.cs
| 2.75
| 3
|
using FixedBookings.BusinessObject.Models;
using FixedBookings.Service.API.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
namespace FixedBookings.Service.API.Mappings
{
public static class BookingMappings
{
public static BookingModel ToModel(this Booking model)
{
return model != null ? new BookingModel
{
Id = model.Id,
Comments = model.Comments,
CustomerName = model.CustomerName,
EndDate = model.EndDate,
FieldName = model.FieldName,
PhoneNumber = model.PhoneNumber,
StartDate = model.StartDate
} : null;
}
public static Booking ToServiceModel(this BookingModel model)
{
return model != null ? new Booking
{
Id = model.Id,
Comments = model.Comments,
CustomerName = model.CustomerName,
EndDate = model.EndDate,
FieldName = model.FieldName,
PhoneNumber = model.PhoneNumber,
StartDate = model.StartDate
} : null;
}
public static IReadOnlyCollection<BookingModel> ToModel(this IReadOnlyCollection<Booking> models)
{
if (models.Count == 0)
{
return Array.Empty<BookingModel>();
}
var bookings = new BookingModel[models.Count];
var i = 0;
foreach (var model in models)
{
bookings[i] = model.ToModel();
++i;
}
return new ReadOnlyCollection<BookingModel>(bookings);
}
}
}
|
650313973e33d008a5e419e5299c37d2a4357221
|
C#
|
pasi0014/Lab-3-ASP.NET
|
/Models/CourseComparerByName.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AlgonquinCollege.Registration.Entities;
namespace Lab_3.Models
{
public class CourseComparerByName : IComparer<Course>
{
public CourseComparerByName()
{
}
public int Compare(Course c1, Course c2)
{
if (c1 == null)
{
throw new ArgumentNullException("c1");
}
if (c2 == null)
{
throw new ArgumentNullException("c2");
}
string cName1 = c1.CourseName.Split(' ')[0];
string cName2 = c2.CourseName.Split(' ')[0];
if(cName1.CompareTo(cName2) != 0)
{
return cName1.CompareTo(cName2);
}
return c1.CourseNumber.CompareTo(c2.CourseNumber);
}
}
}
|
f0c7b87eb26683c1fa756b8a4aa3db197cd92091
|
C#
|
anatolii-kabanov/prime-number-multiplication
|
/Avast.Tests.PrimeNumber/Generators/PrimeNumberGeneratorTests.cs
| 2.875
| 3
|
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Avast.PrimeNumber.Checkers;
using Avast.PrimeNumber.Generators;
using Microsoft.Extensions.Logging;
using Moq;
using Xunit;
namespace Avast.Tests.PrimeNumber.Generators
{
public class PrimeNumberGeneratorTests
{
private readonly IPrimeNumberGenerator _primeNumberGenerator;
private readonly long[] _primeNumbersArray = new long[] { 2, 3, 5, 7, 11, 13 };
public PrimeNumberGeneratorTests()
{
var mockedLogger = new Mock<ILogger<PrimeNumberGenerator>>();
var mockedPrimeNumberChecker = new Mock<IPrimeNumberChecker>();
mockedPrimeNumberChecker.Setup(p => p.IsPrime(It.IsAny<long>(), It.IsAny<CancellationToken>())).ReturnsAsync(true);
_primeNumberGenerator = new PrimeNumberGenerator(mockedPrimeNumberChecker.Object, mockedLogger.Object);
}
[Theory]
[InlineData(1)]
[InlineData(2)]
public async Task Next_Should_Return_Excpected_Array(int quantity)
{
var resultArray = await _primeNumberGenerator.Next(quantity).ConfigureAwait(false);
Assert.Equal(resultArray.Length, quantity + 1);
Assert.All(resultArray, item => _primeNumbersArray.Contains(item));
}
[Theory]
[InlineData(0)]
[InlineData(-123)]
public void Next_Throws_ArgumentOutOfRangeException(int quantity)
{
Assert.ThrowsAsync<ArgumentOutOfRangeException>(async () => await _primeNumberGenerator.Next(quantity).ConfigureAwait(false));
}
}
}
|
6062ddb9da976a94c507e4391410c4a9581a3343
|
C#
|
oguzhankahyaoglu/joinextensions-leftjoin
|
/LeftJoin/LeftJoinExtensions.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using LinqKit;
namespace LeftJoin
{
public static class LeftJoinExtensions
{
public static IQueryable<TResult> LeftJoin<TLeft, TRight, TKey, TResult>(
this IQueryable<TLeft> left,
IQueryable<TRight> right,
Expression<Func<TLeft, TKey>> leftKey,
Expression<Func<TRight, TKey>> rightKey,
Func<TLeft, TRight, TResult> resultFunc
)
{
/*
var query = (
from l in left
join r in right on leftKey(l) equals rightKey(r)
into j1
from r1 in j1.DefaultIfEmpty()
select resultFunc(l, r1)
);
*/
// var query = left
// .GroupJoin(right, leftKey, rightKey, (l, j1) => new {l, j1})
// .SelectMany(t => t.j1.DefaultIfEmpty(), (t, r1) => resultFunc(t.l, r1));
var result = left
.AsExpandable()// Tell LinqKit to convert everything into an expression tree.
.GroupJoin(
right,
leftKey,
rightKey,
(outerItem, innerItems) => new { outerItem, innerItems })
.SelectMany(
joinResult => joinResult.innerItems.DefaultIfEmpty(),
(joinResult, innerItem) =>
resultFunc(joinResult.outerItem, innerItem));
return result;
}
/// <summary>
/// DO NOT USE THIS OVERLOAD (Ienumerable) with EntityFramework or Database-related logic, since it will directly enumerate the query to database.
/// In order to ensure that your query works on your database, USE IQUERYABLE OVERLOAD
/// </summary>
[Obsolete("DO NOT USE THIS OVERLOAD (Ienumerable) with EntityFramework or Database-related logic, since it will directly enumerate the query to database. In order to ensure that your query works on your database, USE IQUERYABLE OVERLOAD")]
public static IEnumerable<TResult> LeftJoin<TLeft, TRight, TKey, TResult>(
this IEnumerable<TLeft> left,
IEnumerable<TRight> right,
Func<TLeft, TKey> leftKey,
Func<TRight, TKey> rightKey,
Func<TLeft, TRight, TResult> resultFunc
)
{
/*
var query = (
from l in left
join r in right on leftKey(l) equals rightKey(r)
into j1
from r1 in j1.DefaultIfEmpty()
select resultFunc(l, r1)
);
*/
var query = left
.GroupJoin(right, leftKey, rightKey, (l, j1) => new {l, j1})
.SelectMany(t => t.j1.DefaultIfEmpty(), (t, r1) => resultFunc(t.l, r1));
return query;
}
}
}
|
c25c01b5ff49e4cb36c4061e3453a5c2e11f5cf6
|
C#
|
taeNero/PremiumService
|
/premiumTravel/premiumTravel/TripStateComplete.cs
| 2.859375
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace premiumTravel
{
public class TripStateComplete : TripState
{
public TripStateComplete(TripContext context) :
base(context, TripState.Status.Complete)
{
}
public override TripStateLoop.Status Execute()
{
Console.WriteLine(Environment.NewLine + "***COMPLETE - ITINERARY AVAILABLE ***");
Console.WriteLine();
//this is the end, so stop looping
return TripStateLoop.Status.Stop;
}
}
}
|
59d301916c7392cb3c6b525d6140bfac3c3f7b7a
|
C#
|
lijinchuan/LJC.FrameWork
|
/LJC.FrameWork/Data/QuickDataBase/DataContextMoudelSelect.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Linq.Expressions;
using System.Text.RegularExpressions;
using LJC.FrameWork.Comm;
namespace LJC.FrameWork.Data.QuickDataBase
{
public static class DataContextMoudelSelect
{
/// <summary>
/// 变量名正则
/// </summary>
private static readonly Regex varNameReg = new Regex(@"\.([_a-zA-Z\u4E00-\u9FA5\uF900-\uFA2D][_a-zA-Z0-9\u4E00-\u9FA5 \uF900-\uFA2D]*)",RegexOptions.Compiled);
internal static string GetColNameFromExpression<T>(this DataContextMoudle<T> dataContext, string expressionBody) where T : new()
{
string propname= varNameReg.Match(expressionBody).Groups[1].Value;
var reportattr= dataContext.rpAttrList.Find(p => p.Property.Name.Equals(propname, StringComparison.OrdinalIgnoreCase));
if (reportattr == null)
throw new Exception(string.Format("找不到属性'{0}'对应的表列。",propname));
return reportattr.Column;
}
private static void Addp(this List<Mess_Three<string, string, object>> list, Mess_Three<string, string, object> addVal)
{
if (list == null)
list = new List<Mess_Three<string, string, object>>();
int i = 0;
if ((i = list.Where((m) => m.First.Equals(addVal.First)).Count()) > 0)
{
addVal.First += "$" + i;
list.Add(addVal);
}
else
{
list.Add(addVal);
}
}
public static DataContextMoudle<T> Top<T>(this DataContextMoudle<T> dataContext, int top) where T : new()
{
dataContext.topNum = top;
return dataContext;
}
public static DataContextMoudle<T> WhereEq<T>(this DataContextMoudle<T> dataContext, string column, object val) where T : new()
{
dataContext.selPara.Addp(new Mess_Three<string, string, object>(column, "=", val));
return dataContext;
}
public static DataContextMoudle<T> WhereIn<T>(this DataContextMoudle<T> dataContext, string column, object val) where T : new()
{
dataContext.selPara.Addp(new Mess_Three<string,string,object>(column," in ",val));
return dataContext;
}
public static DataContextMoudle<T> WhereIn<T>(this DataContextMoudle<T> dataContext, Expression<Func<T, object>> colExpress, object val) where T : new()
{
return dataContext.WhereIn<T>(dataContext.GetColNameFromExpression(colExpress.Body.ToString()), val);
}
public static DataContextMoudle<T> WhereEq<T>(this DataContextMoudle<T> dataContext, Expression<Func<T, object>> colExpress, object val) where T : new()
{
return dataContext.WhereEq(dataContext.GetColNameFromExpression(colExpress.Body.ToString()), val);
}
public static DataContextMoudle<T> WhereNotEq<T>(this DataContextMoudle<T> dataContext, string column, object val) where T : new()
{
dataContext.selPara.Addp(new Mess_Three<string, string, object>(column, "<>", val));
return dataContext;
}
public static DataContextMoudle<T> WhereNotEq<T>(this DataContextMoudle<T> dataContext,Expression<Func<T,object>> colExpress, object val) where T : new()
{
return dataContext.WhereNotEq(dataContext.GetColNameFromExpression(colExpress.Body.ToString()), val);
}
public static DataContextMoudle<T> WhereBiger<T>(this DataContextMoudle<T> dataContext, string column, object val) where T : new()
{
dataContext.selPara.Addp(new Mess_Three<string, string, object>(column, ">", val));
return dataContext;
}
public static DataContextMoudle<T> WhereBiger<T>(this DataContextMoudle<T> dataContext, Expression<Func<T, object>> colExpress, object val) where T : new()
{
return dataContext.WhereBiger(dataContext.GetColNameFromExpression(colExpress.Body.ToString()), val);
}
public static DataContextMoudle<T> WhereBigerEq<T>(this DataContextMoudle<T> dataContext, string column, object val) where T : new()
{
dataContext.selPara.Addp(new Mess_Three<string, string, object>(column, ">=", val));
return dataContext;
}
public static DataContextMoudle<T> WhereBigerEq<T>(this DataContextMoudle<T> dataContext, Expression<Func<T, object>> colExpress, object val) where T : new()
{
return dataContext.WhereBigerEq(dataContext.GetColNameFromExpression(colExpress.Body.ToString()), val);
}
public static DataContextMoudle<T> WhereSmaller<T>(this DataContextMoudle<T> dataContext, string column, object val) where T : new()
{
dataContext.selPara.Addp(new Mess_Three<string, string, object>(column, "<", val));
return dataContext;
}
public static DataContextMoudle<T> WhereSmaller<T>(this DataContextMoudle<T> dataContext, Expression<Func<T, object>> colExpress, object val) where T : new()
{
return dataContext.WhereSmaller(dataContext.GetColNameFromExpression(colExpress.Body.ToString()), val);
}
public static DataContextMoudle<T> WhereSmallerEq<T>(this DataContextMoudle<T> dataContext, string column, object val) where T : new()
{
dataContext.selPara.Addp(new Mess_Three<string, string, object>(column, "<=", val));
return dataContext;
}
public static DataContextMoudle<T> WhereSmallerEq<T>(this DataContextMoudle<T> dataContext, Expression<Func<T, object>> colExpress, object val) where T : new()
{
return dataContext.WhereSmallerEq(dataContext.GetColNameFromExpression(colExpress.Body.ToString()), val);
}
public static DataContextMoudle<T> OrderBy<T>(this DataContextMoudle<T> dataContext, string col) where T : new()
{
dataContext.orderByList.Add(new DBOrderby
{
OrderbyColumnName=col,
OrderbyDirection=DBOrderbyDirection.asc,
});
return dataContext;
}
public static DataContextMoudle<T> OrderBy<T>(this DataContextMoudle<T> dataContext, Expression<Func<T, object>> colExpress) where T : new()
{
return dataContext.OrderBy<T>(dataContext.GetColNameFromExpression(colExpress.Body.ToString()));
}
public static DataContextMoudle<T> OrderByDesc<T>(this DataContextMoudle<T> dataContext, string col) where T : new()
{
dataContext.orderByList.Add(new DBOrderby
{
OrderbyColumnName = col,
OrderbyDirection = DBOrderbyDirection.desc,
});
return dataContext;
}
public static DataContextMoudle<T> OrderByDesc<T>(this DataContextMoudle<T> dataContext, Expression<Func<T, object>> colExpress) where T : new()
{
return dataContext.OrderByDesc<T>(dataContext.GetColNameFromExpression(colExpress.Body.ToString()));
}
public static bool Exists<T>(this DataContextMoudle<T> dataContext, string column, object val) where T : new()
{
return dataContext.WhereEq(column, val).ExecuteEntity() != null;
}
public static bool Exists<T>(this DataContextMoudle<T> dataContext, Expression<Func<T, object>> colExpress, object val) where T : new()
{
return dataContext.Exists(dataContext.GetColNameFromExpression(colExpress.Body.ToString()), val);
}
public static bool Exists<T>(this DataContextMoudle<T> dataContext) where T : new()
{
return dataContext.Exists(dataContext.keyName, dataContext.GetKeyValue());
}
}
}
|
01252bfaa8d76ebf64d9774aaf40656a745ef81e
|
C#
|
sobanskikarol91/Duel
|
/Duel/Assets/Scripts/PlayerDeck.cs
| 2.640625
| 3
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
[System.Serializable]
public class PlayerDeck
{
public List<PlayerCard> slotOnTable;
public Dictionary<CARD_TYPE, List<PlayerCard>> _cards { get; set; } = new Dictionary<CARD_TYPE, List<PlayerCard>>();
Card _card;
Player _player;
public bool CheckSymbol(Card card)
{
// List<Card> cards = _cards[card.type];
// return cards.Exists(c => c.getForSign == card.signToFreeBuy);
return false;
}
#region Convert List of Empty slots to Dictionary
public void Init(Player p)
{
_player = p;
ConvertListSlotsToDict();
SortSlotsInLists();
SetOrderingInLayerSlots();
}
void ConvertListSlotsToDict()
{
for (int i = 0; i < slotOnTable.Count; i++)
{
CARD_TYPE type = slotOnTable[i].type;
if (_cards.ContainsKey(type))
AddEmptySlotToExistListInDictionary(slotOnTable[i]);
else
AddSlotAsNewKeyInDirection(slotOnTable[i]);
}
}
void AddEmptySlotToExistListInDictionary(PlayerCard slot)
{
List<PlayerCard> slotList = _cards[slot.type];
slotList.Add(slot);
}
void AddSlotAsNewKeyInDirection(PlayerCard slot)
{
_cards.Add(slot.type, new List<PlayerCard>());
}
#endregion
#region Add bought Card to Player's specific cards group
public void AddCardToPlayerSlot(Card _card)
{
this._card = _card;
PlayerCard empty = FindEmptySpotInGroup();
empty._card = _card;
empty.Display();
}
PlayerCard FindEmptySpotInGroup()
{
List<PlayerCard> _cardGroup = GetAllSlotsForCardType();
return _cardGroup.First(p => p._card == null);
}
List<PlayerCard> GetAllSlotsForCardType()
{
List<PlayerCard> c = new List<PlayerCard>();
if (!_cards.TryGetValue(_card.Type, out c))
Debug.Log("Nie ma takiego typu:" + _card.Type);
return _cards[_card.Type];
}
#endregion
public void SortSlotsInLists()
{
int direction = _player.Id == 1 ? 1 : -1;
foreach (var list in _cards)
{
list.Value.Sort(
delegate (PlayerCard p1, PlayerCard p2)
{ return ((direction) * p1.transform.position.y).
CompareTo(p2.transform.position.y * (direction));}
);
}
}
void SetOrderingInLayerSlots()
{
foreach (var list in _cards)
for (int i = 0; i < list.Value.Count; i++)
list.Value[i].GetComponent<SpriteRenderer>().sortingOrder = i;
}
}
|
218165cfc43f5fb71ff7b2c5c3debf748d85e578
|
C#
|
Zexks/QLite
|
/QLite V3/Servers/Row.cs
| 2.859375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace QLite.Servers
{
public class Row
{
public List<Column> Columns { get; set; }
public int ColCount { get; set; }
public string[] DataTypes { get; set; }
public string[] Values { get; set; }
public Row() { }
public Row(DataRow row)
{
ColCount = row.ItemArray.Length;
LoadDataTypes(row);
LoadDataValues(row);
}
private void LoadDataTypes(DataRow row)
{
int count = 0;
DataTable tmpTable = row.Table;
foreach (DataColumn col in tmpTable.Columns)
Columns.Add(new Column(col));
DataTypes = new string[Columns.Count];
foreach (Column col in Columns)
DataTypes[count] = col.DataType;
}
private void LoadDataValues(DataRow row)
{
DataTable tmpTable = row.Table;
Values = new string[Columns.Count];
for (int x = 0; x < row.ItemArray.Length; x++)
Values[x] = row.ItemArray[x].ToString();
}
#region Resource Cleanup
private bool IsDisposed = false;
public void Free()
{
if (IsDisposed)
{ throw new System.ObjectDisposedException("Object Name"); }
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~Row()
{
Dispose(false);
}
protected virtual void Dispose(bool disposedStatus)
{
if (!IsDisposed)
{
IsDisposed = true;
if (disposedStatus) { }
}
}
#endregion
}
}
|
03a04dae3c71a8d46416ff54e4cc34644eef277a
|
C#
|
bursson/Drinkkirobotti_4_1
|
/OperatorUI/ViewModel.cs
| 2.78125
| 3
|
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using System.Windows.Shapes;
namespace OperatorUI
{
public sealed class ViewModel : INotifyPropertyChanged, IOperatorLogger
{
public ViewModel()
{
LogOutputs = new ObservableCollection<LogOutput>();
}
private int _counter;
public int Counter
{
get { return _counter; }
set
{
if (value == _counter) return;
_counter = value;
OnPropertyChanged();
}
}
public ObservableCollection<LogOutput> LogOutputs { get; set; }
public void AddLogOutput(LogOutput newOutput)
{
LogOutputs.Insert(0, newOutput);
// TODO This never seems to return? :o
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private Shape _layoutImage;
public Shape LayoutImage
{
get { return _layoutImage; }
set
{
_layoutImage = value;
OnPropertyChanged();
}
}
public void InitializeLayoutImage(MainWindow mainWindow)
{
double width = mainWindow.LayoutCanvas.Width;
double height = width;
double unit = width / 12;
List<List<Vector>> shapeList = new List<List<Vector>>();
// Borders
List<Vector> borders = new List<Vector>();
borders.Add(new Vector(0, 0));
borders.Add(new Vector(0, width));
borders.Add(new Vector(height, width));
borders.Add(new Vector(height, 0));
borders.Add(new Vector(0, 0));
shapeList.Add(borders);
// Outer lines
List<Vector> outerShape = new List<Vector>();
outerShape.Add(new Vector(0, 0));
outerShape.Add(new Vector(0, 4 * unit));
outerShape.Add(new Vector(8 * unit, 4 * unit));
outerShape.Add(new Vector(8 * unit, 12 * unit));
outerShape.Add(new Vector(12 * unit, 12 * unit));
shapeList.Add(outerShape);
// Inner lines
List<Vector> innerShape = new List<Vector>();
innerShape.Add(new Vector(2*unit, 0));
innerShape.Add(new Vector(2*unit, 2*unit));
innerShape.Add(new Vector(10*unit, 2*unit));
innerShape.Add(new Vector(10*unit, 10*unit));
innerShape.Add(new Vector(12*unit, 10*unit));
shapeList.Add(innerShape);
foreach (var shape in shapeList)
{
for (int i = 0; i < shape.Count - 1; i++)
{
var line = new Line();
line.Stroke = Brushes.Black;
line.X1 = shape[i].X;
line.Y1 = shape[i].Y;
line.X2 = shape[i + 1].X;
line.Y2 = shape[i + 1].Y;
mainWindow.LayoutCanvas.Children.Add(line);
}
}
// Add drinks
// TODO: somehow link objects to private members so color can be changed
// Lower
var ellipse = new Ellipse();
ellipse.Stroke = Brushes.DarkRed;
ellipse.StrokeThickness = 3;
ellipse.Width = 1.5*unit;
ellipse.Height = 1.5*unit;
Canvas.SetLeft(ellipse, 0.25*unit);
Canvas.SetTop(ellipse, 2.25*unit);
mainWindow.LayoutCanvas.Children.Add(ellipse);
var ellipse2 = new Ellipse();
ellipse2.Stroke = Brushes.DarkRed;
ellipse2.StrokeThickness = 3;
ellipse2.Width = 1.5 * unit;
ellipse2.Height = 1.5 * unit;
Canvas.SetLeft(ellipse2, 5.25 * unit);
Canvas.SetTop(ellipse2, 2.25 * unit);
mainWindow.LayoutCanvas.Children.Add(ellipse2);
var ellipse3 = new Ellipse();
ellipse3.Stroke = Brushes.DarkRed;
ellipse3.StrokeThickness = 3;
ellipse3.Width = 1.5 * unit;
ellipse3.Height = 1.5 * unit;
Canvas.SetLeft(ellipse3, 8.25 * unit);
Canvas.SetTop(ellipse3, 5.25 * unit);
mainWindow.LayoutCanvas.Children.Add(ellipse3);
var ellipse4 = new Ellipse();
ellipse4.Stroke = Brushes.DarkRed;
ellipse4.StrokeThickness = 3;
ellipse4.Width = 1.5 * unit;
ellipse4.Height = 1.5 * unit;
Canvas.SetLeft(ellipse4, 8.25 * unit);
Canvas.SetTop(ellipse4, 10.25 * unit);
mainWindow.LayoutCanvas.Children.Add(ellipse4);
// Higher
var ellipse5 = new Ellipse();
ellipse5.Stroke = Brushes.DarkRed;
ellipse5.StrokeThickness = 3;
ellipse5.Width = 1.5 * unit;
ellipse5.Height = 1.5 * unit;
Canvas.SetLeft(ellipse5, 4.25 * unit);
Canvas.SetTop(ellipse5, 0.25 * unit);
mainWindow.LayoutCanvas.Children.Add(ellipse5);
var ellipse6 = new Ellipse();
ellipse6.Stroke = Brushes.DarkRed;
ellipse6.StrokeThickness = 3;
ellipse6.Width = 1.5 * unit;
ellipse6.Height = 1.5 * unit;
Canvas.SetLeft(ellipse6, 10.25 * unit);
Canvas.SetTop(ellipse6, 0.25 * unit);
mainWindow.LayoutCanvas.Children.Add(ellipse6);
var ellipse7 = new Ellipse();
ellipse7.Stroke = Brushes.DarkRed;
ellipse7.StrokeThickness = 3;
ellipse7.Width = 1.5 * unit;
ellipse7.Height = 1.5 * unit;
// Tooltip test
var tooltip = new ToolTip();
tooltip.Content = "Olen viinaa";
ellipse.ToolTip = tooltip;
tooltip.Placement = PlacementMode.Right;
tooltip.HorizontalOffset = 10;
tooltip.VerticalOffset = 10;
Canvas.SetLeft(ellipse7, 10.25 * unit);
Canvas.SetTop(ellipse7, 6.25 * unit);
mainWindow.LayoutCanvas.Children.Add(ellipse7);
}
private class Vector
{
public Vector(double x, double y)
{
X = x;
Y = y;
}
public double X;
public double Y;
}
private Ellipse _testEllipse;
}
}
|
2d869879d40b3ca47198091df5114aeca188de56
|
C#
|
CrimeMasterGogo31/DsAlgoSample
|
/LeetCode/MaxArea.cs
| 3.390625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace DemoConsole.LeetCode
{
public class MaxAreaClass
{
static Dictionary<string, int> d = new Dictionary<string, int>();
public int MaxArea(int[] height)
{
var res = DP(0, height.Length - 1, height);
return res;
}
int DP(int s, int e, int[] height)
{
if (s >= e)
return 0;
//var key = $"{s}#{e}";
var h = Math.Min(height[s], height[e]);
var area = h * (e - s);
return Math.Max(
area, Math.Max(
DP(s + 1, e, height),
Math.Max(
DP(s, e - 1, height),
DP(s + 1, e - 1, height))));
}
}
}
|
72391cabda3410f2370f8d49aaaadb695f0bbcfb
|
C#
|
shendongnian/download4
|
/latest_version_download2/58228-10491713-24151614-2.cs
| 2.84375
| 3
|
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["StartDates"] == null)
{
startDates = new ArrayList();
}
else
{
startDates = ViewState["StartDates"] as ArrayList;
}
}
protected void StartSelection_Changed(Object sender, EventArgs e)
{
startCalendar.SelectedDate = new DateTime(startCalendar.SelectedDate.Year,
startCalendar.SelectedDate.Month, startCalendar.SelectedDate.Day, 0, 0, 0);
// c.f. http://www.mikepope.com/blog/AddComment.aspx?blogid=604
int index = -1;
index = startDates.IndexOf(startCalendar.SelectedDate);
if (index >= 0)
{
startDates.RemoveAt(index);
}
else
{
DateTime dateTime
= new DateTime(startCalendar.SelectedDate.Year,
startCalendar.SelectedDate.Month,
startCalendar.SelectedDate.Day, 0, 0, 0);
startDates.Add(dateTime);
}
ViewState["StartDates"] = startDates;
DisplaySelectedDates();
}
protected void DisplaySelectedDates()
{
startCalendar.SelectedDates.Clear();
for (int i = 0; i < startDates.Count; i++)
{
startCalendar.SelectedDates.Add((DateTime)startDates[i]);
}
}
|
364e0362a46e89223678a17202c58aa6a1884856
|
C#
|
Tanvas/convertorXML2HTML
|
/CourceToWebUC/Model/CommonModels/IItemModel.cs
| 2.71875
| 3
|
/*
* Библиотека для конвертации курса в web формат
* Разработчик: Лобанова Т.В.
*
* Файл: IItemModel.cs
* Создан: 25.02.2015
* Редактирован: 04.03.2015
*
*
* Описание:
* Section - Учебный раздел, входящий в курс или в другой учебный раздел
* Theme - Учебная тема
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.XPath;
namespace CourceToWebUC.Model
{
/// <summary>
/// интерфейс элемента
/// курса
/// </summary>
public interface IItemModel
{
/// <summary>
/// идентификатор элемента
/// </summary>
Guid Id {get;}
/// <summary>
/// тип элемента
/// </summary>
ItemType Type { get; }
/// <summary>
/// название
/// </summary>
string Title { get; }
/// <summary>
/// коллекция дочерних
/// элементов курса
/// </summary>
IList<IItemModel> Items { get; }
/// <summary>
/// конвертировать
/// ли элемент курса
/// </summary>
bool IsConvert { get; }
/// <summary>
/// установить флаг конвертации
/// себе или дочерниму элементу
/// </summary>
/// <param name="id">идентификатор</param>
/// <param name="_isConvert">значение флага</param>
/// <returns>успешность установки</returns>
bool SetIsConvertSelfOrChildren(Guid id, bool _isConvert);
/// <summary>
/// получить элемент курса по
/// идентификатору в потомках
/// </summary>
/// <param name="_id">идентификатор</param>
/// <returns>элемент курса</returns>
IItemModel GetItemInChildren(Guid _id);
}
}
|
2ff0cf739d9a2f6dac28786897d495ad2981eb11
|
C#
|
johndmeyer/sovoscodingexercise
|
/Backup/SovosCodingExercise.Api/Controllers/IngredientController.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using SovosCodingExercise.BusinessLogic;
using SovosCodingExercise.DataModels;
namespace SovosCodingExercise.Api.Controllers
{
/// <summary>
/// Need comments here
/// </summary>
public class IngredientController : ApiController
{
private readonly IngredientLogic _ingredientLogic = null;
/// <summary>
/// Comments here
/// </summary>
public IngredientController()
{
_ingredientLogic = new IngredientLogic();
}
// GET api/values
/// <summary>
/// Comments here
/// </summary>
/// <returns></returns>
public IEnumerable<IngredientDataModel> Get()
{
// Error Handling
try
{
// Validate Inputs
// Call Business Logic to get data
return _ingredientLogic.RetrieveIngredients();
}
catch
{
// Log Error
// Return Error
return new List<IngredientDataModel> { new IngredientDataModel { ErrorMessage = "Error occured" } };
}
}
//// GET api/values/5
//public string Get(int id)
//{
// return "value";
//}
//// POST api/values
//public void Post([FromBody]string value)
//{
//}
//// PUT api/values/5
//public void Put(int id, [FromBody]string value)
//{
//}
//// DELETE api/values/5
//public void Delete(int id)
//{
//}
}
}
|
b915897e47eeb545d00e99f1106f130eb5382a8c
|
C#
|
alexhagithub/zav-crud-server-cshard
|
/Crud.Domain/ModelConfig/VisitaConfig.cs
| 2.546875
| 3
|
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Crud.Domain
{
class VisitaConfig : IEntityTypeConfiguration<VisitaEntity>
{
public void Configure(EntityTypeBuilder<VisitaEntity> builder)
{
builder.ToTable("Visita", "dbo")
.HasKey(k => k.Id);
builder.Property(p => p.Id)
.ValueGeneratedOnAdd();
builder.Property(p => p.Nombre)
.HasMaxLength(30)
.IsUnicode(false)
.IsRequired();
builder.Property(p => p.Correo)
.HasMaxLength(150)
.IsUnicode(true)
.IsRequired();
builder.Property(p => p.Celular)
.IsRequired();
builder.Property(p => p.Motivo)
.IsRequired();
builder.Property(p => p.Comentario)
.HasColumnType("varchar(MAX)");
builder.Seed();
}
}
}
|
9fa148e2fe58721633c7f740b4678141b00dc53c
|
C#
|
luisferop/DesignPatterns
|
/prjBehavioral/Observer/Unsubscriber.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace prjBehavioral.Observer
{
class Unsubscriber : IDisposable
{
private List<IObserver<Carro>> _observers;
private IObserver<Carro> _observer;
public Unsubscriber(List<IObserver<Carro>> observers, IObserver<Carro> observer)
{
this._observers = observers;
this._observer = observer;
}
public void Dispose()
{
if (!(_observer == null)) _observers.Remove(_observer);
}
}
}
|
240adc4dc2cbedb37635647df6615579893bc78b
|
C#
|
otaviorbarros/praticasdiarias
|
/Praticas/FrmFuncao.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Praticas
{
public partial class FrmFuncao : Form
{
public FrmFuncao()
{
InitializeComponent();
}
private void btnCalcular_Click(object sender, EventArgs e)
{
double num1 = Convert.ToDouble((txtNum_1.Text) == "" ? 0 : Convert.ToDouble(txtNum_1.Text));
double num2 = Convert.ToDouble((txtNum_2.Text) == "" ? 0 : Convert.ToDouble(txtNum_2.Text));
double num3 = Convert.ToDouble((txtNum_3.Text) == "" ? 0 : Convert.ToDouble(txtNum_3.Text));
double num4 = Convert.ToDouble((txtNum_4.Text) == "" ? 0 : Convert.ToDouble(txtNum_4.Text));
double num5 = Convert.ToDouble((txtNum_5.Text) == "" ? 0 : Convert.ToDouble(txtNum_5.Text));
double calc1 = Calculo_1(num1, num2);
double div = Dividir(calc1, num3);
double quad = Quadrado(div, num4);
double sub = Subtrair(quad, num5);
lblResultado.Text = sub.ToString();
}
private double Calculo_1(double num1, double num2)
{
return num1 + num2;
}
private double Dividir(double result_cal1, double num3)
{
return result_cal1 / num3;
}
private double Quadrado(double result_div, double num4)
{
return result_div +(num4 * num4);
}
private double Subtrair(double resultQuad, double num5)
{
return resultQuad - num5;
}
private void btnLimpar_Click(object sender, EventArgs e)
{
txtNum_1.Clear();
txtNum_2.Clear();
txtNum_3.Clear();
txtNum_4.Clear();
txtNum_5.Clear();
lblResultado.Text = "";
}
}
}
|
6797e9258e037d26fff29abb6cf709ee4e979b61
|
C#
|
Lalitha23/BankApp17
|
/BankApp/Bank.cs
| 3.265625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankApp
{
public static class Bank
{
private static BankModel db = new BankModel();
// private static List<Account> accounts = new List<Account>();
/// <summary>
/// Create a bank account
/// </summary>
/// <param name="emailAddress">Email address for acc</param>
/// <param name="accountName">Name of the account</param>
/// <param name="accountType">Type of account</param>
/// <returns>Returns bank account</returns>
/// <exception cref="ArgumentNullException"/>
public static Account CreateAccount(String emailAddress, string accountName = "Default Name",
TypeOfAccount accountType = TypeOfAccount.Checkings)
{
if(string.IsNullOrEmpty(emailAddress))
{ throw new ArgumentNullException("emailAddress", "Email address cannot be empty."); }
var account = new Account
{
EmailAddress = emailAddress,
AccountName = accountName,
AccountType = accountType
};
db.Accounts.Add(account);
db.SaveChanges();
return account;
}
public static List<Account> GetAllAccounts(string emailAddress)
{
return db.Accounts.Where(a => a.EmailAddress == emailAddress).ToList();
}
public static List<Transaction> GetAllTransactions(int accountNumber)
{
return db.Transactions.Where(t => t.AccountNumber == accountNumber).OrderByDescending(t => t.TransactionDate).ToList();
}
public static void Deposit(int accountNumber, decimal amount)
{
var account = db.Accounts.Where(a => a.AccountNumber == accountNumber).FirstOrDefault();
if(account != null)
{
account.Deposit(amount);
var transaction = new Transaction
{
TransactionDate = DateTime.Now,
TypeOfTransaction = TransactionType.Credit,
TransactionAmount = amount,
Description = " Deposit from branch",
AccountNumber = account.AccountNumber
};
db.Transactions.Add(transaction);
db.SaveChanges();
}
}
public static Account EditAccount(Account account)
{
if (account == null)
throw new ArgumentNullException("account", "Invalid account");
var oldAccount = db.Accounts.Find(account.AccountNumber);
db.Entry(oldAccount).CurrentValues.SetValues(account);
db.SaveChanges();
}
public static void Withdraw(int accountNumber, decimal amount)
{
var account = db.Accounts.Where(a => a.AccountNumber == accountNumber).FirstOrDefault();
if (account != null)
{
account.Withdraw(amount);
var transaction = new Transaction
{
TransactionDate = DateTime.Now,
TypeOfTransaction = TransactionType.Debit,
TransactionAmount = amount,
Description = "Withdraw from branch",
AccountNumber = account.AccountNumber
};
db.Transactions.Add(transaction);
db.SaveChanges();
}
}
}
}
|
de05097380b2adca21cdbf5ea670ff2c18419ce0
|
C#
|
Yangjunfengx/cip-client
|
/Test/Program.cs
| 2.59375
| 3
|
using System;
using CIPlib;
namespace Test
{
class Program
{
static void Main(string[] args)
{
try
{
CIP c = new CIP("192.168.0.222");
c.RegisterSession();
c.Browse();
//c.Read("Teeq"); // DINT: ok
//c.Read("Local:2:I"); // UDT: byte array [TODO]
//c.Read("Local:2:I.Ch0Data"); // UDT member: REAL - ok
//c.Read("ints.a"); // UDT member: DINT - ok
//c.Read("ints.b"); // UDT member: INT - ok
//c.Read("V1.diOp"); // UDT member: BOOL - ok
//c.Read("Local:2:C.Ch0Config.RangeType"); // nested UDT: ok
/*while (ok)
{
c.Read("Local:2:I.Ch0Data");
Thread.Sleep(1000);
}*/
//c.Write("Teeq", 9); // writing DINT: ok
//c.Read("Teeq");
c.Write("Local:3:O.Ch6Data", 4.23f); // writing REAL: ok
c.Read("Local:3:O.Ch6Data");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.WriteLine("bye");
Console.ReadLine();
}
}
}
|
3fa1af4c7d21fb28222e8ed1bf3f6d9a4f05e9a6
|
C#
|
angela-sc/TFG-PlataformaIOT
|
/Servicios/ServicioInsertaInformacion.cs
| 2.546875
| 3
|
using Libreria.Entidades;
using Libreria.Interfaces;
using Microsoft.Extensions.Configuration;
using Repositorio.SQLServer;
using Serilog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace Servicios
{
public class ServicioInsertaInformacion : IServicioInsertaInformacion
{
private ILogger log;
private IRepositorioSensor repositorioSensor;
private IRepositorioEstacionBase repositorioEstacion;
public ServicioInsertaInformacion(string cadenaConexion, ILogger logger)
{
this.log = logger;
this.repositorioSensor = new RepositorioSensor(cadenaConexion, log);
this.repositorioEstacion = new RepositorioEstacionBase(cadenaConexion, log);
}
public async Task<bool> InsertaPeticion(EntidadPeticion entidadPeticion)
{
if (entidadPeticion == null)
return false;
string nombreProyecto = entidadPeticion.Proyecto;
string nombreEstacionBase = entidadPeticion.EstacionBase;
string nombreSensor = entidadPeticion.Sensor;
int estacionId = -1, sensorId = -1;
bool result = true; //booleano para saber si ha ocurrido un error durante la insercion de datos
try
{
//obtenemos los datos: id de la estacion e id del sensor
estacionId = await repositorioEstacion.ObtenerId(nombreProyecto, nombreEstacionBase);
sensorId = await repositorioSensor.ObtenerId(nombreSensor, estacionId);
if (estacionId != -1 && sensorId != -1)
{
foreach (EntidadDatoBase datoBase in entidadPeticion.Datos)
{
var dato = new EntidadDato();
dato.Stamp = datoBase.Stamp;
dato.Humedad = datoBase.Humedad;
dato.Temperatura = datoBase.Temperatura;
dato.FK_IdSensor = sensorId;
result = (result && await repositorioSensor.InsertaDato(dato)); //si falla alguna da false
}
}
else
{
if (estacionId == -1)
{
log.Warning($"ERR. SERVICIO INSERTA INFORMACION (InsertaPeticion) - No existe la estacion '{nombreEstacionBase}' en la base de datos");
}
if (sensorId == -1)
{
log.Warning($"ERR. SERVICIO INSERTA INFORMACION (InsertaPeticion) - No existe el sensor {sensorId} en la base de datos");
}
result = false;
}
}
catch(Exception ex)
{
log.Error($"ERR. SERVICIO INSERTA INFORMACION (InsertaPeticion) -{ex.Message}");
result = false;
}
return result;
}
}
}
|
73e57af08493e2c5a64d6d205e671adc043bcfcc
|
C#
|
hunpody/psimulex
|
/VapeTeam.Psimulex/VapeTeam.Psimulex.Tests/FunctionTests.cs
| 2.703125
| 3
|
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using VapeTeam.Psimulex.Core.Commands;
using VapeTeam.Psimulex.Core.Types;
using VapeTeam.Psimulex.Core;
namespace VapeTeam.Psimulex.Tests
{
/// <summary>
/// Summary description for FunctionTests
/// </summary>
[TestClass]
public class FunctionTests
{
public FunctionTests()
{
//
// TODO: Add constructor logic here
//
}
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
// You can use the following additional attributes as you write your tests:
//
// Use ClassInitialize to run code before running the first test in the class
// [ClassInitialize()]
// public static void MyClassInitialize(TestContext testContext) { }
//
// Use ClassCleanup to run code after all tests in a class have run
// [ClassCleanup()]
// public static void MyClassCleanup() { }
//
// Use TestInitialize to run code before running each test
// [TestInitialize()]
// public void MyTestInitialize() { }
//
// Use TestCleanup to run code after each test has run
// [TestCleanup()]
// public void MyTestCleanup() { }
//
#endregion
[TestMethod]
public void FunctionCallByAddress1()
{
// Test native calls
/* The program is:
*
* int i = 0;
* for (int j=0; j<10; ++j)
* i = inc(i);
* print(i);
* int inc(int i) { return i + 1; }
*
* Result == 45
*/
var process = Helpers.SystemHelper.CreateMachineAndRunProgram(
VapeTeam.Psimulex.Core.Factories.ProgramBuilder.Create().Add(
new Declare("i", TypeEnum.Integer),
new Push(0),
new Initialize("j", TypeEnum.Integer),
new Push("j", ValueAccessModes.LocalVariableReference),
new Push(10),
new Compare(Compare.ComparisonModes.LessThan),
new RelativeJumpIfFalse(11),
new Push("i", ValueAccessModes.LocalVariableReference),
new Push("i", ValueAccessModes.LocalVariableReference),
new Call(20),
new Assign(),
new Push("j", ValueAccessModes.LocalVariableReference),
new Push("j", ValueAccessModes.LocalVariableReference),
new Push(1),
new BinaryOperation(BinaryOperation.Operations.Addition),
new Assign(),
new RelativeJump(-13),
new Push("i", ValueAccessModes.LocalVariableReference),
new Call("print"),
new Return(),
// Here begins the inc function
new Initialize("i", TypeEnum.Integer),
new Push("i", ValueAccessModes.LocalVariableReference),
new Push(1),
new BinaryOperation(BinaryOperation.Operations.Addition),
new Return()));
Assert.AreEqual("10", process.StandardOutput);
Assert.AreEqual(19, process.MainThread.PC);
}
#region Fibonacci-test
private long Fibonacci(long n)
{
if (n <= 0) return 0;
if (n == 1) return 1;
return Fibonacci(n - 2) + Fibonacci(n - 1);
}
private VapeTeam.Psimulex.Core.Process CreateAndRunFibonacci(long n)
{
/* The program is:
*
* print(fib(x));
* int fib(int n) { if (n <= 0) return 0; if (n == 1) return 1; return fib(n-2) + fib(n-1); }
*
* Result == Fibonacci(x)
*/
var process = Helpers.SystemHelper.CreateMachineAndRunProgram(
VapeTeam.Psimulex.Core.Factories.ProgramBuilder.Create().Add(
new Push(n),
new Call(4),
new Call("print"),
new Return(),
// fib
new Initialize("n", TypeEnum.Integer),
new Push("n", ValueAccessModes.LocalVariableReference),
new Push(0),
new Compare(Compare.ComparisonModes.LessThanOrEqual),
new RelativeJumpIfFalse(3),
new Push(0),
new Return(),
new Push("n", ValueAccessModes.LocalVariableReference),
new Push(1),
new Compare(Compare.ComparisonModes.Equal),
new RelativeJumpIfFalse(3),
new Push(1),
new Return(),
new Push("n", ValueAccessModes.LocalVariableReference),
new Push(2),
new BinaryOperation(BinaryOperation.Operations.Subtraction),
new Call(4),
new Push("n", ValueAccessModes.LocalVariableReference),
new Push(1),
new BinaryOperation(BinaryOperation.Operations.Subtraction),
new Call(4),
new BinaryOperation(BinaryOperation.Operations.Addition),
new Return()
));
return process;
}
[TestMethod]
public void RecursiveFunctionCallByAddress_Fibonacci1()
{
// Test recursive native calls
for (int i = 0; i <= 10; ++i)
{
Assert.AreEqual(Fibonacci(i).ToString(), CreateAndRunFibonacci(i).StandardOutput);
}
}
#endregion
[TestMethod]
public void UserDefinedFunctions1()
{
Program program = VapeTeam.Psimulex.Core.Factories.ProgramBuilder.Create().Add(
new Push(2),
new Push(3),
new Call("add"),
new Call("print")
);
UserDefinedFunction addFunction = new UserDefinedFunction
{
Name = "add",
Parameters = new List<VariableDescriptor> {
new VariableDescriptor
{
Type = new TypeIdentifier { TypeEnum = TypeEnum.Integer },
Name = "a"
},
new VariableDescriptor
{
Type = new TypeIdentifier { TypeEnum = TypeEnum.Integer },
Name = "b"
}
},
ReturnValueType = new VariableDescriptor
{
Type = new TypeIdentifier { TypeEnum = TypeEnum.Integer }
},
Commands = new CommandList
{
new Push("a", ValueAccessModes.LocalVariable),
new Push("b", ValueAccessModes.LocalVariable),
new BinaryOperation(BinaryOperation.Operations.Addition),
new Return(true),
}
};
program.AddFunction(addFunction);
var process = Helpers.SystemHelper.CreateMachineAndRunProgram(program);
Assert.AreEqual("5", process.StandardOutput);
}
[TestMethod]
public void UserDefinedFunctions2()
{
Program program = VapeTeam.Psimulex.Core.Factories.ProgramBuilder.Create().Add(
new Push(2),
new Push(3),
new Call("subtract"),
new Call("print")
);
UserDefinedFunction addFunction = new UserDefinedFunction
{
Name = "subtract",
Parameters = new List<VariableDescriptor> {
new VariableDescriptor
{
Type = new TypeIdentifier { TypeEnum = TypeEnum.Integer },
Name = "a"
},
new VariableDescriptor
{
Type = new TypeIdentifier { TypeEnum = TypeEnum.Integer },
Name = "b"
}
},
ReturnValueType = new VariableDescriptor
{
Type = new TypeIdentifier { TypeEnum = TypeEnum.Integer }
},
Commands = new CommandList
{
new Push("a", ValueAccessModes.LocalVariable),
new Push("b", ValueAccessModes.LocalVariable),
new BinaryOperation(BinaryOperation.Operations.Subtraction),
new Return(true),
}
};
program.AddFunction(addFunction);
var process = Helpers.SystemHelper.CreateMachineAndRunProgram(program);
Assert.AreEqual("-1", process.StandardOutput);
}
[TestMethod]
public void UserDefinedFunctions3()
{
Program program = VapeTeam.Psimulex.Core.Factories.ProgramBuilder.Create().Add(
new Push(2),
new Push(3),
new Call("multiply", 2),
new Call("print"),
new Push(2),
new Push(3),
new Push(4),
new Call("multiply", 3),
new Call("print")
);
UserDefinedFunction mulFunction1 = new UserDefinedFunction
{
Name = "multiply",
Parameters = new List<VariableDescriptor> {
new VariableDescriptor
{
Type = new TypeIdentifier { TypeEnum = TypeEnum.Integer },
Name = "a"
},
new VariableDescriptor
{
Type = new TypeIdentifier { TypeEnum = TypeEnum.Integer },
Name = "b"
}
},
ReturnValueType = new VariableDescriptor
{
Type = new TypeIdentifier { TypeEnum = TypeEnum.Integer }
},
Commands = new CommandList
{
new Push("a", ValueAccessModes.LocalVariable),
new Push("b", ValueAccessModes.LocalVariable),
new BinaryOperation(BinaryOperation.Operations.Multiplication),
new Return(true),
}
};
UserDefinedFunction mulFunction2 = new UserDefinedFunction
{
Name = "multiply",
Parameters = new List<VariableDescriptor> {
new VariableDescriptor
{
Type = new TypeIdentifier { TypeEnum = TypeEnum.Integer },
Name = "a"
},
new VariableDescriptor
{
Type = new TypeIdentifier { TypeEnum = TypeEnum.Integer },
Name = "b"
},
new VariableDescriptor
{
Type = new TypeIdentifier { TypeEnum = TypeEnum.Integer },
Name = "c"
}
},
ReturnValueType = new VariableDescriptor
{
Type = new TypeIdentifier { TypeEnum = TypeEnum.Integer }
},
Commands = new CommandList
{
new Push("a", ValueAccessModes.LocalVariable),
new Push("b", ValueAccessModes.LocalVariable),
new BinaryOperation(BinaryOperation.Operations.Multiplication),
new Push("c", ValueAccessModes.LocalVariable),
new BinaryOperation(BinaryOperation.Operations.Multiplication),
new Return(true),
}
};
program.AddFunction(mulFunction1);
program.AddFunction(mulFunction2);
var process = Helpers.SystemHelper.CreateMachineAndRunProgram(program);
Assert.AreEqual("624", process.StandardOutput);
}
private string GetPsimulexFactorial(int n)
{
Program program = VapeTeam.Psimulex.Core.Factories.ProgramBuilder.Create().Add(
new Push(n),
new Call("factor"),
new Call("print")
);
UserDefinedFunction factor = new UserDefinedFunction
{
Name = "factor",
Parameters = new List<VariableDescriptor> {
new VariableDescriptor
{
Type = new TypeIdentifier { TypeEnum = TypeEnum.Integer },
Name = "n"
}
},
ReturnValueType = new VariableDescriptor
{
Type = new TypeIdentifier { TypeEnum = TypeEnum.Integer }
},
Commands = new CommandList
{
new Push("n", ValueAccessModes.LocalVariable),
new Push(1),
new Compare(Compare.ComparisonModes.LessThanOrEqual),
new RelativeJumpIfFalse(3),
new Push(1),
new Return(true),
new Push("n", ValueAccessModes.LocalVariable),
new Push("n", ValueAccessModes.LocalVariable),
new Push(1),
new BinaryOperation(BinaryOperation.Operations.Subtraction),
new Call("factor"),
new BinaryOperation(BinaryOperation.Operations.Multiplication),
new Return(true),
}
};
program.AddFunction(factor);
var process = Helpers.SystemHelper.CreateMachineAndRunProgram(program);
return process.StandardOutput;
}
private int GetFactorial(int n)
{
if (n <= 1) return 1;
else return n * GetFactorial(n - 1);
}
[TestMethod]
public void UserDefinedFunctions4_Factorial()
{
for (int i = 0; i < 10; ++i)
Assert.AreEqual(GetFactorial(i).ToString(), GetPsimulexFactorial(i));
}
}
}
|
8942ad1beb33e92b2a8eebaa8fe7445ec1ab3536
|
C#
|
burschi1981/BonniGit
|
/BonniViewModel/ViewModel/ShopAdminViewModel.cs
| 2.84375
| 3
|
using BonnyUI.DBConnection;
using BonnyUI.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace BonnyUI.ViewModel
{
/// <summary>
/// Viewmodel der Shop-Admin
/// Hinzufügen und Ändern von Shops
/// </summary>
public class ShopAdminViewModel:ViewModelBase
{
#region private fields
private int _currentID;
private ObservableCollection<ShopViewModel> _allShops;
private string _currentShopName;
private DBConnector _DBConnection;
private IList<Shop> _shops;
private ShopViewModel _currentShop;
#endregion
#region Konstruktoren
public ShopAdminViewModel(IList<Shop> shops, DBConnector dbConnection)
{
_shops = shops;
SaveShopDatesAsNewCommand = new ActionCommand(SaveShopDatesAsNew, CanUpdateShopDates);
UpdateShopDatesCommand = new ActionCommand(UpdateShopDates, CanUpdateShopDates);
_DBConnection = dbConnection;
ReloadShopViewModels();
}
#endregion
#region public Properties
public ICommand SaveShopDatesAsNewCommand { get; private set; }
public ICommand UpdateShopDatesCommand { get; private set; }
public string CurrentShopName
{
get
{
return _currentShopName;
}
set
{
_currentShopName = value;
}
}
public IList<Shop> Shops
{
get { return _shops; }
set
{
_shops = value;
}
}
public ObservableCollection<ShopViewModel> AllShops
{
get { return _allShops; }
}
public ShopViewModel CurrentShop
{
get { return _currentShop; }
set
{
_currentShop = value;
if (_currentShop != null)
{
_currentShopName = _currentShop.Name;
_currentID = _currentShop.ID;
}
else
{
_currentShopName = "";
}
RaisePropertyChanged("CurrentShopName");
RaisePropertyChanged("CurrentShop");
}
}
#endregion
#region public voids
public void ReloadShopViewModels()
{
// Geschäfte laden:
ObservableCollection<ShopViewModel> obs = new ObservableCollection<ShopViewModel>();
foreach (Shop shop in _shops)
obs.Add(new ShopViewModel(shop));
_allShops = obs;
CurrentShop = GetCurrentShop();
if (CurrentShop == null && AllShops.Count > 0)
CurrentShop = AllShops[0];
RaisePropertyChanged("CurrentShop");
RaisePropertyChanged("AllShops");
}
#endregion
#region private voids
private ShopViewModel GetCurrentShop()
{
var retval = _allShops.Where(x => x.ID.Equals(_currentID)).FirstOrDefault();
return retval;
}
private void UpdateShopDates(object obj)
{
try
{
_currentShop.WrappedObject.Name = _currentShopName;
_currentShop.Name = _currentShopName;
_DBConnection.ChangeShop(CurrentShop.WrappedObject);
ReloadShopViewModels();
RaisePropertyChanged("Shops");
}
catch (Exception ex)
{
throw new Exception("Fehler beim Ändern der Daten des Geschäfts", ex);
}
}
private void SaveShopDatesAsNew(object obj)
{
try
{
_currentID = _DBConnection.AddShop(CurrentShopName);
Shops = _DBConnection.GetAllShops();
ReloadShopViewModels();
RaisePropertyChanged("Shops");
}
catch (Exception ex)
{
throw new Exception("Fehler beim Anlegen des neuen Geschäfts", ex);
}
}
private bool CanUpdateShopDates(object obj)
{
bool retval = true;
if (_currentShopName == null || _currentShopName == "" || ShopAlreadyExists())
retval = false;
return retval;
}
private bool ShopAlreadyExists()
{
bool retval = false;
if (_allShops != null)
{
if (_allShops.Where(x => x.Name.Equals(CurrentShopName)).FirstOrDefault() != null)
retval = true;
}
return retval;
}
#endregion
}
}
|
2373b92bce05615ceddf86f1667efd02cd0a2f1a
|
C#
|
bstrzelecki/StarGame
|
/StarGame/MainBehaviour/Player/SimulationProxy.cs
| 2.609375
| 3
|
using Microsoft.Xna.Framework;
namespace StarGame
{
internal class SimulationProxy
{
public Player blip;
public int simulationSpeed = 5;
public int simulationSteps = 25;
public Vector2[] blips;
public int count = 0;
public SimulationProxy()
{
blip = new Player();
Time.OnTick += Time_OnTick;
blips = new Vector2[simulationSteps];
for (int i = 0; i < simulationSteps; i++)
{
blips[i] = new Vector2(0, 0);
}
}
private void Time_OnTick()
{
for (int i = 0; i < simulationSpeed; i++)
{
blip.Time_OnTick();
}
if (count > simulationSteps - 1)
{
count = 0;
blip = (Player)MainScene.player.Clone();
}
blips[count] = blip.position;
count++;
}
}
}
|
e8da427c264069346243bebc032800a4043b2ec7
|
C#
|
fayte0618/ProjectClock
|
/Assets/Scripts/ClockHand.cs
| 2.96875
| 3
|
using UnityEngine;
using System.Collections;
[System.Serializable]
public class ClockHand : MonoBehaviour
{
//clockwise is negative, counterclockwise is positive
public enum Direction
{
Clockwise, CounterClockwise, None
};
#region PRIVATE PROPERITES
[SerializeField]
private Direction _direction = Direction.None;
[SerializeField]
private float _speed = 0f;
#endregion
#region PRIVATE METHODS
// Update is called once per frame
void Update ()
{
rect.Rotate (Vector3.forward, _speed * Time.deltaTime, Space.Self);
}
#endregion
#region PUBLIC PROPERTIES
public RectTransform rect;
public Direction direction
{
get
{
return _direction;
}
set
{
_direction = value;
if (_direction == Direction.Clockwise)
{
if (_speed > 0) { _speed = -speed; }
}
else if (_direction == Direction.CounterClockwise)
{
if (_speed < 0) { _speed = Mathf.Abs(_speed); }
}
}
}
public float speed
{
get
{
return _speed;
}
set
{
_speed = value;
if (_speed > 0) { _direction = Direction.CounterClockwise; }
else if (_speed < 0) { _direction = Direction.Clockwise; }
else { _direction = Direction.None; }
}
}
#endregion
#region PUBLIC METHODS
#endregion
}
|
96ef92e96591d518da067c387f55fe5c490ce4db
|
C#
|
ayende/Subtext
|
/SubtextSolution/Subtext.Framework/Services/IFeedbackSpamService.cs
| 2.6875
| 3
|
using System;
using Subtext.Framework.Components;
namespace Subtext.Framework.Services
{
/// <summary>
/// Base interface for comment spam services such as Akismet.
/// </summary>
public interface IFeedbackSpamService
{
/// <summary>
/// Examines the item and determines whether or not it is spam.
/// </summary>
/// <param name="feedback"></param>
/// <returns></returns>
bool IsSpam(FeedbackItem feedback);
/// <summary>
/// Submits the item to the service as a false positive.
/// Something that should not have been marked as spam.
/// </summary>
/// <param name="feedback"></param>
void SubmitGoodFeedback(FeedbackItem feedback);
/// <summary>
/// Submits the item to the service as a piece of SPAM that got through
/// the filter. Something that should've been marked as SPAM.
/// </summary>
/// <param name="feedback"></param>
void SubmitSpam(FeedbackItem feedback);
}
}
|
6cfa0b76f998f00ad0946b3e88434170f75afb17
|
C#
|
shendongnian/download4
|
/first_version_download2/127941-22203114-59621969-2.cs
| 2.765625
| 3
|
const int TargetSize = 14;
private static void Save(Geometry geometry, string fileName)
{
var rect = geometry.GetRenderBounds(new Pen(Brushes.Black, 0));
var bigger = rect.Width > rect.Height ? rect.Width : rect.Height;
var scale = TargetSize / bigger;
Geometry scaledGeometry = Geometry.Combine(geometry, geometry, GeometryCombineMode.Intersect, new ScaleTransform(scale, scale));
rect = scaledGeometry.GetRenderBounds(new Pen(Brushes.Black, 0));
Geometry transformedGeometry = Geometry.Combine(scaledGeometry, scaledGeometry, GeometryCombineMode.Intersect, new TranslateTransform(((TargetSize - rect.Width) / 2) - rect.Left, ((TargetSize - rect.Height) / 2) - rect.Top));
RenderTargetBitmap bmp = new RenderTargetBitmap(TargetSize, TargetSize, // Size
96, 96, // DPI
PixelFormats.Pbgra32);
DrawingVisual viz = new DrawingVisual();
using (DrawingContext dc = viz.RenderOpen())
{
dc.DrawGeometry(Brushes.Black, null, transformedGeometry);
}
bmp.Render(viz);
PngBitmapEncoder pngEncoder = new PngBitmapEncoder();
pngEncoder.Frames.Add(BitmapFrame.Create(bmp));
using (FileStream file = new FileStream(fileName, FileMode.Create))
pngEncoder.Save(file);
}
|
3fafdb205271a68ea5308fcc523954db62290d54
|
C#
|
Booolzay/Unity-Hack-and-Slash-Game-Project
|
/Unity Hack and Slash Game Project/Scripts/throwObj.cs
| 2.5625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//Adapted from 2 tutorials : grabbing: https://www.youtube.com/watch?v=bA12WEA5MLo , thorwing: https://www.youtube.com/watch?v=_xMhkK6GTXA
public class throwObj : MonoBehaviour
{
RaycastHit grabRay;
GameObject grabAble;
public Transform grabPos;
public float force = 200;
public GameObject throwDirection;
public static bool magicState;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKey("e") && Physics.Raycast(transform.position, transform.forward, out grabRay, 50) && grabRay.transform.GetComponent<Rigidbody>())
{
grabAble = grabRay.transform.gameObject;
magicState = true;
}
else if(Input.GetMouseButtonUp(0))
{
grabAble.GetComponent<Rigidbody>().AddForce(throwDirection.transform.forward*force) ;
grabAble = null;
magicState = false;
}
if (grabAble)
{
grabAble.GetComponent<Rigidbody>().velocity = (grabPos.position - grabAble.transform.position) * 50;
}
}
}
|
101ede7b69bc0996a52ebb3857e30eb0de285dfb
|
C#
|
Giullianogp/MeuPet.API
|
/MeuPet.API/Middlewares/AuthenticateMiddleware.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using MeuPet.API.Context;
using MeuPet.API.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
namespace MeuPet.API.Middlewares
{
public class AuthenticateMiddleware
{
readonly RequestDelegate _next;
public AuthenticateMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
var auth = context.Request.Headers["Authorization"].ToString();
if (string.IsNullOrWhiteSpace(auth))
{
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return;
}
if (string.IsNullOrEmpty(auth))
{
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return;
}
auth = auth.Replace("Basic ", "");
try
{
var decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(auth));
var usuario = new Usuario
{
Nome = decodedToken.Split(':')[0],
Senha = decodedToken.Split(':')[1]
};
context.Items.Add("usuario", usuario);
}
catch (Exception)
{
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
}
await _next.Invoke(context);
}
}
}
|
1a5474c35cfb328f271329f0b8dec76ad242fcae
|
C#
|
nemss/SoftUni-Education
|
/07.C# OOP Advanced/Lab - Generics/BoxOfT/Box.cs
| 3.34375
| 3
|
using System.Collections.Generic;
using System.Linq;
public class Box<T>
{
public Box()
{
this.elements = new List<T>();
}
private IList<T> elements;
public int Count => this.elements.Count;
public void Add(T element)
{
this.elements.Add(element);
}
public T Remove()
{
var last = elements.LastOrDefault();
elements.RemoveAt(elements.Count - 1);
return last;
}
}
|
fa0ae780b919809e5c2bca51e6c9e1d4a67606f2
|
C#
|
reecerussell/distro-cms
|
/Shared/Shared.Tests/Passwords/ValidatorTests.cs
| 2.890625
| 3
|
using System;
using Microsoft.Extensions.Options;
using Shared.Exceptions;
using Shared.Passwords;
using Xunit;
namespace Shared.Tests.Passwords
{
public class ValidatorTests
{
[Fact]
public void TestConstructorWithNullOptions()
{
Assert.Throws<InvalidOperationException>(() => new PasswordValidator(null));
Assert.Throws<InvalidOperationException>(() =>
{
var options = Options.Create<PasswordOptions>(null);
_ = new PasswordValidator(options);
});
Assert.Throws<InvalidOperationException>(() =>
{
var options = Options.Create(new PasswordOptions{Validation = null});
_ = new PasswordValidator(options);
});
}
[Theory]
[InlineData("")]
[InlineData(null)]
public void TestValidateWithEmptyOrNullPassword(string password)
{
var validator = new PasswordValidator(Options.Create(new PasswordOptions()));
var ex = Assert.Throws<ValidationException>(() => validator.Validate(password));
Assert.Equal(ErrorMessages.PasswordRequired, ex.Message);
}
[Theory]
[InlineData("3849")]
[InlineData("0jnvs")]
[InlineData("Pass12")]
public void TestValidateWithPasswordShorterThan10(string password)
{
var options = new PasswordOptions
{
Validation =
{
RequiredLength = 10
}
};
var validator = new PasswordValidator(Options.Create(options));
var ex = Assert.Throws<ValidationException>(() => validator.Validate(password));
Assert.Equal(
string.Format(ErrorMessages.PasswordTooShort, options.Validation.RequiredLength),
ex.Message);
}
[Theory]
[InlineData("aBc3inds")]
[InlineData("3nedd9nc")]
public void TestValidateWhereNonAlphaNumericIsRequired(string password)
{
var options = new PasswordOptions
{
Validation =
{
RequiredLength = 8,
RequireNonAlphanumeric = true
}
};
var validator = new PasswordValidator(Options.Create(options));
var ex = Assert.Throws<ValidationException>(() => validator.Validate(password));
Assert.Equal(
ErrorMessages.PasswordRequiresNonAlphanumeric,
ex.Message);
}
[Theory]
[InlineData("aBc3i+nds")]
[InlineData("3ned-d9nc")]
public void TestValidateWhereNonAlphaNumericIsRequiredWithAlphaNumeric(string password)
{
var options = new PasswordOptions
{
Validation =
{
RequiredLength = 8,
RequireNonAlphanumeric = true
}
};
var validator = new PasswordValidator(Options.Create(options));
validator.Validate(password);
}
[Theory]
[InlineData("aBcf@nds")]
[InlineData("!nedd-nc")]
public void TestValidateWhereDigitIsRequired(string password)
{
var options = new PasswordOptions
{
Validation =
{
RequiredLength = 8,
RequireDigit = true
}
};
var validator = new PasswordValidator(Options.Create(options));
var ex = Assert.Throws<ValidationException>(() => validator.Validate(password));
Assert.Equal(
ErrorMessages.PasswordRequiresDigit,
ex.Message);
}
[Theory]
[InlineData("aBc3i+nds")]
[InlineData("3ned-d9nc")]
public void TestValidateDigitIsRequiredWithDigit(string password)
{
var options = new PasswordOptions
{
Validation =
{
RequiredLength = 8,
RequireDigit = true
}
};
var validator = new PasswordValidator(Options.Create(options));
validator.Validate(password);
}
[Theory]
[InlineData("ABCF@123")]
[InlineData("!AKEM@12")]
public void TestValidateWhereLowercaseIsRequired(string password)
{
var options = new PasswordOptions
{
Validation =
{
RequiredLength = 8,
RequireLowercase = true
}
};
var validator = new PasswordValidator(Options.Create(options));
var ex = Assert.Throws<ValidationException>(() => validator.Validate(password));
Assert.Equal(
ErrorMessages.PasswordRequiresLowercase,
ex.Message);
}
[Theory]
[InlineData("aBc3i+nds")]
[InlineData("3ned-d9nc")]
public void TestValidateWhereLowercaseIsRequiredWithLowercase(string password)
{
var options = new PasswordOptions
{
Validation =
{
RequiredLength = 8,
RequireLowercase = true
}
};
var validator = new PasswordValidator(Options.Create(options));
validator.Validate(password);
}
[Theory]
[InlineData("abcf@123")]
[InlineData("!akem@12")]
public void TestValidateWhereUppercaseIsRequired(string password)
{
var options = new PasswordOptions
{
Validation =
{
RequiredLength = 8,
RequireUppercase = true
}
};
var validator = new PasswordValidator(Options.Create(options));
var ex = Assert.Throws<ValidationException>(() => validator.Validate(password));
Assert.Equal(
ErrorMessages.PasswordRequiresUppercase,
ex.Message);
}
[Theory]
[InlineData("aBc3i+nds")]
[InlineData("3NEd-d9nc")]
public void TestValidateWhereUppercaseRequiredWithUppercase(string password)
{
var options = new PasswordOptions
{
Validation =
{
RequiredLength = 8,
RequireUppercase = true
}
};
var validator = new PasswordValidator(Options.Create(options));
validator.Validate(password);
}
[Theory]
[InlineData("Password")]
[InlineData("HelloWorld")]
public void TestValidateWhere8UniqueCharsAreRequired(string password)
{
var options = new PasswordOptions
{
Validation =
{
RequiredLength = 8,
RequireDigit = false,
RequiredUniqueChars = 8
}
};
var validator = new PasswordValidator(Options.Create(options));
var ex = Assert.Throws<ValidationException>(() => validator.Validate(password));
Assert.Equal(
string.Format(ErrorMessages.PasswordRequiresUniqueChars, options.Validation.RequiredUniqueChars),
ex.Message);
}
[Theory]
[InlineData('0')]
[InlineData('1')]
[InlineData('2')]
[InlineData('3')]
[InlineData('4')]
[InlineData('5')]
[InlineData('6')]
[InlineData('7')]
[InlineData('8')]
[InlineData('9')]
public void TestIsDigit(char c)
{
Assert.True(PasswordValidator.IsDigit(c));
}
[Theory]
[InlineData('d')]
[InlineData('H')]
[InlineData('.')]
[InlineData('-')]
public void TestIsNotDigit(char c)
{
Assert.False(PasswordValidator.IsDigit(c));
}
[Theory]
[InlineData('a')]
[InlineData('b')]
[InlineData('c')]
[InlineData('d')]
[InlineData('e')]
[InlineData('f')]
[InlineData('g')]
[InlineData('h')]
[InlineData('i')]
[InlineData('j')]
[InlineData('k')]
[InlineData('l')]
[InlineData('m')]
[InlineData('n')]
[InlineData('o')]
[InlineData('p')]
[InlineData('q')]
[InlineData('r')]
[InlineData('s')]
[InlineData('t')]
[InlineData('u')]
[InlineData('v')]
[InlineData('w')]
[InlineData('x')]
[InlineData('y')]
[InlineData('z')]
public void TestIsLower(char c)
{
Assert.True(PasswordValidator.IsLower(c));
}
[Theory]
[InlineData('7')]
[InlineData('-')]
[InlineData('U')]
[InlineData('L')]
[InlineData('F')]
public void TestIsNotLower(char c)
{
Assert.False(PasswordValidator.IsLower(c));
}
[Theory]
[InlineData('A')]
[InlineData('B')]
[InlineData('C')]
[InlineData('D')]
[InlineData('E')]
[InlineData('F')]
[InlineData('G')]
[InlineData('H')]
[InlineData('I')]
[InlineData('J')]
[InlineData('K')]
[InlineData('L')]
[InlineData('M')]
[InlineData('N')]
[InlineData('O')]
[InlineData('P')]
[InlineData('Q')]
[InlineData('R')]
[InlineData('S')]
[InlineData('T')]
[InlineData('U')]
[InlineData('V')]
[InlineData('W')]
[InlineData('X')]
[InlineData('Y')]
[InlineData('Z')]
public void TestIsUpper(char c)
{
Assert.True(PasswordValidator.IsUpper(c));
}
[Theory]
[InlineData('7')]
[InlineData('-')]
[InlineData('u')]
[InlineData('l')]
[InlineData('f')]
public void TestIsNotUpper(char c)
{
Assert.False(PasswordValidator.IsUpper(c));
}
[Theory]
[InlineData('a')]
[InlineData('3')]
[InlineData('D')]
public void TestIsLetterOrDigit(char c)
{
Assert.True(PasswordValidator.IsLetterOrDigit(c));
}
[Theory]
[InlineData('-')]
[InlineData('.')]
[InlineData('£')]
public void TestIsNotLetterOrDigit(char c)
{
Assert.False(PasswordValidator.IsLetterOrDigit(c));
}
}
}
|
d8d7ccdc560103f0c87034166687afe5c7f21fdb
|
C#
|
CheffOfGames/Mafia-Quickplay-DiscordBot
|
/DiscordBot/Commands/PlayerListCommand.cs
| 3.046875
| 3
|
using Discord.Commands;
using Discord;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DiscordBot.Commands
{
class PlayerListCommand
{
public static void createCommand(DiscordClient _client)
{
_client.GetService<CommandService>().CreateCommand("playerList")
.Alias(new String[] {"list","players"})
.Description("Get a list of people currently in the mafia game on the current server")
.Do(async e =>
{
//If the game hasn't started yet, show the signup list
if (!Program.servers[e.Server].gameRunning)
{
if (Program.servers[e.Server].Objects.Count > 0)
{
string playerList = "";
int i = 0;
foreach (var item in Program.servers[e.Server].Objects)
{
i++;
playerList += i + ". " + item.User.Name + "\n";
}
await e.Channel.SendMessage(e.User.Mention + "\n\n**Players in current game:**```" + playerList + "```");
return;
}
else await e.Channel.SendMessage(e.User.Mention + " There is nobody currently in the game! :x:");
}
else
{
string playerList = "";
int i = 0;
foreach (var item in Program.servers[e.Server].Objects)
{
i++;
try
{
playerList += i + ". " + item.User.Name + " Votes: " + item.LynchTarget.User.Name + "\n";
}
catch (Exception)
{
playerList += i + ". " + item.User.Name + " Votes: -\n";
}
}
await e.Channel.SendMessage(e.User.Mention + "\n\n**Players in current game:**```" + playerList + "```");
return;
}
});
}
}
}
|
5db0ab50d9622c06e256194e8f6be56699c281f5
|
C#
|
ravcio/MapNet
|
/hiMapNet/Layer/Layers.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace hiMapNet
{
public class Layers : IList<LayerAbstract>
{
private List<LayerAbstract> m_oLayers = new List<LayerAbstract>();
LayerAbstract animationLayer = null;
public LayerAbstract AnimationLayer
{
get { return animationLayer; }
set { animationLayer = value; }
}
#region IList<Layer> Members
public int IndexOf(LayerAbstract item)
{
return m_oLayers.IndexOf(item);
}
public void Insert(int index, LayerAbstract item)
{
m_oLayers.Insert(index, item);
item.Parent = this;
}
public void RemoveAt(int index)
{
m_oLayers.RemoveAt(index);
}
public LayerAbstract this[int index]
{
get
{
return m_oLayers[index];
}
set
{
m_oLayers[index] = value;
}
}
#endregion
#region ICollection<ILayer> Members
public void Add(LayerAbstract item)
{
m_oLayers.Add(item);
item.Parent = this;
}
public void Clear()
{
m_oLayers.Clear();
}
public bool Contains(LayerAbstract item)
{
return m_oLayers.Contains(item);
}
public void CopyTo(LayerAbstract[] array, int arrayIndex)
{
throw new NotImplementedException("operation not supported");
}
public int Count
{
get { return m_oLayers.Count; }
}
public bool IsReadOnly
{
get { throw new Exception("The method or operation is not implemented."); }
}
public bool Remove(LayerAbstract item)
{
return m_oLayers.Remove(item);
}
#endregion
#region IEnumerable<LayerAbstract> Members
public IEnumerator<LayerAbstract> GetEnumerator()
{
return m_oLayers.GetEnumerator();
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return m_oLayers.GetEnumerator();
}
#endregion
internal bool IsDirty()
{
foreach (LayerAbstract layer in m_oLayers)
{
if (layer != AnimationLayer)
{
if (layer.IsDirty()) return true;
}
}
return false;
}
public void Invalidate()
{
foreach (LayerAbstract layer in m_oLayers)
{
layer.Invalidate();
}
}
}
}
|
1c6ecd52387472f6a31418e48e110345d9843855
|
C#
|
salocinx/Multipurpose-Robot-Controller
|
/VisualStudio/ALAN2/CommonCtrl/Components/Actuators/InfraredTx.cs
| 2.53125
| 3
|
#region Usings
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
#endregion
namespace CommonCtrl {
[Serializable]
public class InfraredTx : Infrared {
#region Fields
private ushort pin = 5; // interrupt driven pin for sending ir signals (fixed pin by IRremote lib) !
#endregion
#region Enumerations
#endregion
#region Lifecycle
public InfraredTx() {
// used for xml serialization ...
}
#endregion
#region Properties
public ushort Pin {
get { return pin; }
set { pin=value; }
}
#endregion
#region Functions
public override void open() {
if(active) {
arduino.initInfraredTx(pin);
}
}
public override void close() {
if(active) {
// nothing to do yet ...
}
}
public override string ToString() {
return name+" [D"+pin+"]";
}
#endregion
#region Update
public override void update(Component component) {
if(GetType() == component.GetType()) {
InfraredTx c = (InfraredTx)component;
#region Update Properties
this.active = c.Active;
this.name = c.Name;
this.protocol = c.Protocol;
#endregion
}
}
#endregion
}
}
|
5e8e60e1bc460930d19f87a3273a2041838374b1
|
C#
|
MangoFloat/avl-tree-csharp
|
/NUnit Tests/TestAVLTree.cs
| 3.390625
| 3
|
using NUnit.Framework;
using System.Text;
namespace CountryAssignment.NUnit_Tests
{
[TestFixture(Author = "jaictinjune@gmail.com", Category = "Tree", Description = "Testing the AVLTree class.")]
public class TestAVLTree
{
[Test(Author = "jaictinjune@gmail.com", Description = "Test the initiation of the AVL Tree.")]
public void NewAVLTree()
{
AVLTree<int> tree = new AVLTree<int>();
tree.InsertItem(1); // 4
tree.InsertItem(2); // 2 6
tree.InsertItem(3); // 1 3 5 8
tree.InsertItem(4); // 7 9
tree.InsertItem(5); //
tree.InsertItem(6); //
tree.InsertItem(7); //
tree.InsertItem(8); //
tree.InsertItem(9); //
Assert.IsInstanceOf<AVLTree<int>>(tree);
}
[Test(Author = "jaictinjune@gmail.com", Description = "Test the rotation of the tree, checking if the orders are correct when adding/removing nodes to the tree.")]
public void TestRotations()
{
AVLTree<int> tree = new AVLTree<int>();
tree.InsertItem(1); // 4
tree.InsertItem(4); // 2 7
tree.InsertItem(6); // 1 3 6 8
tree.InsertItem(2); // 5 9
tree.InsertItem(8); //
tree.InsertItem(3); //
tree.InsertItem(7); //
tree.InsertItem(5); //
tree.InsertItem(9); //
// Using AVL Tree visualiser.
StringBuilder strInOrder1 = new StringBuilder();
string strInOrder2 = "1,2,3,4,5,6,7,8,9,";
tree.InOrder(ref strInOrder1);
StringBuilder strPreOrder1 = new StringBuilder();
string strPreOrder2 = "4,2,1,3,7,6,5,8,9,";
tree.PreOrder(ref strPreOrder1);
StringBuilder strPostOrder1 = new StringBuilder();
string strPostOrder2 = "1,3,2,5,6,9,8,7,4,";
tree.PostOrder(ref strPostOrder1);
Assert.AreEqual(strInOrder1.ToString(), strInOrder2);
Assert.AreEqual(strPreOrder1.ToString(), strPreOrder2);
Assert.AreEqual(strPostOrder1.ToString(), strPostOrder2);
tree.RemoveItem(7); // 4
// 2 8
// 1 3 6 9
// 5
strInOrder1.Clear();
string strInOrder3 = "1,2,3,4,5,6,8,9,";
tree.InOrder(ref strInOrder1);
strPreOrder1.Clear();
string strPreOrder3 = "4,2,1,3,8,6,5,9,";
tree.PreOrder(ref strPreOrder1);
strPostOrder1.Clear();
string strPostOrder3 = "1,3,2,5,6,9,8,4,";
tree.PostOrder(ref strPostOrder1);
Assert.AreEqual(strInOrder1.ToString(), strInOrder3);
Assert.AreEqual(strPreOrder1.ToString(), strPreOrder3);
Assert.AreEqual(strPostOrder1.ToString(), strPostOrder3);
tree.RemoveItem(9); // 4
// 2 6
// 1 3 5 8
strInOrder1.Clear();
string strInOrder4 = "1,2,3,4,5,6,8,";
tree.InOrder(ref strInOrder1);
strPreOrder1.Clear();
string strPreOrder4 = "4,2,1,3,6,5,8,";
tree.PreOrder(ref strPreOrder1);
strPostOrder1.Clear();
string strPostOrder4 = "1,3,2,5,8,6,4,";
tree.PostOrder(ref strPostOrder1);
Assert.AreEqual(strInOrder1.ToString(), strInOrder4);
Assert.AreEqual(strPreOrder1.ToString(), strPreOrder4);
Assert.AreEqual(strPostOrder1.ToString(), strPostOrder4);
}
}
}
|
1dfe48dc93a67315bf1736b91903c679ff6afc93
|
C#
|
Timur999/KrokPoKroku
|
/Chapter 5 Petle/Chapter 5 Petle/Program.cs
| 3.53125
| 4
|
using System;
using System.IO;
namespace Chapter_5_Petle
{
class Program
{
static void Main(string[] args)
{
//WyswietlZawartoscPliku();
ZnajdzKlucz();
Console.ReadKey();
}
static void PetlaWhile()
{
int i = 10;
while(i > 0)
{
Console.WriteLine(i);
i--;
}
Console.WriteLine("Rakieta leci na Saturna");
/* Note: zmienna która służy tylko do kontroli wykonanych iteracji nazywamy zmienna sterującą lub pomocniczą.
* Tak jak w instrukcji if zaleca się stosować blok kodu (nawisów { }) gdy petla while zawiera jedną instrukcje.
*/
while (i < 10)
Console.WriteLine("nieskończonośc");
i++;
}
static void WyswietlZawartoscPliku()
{
CzytajPlik(PobierzPlik());
}
static TextReader PobierzPlik()
{
string path = @"d:/Mircosoft krok po kroku/mojeProjekty/Chapter 5 Petle/Chapter 5 Petle/Resources/Tekst.txt";
return new StreamReader(path);
}
static void CzytajPlik(TextReader stream)
{
string line = stream.ReadLine();
while (line != null)
{
Console.WriteLine(line);
line = stream.ReadLine();
}
stream.Dispose();
}
static void PetlaFor(TextReader stream)
{
// Możliwe jst pominięcie dowolnej części w instrukcji for
for (int i = 0; ; i++)
{
Console.Write("czy może mnie ktoś zatrzymać!");
}
for (int i = 0, j = 10; i < j; i++, j--)
{
Console.Write("Instrukcja logiczna może być tylko jedna");
}
for (string line = stream.ReadLine(); line != null; line = stream.ReadLine())
{
Console.WriteLine(line);
}
stream.Dispose();
//Note: Zakres zmiennych ograniczony jest do ciała pętli i przestaje istnieć po.
}
static void ZnajdzKlucz()
{
bool parseSucceed = int.TryParse(Console.ReadLine(), out int secretNumber);
if (parseSucceed)
{
for (int i = 0; ; i++)
{
if(i != secretNumber)
{
continue;
}
Console.WriteLine($"Znalazłem klucz! {i}");
break;
}
}
}
static char KonwertujLiczbeDoZnaku(int liczba)
{
/* Note. Każdy znak jest reprezentowany przez liczbę całkowitą. Język C# umożliwia traktowanie znaku jako liczby
* i wykonywanie na niej operacji arytmetycznych. Znak '0' jest reprezentowany przez liczbę 48, '1' = 49, ... '9' = 57.
* Jest to tak zwany system kodowania znaków, w zależności zestawu znaków uzywany przez systemu operacyjnego niekture
* znaki bedą reprezentowane przez inne liczby.
* http://kursdlaopornych.pl/iso-ascii-unicode-kodowanie-znakow/
*/
int liczbaAscii = '0' + liczba;
char znak = Convert.ToChar(liczbaAscii);
return znak;
}
}
}
|
a076bf17fdca6a304b5691a2069b4c6c2424186d
|
C#
|
bethfbillings/revature_P1
|
/P1/P1.Domain/Models/Location.cs
| 2.8125
| 3
|
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using P1.Data.Entities;
namespace P1.Domain.Models
{
public class Location
{
private readonly p1Context _db = new p1Context();
public int Id { get; set; }
public string Street { get; set; }
public string Town { get; set; }
public string Province { get; set; }
public Location(string NewStreet, string NewTown, string NewProvince)
{
Street = NewStreet;
Town = NewTown;
Province = NewProvince;
}
public Location()
{
}
public void FindId()
{
var locs = _db.Location.ToList();
foreach (var loc in locs)
{
if (loc.Street.Equals(Street))
{
Id = loc.LocationId;
}
}
}
public void AddNewCrust(Crust c)
{
_db.Crust.Add(new P1.Data.Entities.Crust
{
Name = c.Name,
Price = c.Price
});
_db.SaveChanges();
}
public void AddNewTopping(Topping t)
{
_db.Crust.Add(new P1.Data.Entities.Crust
{
Name = t.Name,
Price = t.Price
});
_db.SaveChanges();
}
public void AddNewSize(Size s)
{
_db.Size.Add(new P1.Data.Entities.Size
{
Name = s.Name,
Price = s.Price
});
_db.SaveChanges();
}
public void AddNewRecipe(Recipe r)
{
_db.Recipe.Add(new P1.Data.Entities.Recipe
{
Name = r.Name,
CrustId = r.Crust.Id,
ToppingsId = r.Toppings.Id
});
_db.SaveChanges();
}
public List<Data.Entities.Crust> GetCrustList()
{
return _db.Crust.ToList();
}
public List<Data.Entities.Size> GetSizeList()
{
return _db.Size.ToList();
}
//Location should be able to view its inventory
public List<Data.Entities.Topping> ViewInventory()
{
FindId();
var AllToppings = _db.Topping.ToList();
var LocToppings = new List<Data.Entities.Topping>();
foreach (var Topping in AllToppings)
{
if (Topping.LocationId.Equals(Id))
{
LocToppings.Add(Topping);
}
}
return LocToppings;
}
public List<Data.Entities.Recipe> GetRecipeList()
{
return _db.Recipe.ToList();
}
public List<Data.Entities.Order> GetLocOrders()
{
FindId();
var AllOrders = _db.Order.ToList();
var LocOrders = new List<Data.Entities.Order>();
foreach (var Order in AllOrders)
{
if (Order.LocationId.Equals(Id))
{
LocOrders.Add(Order);
}
}
return LocOrders;
}
//Location should be able to view its orders (number of pizzas sold)
public int ViewOrders()
{
int orders = 0;
var PPizzas = _db.PresetPizza.ToList();
var CPizzas = _db.CustomPizza.ToList();
var LocOrders = GetLocOrders();
foreach (var Order in LocOrders)
{
foreach (var Pizza in PPizzas)
{
if (Pizza.OrderId.Equals(Order.LocationId))
{
orders++;
}
}
foreach (var Pizza in CPizzas)
{
if (Pizza.OrderId.Equals(Order.LocationId))
{
orders++;
}
}
}
return orders;
}
//Location should be able to view its users
public List<Data.Entities.User> ViewUsers()
{
var LocOrders = GetLocOrders();
var Users = _db.User.ToList();
var LocUsers = new List<Data.Entities.User>();
foreach (var User in Users)
{
foreach (var Order in LocOrders)
{
if (Order.UserId.Equals(User.UserId))
{
if (!LocUsers.Contains(User))
{
LocUsers.Add(User);
}
}
}
}
return LocUsers;
}
//Location should be able to view its sales
public int ViewSales()
{
return ViewUsers().Count;
}
}
}
|
8e0673504da8b2be7c5345ada148c00ef8de800b
|
C#
|
thoefut/problemsetsolutions
|
/solutions/Vowel Counter/Vowel Counter.cs
| 4.03125
| 4
|
/*Count Vowels
* Enter a string and the program counts the number of vowels in the text. For added complexity have it report a sum of each vowel found.
*
* Input = User enters a line for the program to analyze
* Output = Statistics on each vowel used. Total number of vowels in the provided string.
*/
using System;
using System.Collections.Generic;
namespace Vowel_Counter
{
static class Program
{
static void Main()
{
Console.WriteLine("Enter line to analyze");
Vowel_counter.PrintStatisticsToConsole(Console.ReadLine());
}
}
public class Vowel_counter
{
static readonly char[] consonants = { 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z' };
static readonly char[] vowels = { 'a', 'e', 'i', 'o', 'u', 'y' };
public static void PrintStatisticsToConsole(string toAnalyze)
{
SortedDictionary<char, int> dict = CountVowels(toAnalyze);
int numberofvowels = 0;
foreach (char key in dict.Keys)
{
Console.WriteLine("{0} = {1}", key, dict[key]);
numberofvowels += dict[key];
}
Console.WriteLine("Total number of vowels = {0}", numberofvowels);
}
public static SortedDictionary<char, int> CountVowels(string toCount)
{
SortedDictionary<char, int> dict = new SortedDictionary<char, int>();
foreach (char vow in vowels)
{
dict.Add(vow, 0);
}
foreach (char character in toCount)
{
if (dict.ContainsKey(character)) { dict[character]++; }
}
return dict;
}
}
}
|
c0318261cd168663baa0e496b378544c0e4c0beb
|
C#
|
turgaykya/Web-ve-Mvc-ornekleri
|
/MVC - Get-Post Örneği/NorthwindManagement/Controllers/EmployeeController.cs
| 2.84375
| 3
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace NorthwindManagement.Controllers
{
public class EmployeeController : Controller
{
public NorthwindEntities _dbContext;
public EmployeeController()
{
_dbContext = new NorthwindEntities();
}
/// <summary>
/// çalışanları gosteren view'ı cagırır
/// </summary>
/// <returns></returns>
public ActionResult Index()
{
var employeeList = _dbContext.Employees.ToList();
return View(employeeList);
}
/// <summary>
/// calısan eklemek icin gerekli olan ekleme formunu içeren View'i cagırır
/// </summary>
/// <returns></returns>
public ActionResult AddForm()
{
return View();
}
/// <summary>
/// calısan ekleme View'ından gelen dataları yeni calısan nesnesinde biriktirip database'e kaydeder ve sonrasında listeleme sayfasının Action'ına yonlendirir.
/// </summary>
/// <param name="firstName"></param>
/// <param name="lastName"></param>
/// <param name="city"></param>
/// <param name="title"></param>
/// <returns></returns>
/// string firstName, string lastName, string city, string title
public ActionResult Add()
{
Employee newEmp = new Employee(/*string firstName, string lastName, string city, string title*/);
newEmp.FirstName = Request.Form["firstName"];
newEmp.LastName = Request.Form["lastName"];
newEmp.City = Request.Form["city"];
newEmp.Title = Request["title"]; // bude olur
//newEmp.FirstName = firstName;
//newEmp.LastName = lastName;
//newEmp.City = city;
//newEmp.Title = title;
_dbContext.Employees.Add(newEmp);
_dbContext.SaveChanges();
//Yöntem 1:
//return View("Index", _dbContext.Employees.ToList());
//Yöntem 2:
return RedirectToAction("Index");
}
/// <summary>
/// parametre olarak gelen Id'ye sahip calısanı databaseden siler ve calısan listesini barındıran Action'ına yönlendirir.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public ActionResult Delete(int id)
{
Employee emp = _dbContext.Employees.Find(id);
_dbContext.Employees.Remove(emp);
//_dbContext.Entry(emp).State = EntityState.Deleted;
_dbContext.SaveChanges();
return RedirectToAction("Index");
}
/// <summary>
/// calısan guncellemek icin gerekli olan ekleme formunu iceren View ı cagırır.ilgili calısanın datası da model olarak view'a gider.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public ActionResult UpdateForm(int id)
{
Employee emp = _dbContext.Employees.Find(id);
return View(emp);
}
public ActionResult Update(int id, string firstName, string lastname, string title, string city)
{
Employee emp = _dbContext.Employees.Find(id);
emp.FirstName = firstName;
emp.LastName = lastname;
emp.Title = title;
emp.City = city;
_dbContext.SaveChanges();
return RedirectToAction("Index");
}
}
}
|
caa764819893302f20123a4047f77faa877c796b
|
C#
|
Woarkeswat/UMLDesigner
|
/UMLDesign/AppLayer/DrawingComponents/ClassDiagramFactory.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
namespace AppLayer.DrawingComponents
{
public class ClassDiagramFactory
{
private static ClassDiagramFactory _instance;
private static readonly object MyLock = new object();
private ClassDiagramFactory() { }
public static ClassDiagramFactory Instance
{
get
{
lock (MyLock)
{
if (_instance == null)
_instance = new ClassDiagramFactory();
}
return _instance;
}
}
public string ResourceNamePattern { get; set; }
public Type ReferenceType { get; set; }
private readonly Dictionary<string, ClassDiagramWithIntrinsicState> _sharedTrees = new Dictionary<string, ClassDiagramWithIntrinsicState>();
public ClassDiagramWithAllState GetTree(ClassDiagramExtrinsicState extrinsicState)
{
ClassDiagramWithIntrinsicState treeWithIntrinsicState;
if (_sharedTrees.ContainsKey(extrinsicState.TreeType))
treeWithIntrinsicState = _sharedTrees[extrinsicState.TreeType];
else
{
treeWithIntrinsicState = new ClassDiagramWithIntrinsicState();
string resourceName = string.Format(ResourceNamePattern, extrinsicState.TreeType);
treeWithIntrinsicState.LoadFromResource(resourceName, ReferenceType);
_sharedTrees.Add(extrinsicState.TreeType, treeWithIntrinsicState);
}
return new ClassDiagramWithAllState(treeWithIntrinsicState, extrinsicState);
}
}
}
|
a0ce86f0b02acb22c028dc5dba590a156306ab6a
|
C#
|
luyiwang1/CPSC481Project
|
/Ordering System/Ordering System/LunchMenu.xaml.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Ordering_System
{
/// <summary>
/// Interaction logic for LunchMenu.xaml
/// </summary>
public partial class LunchMenu : UserControl
{
public LunchMenu()
{
InitializeComponent();
}
private void Help_Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Select the quantity of each item using the plus/minus buttons." + "\n" + "Then press the ADD button to add the items to your order.");
}
private void Server_Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("A staff member will be with you shortly.");
}
private void Appetizer_Button_Click(object sender, RoutedEventArgs e)
{
Switcher.Switch(new AppetizerMenu());
}
private void Breakfast_Button_Click(object sender, RoutedEventArgs e)
{
Switcher.Switch(new BreakfastMenu());
}
private void Dinner_Button_Click(object sender, RoutedEventArgs e)
{
Switcher.Switch(new DinnerMenu());
}
private void Dessert_Button_Click(object sender, RoutedEventArgs e)
{
Switcher.Switch(new DessertMenu());
}
private void Drinks_Button_Click(object sender, RoutedEventArgs e)
{
Switcher.Switch(new DrinksMenu());
}
private void My_Order_Button_Click(object sender, RoutedEventArgs e)
{
Switcher.Switch(new Order_C1());
}
private void Bill_Button_Click(object sender, RoutedEventArgs e)
{
Switcher.Switch(new CheckOut());
}
private void DOWN_Button_Click(object sender, RoutedEventArgs e)
{
Switcher.Switch(new LunchMenu_2());
}
//==================================THIS SECTION IS FOR THE ADDING/MINUS OF THE CLASSIC BURGER============================================
private int burger = 0;
private int quantity_burger;
private void Burger_Add_Click(object sender, RoutedEventArgs e)
{
quantity_burger = burger; //Variable to use when adding the prices
burger = 0;
App_Count1.Text = burger.ToString();
}
private void Add_Burger_Click(object sender, RoutedEventArgs e)
{
burger++;
App_Count1.Text = burger.ToString();
}
private void Minus_Burger_Click(object sender, RoutedEventArgs e)
{
if (burger < 1)
{
App_Count1.Text = burger.ToString();
}
else
burger--;
App_Count1.Text = burger.ToString();
}
//==================================THIS SECTION IS FOR THE ADDING/MINUS OF THE SPICY SHRIMP TACOS============================================
private int shrimp = 0;
private int quantity_shrimp;
private void Shrimp_Add_Click(object sender, RoutedEventArgs e)
{
quantity_shrimp = shrimp; //Variable to use when adding the prices
shrimp = 0;
App_Count2.Text = shrimp.ToString();
}
private void Add_Shrimp_Click(object sender, RoutedEventArgs e)
{
shrimp++;
App_Count2.Text = shrimp.ToString();
}
private void Minus_Shrimp_Click(object sender, RoutedEventArgs e)
{
if (shrimp < 1)
{
App_Count2.Text = shrimp.ToString();
}
else
shrimp--;
App_Count2.Text = shrimp.ToString();
}
private void GoBack_Button_Click(object sender, RoutedEventArgs e)
{
Switcher.Switch(new WelcomeScreen());
}
}
}
|
f0f7fdfe948df0d6e628b85e4a34daed87208563
|
C#
|
soola-sys/Todolist
|
/Home.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RegistrationAndLogin
{
public partial class Home : Form
{
public Home()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void label3_Click(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
SqlConnection cn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\123\Desktop\RegistrationAndLogin\RegistrationAndLogin\Database.mdf;Integrated Security=True");
private void button2_Click(object sender, EventArgs e)
{
try
{
cn.Open();
string query = "insert into CatTable values (" + CatIdTb.Text + " , '" + CatNameTb.Text + "' , '" + CatDescTb.Text + "')";
SqlCommand com = new SqlCommand(query, cn);
com.ExecuteNonQuery();
MessageBox.Show("The category added successfully!");
cn.Close();
}
catch(Exception exp)
{
MessageBox.Show(exp.Message);
}
}
private void populate()
{
cn.Open();
string qerty = "select * from CatTable";
SqlDataAdapter sda = new SqlDataAdapter(qerty, cn);
SqlCommandBuilder builder = new SqlCommandBuilder(sda);
var ds = new DataSet();
sda.Fill(ds);
CatDGView.DataSource = ds.Tables[0];
cn.Close();
}
private void Home_Load(object sender, EventArgs e)
{
populate();
}
private void CatDGView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
CatIdTb.Text = CatDGView.SelectedRows[0].Cells[0].Value.ToString();
CatNameTb.Text = CatDGView.SelectedRows[0].Cells[1].Value.ToString();
CatDescTb.Text = CatDGView.SelectedRows[0].Cells[2].Value.ToString();
}
private void button4_Click(object sender, EventArgs e)
{
try
{
if (CatIdTb.Text == " ")
{
MessageBox.Show("Select the category to delete");
}
else
{
cn.Open();
string query = "delete from CatTable where CatId =" + CatIdTb.Text + " ";
SqlCommand cmd = new SqlCommand(query, cn);
cmd.ExecuteNonQuery();
MessageBox.Show("Success!");
cn.Close();
populate();
}
}
catch(Exception exp)
{
MessageBox.Show(exp.Message);
}
}
private void button3_Click(object sender, EventArgs e)
{
try
{
if(CatIdTb.Text == " " || CatNameTb.Text == " " || CatDescTb.Text == " ")
{
MessageBox.Show("Missing information!");
}
else {
cn.Open();
string query = "update CatTable set CatName = '" + CatNameTb.Text + "', CatDesc = '" + CatDescTb.Text + "' where CatId = " + CatIdTb.Text + "; ";
SqlCommand cmd = new SqlCommand(query, cn);
cmd.ExecuteNonQuery();
MessageBox.Show("Successfully updated!");
cn.Close();
populate();
}
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
private void btnLogOut_Click(object sender, EventArgs e)
{
Login log = new Login();
log.Show();
this.Hide();
}
}
}
|
78b703b35524b02ebd794e05198df9f160e83e7a
|
C#
|
Alaanor/udh-gamejam
|
/Assets/Scripts/Game/PlayerInput.cs
| 2.640625
| 3
|
using UnityEngine;
namespace Game
{
public class PlayerInput
{
public Vector2 RawMovement;
public bool IsShooting;
public void Update()
{
RawMovement = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
if (Input.GetKeyDown(KeyCode.Space))
IsShooting = !IsShooting;
}
}
}
|
a73d45c2630530f11b2cbc27b250526908ece447
|
C#
|
matthew-pye/Uni-Work
|
/Tutorial 15/Vehicle/Vehicle/Form1.cs
| 3
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Vehicle
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Vehicle V = new Vehicle();
Bicycle Bike = new Bicycle(true,"Red",21);
BicycleLabel.Text = Bike.ToString();
MotorBike MBike = new MotorBike("Green", 1600, "Fork");
MotorBikeLabel.Text = MBike.ToString();
Car C = new Car("Red", 2000, 5);
CarLabel.Text = C.ToString();
Total.Text = "There are " + Convert.ToString(V.GetCount()) + "Vehicles";
}
}
}
|
d3c6bda3b8c390845c7cf62bf7cf8bb5020993a3
|
C#
|
JasperFx/jasper
|
/src/Samples/OrderSagaSample/OrderSaga.cs
| 2.796875
| 3
|
using Baseline.Dates;
using Jasper;
namespace OrderSagaSample;
#region sample_Order_saga
public record StartOrder(string OrderId);
public record CompleteOrder(string Id);
public record OrderTimeout(string Id) : TimeoutMessage(1.Minutes());
public class Order : Saga
{
public string? Id { get; set; }
// This method would be called when a StartOrder message arrives
// to start a new Order
public OrderTimeout Start(StartOrder order, ILogger<Order> logger)
{
Id = order.OrderId; // defining the Saga Id.
logger.LogInformation("Got a new order with id {Id}", order.OrderId);
// creating a timeout message for the saga
return new OrderTimeout(order.OrderId);
}
// Apply the CompleteOrder to the saga
public void Handle(CompleteOrder complete, ILogger<Order> logger)
{
logger.LogInformation("Completing order {Id}", complete.Id);
// That's it, we're done. Delete the saga state after the message is done.
MarkCompleted();
}
// Delete this order if it has not already been deleted to enforce a "timeout"
// condition
public void Handle(OrderTimeout timeout, ILogger<Order> logger)
{
logger.LogInformation("Applying timeout to order {Id}", timeout.Id);
// That's it, we're done. Delete the saga state after the message is done.
MarkCompleted();
}
}
#endregion
|
8399ab70d989e814749442253dddcc160845f014
|
C#
|
teja-vellanki/AngloAmericanTest
|
/Utils/SetDriver.cs
| 2.65625
| 3
|
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using Microsoft.Edge.SeleniumTools;
namespace AngloAmericanTest.Utils
{
/// <summary>
/// This class performs an important function.
/// </summary>
public class SetDriver
{
public IWebDriver GetDriver(string browser)
{
switch (browser.ToLower())
{
//Using switch acase to run tests on specific browser
case "chrome":
var chromeOptions = new ChromeOptions();
chromeOptions.AddArgument("--start-mazimised");
chromeOptions.AddArgument("--disable-notifications");
return new ChromeDriver(Helper.WebDriverDirectory, chromeOptions);
case "edge":
EdgeOptions edgeOptions = new EdgeOptions();
edgeOptions.UseChromium = true;
return new EdgeDriver(Helper.WebDriverDirectory, edgeOptions);
default:
return new ChromeDriver();
}
}
}
}
|
3e341c906b54daba476db63642c1fbd6471b9d50
|
C#
|
MMSZ/CodingDojo-ChineseCharacterTrainer
|
/ChineseCharacterTrainer.Implementation/Converters/PinyinConverter.cs
| 2.796875
| 3
|
using System;
using System.Globalization;
using System.Windows.Data;
using ChineseCharacterTrainer.Implementation.Services;
namespace ChineseCharacterTrainer.Implementation.Converters
{
public class PinyinConverter : IValueConverter
{
private IPinyinBeautifier _beautifier;
public IPinyinBeautifier Beautifier
{
get { return _beautifier ?? (new PinyinBeautifier()); }
set { _beautifier = value; }
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var stringValue = value as string;
return Beautifier.Beautify(stringValue);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
}
|
60ffb71fbb1c1e2048163aa8d0a39df8307f93ac
|
C#
|
Xamarians/OfflineSync
|
/SyncPocService/SyncPocService/Models/ApiResult.cs
| 2.609375
| 3
|
namespace SyncPocService.Models
{
public interface IResponse
{
bool Success { get; set; }
string Message { get; set; }
}
public interface IResponse<TData> : IResponse
{
TData Data { get; set; }
}
public class ApiResponse : IResponse
{
public bool Success { get; set; }
public string Message { get; set; }
public ApiResponse()
{
}
public ApiResponse(string errorMessage)
{
Success = false;
Message = errorMessage;
}
}
public class ApiResponse<TData> : ApiResponse, IResponse<TData>
{
public TData Data { get; set; }
public ApiResponse(TData data)
{
Success = true;
Data = data;
}
}
}
|
e1ce3e8d980df33c660361dbed285775f3099ded
|
C#
|
gsulc/NConfig
|
/src/NConfig.Ini/KeyDataExtensions.cs
| 2.609375
| 3
|
using IniParser.Model;
using System;
namespace NConfig.Ini
{
internal static class KeyDataExtensions
{
internal static void SetKeyDataToProperties(this KeyDataCollection keyDataCollection, object obj)
{
foreach (var key in keyDataCollection)
{
var keyInfo = obj.GetType().GetProperty(key.KeyName);
var keyType = keyInfo.PropertyType;
object keyObject = Activator.CreateInstance(keyType);
object value = Convert.ChangeType(key.Value, keyType);
keyInfo.SetValue(obj, value);
}
}
}
}
|
eab9059ca9ef7b2702f66411cc51beaa6710c9fa
|
C#
|
ly774508966/CardGame
|
/CardGame.Server/Factories/CardInstanceFactory.cs
| 3
| 3
|
using CardGame.Server.Instances.Game;
using CardGame.Server.Instances.Players;
using CardGame.Server.Instances.Cards;
using CardGame.Shared.Attributes;
using CardGame.Shared.Enums;
using CardGame.Shared.Models.Cards;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace CardGame.Server.Factories
{
/// <summary>
/// This is the factory that provides instances of cards declared in an <see cref="Assembly"/>.
/// </summary>
public class CardInstanceFactory
{
private readonly Dictionary<Card, Type> _cards;
/// <summary>
/// Creates a factory basing on the cards declared in an <paramref name="assembly"/>.
/// </summary>
public CardInstanceFactory(Assembly assembly)
{
_cards = new Dictionary<Card, Type>();
foreach (var type in assembly.GetTypes().Where(t => IsPlayableCard(t)))
{
var card = (Card)Activator.CreateInstance(type);
var attr = type.GetCustomAttribute<PlayableCard>();
_cards.Add(card, attr.InstanceType);
}
}
/// <summary>
/// Creates a <see cref="CardInstance"/> from a <paramref name="shortName"/>,
/// and also sets its <paramref name="owner"/>.
/// </summary>
public CardInstance Create(string shortName, GameInstance game, PlayerInstance owner)
=> Create(_cards.Keys.First(c => c.ShortName == shortName), game, owner);
/// <summary>
/// Create a <see cref="CardInstance"/> from a base card of type <typeparamref name="T"/>,
/// and also sets its <paramref name="owner"/>.
/// </summary>
public CardInstance Create<T>(GameInstance game, PlayerInstance owner) where T : Card
=> Create(_cards.Keys.First(c => c is T), game, owner);
private CardInstance Create(Card card, GameInstance game, PlayerInstance owner)
{
CardInstance instance = null;
switch (card)
{
case CreatureCard x:
instance = CreateCreature(x);
break;
}
instance.Game = game;
instance.Owner = owner;
instance.Id = Guid.NewGuid();
instance.ManaCost = card.ManaCost;
return instance;
}
private CreatureCardInstance CreateCreature(CreatureCard card)
{
var type = _cards[card];
var instance = (CreatureCardInstance)Activator.CreateInstance(type);
instance.Base = card;
instance.Attack = card.Attack;
instance.Health = card.Health;
instance.Features = CardFeature.None;
if (HasAttribute<Taunt>(card.GetType())) instance.Features |= CardFeature.Taunt;
if (HasAttribute<Rush>(card.GetType())) instance.Features |= CardFeature.Rush;
return instance;
}
private static bool IsPlayableCard(Type type)
=> type.CustomAttributes.Any(a => a.AttributeType == typeof(PlayableCard));
private static bool HasAttribute<T>(Type type) where T : Attribute
=> type.GetCustomAttribute<T>() != null;
}
}
|
2fff50d22dbd04139a3ff6735f2b51aed665c170
|
C#
|
debayanmitra/Threading-in-CSharp-vs-Java
|
/Accessing shared variable/ThreadTest.cs
| 3.21875
| 3
|
using System;
using System.Threading;
class ThreadTest
{
static readonly object locker
= new object();
static int sharedVariable;
static void Main()
{
Thread t = new Thread (Method);
t.Start();
lock(locker)
{
// sample operation
if(sharedVariable==0)
{
sharedVariable = 1;
}
}
}
static void Method()
{
lock(locker)
{
// sample operation
if(sharedVariable>0)
{
sharedVariable++;
}
}
}
}
|
6da68433254d98785783bfb6a4c7d82081cac282
|
C#
|
franciscoamartin/Aula1Turma2
|
/ImoveisProprietarios/ImoveisProprietarios/Migrations/Configuration.cs
| 2.640625
| 3
|
namespace ImoveisProprietarios.Migrations
{
using ImoveisProprietarios.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<ImoveisProprietarios.Models.ImobiliariaContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(ImoveisProprietarios.Models.ImobiliariaContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data.
var listProprietarios = new List<Proprietarios>()
{
new Proprietarios()
{
Nome = "Francisco",
Email = "teste@teste.com",
DataNascimento = DateTime.Now
},
new Proprietarios()
{
Nome = "Teste2",
Email = "teste2@teste.com",
DataNascimento = DateTime.Now
}
};
listProprietarios.ForEach(s => context.Proprietarios.AddOrUpdate(x => x.Nome, s)
);
context.SaveChanges();
var listaImoveis = new List<Imoveis>()
{
new Imoveis()
{
Cep = "88048301",
Bairro = "Centro",
Municipio = "Blumenau",
Complemento = "casa",
Numero = "200",
Logradouro = "Rua teste",
ProprietarioId = context.Proprietarios.FirstOrDefault(x => x.Nome == "Francisco").Id
},
new Imoveis()
{
Cep = "88048300",
Bairro = "Centro",
Municipio = "Blumenau",
Complemento = "casa",
Numero = "20",
Logradouro = "Rua teste2",
ProprietarioId = context.Proprietarios.FirstOrDefault(x => x.Nome == "Teste2").Id
}
};
listaImoveis.ForEach(s => context.Imoveis.AddOrUpdate(x => new { x.ProprietarioId, x.Cep }, s)
);
context.SaveChanges();
}
}
}
|
0072178962b1e9fe02bd9f5fb790beb5fb063216
|
C#
|
tectronics/moo-poo-civilisation-4info
|
/Model/Tests/Program.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Wrapper;
using modele.impl;
using modele.interfaces;
namespace Tests
{
class Program
{
unsafe static void Main(string[] args)
{
WrapperAlgo w = new WrapperAlgo(25);
for (int i = 0; i < 25; i++)
{
for (int j = 0; j < 25; j++)
{
System.Console.Write(((w.getCase(i, j)&(1<<15))>>15)+" ");
//System.Console.Write(w.getCase(i, j) + " ");
}
System.Console.WriteLine();
}
System.Console.WriteLine();
System.Console.WriteLine();
for (int i = 0; i < 25; i++)
{
for (int j = 0; j < 25; j++)
{
System.Console.Write(((w.getCase(i, j) & 1 << 16) >> 16) + " ");
//System.Console.Write(w.getCase(i, j) + " ");
}
System.Console.WriteLine();
}
System.Console.Write(w.getEmplacementVille(10, 10,0)+" "+w.getEmplacementVille(10, 10,1));
Console.ReadLine();
/*
JoueurImpl j0 = new JoueurImpl("Jean-pierre","INFO");
JoueurImpl j1 = new JoueurImpl("Jean-luc","EII");
CarteImpl c = new CarteImpl(2);
Desert d0 = new Desert();
Desert d1 = new Desert();
c.cases[0,0] = d0;
c.cases[0,1] = d1;
List<Unite> l00 = new List<Unite>();
List<Unite> l11 = new List<Unite>();
c.cases[0, 0].unites = l00;
c.cases[0, 1].unites = l11;
JeuImpl.INSTANCE.carte = c;
EtudiantInfo i = new EtudiantInfo();
i.joueur = j0;
i.attaque = 4;
i.defense = 4;
i.x = 0;
i.y = 0;
i.mouvement = 4;
i.vie = 10;
EtudiantEii e = new EtudiantEii();
e.joueur = j1;
e.attaque = 4;
e.defense = 2;
e.x = 0;
e.y = 1;
e.vie = 2;
JeuImpl j = JeuImpl.INSTANCE;
Carte carteofshit = j.carte;
Case c0 = carteofshit.getCase(0, 0);
Case c1 = carteofshit.getCase(0, 1);
List<Unite> l0 = c0.unites;
List<Unite> l1 = c1.unites;
l0.Add(i);
l1.Add(e);
UniteImpl u0 = (UniteImpl)JeuImpl.INSTANCE.carte.getCase(0, 0).unites.First();
UniteImpl u1 = (UniteImpl)JeuImpl.INSTANCE.carte.getCase(0,1).unites.First();
i.attaquer(0,1);
System.Console.WriteLine();
System.Console.WriteLine("Vie de i - Attaquant");
System.Console.WriteLine(i.vie);
System.Console.WriteLine("Vie de e - Defenseur ");
System.Console.WriteLine(e.vie);
System.Console.WriteLine("Position de i - Attaquant ");
System.Console.WriteLine(i.x+" "+i.y);
System.Console.ReadLine();
*/
}
}
}
|
3b7a5d78a499fe10700fedfedc618a7ef572b838
|
C#
|
nsarris/Idotf
|
/IdotF/DeferredIfWithInput.cs
| 2.96875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace IdotF
{
public sealed class DeferredIfWithInput<Tin>
{
private readonly List<CaseWithInput<Tin>> cases;
public DeferredIfWithInput(bool condition, Action<Tin> action)
{
cases = new List<CaseWithInput<Tin>>();
if (condition) cases.Add(new CaseWithInput<Tin>(action));
}
public DeferredIfWithInput(Func<bool> condition, Action<Tin> action)
{
cases = new List<CaseWithInput<Tin>> { new CaseWithInput<Tin>(condition, action) };
}
internal DeferredIfWithInput(IEnumerable<CaseWithInput<Tin>> cases, CaseWithInput<Tin> nextCase)
{
this.cases = cases.ToList();
this.cases.Add(nextCase);
}
internal DeferredIfWithInput(IEnumerable<CaseWithInput<Tin>> cases)
{
this.cases = cases.ToList();
}
public DeferredIfWithInput<Tin> ElseIf(bool condition, Action<Tin> action)
{
return
condition ?
new DeferredIfWithInput<Tin>(cases, new CaseWithInput<Tin>(action)) :
new DeferredIfWithInput<Tin>(cases);
}
public DeferredIfWithInput<Tin> ElseIf(Func<bool> condition, Action<Tin> action)
{
return new DeferredIfWithInput<Tin>(cases, new CaseWithInput<Tin>(condition, action));
}
public DeferredEndIfWithInput<Tin> Else(Action<Tin> action)
{
return new DeferredEndIfWithInput<Tin>(cases, new CaseWithInput<Tin>(action));
}
public DeferredIfResult Execute(Tin input)
{
return Execute(input, cases);
}
internal static DeferredIfResult Execute(Tin input, IEnumerable<CaseWithInput<Tin>> cases)
{
foreach (var item in cases)
{
if (item.Condition == null || item.Condition())
{
item.Action(input);
return new DeferredIfResult(true);
}
}
return new DeferredIfResult(false);
}
}
}
|
31c24926a2a3cabefb70ab76b319ce3491ee5c8b
|
C#
|
OELib/ObjectEntanglementLibrary
|
/ObjectEntanglementLibrary/OELib/UniversalConnection/UCServer.cs
| 2.53125
| 3
|
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using OELib.LibraryBase;
using OELib.ObjectTunnel;
namespace OELib.UniversalConnection
{
public class UcServer : CommunicationServer<UCServerConnection>, IObjectTunnelConnection
{
private readonly object _reactingObject;
private readonly string _rootPath;
public UcServer(int port, object reactingObject, string rootPath, IFormatter formatter = null, ILogger logger = null, bool useCompression = false)
: base(new IPEndPoint(IPAddress.Any, port), formatter, logger, useCompression)
{
_reactingObject = reactingObject;
_rootPath = rootPath;
}
protected override UCServerConnection createInstance(TcpClient client)
{
var c = new UCServerConnection(client, _reactingObject, _rootPath, Formatter, Logger, UseCompression);
c.ObjectReceived += C_ObjectReceived;
return c;
}
public event EventHandler<object> ObjectReceived;
private void C_ObjectReceived(object sender, object e)
{
ObjectReceived?.Invoke(sender, e);
}
public bool SendObject<T>(T objectToSend)
{
var results = new ConcurrentBag<bool>();
Parallel.ForEach(Connections, c =>
{
if (c.IsReady) results.Add(c.SendObject(objectToSend));
});
return results.ToArray().All(r => r);
}
}
}
|
62ceea9447425dbaf83ac6c0db526d2e2d5ae2a5
|
C#
|
alandraper/Skybrud.Umbraco.GridData
|
/src/Skybrud.Umbraco.GridData/Converters/GridConverterAttribute.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Skybrud.Umbraco.GridData.Converters {
/// <summary>
/// Mark a class to be Auto-converted using the editor.Alias as a key
/// </summary>
public sealed class GridConverterAttribute : Attribute {
/// <summary>
/// Mark a class to be Auto-converted using the editor.Alias as a key
/// </summary>
/// <param name="editorAlias">The string which should match the editor.Alias of the grid control</param>
/// <param name="configType">The type for the Config (optional)</param>
public GridConverterAttribute(string editorAlias, Type configType = null) {
this.EditorAlias = editorAlias;
this.ConfigType = configType;
}
/// <summary>
/// The string which should match the editor.Alias of the grid control
/// </summary>
public string EditorAlias { get; }
/// <summary>
/// The type for the Config (optional)
/// </summary>
public Type ConfigType { get; }
}
}
|
523d4727294129640aef8c009e892aa8429c81f1
|
C#
|
Ramcste/Hall-Dining-Management-System
|
/HallDiningManagementSystem1/WpfApplication4/ManagerUI.xaml.cs
| 2.5625
| 3
|
using System;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication4
{
/// <summary>
/// Interaction logic for ManagerUI.xaml
/// </summary>
public partial class ManagerUI
{
public ManagerUI()
{
InitializeComponent();
}
private void Btnmanagerave_OnClick(object sender, RoutedEventArgs e)
{
if (TxtmanagernameBox.Text == string.Empty)
{
MessageBox.Show("Enter manager name first");
}
else if (PasswdBox.Password == string.Empty)
{
MessageBox.Show("Enter Password first!!");
}
else if (PasswdBox1.Password == string.Empty)
{
MessageBox.Show("Enter Password Again To confirm!!");
}
else
{
//@"^([A-Z][a-z]+|[A-Z][a-z]+\s[A-Z][a-z]+|[A-Z][a-z]+\s[A-Z][a-z]+\s[A-Z][a-z]+)$"
bool value1 = Regex.IsMatch(TxtmanagernameBox.Text,
@"^([A-Z][a-z]+|[A-Z][a-z]+\s[A-Z][a-z]+|[A-Z][a-z]+\s[A-Z][a-z]+\s[A-Z][a-z]+)$");
bool value2 = Regex.IsMatch(PasswdBox1.Password, @"^[a-z0-9_-]{6,18}$");
bool value3 = Regex.IsMatch(PasswdBox.Password, @"^[a-z0-9_-]{6,18}$");
int id = int.Parse(Txtmanagerid.Text);
if (value1 && value2 && value3)
{
if (PasswdBox.Password == PasswdBox1.Password)
{
if (id<= 4)
{
String ConnectionString = @"server=Roshani;Database=Dinning;Integrated Security=true";
String query = string.Format("insert into manager values('{0}','{1}','{2}','{3}')",
id, TxtmanagernameBox.Text,
PasswdBox.Password, Dtstartmanagering);
var connection = new SqlConnection(ConnectionString);
try
{
connection.Open();
var cmd = new SqlCommand(query, connection);
cmd.ExecuteNonQuery();
MessageBox.Show("Data is inserted Successfully!!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
MessageBox.Show("Manager Cann't be more than four");
}
}
else
{
MessageBox.Show("Enter same Password to Proceed");
}
}
else
{
MessageBox.Show(
"Password is mustbe the combination of digits and alphabet and at least 6 length !!");
}
}
}
private void GetAdminId()
{
String ConnectionString = @"server=Roshani;Database=Dinning;Integrated Security=true";
String query = string.Format("select Id from manager");
var connection = new SqlConnection(ConnectionString);
try
{
connection.Open();
var cmd = new SqlCommand(query, connection);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int sid = int.Parse(reader[0].ToString());
sid += 1;
Txtmanagerid.Text = sid.ToString(CultureInfo.InvariantCulture);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void TabItem_Loaded_1(object sender, RoutedEventArgs e)
{
Dtstartmanagering.Text = DateTime.Today.ToString(CultureInfo.InvariantCulture);
GetId();
}
private void BtnLoad_OnClick(object sender, RoutedEventArgs e)
{
String ConnectionString = @"server=Roshani; Database=Dinning; Integrated Security=true";
String query = string.Format("select Id,name,passwd from manager");
var connection = new SqlConnection(ConnectionString);
var ds = new DataSet();
var adapter = new SqlDataAdapter();
try
{
connection.Open();
var cmd = new SqlCommand(query, connection);
adapter.SelectCommand = cmd;
adapter.Fill(ds);
LstManager.DataContext = ds.Tables[0].DefaultView; // ListView
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void BtnOkay_OnClick(object sender, RoutedEventArgs e)
{
Close();
}
private void BtnUpadate_Click(object sender, RoutedEventArgs e)
{
if (TxtConfirmpassBox.Password == string.Empty)
{
MessageBox.Show("Enter again Password to confirm it");
}
else
{
if (TxtpassBox.Text == TxtConfirmpassBox.Password)
{
String ConnectionString = @"server=Roshani;Database=Dinning;Integrated Security=true";
String query =
string.Format("update manager set name='" + Txtmanagername.Text + "' , passwd='" +
TxtpassBox.Text +
"' where Id='" + ComboId.SelectedItem + "'");
var connection = new SqlConnection(ConnectionString);
try
{
connection.Open();
var cmd = new SqlCommand(query, connection);
cmd.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Ur Data is Updated Successfully!!!");
ClearValue();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
MessageBox.Show("Enter again Password to confirm it!!");
}
}
}
private void ClearValue()
{
TxtConfirmpassBox.Password = string.Empty;
}
private void ComboId_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
String ConnectionString = @"server=Roshani;Database=Dinning;Integrated Security=true";
String query = string.Format("select name,passwd from manager where Id='" + ComboId.SelectedItem + "'");
var connection = new SqlConnection(ConnectionString);
try
{
connection.Open();
var cmd = new SqlCommand(query, connection);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string sname = reader[0].ToString();
string spasswd = reader[1].ToString();
Txtmanagername.Text = sname;
TxtpassBox.Text = spasswd;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void TabItem_Loaded_2(object sender, RoutedEventArgs e)
{
Load();
}
private void Load()
{
String ConnectionString = @"server=Roshani; Database=Dinning; Integrated Security=true";
String query = string.Format("select Id from manager");
var connection = new SqlConnection(ConnectionString);
try
{
connection.Open();
var cmd = new SqlCommand(query, connection);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string sid = reader[0].ToString();
ComboId.Items.Add(sid);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Btnokay_Click(object sender, RoutedEventArgs e)
{
Close();
}
private void BtnShow_Click(object sender, RoutedEventArgs e)
{
String ConnectionString = @"server=Roshani;Database=Dinning;Integrated Security=true";
String query = string.Format("select name from manager where dateofstartingmanagering='" + TxtDate + "'");
var connection = new SqlConnection(ConnectionString);
try
{
connection.Open();
var cmd = new SqlCommand(query, connection);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string sname = reader[0].ToString();
ListManager.Items.Add(sname);
//MessageBox.Show(sname);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void TC_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var ti = TC.SelectedItem as TabItem;
if (ti != null) Title = ti.Header.ToString();
}
private void EditBatchButton_OnClick(object sender, RoutedEventArgs e)
{
if (BatchTextBox.Text == string.Empty)
{
MessageBox.Show("Fill the box!! ");
}
else if (!Regex.Match(BatchTextBox.Text, @"^(1st||2nd||3rd||[4-9]th||[12][0-9]th)$").Success)
{
MessageBox.Show(
"Error in Batch format.Batch should be written as firstnumber and then(st,nd,rdand th)", "Message",
MessageBoxButton.OK, MessageBoxImage.Error);
}
else if (Activate())
{
String ConnectionString = @"server=Roshani;Database=Dinning;Integrated Security=true";
String query =
string.Format("update batch set Batchname='" + BatchTextBox.Text + "' where Id='" +
BatchIdComboBox.SelectionBoxItem + "'");
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(query, connection);
cmd.ExecuteNonQuery();
MessageBox.Show("Ur data is Updated!!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void DepartmentButton_OnClick(object sender, RoutedEventArgs e)
{
if (DepartmentBox.Text == string.Empty)
{
MessageBox.Show("Fill all the boxes!! ");
}
else if (
!Regex.Match(DepartmentBox.Text,
@"^([A-Z]+|[A-Z][a-z]+|[A-Z][a-z]+\s[A-Z][a-z]+|[A-Z][a-z]+\s[A-Z][a-z]+\s[A-Z][a-z]+\s[A-Z][a-z]+\s[A-Z][a-z]+)$")
.Success)
{
MessageBox.Show(
"Error in Department name format.Department Name should be written as (CSTE,Pharmacy and Computer Science and Telecommunication Engineering)",
"Message",
MessageBoxButton.OK, MessageBoxImage.Error);
}
else if (Activate())
{
String ConnectionString = @"server=Roshani;Database=Dinning;Integrated Security=true";
String query = string.Format("insert into department values('{0}','{1}')", DeptIdTextBox.Text,
DepartmentBox.Text);
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(query, connection);
cmd.ExecuteNonQuery();
MessageBox.Show("Data is inserted Successfully!!");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void BatchButton_OnClick(object sender, RoutedEventArgs e)
{
if (BatchBox.Text == string.Empty)
{
MessageBox.Show("Fill all the boxes!! ");
}
else if (!Regex.Match(BatchBox.Text, @"^(1st||2nd||3rd||[4-9]th||[12][0-9]th)$").Success)
{
MessageBox.Show(
"Error in Batch format.Batch should be written as firstnumber and then(st,nd,rdand th)", "Message",
MessageBoxButton.OK, MessageBoxImage.Error);
}
else if (Activate())
{
String ConnectionString = @"server=Roshani;Database=Dinning;Integrated Security=true";
String query = string.Format("insert into batch values('{0}','{1}')", BatchIdBox.Text, BatchBox.Text);
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(query, connection);
cmd.ExecuteNonQuery();
MessageBox.Show("Data is inserted Successfully!!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void EditDepartmentButton_OnClick(object sender, RoutedEventArgs e)
{
if (DepartmentBox1.Text == string.Empty)
{
MessageBox.Show("Enter Department u want to update");
}
else if (
!Regex.Match(DepartmentBox1.Text,
@"^([A-Z]+|[A-Z][a-z]+|[A-Z][a-z]+\s[A-Z][a-z]+|[A-Z][a-z]+\s[A-Z][a-z]+\s[A-Z][a-z]+\s[A-Z][a-z]+\s[A-Z][a-z]+)$")
.Success)
{
MessageBox.Show("Error In Department Format", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
}
else if (Activate())
{
String ConnectionString = @"server=Roshani;Database=Dinning;Integrated Security=true";
String query =
string.Format("update department set Departmentname='" + DepartmentBox1.Text + "' where Id='" +
DeptIdCombobox.SelectionBoxItem + "'");
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(query, connection);
cmd.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Ur Data is Updated Successfully!!!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void AddAdminButton_OnClick(object sender, RoutedEventArgs e)
{
if (NameTextBox.Text == string.Empty || AdminPasswordBox.Password == string.Empty ||
PositionComboBox.Text == string.Empty)
{
MessageBox.Show("Enter all the fields and select position!!");
}
else if (
!Regex.Match(NameTextBox.Text,
@"^([A-Z][a-z]+|[A-Z][a-z]+\s[A-Z][a-z]+|[A-Z][a-z]+\s[A-Z][a-z]+\s[A-Z][a-z]+)$").Success)
{
MessageBox.Show("Error In Admin Name", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
}
else if (!Regex.Match(AdminPasswordBox.Password, @"^[a-z0-9_-]{6,18}$").Success)
{
MessageBox.Show("Error in Password ,Password length must be 6.", "Message", MessageBoxButton.OK,
MessageBoxImage.Error);
}
else if (PositionComboBox.Text == string.Empty)
{
MessageBox.Show("Select a Postion for the Admin");
}
else if (Activate())
{
if (GetCountAdminId() > 4)
{
String ConnectionString = @"server=Roshani;Database=Dinning;Integrated Security=true";
String query = string.Format("insert into admin values('{0}','{1}','{2}','{3}')",
AdminIdTextBox.Text, NameTextBox.Text, AdminPasswordBox.Password,
PositionComboBox.SelectionBoxItem);
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(query, connection);
cmd.ExecuteNonQuery();
MessageBox.Show("Data is inserted Successfully!!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
MessageBox.Show("Admin Can't be more than four!!!");
}
}
}
private void UpdateAdminButton_OnClick(object sender, RoutedEventArgs e)
{
if (
!Regex.Match(NameTextBox1.Text,
@"^([A-Z][a-z]+||[A-Z][a-z]+\s[A-Z][a-z]+||[A-Z][a-z]+\s[A-Z][a-z]+\s[A-Z][a-z]+)$").Success)
{
MessageBox.Show("Error In Admin Name", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
}
else if (!Regex.Match(AdminPasswordBox1.Password, @"^[a-z0-9_-]{6,18}$").Success)
{
MessageBox.Show("Error in Password ,Password length must be 6.", "Message", MessageBoxButton.OK,
MessageBoxImage.Error);
}
else if (!Regex.Match(NewAdminPasswordBox.Password, @"^[a-z0-9_-]{6,18}$").Success)
{
MessageBox.Show("Error in Password ,Password length must be 6.", "Message", MessageBoxButton.OK,
MessageBoxImage.Error);
}
else if (Activate())
{
String ConnectionString = @"server=Roshani;Database=Dinning;Integrated Security=true";
String query =
string.Format("update admin set Name='" + NameTextBox1.Text + "' , Password='" +
NewAdminPasswordBox.Password + "' , Position='" + PositionComboBox1.Text +
"' where Id='" + AdminIdComboBox.SelectionBoxItem + "'");
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(query, connection);
cmd.ExecuteNonQuery();
MessageBox.Show("Data is updated Successfully!!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void OkayButton_OnClick(object sender, RoutedEventArgs e)
{
Close();
}
private void GetId()
{
String ConnectionString = @"server=Roshani;Database=Dinning;Integrated Security=true";
String query = string.Format("select Id from Admin");
var connection = new SqlConnection(ConnectionString);
try
{
connection.Open();
var cmd = new SqlCommand(query, connection);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int sid = int.Parse(reader[0].ToString());
AdminIdComboBox.Items.Add(sid);
int id = sid + 1;
AdminIdTextBox.Text = id.ToString(CultureInfo.InvariantCulture);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void TabControl_Loaded_1(object sender, RoutedEventArgs e)
{
GetAdminId();
LoadData();
}
private void LoadData()
{
String ConnectionString = @"server=Roshani; Database=Dinning; Integrated Security=true";
String query = string.Format("select * from Admin");
SqlConnection connection = new SqlConnection(ConnectionString);
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter();
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(query, connection);
adapter.SelectCommand = cmd;
adapter.Fill(ds);
AdminListView.DataContext = ds.Tables[0].DefaultView; // ListView
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Grid_Loaded_1(object sender, RoutedEventArgs e)
{
GetAdminId();
}
private void AdminIdComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
String ConnectionString = @"server=Roshani;Database=Dinning;Integrated Security=true";
String query =
string.Format("select Name,Password,Position from admin where Id='" + AdminIdComboBox.SelectedItem + "'");
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(query, connection);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string sname = reader[0].ToString();
string spassword = reader[1].ToString();
string sposition = reader[2].ToString();
NameTextBox1.Text = sname;
AdminPasswordBox1.Password = spassword;
PositionComboBox1.Text = sposition;
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private int GetCountManagerId()
{
int i = 0;
String ConnectionString = @"server=Roshani;Database=Dinning;Integrated Security=true";
String query = string.Format("select Count(Id) from manager");
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(query, connection);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
i = int.Parse(reader[0].ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return i;
}
private int GetCountAdminId()
{
int i = 0;
String ConnectionString = @"server=Roshani;Database=Dinning;Integrated Security=true";
String query = string.Format("select count(Id) from admin ");
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(query, connection);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
i = int.Parse(reader[0].ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return i;
}
private void ManagerUI_OnClosing(object sender, CancelEventArgs e)
{
MessageBoxResult key = MessageBox.Show("Are you sure you want to quit?", "Confirm", MessageBoxButton.YesNo,
MessageBoxImage.Question, MessageBoxResult.No);
e.Cancel = (key == MessageBoxResult.No);
}
private void GetBatchId()
{
int i;
String ConnectionString = @"server=Roshani;Database=Dinning;Integrated Security=true";
String query = string.Format("select Id from batch");
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(query, connection);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
i = int.Parse(reader[0].ToString());
BatchIdComboBox.Items.Add(i);
BatchIdBox.Text = (i + 1).ToString(CultureInfo.InvariantCulture);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void GetDepartmentId()
{
int i;
String ConnectionString = @"server=Roshani;Database=Dinning;Integrated Security=true";
String query = string.Format("select Id from department");
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(query, connection);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
i = int.Parse(reader[0].ToString());
DeptIdCombobox.Items.Add(i);
DeptIdTextBox.Text = (i + 1).ToString(CultureInfo.InvariantCulture);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void TabItem_Loaded_3(object sender, RoutedEventArgs e)
{
GetBatchId();
}
private void TabItem_Loaded_4(object sender, RoutedEventArgs e)
{
GetDepartmentId();
}
private void DeptIdCombobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
String ConnectionString = @"server=Roshani;Database=Dinning;Integrated Security=true";
String query =
string.Format("select Departmentname from department where Id='" + DeptIdCombobox.SelectedItem + "'");
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(query, connection);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string sdept = reader[0].ToString();
DepartmentBox1.Text = sdept;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void BatchIdComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
String ConnectionString = @"server=Roshani;Database=Dinning;Integrated Security=true";
String query = string.Format("select Batchname from batch where Id='" + BatchIdComboBox.SelectedItem + "'");
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(query, connection);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string sbatch = reader[0].ToString();
BatchTextBox.Text = sbatch;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
|
e077033d2ae05ef2dc6ea4be1793327511c67f62
|
C#
|
Mishell74/Proyecto-bimestral
|
/2da parte del proyecto bimestral.cs
| 3.015625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using System.Security.Cryptography.X509Certificates;
namespace _2da_parte_del_proyecto
{
class Program
{
static SerialPort Arduino = new SerialPort("COM5", 9600);
static void Main(string[] args)
{
//Nelly Odette Pérez Osoy, Caroline Mishell Saquic Rodas, Khaterine Jazmín Yanes Alvarado, Diego Pablo Huertas Guitierrez
//perdonenos la vida profe pero ni a fuerza se repite :c
int e;
Arduino.Open();
Console.WriteLine("LUCESITA");
Console.WriteLine("1. encender lucesita");
Console.WriteLine("2. apagar lucesita");
e = Convert.ToInt32(Console.ReadLine());
while (e!=3)
{
if (Arduino.IsOpen) ;
}
while (e != 4)
{
if (Arduino.IsOpen)
{
if (e == 1)
{
Console.WriteLine(("encendida"), Console.ForegroundColor = ConsoleColor.Yellow);
byte[] data = Encoding.ASCII.GetBytes("e");
Arduino.Write(data, 0, data.Length);
break;
}
else if (e == 2)
{
Console.WriteLine(("apagada"), Console.ForegroundColor = ConsoleColor.Yellow);
byte[] data = Encoding.ASCII.GetBytes("a");
Arduino.Write(data, 0, data.Length);
Arduino.Close();
//Console.WriteLine("apagada");
}
}
else
{
break;
}
}
Console.ReadKey();
}
}
}
|
7da4dba79cde32a22956ede9a9ba3bba87c9d68c
|
C#
|
ulisses31/ContactsAPI
|
/Data/ContactsAPI.Data/Model/User.cs
| 2.53125
| 3
|
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using System.Threading.Tasks;
namespace ContactsAPI.Data.Model
{
[Table("Users")]
public class User : Base
{
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Username { get; set; }
[JsonIgnore]
public byte[] PasswordHash { get; set; }
[JsonIgnore]
public byte[] PasswordSalt { get; set; }
public int? ContactId { get; set; }
public virtual Contact Contact { get; set; }
public const int UsernameMaxLengh = 30;
public static void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().Property(property => property.Firstname).HasMaxLength(Constants.FirstNameMaxLength).IsRequired();
modelBuilder.Entity<User>().Property(property => property.Lastname).HasMaxLength(Constants.LastNameMaxLength).IsRequired();
modelBuilder.Entity<User>().Property(property => property.Username).HasMaxLength(UsernameMaxLengh).IsRequired();
modelBuilder.Entity<User>().Property(property => property.ContactId).IsRequired();
modelBuilder.Entity<User>()
.HasOne<Contact>(sc => sc.Contact).WithOne(s => s.User)
.HasForeignKey<User>(sc => sc.ContactId);
}
}
}
|
7ea769da98c0772288ef5314b7847e87c14c8b66
|
C#
|
RavilBoyukzade/ASP.NET-CORE-FINAL-PROJECT
|
/ASP.NET-CORE-FINAL-PROJECT/ViewComponents/AboutCardViewComponent.cs
| 2.578125
| 3
|
using ASP.NET_CORE_FINAL_PROJECT.Models;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Repository.Models;
using Repository.Repositories.AboutRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ASP.NET_CORE_FINAL_PROJECT.ViewComponents
{
public class AboutCardViewComponent :ViewComponent
{
private readonly IMapper _mapper;
private IAboutRepository _aboutRepository;
public AboutCardViewComponent(IMapper mapper,IAboutRepository aboutRepository)
{
_mapper = mapper; ;
_aboutRepository = aboutRepository;
}
public IViewComponentResult Invoke()
{
var card = _aboutRepository.GetCards();
var model = _mapper.Map<IEnumerable<AboutCard>,IEnumerable<AboutCardViewModel>>(card);
return View(model);
}
}
}
|
d8002d6c09a58e3dbdc827ab0e46737d3b726368
|
C#
|
rafaelps95/AudictiveMusic
|
/ClassLibrary/Themes/ThemeColor.cs
| 2.65625
| 3
|
using ClassLibrary.Helpers;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI;
using Windows.UI.Xaml.Media;
namespace ClassLibrary.Themes
{
public class ThemeColor : INotifyPropertyChanged
{
public ThemeColor()
{
}
public Color Color { get; set; }
public bool? IsSelected
{
get
{
return ThemeSettings.CustomThemeColor == this.Color;
}
set
{
if (value == true)
ThemeSettings.CustomThemeColor = this.Color;
OnPropertyChanged(this, "IsSelected");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(object sender, string Property)
{
if (PropertyChanged != null)
{
PropertyChanged(sender, new PropertyChangedEventArgs(Property));
}
}
}
}
|
8e0ce0cbda04855e9e7e9b8fe4bbf76bfc5207d9
|
C#
|
dominicbirch/CommandBuilder
|
/CommandBuilder/CommandBuilder.cs
| 3.5625
| 4
|
using System;
using System.Threading;
namespace CommandBuilder
{
/// <summary>
/// Used to create commands which execute each of the supplied commands once in sequence.
/// </summary>
/// <typeparam name="T">The type which the built commands may execute against.</typeparam>
public class CommandBuilder<T> : ICommandBuilder<T>
{
private Func<T, CancellationToken, T> _sequence = (i, _) => i;
private static Func<T, CancellationToken, T> Compose(Func<T, CancellationToken, T> f1, Action<T, CancellationToken> f2) =>
(instance, cancellationToken) =>
{
f2(f1(instance, cancellationToken), cancellationToken);
return instance;
};
/// <inheritdoc />
public ICommandBuilder<T> Add<T1>(T1 command) where T1 : ICommand<T>
{
_sequence = Compose(_sequence, command.Execute);
return this;
}
/// <inheritdoc />
public ICommand<T> Build() => new Command<T>(_sequence);
}
}
|
592f478714d72874bfce85523d680bafa210b64e
|
C#
|
darkl/Expression.js
|
/src/ExpressionJs/Expressions/PropertyOrField.cs
| 2.53125
| 3
|
using System.Linq.Expressions;
using Newtonsoft.Json;
namespace ExpressionJs
{
[JavascriptType("propertyOrField")]
public class PropertyOrField : IExpressionConvertible<MemberExpression>
{
[JsonProperty("expression")]
public virtual IExpressionConvertible<Expression> Expression { get; set; }
[JsonProperty("propertyOrFieldName")]
public virtual string PropertyOrFieldName { get; set; }
public virtual MemberExpression GetExpression(ExpressionBuilder builder)
{
return builder.PropertyOrField(Expression.GetExpression(builder), PropertyOrFieldName);
}
}
}
|
07cc4dab4e10cedd0fcd48a39143ef1023c31b27
|
C#
|
NinjaServ/ToDoApp
|
/ToDoApp/Models/DataTableToCSV.cs
| 3.078125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.IO;
namespace ToDoApp.Models
{
class DataTableToCSV
{
private void ExportDatatviewToCsv(string iFilename, DataView dv)
{
// Open output stream
StreamWriter swFile = new StreamWriter(iFilename);
// Header
string[] colLbls = new string[dv.Table.Columns.Count];
for (int i = 0; i < dv.Table.Columns.Count; i++)
{
colLbls[i] = dv.Table.Columns[i].ColumnName;
colLbls[i] = GetWriteableValueForCsv(colLbls[i]);
}
// Write labels
swFile.WriteLine(string.Join(",", colLbls));
// Rows of Data
foreach (DataRowView rowData in dv)
{
string[] colData = new string[dv.Table.Columns.Count];
for (int i = 0; i < dv.Table.Columns.Count; i++)
{
object obj = rowData[i];
colData[i] = GetWriteableValueForCsv(obj);
}
// Write data in row
swFile.WriteLine(string.Join(",", colData));
}
// Close output stream
swFile.Close();
}
private void ExportDatatableToCsv(string iFilename, DataTable dt)
{
// Open output stream
StreamWriter swFile = new StreamWriter(iFilename);
// Header
string[] colLbls = new string[dt.Columns.Count];
for (int i = 0; i < dt.Columns.Count; i++)
{
colLbls[i] = dt.Columns[i].ColumnName;
colLbls[i] = GetWriteableValueForCsv(colLbls[i]);
}
// Write labels
swFile.WriteLine(string.Join(",", colLbls));
// Rows of Data
foreach (DataRow rowData in dt.Rows)
{
string[] colData = new string[dt.Columns.Count];
for (int i = 0; i < dt.Columns.Count; i++)
{
object obj = rowData[i];
colData[i] = GetWriteableValueForCsv(obj);
}
// Write data in row
swFile.WriteLine(string.Join(",", colData));
}
// Close output stream
swFile.Close();
}
public static string GetWriteableValueForCsv(object obj)
{
// Nullable types to blank
if (obj == null || obj == Convert.DBNull)
return "";
// if string has no ','
if (obj.ToString().IndexOf(",") == -1)
return obj.ToString();
// remove backslahes
return "\"" + obj.ToString() + "\"";
}
}
}
|
0750c068982e45c3712cab93213e47f6bcd6e080
|
C#
|
N1NTENDO1999/Chat
|
/ChatWebApi/ChatWebApi/Application/Messages/Commands/DeleteMessageByIdCommand.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ChatWebApi.Infrastructure;
using ChatWebApi.Interfaces.Requests;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace ChatWebApi.Application.Messages.Commands
{
public class DeleteMessageByIdCommand : IRequest<CommandResult>
{
public int Id { get; set; }
}
public class DeleteMessageByIdCommandHandler : IRequestHandler<DeleteMessageByIdCommand, CommandResult>
{
private readonly ChatContext _db;
public DeleteMessageByIdCommandHandler(ChatContext chatContext)
{
_db = chatContext;
}
public async Task<CommandResult> Handle(DeleteMessageByIdCommand request, CancellationToken cancellationToken)
{
var message = await _db.Messages.FirstAsync(p => p.Id == request.Id);
message.Text = "Updated";
_db.Messages.Update(message);
await _db.SaveChangesAsync();
return new CommandResult();
}
}
}
|
0bb258de2ebe95972079bc7fcf031b40cc06ac74
|
C#
|
RomaPatch/FlappyActionAnimals
|
/Assets/Scripts/Common/ObjectPool.cs
| 2.84375
| 3
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ObjectPool : MonoBehaviour
{
public GameObject objectToPool;
public int pooledQuantity = 10;
public bool willGrow = true;
private List<GameObject> pooledObjects = new List<GameObject>();
void Awake()
{
for (var i = 0; i < pooledQuantity; i++)
{
CreatePooledObject();
}
}
private GameObject CreatePooledObject()
{
var pooledObject = (GameObject)Instantiate(objectToPool, transform);
// pooledObject.transform.parent = transform;
pooledObject.SetActive(false);
pooledObjects.Add(pooledObject);
return pooledObject;
}
public GameObject GetPooledObject()
{
GameObject pooledObject = null;
for (var i = 0; i < pooledObjects.Count; i++)
{
pooledObject = pooledObjects[i];
if (pooledObject.activeSelf){continue;}
return pooledObject;
}
if (willGrow)
{
pooledObject = CreatePooledObject();
return pooledObject;
}
return pooledObject;
}
}
|
bfc6a04990be3830b915dbaa0b43fd69ace82c88
|
C#
|
warrenfp/MenuLog
|
/MenuLog.Core/Factories/Ranking/DefaultRankingFactory.cs
| 2.640625
| 3
|
using MenuLog.Core.Interfaces;
namespace MenuLog.Core.Factories.Ranking
{
public class DefaultRankingFactory : IRankingFactory
{
public virtual IRankingStrategy GetStrategy(string strategyName = "")
{
throw new System.NotImplementedException(@"Please implement your own ranking factory.
Ensure you specify your strategy name in the Stragies configuration section. eg. Strategies:YourStrategy:Name");
//For the sake of this demo. Ensure the user has to have their own implementation.
}
}
}
|
78dfdf1da2f555243489fab93ee146414c04bc2b
|
C#
|
YLiohenki/leetcodeinterviewquestions
|
/leetcodeinterviewquestions/Trees and Graphs/PopulatingNextRightPointersInEachNode.cs
| 3.5625
| 4
|
using System;
using System.Collections.Generic;
using System.Text;
namespace leetcodeinterviewquestions.Trees_and_Graphs
{
public class Node
{
public int val;
public Node left;
public Node right;
public Node next;
public Node() { }
public Node(int _val)
{
val = _val;
}
public Node(int _val, Node _left, Node _right, Node _next)
{
val = _val;
left = _left;
right = _right;
next = _next;
}
}
public class PopulatingNextRightPointersInEachNode
{
public Node Connect(Node root)
{
if (root != null)
ConnectRecurs(root, null);
return root;
}
private void ConnectRecurs(Node root, Node toTheRight)
{
if (root.left == null)
return;
root.left.next = root.right;
root.right.next = toTheRight?.left;
ConnectRecurs(root.right, toTheRight?.left);
ConnectRecurs(root.left, root.right);
}
}
}
|
e9ede27641728a4bb129deed252dd6dd8f5f8103
|
C#
|
jeremyyang824/Leetcode
|
/Leetcode.Core/OJ117_PopulatingNextRightPointersInEachNodeII.cs
| 3.640625
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Leetcode.Core
{
/*
* Follow up for problem "Populating Next Right Pointers in Each Node".
* What if the given tree could be any binary tree? Would your previous solution still work?
*
* Note: You may only use constant extra space.
* For example,
* Given the following binary tree,
* 1
* / \
* 2 3
* / \ \
* 4 5 7
* After calling your function, the tree should look like:
* 1 -> NULL
* / \
* 2 -> 3 -> NULL
* / \ \
* 4-> 5 -> 7 -> NULL
*/
public class OJ117_PopulatingNextRightPointersInEachNodeII
{
public void connect(TreeLinkNode root)
{
if (root == null || (root.left == null && root.right == null))
return;
TreeLinkNode current = null;
if (root.left != null && root.right != null)
{
root.left.next = root.right;
current = root.right;
}
else
{
current = root.left != null ? root.left : root.right;
}
TreeLinkNode rootNext = root.next;
while (rootNext != null)
{
if (rootNext.left != null || rootNext.right != null)
{
current.next = rootNext.left != null ? rootNext.left : rootNext.right;
break;
}
rootNext = rootNext.next;
}
connect(root.right); //先连右边!!!
connect(root.left);
}
}
}
|
106d317591f2fb984acbe10eb22203b359ca0728
|
C#
|
adonismendozaperez/ECommerce
|
/ECommerce/ECommerce/Models/User.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace ECommerce.Models
{
public class User
{
[Key]
public int UserId { get; set; }
[Required(ErrorMessage = "The field {0} is required.")]
[MaxLength(256)]
[Display(Name = "E-Mail")]
[Index("UserName", IsUnique = true)]
[DataType(DataType.EmailAddress)]
public string UserName { get; set; }
[Required(ErrorMessage = "The field {0} is required.")]
[MaxLength(50)]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "The field {0} is required.")]
[MaxLength(50)]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required(ErrorMessage = "The field {0} is required.")]
[MaxLength(20)]
[Display(Name = "Phone")]
[DataType(DataType.PhoneNumber)]
public string Phone { get; set; }
[Required(ErrorMessage = "The field {0} is required.")]
[MaxLength(200)]
public string Address { get; set; }
[DataType(DataType.ImageUrl)]
public string Photo { get; set; }
[Required(ErrorMessage = "The field {0} is required.")]
[Range(1, double.MaxValue)]
[Display(Name = "Department")]
public int DepartmentId { get; set; }
[Required(ErrorMessage = "The field {0} is required.")]
[Range(1, double.MaxValue)]
[Display(Name = "City")]
public int CityId { get; set; }
[Required(ErrorMessage = "The field {0} is required.")]
[Range(1, double.MaxValue)]
[Display(Name = "Company")]
public int CompanyId { get; set; }
[Display(Name = "User")]
public string FullName { get {return string.Format("{0} {1}",FirstName,LastName); } }
[NotMapped]
public HttpPostedFileBase PhotoFile { get; set; }
//obtenemos el id del departamento
public virtual Department Department { get; set; }
//obtenemos el id de la ciudad
public virtual City City { get; set; }
//obtenemos el id de la compania
public virtual Company Company { get; set; }
}
}
|
40d0dbcde8af3d7a9a7f32f74bb64fb8121e3cf6
|
C#
|
Neveark/JubeatFrontendCheckerDemo
|
/JubeatFrontendCheckerDemo/Program.cs
| 2.65625
| 3
|
using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Timers;
namespace JubeatFrontendCheckerDemo
{
class Program
{
static void Main(string[] args)
{
//check jubeat is frontend or not
System.Timers.Timer timer = new System.Timers.Timer();
timer.Enabled = true;
timer.Interval = 3000; //3 seconds
timer.Start();
timer.Elapsed += new System.Timers.ElapsedEventHandler(JubeatFrontendChecker);
Console.ReadKey();
}
private static void JubeatFrontendChecker(object source, ElapsedEventArgs e)
{
BringWindowByNameToFront("L44 - jubeat");
Console.WriteLine("done!");
}
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern int SetForegroundWindow(IntPtr hwnd);
public static IntPtr WinGetHandle(string wName)
{
foreach (Process pList in Process.GetProcesses())
if (pList.MainWindowTitle.Contains(wName))
return pList.MainWindowHandle;
return IntPtr.Zero;
}
public static void BringWindowByNameToFront(string windowName)
{
IntPtr hwnd = WinGetHandle(windowName);
SetForegroundWindow(hwnd);
}
}
}
|
57f69ebd1e2a54135511e972f51a77c355f03f64
|
C#
|
MorganMBA/ConsoleExplore
|
/Arborescence/Explorateur.cs
| 3.09375
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Arborescence
{
public class Explorateur : IExplore
{
public Explorateur()
{
}
/// <summary>
/// returns a list of files in a given directory
/// </summary>
/// <param name="rep"></param>
/// <returns></returns>
public List<Element> GetFichiers(Environment.SpecialFolder rep)
{
string docPath = Environment.GetFolderPath(rep);
List<Element> myFiles = new List<Element>();
DirectoryInfo diTop = new DirectoryInfo(docPath);
try
{
foreach (var fi in diTop.EnumerateFiles())
{
var f = new Fichier(fi.FullName, fi.Length);
myFiles.Add(f);
}
}
catch (UnauthorizedAccessException unAuthTop)
{
Console.WriteLine($"{unAuthTop.Message}");
}
return myFiles;
}
/// <summary>
/// returns a list of repository in a given parent directory
/// </summary>
/// <param name="rep"></param>
/// <returns></returns>
public List<Element> GetRepertoires(Environment.SpecialFolder rep)
{
string docPath = Environment.GetFolderPath(rep);
List<Element> myRep = new List<Element>();
DirectoryInfo diTop = new DirectoryInfo(docPath);
long taille = 0;
try
{
foreach (var reps in diTop.EnumerateDirectories("*", SearchOption.AllDirectories))
{
foreach (var fi in reps.EnumerateFiles("*", SearchOption.AllDirectories))
{
taille += fi.Length;
var r = new Repertoire(reps.FullName, taille);
myRep.Add(r);
}
}
}
catch (UnauthorizedAccessException unAuthSubDir)
{
Console.WriteLine($"unAuthSubDir: {unAuthSubDir.Message}");
}
return myRep;
}
}
}
|
65dc54746348b27013576e67416132b54c8d2cc4
|
C#
|
luhis/DapperLinter
|
/DapperAnalyser/DapperAnalyser.Test/DapperSqlStyleAnalyzerUnitTest.cs
| 2.515625
| 3
|
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using TestHelper;
using Xunit;
namespace DapperAnalyser.Test
{
public class DapperSqlStyleAnalyzerUnitTest : CodeFixVerifier
{
//No diagnostics expected to show up
[Fact]
public void EmptyCode()
{
var test = @"";
VerifyCSharpDiagnostic(test);
}
[Fact]
public void InnerJoin()
{
var test = @"
namespace DapperDemo
{
using Dapper;
using System.Collections.Generic;
using System.Data.SqlClient;
public class C1
{
public IEnumerable<int> A()
{
using (var connection = new SqlConnection(
""Server = tcp:mhknbn2kdz.database.windows.net; Database = AdventureWorks2012; User ID = sqlfamily; Password = sqlf@m1ly; ""))
{
const string sql = ""SELECT * FROM Users INNER JOIN Departments ON Departments.DepartmentId = Users.DepartmentId"";
return connection.Query<int>(sql);
}
}
}
}";
var expected = new DiagnosticResult
{
Id = "DapperSqlStyleAnalyser",
Message = "'\"SELECT * FROM Users INNER JOIN Departments ON Departments.DepartmentId = Users.DepartmentId\"' contains incorrectly styled SQL",
Severity = DiagnosticSeverity.Warning,
Locations =
new[] {
new DiagnosticResultLocation("Test0.cs", 15, 30)
}
};
VerifyCSharpDiagnostic(test, expected);
var fixtest = @"
namespace DapperDemo
{
using Dapper;
using System.Collections.Generic;
using System.Data.SqlClient;
public class C1
{
public IEnumerable<int> A()
{
using (var connection = new SqlConnection(
""Server = tcp:mhknbn2kdz.database.windows.net; Database = AdventureWorks2012; User ID = sqlfamily; Password = sqlf@m1ly; ""))
{
const string sql = ""SELECT * FROM Users JOIN Departments ON Departments.DepartmentId = Users.DepartmentId"";
return connection.Query<int>(sql);
}
}
}
}";
VerifyCSharpFix(test, fixtest);
}
[Fact]
public void NotDapper()
{
var test = @"
namespace DapperDemo
{
using System;
using System.Collections.Generic;
public class Class2
{
public IEnumerable<Customer> A()
{
using (var connection = new Object())
{
const string x = ""select* from Person.Person where FirstName = 'Mark'"";
return connection.Query<Customer>(x);
}
}
}
}";
VerifyCSharpDiagnostic(test);
}
protected override CodeFixProvider GetCSharpCodeFixProvider()
{
return new DapperSqlStyleAnalyzerCodeFixProvider();
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new DapperSqlStyleAnalyzer();
}
}
}
|
14fe44693ee5c73f53237a8393ebe4574269e0b9
|
C#
|
kevadsett/ProcJam2017
|
/Unity/Assets/Scripts/BeatManager.cs
| 2.59375
| 3
|
using System.Collections;
using UnityEngine;
public class BeatManager : MonoBehaviour
{
public int BPM = 120;
public bool ShouldPlay = false;
private const float DELAY = 0.5f;
public delegate void TickOccurredAction(float tick);
public static event TickOccurredAction OnTickOccurred;
public float NextTick
{
get { return _tickCount + 1 / DIVISOR; }
}
private const float DIVISOR = 32f;
private float _tickCount = 0f;
private float _singleTickTime;
private float _timeSinceLastTick;
void Start ()
{
_singleTickTime = 60f / (float)BPM / DIVISOR * 4f; // because a whole note (semibreve) is 4 beats
StartCoroutine (StartTicking ());
}
void OnDestroy()
{
StopAllCoroutines ();
}
void Update()
{
if (ShouldPlay == false)
{
return;
}
_timeSinceLastTick += Time.deltaTime;
if (_timeSinceLastTick >= _singleTickTime)
{
_timeSinceLastTick -= _singleTickTime;
if (OnTickOccurred != null)
{
OnTickOccurred (_tickCount);
}
_tickCount += (1 / DIVISOR);
}
}
private IEnumerator StartTicking()
{
yield return new WaitForSeconds (DELAY);
ShouldPlay = true;
}
}
|
7e2325feea3296342ab4154bb57d1a3bc7db9b3f
|
C#
|
VSacr1/Robot-Game
|
/Collectables/Powerup/HealthPU.cs
| 2.734375
| 3
|
using System;
using Mogre;
using PhysicsEng;
namespace Game
{
class HealthPU : Powerup
{
SceneManager mSceneMgr;
PhysObj physObj;
Physics physics;
protected ModelElement healthPuModel;
/// <summary>
/// Gets the return value of healthPuModel and sets the value.
/// </summary>
public ModelElement HealthPuModel
{
get { return healthPuModel; }
set { healthPuModel = value; }
}
/// <summary>
/// This constructor increases the stat health by the value specified and contains the load model.
/// </summary>
/// <param name="health"></param>
/// <param name="mSceneMgr"></param>
public HealthPU(Stat health, SceneManager mSceneMgr)
{
this.mSceneMgr = mSceneMgr;
gameNode = mSceneMgr.CreateSceneNode();
this.stat = health;
LoadModel();
increase = 50;
}
/// <summary>
/// Contains the parts of the model and gives the model physics.
/// </summary>
protected void LoadModelElement()
{
removeMe = false;
healthPuModel = new ModelElement(mSceneMgr, "PowerCells.Mesh");
gameNode.Scale(2, 2, 2);
physObj = new PhysObj(10, "Health", 0.1f, 0.01f, 0.5f);
physObj.SceneNode = gameNode;
physObj.AddForceToList(new WeightForce(physObj.InvMass));
Physics.AddPhysObj(physObj);
}
/// <summary>
/// Assembles the model together.
/// </summary>
virtual protected void AssembleModel()
{
gameNode.AddChild(healthPuModel.GameNode);
mSceneMgr.RootSceneNode.AddChild(this.gameNode);
}
/// <summary>
/// Set the position of the gameNode and physObj.
/// </summary>
/// <param name="position"></param>
public override void SetPosition(Vector3 position)
{
gameNode.Position = position;
physObj.Position = position;
}
/// <summary>
/// Loads the model.
/// </summary>
protected override void LoadModel()
{
base.LoadModel();
LoadModelElement();
AssembleModel();
}
bool isActive = true;
/// <summary>
/// Update method and sets the collision if isActive = true.
/// </summary>
/// <param name="evt"></param>
public override void Update(FrameEvent evt)
{
if(isActive == true)
{
Collision();
}
}
/// <summary>
/// Is called in the update method and disposes of the object if it is colliding with the player.
/// </summary>
public void Collision()
{
removeMe = IsCollidingWith("Player");
if(removeMe == true)
{
isActive = false;
}
}
/// <summary>
/// If colliding with the player the health increases by the increase value set in the constructor.
/// </summary>
/// <param name="objName"></param>
/// <returns></returns>
private bool IsCollidingWith(string objName)
{
bool isColliding = false;
foreach (Contacts c in physObj.CollisionList)
{
if (c.colliderObj.ID == objName || c.colliderObj.ID == objName)
{
isColliding = true;
stat.Increase(increase);
Dispose();
break;
}
}
return isColliding;
}
/// <summary>
/// Disposes of the physics and the model.
/// </summary>
public override void Dispose()
{
Physics.RemovePhysObj(physObj);
physObj = null;
gameNode.Parent.RemoveChild(healthPuModel.GameNode);
healthPuModel.GameNode.DetachAllObjects();
healthPuModel.GameNode.Dispose();
healthPuModel.Dispose();
}
}
}
|
2d74da4639ccf49300347d393a2f7320fee604d7
|
C#
|
AshleyVMetz/C-RentMe
|
/RentMe/Model/ReturnedItem.cs
| 3.0625
| 3
|
using System;
namespace RentMe.Model
{
/// <summary>
/// This class models a ReturnedItem.
/// </summary>
class ReturnedItem
{
/// <summary>
/// Accessors for ReturnedItem instance variables.
/// </summary>
public int ReturnID { get; }
public int RentalID { get; }
public DateTime ReturnDate { get; }
public DateTime ScheduledReturn { get; }
public string EmployeeFullName { get; }
public string ItemSerial { get; }
public string ItemDescription { get; }
public int ItemQuantity { get; }
public decimal FineDue { get; }
public decimal RefundDue { get; }
/// <summary>
/// Constructor method.
/// </summary>
/// <param name="returnID">The ID of the return.</param>
/// <param name="rentalID">The ID of the rental.</param>
/// <param name="returnDate">The date of the return.</param>
/// <param name="scheduledReturn">The scheduled return date of the rental.</param>
/// <param name="employeeFullName">The full name of the employee who accepted the return of the item(s).</param>
/// <param name="itemSerial">The serial # of the item returned.</param>
/// <param name="itemDescription">The description of the item returned.</param>
/// <param name="itemQuantity">The quantity of the item returned.</param>
/// <param name="fineDue">The fine due for the item returned.</param>
/// <param name="refundDue">The refund due for the item returned.</param>
public ReturnedItem(int returnID, int rentalID, DateTime returnDate, DateTime scheduledReturn, string employeeFullName, string itemSerial, string itemDescription,
int itemQuantity, decimal fineDue, decimal refundDue)
{
this.ReturnID = returnID;
this.RentalID = rentalID;
this.ReturnDate = returnDate;
this.ScheduledReturn = scheduledReturn;
this.EmployeeFullName = employeeFullName;
this.ItemSerial = itemSerial;
this.ItemDescription = itemDescription;
this.ItemQuantity = itemQuantity;
this.FineDue = fineDue;
this.RefundDue = refundDue;
}
}
}
|
d55f81a263bfe645183bb74bfe459d5478fc860f
|
C#
|
Arniox/AspnetMicroservices
|
/src/WebApps/AspnetRunBasics/Services/OrderService.cs
| 2.515625
| 3
|
using AspnetRunBasics.Extensions;
using AspnetRunBasics.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace AspnetRunBasics.Services
{
public class OrderService : IOrderService
{
//Objects
private readonly HttpClient _client;
//Constructor
public OrderService(HttpClient client)
{
_client = client ?? throw new ArgumentNullException(nameof(client));
}
public async Task<IEnumerable<OrderResponseModel>> GetOrdersByUserName(string userName)
{
//Get Response
var response = await _client.GetAsync($"/Order/{userName}");
//Return
return await response.ReadAsJsonAsync<List<OrderResponseModel>>();
}
public async Task<IEnumerable<OrderResponseModel>> GetOrdersByFirstName(string firstName)
{
//Get Response
var response = await _client.GetAsync($"/Order/ByFirstName/{firstName}");
//Return
return await response.ReadAsJsonAsync<List<OrderResponseModel>>();
}
public async Task<IEnumerable<OrderResponseModel>> GetOrdersByLastName(string lastName)
{
//Get Response
var response = await _client.GetAsync($"/Order/ByLastName/{lastName}");
//Return
return await response.ReadAsJsonAsync<List<OrderResponseModel>>();
}
public async Task<IEnumerable<OrderResponseModel>> GetOrdersByEmail(string email)
{
//Get Response
var response = await _client.GetAsync($"/Order/ByEmail/{email}");
//Return
return await response.ReadAsJsonAsync<List<OrderResponseModel>>();
}
public async Task<IEnumerable<OrderResponseModel>> GetOrdersByCountry(string country)
{
//Get Response
var response = await _client.GetAsync($"/Order/ByCountry/{country}");
//Return
return await response.ReadAsJsonAsync<List<OrderResponseModel>>();
}
}
}
|
040b7999b751dd74501dee9447e3b347310729de
|
C#
|
HairDontGo/Link-Local
|
/C#/虚数运算.cs
| 3.65625
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Cons
{
public class Complex
{
private int real;
private int imaginary;
public Complex(int x, int y)
{
real = x;
imaginary = y;
}
public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
}
public static Complex operator *(Complex c1, Complex c2)
{
return new Complex(c1.real * c2.real - c1.imaginary * c2.imaginary,
c1.real * c2.imaginary + c1.imaginary * c2.real);
}
public override string ToString()
{
return (string.Format("{0}+{1}i",real,imaginary ));
}
}
class Program
{
static void Main(string[] args)
{
Complex c1 = new Complex(5, 6);
Complex c2 = new Complex(8, 9);
Console.WriteLine("Complex Number n1={0}", c1.ToString());
Console.WriteLine("Complex Number n2={0}", c2.ToString());
Complex sum = c1 + c2;
Console.WriteLine("Complex Number sum={0}", sum.ToString());
Complex product = c1 * c2;
Console.WriteLine("Complex Number product={0}", product.ToString());
Console.Read();
}
}
}
|
26ea5d55f26395dda439bf2a665ccff138f45ce1
|
C#
|
1729-Dev/AcmeCustomerEngage
|
/AcmeCustomerEngage/Console.cs
| 3.078125
| 3
|
using AcmeCustomerEngage.DataModels;
using System.Collections.Generic;
namespace AcmeCustomerEngage
{
public class Console
{
public static void Main()
{
// Query and trim the weather snapshots to the correct date range
WeatherService weatherService = new WeatherService();
List<WeatherModel> trimmedWeather = EngagementLogic.TrimWeatherSnapshots(weatherService.QueryWeather());
// Potentially display an error or warning
string preMessage = EngagementLogic.WeatherSnapshotsQuantity(trimmedWeather);
if (!string.IsNullOrEmpty(preMessage))
{
System.Console.WriteLine(preMessage);
}
// Output the recommended communication method for the remaining weather snapshots
foreach (WeatherModel weatherSnapShot in trimmedWeather)
{
string message = string.Format("{0} - {1}", weatherSnapShot.Start.ToString(), EngagementLogic.CommunicationMethod(weatherSnapShot));
System.Console.WriteLine(message);
}
}
}
}
|
e9a739f711051999fdf41f927f5815723dc69953
|
C#
|
drunaar/Parus.Tornado.Examples
|
/Packages/Waybills/PerishablesWaybills/PerishablesWaybills.Interface/Домены/WearPercent.cs
| 2.828125
| 3
|
using System;
using System.Reflection;
using Parus.Net.Server;
namespace Acme.Business.Waybills.PerishablesWaybills
{
/// <summary>
/// Домен Acme.Business.Waybills.PerishablesWaybills.WearPercent - автоматически созданный класс.
/// </summary>
[Serializable]
[Metadata("Acme.Business.Waybills.PerishablesWaybills.Домены.WearPercent.metadata")]
public partial class WearPercent :
Parus.Net.Server.Domains.DecimalDomain
{
/// <summary>
/// Инициализирует экземпляр значением по умолчанию.
/// </summary>
public WearPercent()
{
}
/// <summary>
/// Инициализирует экземпляр переданным нетипизированным значением.
/// </summary>
public WearPercent(object value) : base(value)
{
}
/// <summary>
/// Инициализирует экземпляр переданным значением.
/// </summary>
public WearPercent(decimal value) :
base(value)
{
}
/// <summary>
/// Проверить данные на валидность.
/// </summary>
protected override bool CheckValue(decimal value)
{
return true;
}
/// <summary>
/// Инициализирует экземпляр строковым представлением значения домена.
/// </summary>
public WearPercent(string value) : base(value)
{
}
#region Operators
/// <summary>
/// Оператор неявного приведения decimal к
/// WearPercent.
/// </summary>
public static implicit operator WearPercent(
decimal v)
{
return new WearPercent(v);
}
/// <summary>
/// Бинарный оператор +.
/// </summary>
public static WearPercent operator +(
WearPercent p1, WearPercent p2)
{
return new WearPercent(p1.Value + p2.Value);
}
/// <summary>
/// Унарный оператор декремента.
/// </summary>
public static WearPercent operator --(
WearPercent p)
{
return new WearPercent(p.Value - 1);
}
/// <summary>
/// Бинарный оператор /.
/// </summary>
public static WearPercent operator /(
WearPercent p1, WearPercent p2)
{
return new WearPercent(p1.Value / p2.Value);
}
/// <summary>
/// Унарный оператор инкремента.
/// </summary>
public static WearPercent operator ++(
WearPercent p)
{
return new WearPercent(p.Value + 1);
}
/// <summary>
/// Бинарный оператор %.
/// </summary>
public static WearPercent operator %(
WearPercent p1, WearPercent p2)
{
return new WearPercent(p1.Value % p2.Value);
}
/// <summary>
/// Бинарный оператор *.
/// </summary>
public static WearPercent operator *(
WearPercent p1, WearPercent p2)
{
return new WearPercent(p1.Value * p2.Value);
}
/// <summary>
/// Бинарный оператор -.
/// </summary>
public static WearPercent operator -(
WearPercent p1, WearPercent p2)
{
return new WearPercent(p1.Value - p2.Value);
}
/// <summary>
/// Оператор явного приведения byte к
/// WearPercent.
/// </summary>
public static explicit operator WearPercent(byte v)
{
return new WearPercent((decimal)v);
}
/// <summary>
/// Оператор явного приведения int к
/// WearPercent.
/// </summary>
public static explicit operator WearPercent(int v)
{
return new WearPercent((decimal)v);
}
/// <summary>
/// Оператор явного приведения long к
/// WearPercent.
/// </summary>
public static explicit operator WearPercent(long v)
{
return new WearPercent((decimal)v);
}
/// <summary>
/// Оператор явного приведения float к
/// WearPercent.
/// </summary>
public static explicit operator WearPercent(float v)
{
return new WearPercent((decimal)v);
}
/// <summary>
/// Оператор явного приведения double к
/// WearPercent.
/// </summary>
public static explicit operator WearPercent(double v)
{
return new WearPercent((decimal)v);
}
#endregion
}
}
|
6d35c182c693f9515bfb057b11313476f6ddb0b0
|
C#
|
bitstadium/HockeySDK-Windows
|
/Src/Kit.Core45/DataContracts/PerformanceCounterTelemetry.cs
| 2.5625
| 3
|
namespace Microsoft.HockeyApp.DataContracts
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Channel;
using Extensibility.Implementation.External;
/// <summary>
/// The class that represents information about performance counters.
/// </summary>
[DebuggerDisplay(@"CategoryName={CategoryName}; CounterName={CounterName}; InstanceName={InstanceName}; Value={Value}; Timestamp={Timestamp}")]
internal sealed class PerformanceCounterTelemetry : ITelemetry, ISupportProperties
{
internal const string TelemetryName = "PerformanceCounter";
internal readonly string BaseType = typeof(PerformanceCounterData).Name;
internal readonly PerformanceCounterData Data;
private TelemetryContext context;
/// <summary>
/// Initializes a new instance of the <see cref="PerformanceCounterTelemetry"/> class.
/// </summary>
public PerformanceCounterTelemetry()
{
this.Data = new PerformanceCounterData();
}
/// <summary>
/// Initializes a new instance of the <see cref="PerformanceCounterTelemetry"/> class.
/// </summary>
/// <param name="categoryName">Category name.</param>
/// <param name="counterName">Performance counter name.</param>
/// <param name="instanceName">Instance name.</param>
/// <param name="value">Performance counter value.</param>
public PerformanceCounterTelemetry(string categoryName, string counterName, string instanceName, double value) : this()
{
this.CategoryName = categoryName;
this.CounterName = counterName;
this.InstanceName = instanceName;
this.Value = value;
}
/// <summary>
/// Gets or sets date and time when telemetry was recorded.
/// </summary>
public DateTimeOffset Timestamp { get; set; }
/// <summary>
/// Gets or sets the value that defines absolute order of the telemetry item.
/// </summary>
public string Sequence { get; set; }
/// <summary>
/// Gets the context associated with the current telemetry item.
/// </summary>
public TelemetryContext Context
{
get
{
return LazyInitializer.EnsureInitialized(ref this.context);
}
}
/// <summary>
/// Gets or sets the counter value.
/// </summary>
public double Value
{
get
{
return this.Data.value;
}
set
{
this.Data.value = value;
}
}
/// <summary>
/// Gets or sets the category name.
/// </summary>
public string CategoryName
{
get
{
return this.Data.categoryName;
}
set
{
this.Data.categoryName = value;
}
}
/// <summary>
/// Gets or sets the counter name.
/// </summary>
public string CounterName
{
get
{
return this.Data.counterName;
}
set
{
this.Data.counterName = value;
}
}
/// <summary>
/// Gets or sets the instance name.
/// </summary>
public string InstanceName
{
get
{
return this.Data.instanceName;
}
set
{
this.Data.instanceName = value;
}
}
/// <summary>
/// Gets a dictionary of application-defined property names and values providing additional information about this exception.
/// </summary>
public IDictionary<string, string> Properties
{
get { return this.Data.properties; }
}
/// <summary>
/// Sanitizes the properties based on constraints.
/// </summary>
void ITelemetry.Sanitize()
{
this.CategoryName = Utils.PopulateRequiredStringValue(this.CategoryName, "CategoryName", typeof(PerformanceCounterTelemetry).FullName);
this.CounterName = Utils.PopulateRequiredStringValue(this.CounterName, "CounterName", typeof(PerformanceCounterTelemetry).FullName);
}
}
}
|
4a3a32865c49c8f3938a3d2a06cc76be4d4047e8
|
C#
|
matheuscecilio/MestreDosCodigos.NET
|
/MestreDosCodigos_POO_1_Conceitos/Encapsulamento/Conta.cs
| 3.03125
| 3
|
namespace MestreDosCodigos_POO_1_Conceitos.Encapsulamento
{
public class Conta
{
// Não podemos alterar o saldo diretamente, somente passando por um dos métodos
public double Saldo { get; private set; }
public void Sacar(double valor) => Saldo -= valor;
public void Depositar(double valor) => Saldo += valor;
}
}
|
cc89c5f772533e50aacfdf2b04a2b8ea0e6e4519
|
C#
|
sebaspasker/Planea_M11
|
/TestsLibrary/CADFavoritosTest.cs
| 2.515625
| 3
|
using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using library;
using System.Configuration;
namespace TestsLibrary
{
[TestClass]
public class CADFavoritosTest
{
public CADFavoritosTest()
{
}
private TestContext testContextInstance;
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
private void Insertar(ENFavoritos favorito)
{
favorito.nombre_usuario = "apellido apellido";
favorito.nombre_usuario_favorito = "email3@email.com";
if (!favorito.InsertarFavorito())
{
Assert.Fail("No se ha podido insertar el usuario");
}
else
{
if (!favorito.LeerFavorito())
{
Assert.Fail("Sigue sin existir el usuario");
}
}
}
private void Eliminar(ENFavoritos favorito)
{
if (!favorito.BorrarFavorito())
{
Assert.Fail("No se pudo borrar");
}
if (favorito.LeerFavorito())
{
Assert.Fail("Sigue existiendo");
}
}
[TestMethod]
public void InsertarBorrarModificar()
{
ENFavoritos favorito = new ENFavoritos();
favorito.nombre_usuario = "Matias";
try
{
if (!favorito.LeerFavorito())
{
Insertar(favorito);
Modificar(favorito);
Eliminar(favorito);
}
else
{
Modificar(favorito);
Eliminar(favorito);
}
}
catch (Exception e)
{
Assert.Fail("No deberia de haber saltado una excepcion " + e.Message);
}
}
private void Modificar(ENFavoritos f)
{
if (f.LeerFavorito())
{
f.nombre_usuario = "santi";
if (f.ModificarFavorito())
{
ENFavoritos f2 = new ENFavoritos();
f2.nombre_usuario = f.nombre_usuario;
if (f2.LeerFavorito())
{
Assert.AreEqual(f.nombre_usuario, f2.nombre_usuario);
Assert.AreEqual(f2.nombre_usuario_favorito, f.nombre_usuario_favorito);
}
else
{
Assert.Fail("No se ha podido encontrar al usuario");
}
}
else
{
Assert.Fail("No se ha podido modificar el usuario");
}
}
else
{
Assert.Fail("No se puede modificar si no existe");
}
}
}
}
|
3db0f4018b73fe13782aa462eadda619011e506d
|
C#
|
IgorRozani/WikipediaCrawler
|
/WikipediaCrawler.Console/Program.cs
| 3.296875
| 3
|
using HtmlAgilityPack;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WikipediaCrawler.Console
{
class Program
{
const string URL = @"https://pt.wikipedia.org/wiki/";
static void Main(string[] args)
{
var origin = GetOrigin();
var destiny = GetDestiny();
var links = GetLinks(origin);
if (links.Contains(destiny))
System.Console.WriteLine($"{origin} > {destiny}");
else
{
foreach (var link in links)
{
var sublinks = GetLinks(link);
if (sublinks.Contains(destiny))
{
System.Console.WriteLine($"{origin} > {link} > {destiny}");
}
}
}
System.Console.ReadLine();
}
private static string GetOrigin()
{
System.Console.WriteLine("Origin:");
return System.Console.ReadLine();
}
private static string GetDestiny()
{
System.Console.WriteLine("Destiny:");
return System.Console.ReadLine();
}
private static List<string> GetLinks(string subDomain)
{
var fullUrl = $"{URL}{subDomain}";
var htmlWeb = new HtmlWeb();
var htmlPage = htmlWeb.Load(fullUrl);
var content = htmlPage.DocumentNode.SelectSingleNode("/html[1]/body[1]/div[3]/div[3]");
var links = content.SelectNodes("//a[@href]");
var linksFromPage = new List<string>();
foreach (var link in links)
{
var hrefValue = link.GetAttributeValue("href", string.Empty);
if (hrefValue.StartsWith(@"/wiki/") && !hrefValue.Contains(":"))
linksFromPage.Add(hrefValue.Replace(@"/wiki/", string.Empty));
}
return linksFromPage.Distinct().ToList();
}
}
}
|
3778a0129be2dea53375e8449decad6cdde66361
|
C#
|
aimenux/ChannelsDemo
|
/App/Examples/AbstractExample.cs
| 3.140625
| 3
|
using System;
using System.Linq;
using System.Threading.Tasks;
namespace App.Examples
{
public abstract class AbstractExample : IExample
{
private static readonly Random Random = new Random(Guid.NewGuid().GetHashCode());
public abstract string Description { get; }
public abstract Task RunAsync();
protected string GenerateRandomString(int length = 30)
{
const string chars = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var charsArray = Enumerable.Repeat(chars, length)
.Select(s => s[Random.Next(s.Length)])
.ToArray();
return new string(charsArray);
}
}
}
|
9f973e46dfffa34f25d25322ffa28cc1e55658cb
|
C#
|
Bioninja01/vedic_v3
|
/Assets/JamesVinson/Vid_Nodes/codeGeneration/Vid_Number.cs
| 2.5625
| 3
|
using UnityEngine;
using System;
public class Vid_Number : Vid_Object
{
public VidNum_Type type = VidNum_Type.INT;
public string data;
public override void Awake()
{
base.Awake();
output_dataType = VidData_Type.NUM;
}
public override string ToString() {
return data;
}
public void toggleNum_type() {
switch (type) {
case VidNum_Type.INT:
type = VidNum_Type.FLOAT;
if (!setData(data)) {
type = VidNum_Type.INT;
}
break;
case VidNum_Type.FLOAT:
type = VidNum_Type.DOUBLE;
if (!setData(data)) {
type = VidNum_Type.FLOAT;
}
break;
case VidNum_Type.DOUBLE:
type = VidNum_Type.LONG;
if (!setData(data)) {
type = VidNum_Type.DOUBLE;
}
break;
case VidNum_Type.LONG:
type = VidNum_Type.INT;
if (!setData(data)) {
type = VidNum_Type.LONG;
}
break;
default:
break;
}
}
public bool setData(String value)
{
switch (type)
{
case VidNum_Type.INT:
try
{
int i = int.Parse(value);
data = i.ToString();
return true;
}
catch (FormatException e) { Debug.Log(e.ToString()); }
return false;
case VidNum_Type.FLOAT:
try
{
float f = float.Parse(value);
data = f.ToString() +"F";
return true;
}
catch (FormatException e) { Debug.Log(e.ToString()); }
return false;
case VidNum_Type.DOUBLE:
try
{
double d = double.Parse(value);
data = d.ToString() +"D";
return true;
}
catch (FormatException e) { Debug.Log(e.ToString()); }
return false;
case VidNum_Type.LONG:
try
{
long l = long.Parse(value);
data = l.ToString()+"L";
return true;
}
catch (FormatException e) { Debug.Log(e.ToString()); }
return false;
default:
try
{
int i = int.Parse(value);
data = i.ToString();
return true;
}
catch (FormatException e) { Debug.Log(e.ToString()); }
return false;
}
}
}
|
6acca738f71c5aae2364ab5ee286377991c7a568
|
C#
|
CodeMoshete/animals
|
/2D Sidescroller/Assets/Source/PersistentServices/CharacterData.cs
| 2.75
| 3
|
using UnityEngine;
public class CharacterData : MonoBehaviour
{
public static CharacterData Instance { get; private set; }
[SerializeField]
private CharacterManifest manifest;
void Start ()
{
Instance = this;
}
public Character GetCharacter(string CharacterName)
{
for (int i = 0, count = manifest.Characters.Count; i < count; ++i)
{
Character current = manifest.Characters[i];
if (current.Name == CharacterName)
{
return current;
}
}
return null;
}
}
|
d1d737ca46eaf59f33fb1876fd4985d02dab2477
|
C#
|
proyectocontautn2016/Restaurante
|
/ProyectoRestaurante/LogicaRestaurante/MontoPorTipoPagoLN.cs
| 2.5625
| 3
|
using DatosRestaurante;
using EntidadesRestaurante;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LogicaRestaurante
{
public class MontoPorTipoPagoLN
{
public static List<MontoPorTipoPagoEntidad> ObtenerTodos(int id)
{
/*public int idTipoPago { get; set; }
public int encabezadoFactura { get; set; }
public decimal monto { get; set; }*/
List<MontoPorTipoPagoEntidad> lista = new List<MontoPorTipoPagoEntidad>();
DataSet ds = MontoPorTipoPagoDatos.SeleccionarTodos(id);
foreach (DataRow fila in ds.Tables[0].Rows)
{
MontoPorTipoPagoEntidad elemento = new MontoPorTipoPagoEntidad();
elemento.TipoPago.idTipoPago = Convert.ToInt16(fila["idTipoPago"].ToString());
elemento.TipoPago.descripcion = fila["descripcion"].ToString();
elemento.encabezadoFactura = Convert.ToInt16(fila["idEncabezadoFactura"].ToString());
elemento.monto = Convert.ToDecimal(fila["monto"].ToString());
lista.Add(elemento);
}
return lista;
}
public static void Nuevo(MontoPorTipoPagoEntidad pMontoPorTipoPagoEntidad)
{
MontoPorTipoPagoDatos.Insertar(pMontoPorTipoPagoEntidad);
}
}
}
|
d411774d286524d0d91286f64a13ea9b07891bed
|
C#
|
machelbaev/CSharp
|
/sem6/CW/Task01/Program.cs
| 3.578125
| 4
|
/*
Student: Chelbaev Mikhail
Group: BPI182_2
Task: 1
*/
using System;
using System.Collections;
namespace Task01
{
public class ArithmeticProgression
{
int a0, d, n;
public ArithmeticProgression(int a0, int d, int n)
{
this.a0 = a0;
this.d = d;
this.n = n;
}
public IEnumerator GetEnumerator()
{
return new ArithmeticProgressionEnumerator(a0, d, n);
}
class ArithmeticProgressionEnumerator : IEnumerator
{
int a0, d, n, position = -1;
public ArithmeticProgressionEnumerator(int a0, int d, int n)
{
this.a0 = a0;
this.d = d;
this.n = n;
}
public object Current
{
get
{
if (position == -1 || position > n)
throw new InvalidOperationException();
return a0 + d * position;
}
}
public bool MoveNext()
{
if (position < n - 1)
{
position++;
return true;
}
return false;
}
public void Reset()
{
position = -1;
}
}
}
class Program
{
static void Main(string[] args)
{
do
{
Console.Clear();
ArithmeticProgression arithmeticProgression = new ArithmeticProgression(5, 5, 10);
foreach (var item in arithmeticProgression)
{
Console.Write(item + " ");
}
Console.WriteLine("Enter Esc to exit...");
} while (Console.ReadKey().Key != ConsoleKey.Escape);
}
}
}
|
dc7ba48b8df6159223343b1fc80fb41d53656994
|
C#
|
myung6024/The_Virus
|
/The Virus/Assets/script/CardStatus.cs
| 2.8125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CardStatus : MonoBehaviour {
private int CardHP;
private int CardResistance;
private string CardName;
private int CardSpeed;
public void SetHP(int number)
{
CardHP = number;
}
public void SetResistance(int number)
{
CardResistance = number;
}
public void SetSpeed(int number)
{
CardSpeed = number;
}
public int GetHP()
{
return CardHP;
}
public int GetResistance()
{
return CardResistance;
}
public string GetName() // get,set 블록 종류에 따른 카드 이름도 넣음
{
return CardName;
}
public void SetName(string str)
{
CardName = str;
}
public int GetSpeed()
{
return CardSpeed;
}
}
|
cafbeae0b149c92bcbf1dfd92836123eea73f687
|
C#
|
NasAlanMarKPFU/lab5
|
/ConsoleApplication2/Program.cs
| 3.125
| 3
|
using System;
using System.Collections.Generic;
namespace ConsoleApplication2
{
internal class Program
{
public static void qSortR(int[] mass, int left, int right)
{
int pivot;
int lb = left;
int rb = right;
pivot = mass[left];
while (left < right)
{
while ((mass[right] >= pivot) && (left < right))
right--;
if (left != right)
{
mass[left] = mass[right];
left++;
}
while ((mass[left] <= pivot) && (left < right))
left++;
if (left != right)
{
mass[right] = mass[left];
right--;
}
}
mass[left] = pivot;
pivot = left;
left = lb;
right = rb;
if (left < pivot)
qSortR(mass, left, pivot - 1);
if (right > pivot)
qSortR(mass, pivot + 1, right);
}
public static void qSortI(int[] mass, int size)
{
int i, j;
int lb, rb;
int[] lbstack = new int[1000];
int[] rbstack = new int[1000];
int stackpos = 1;
int ppos;
int pivot;
int temp;
lbstack[1] = 0;
rbstack[1] = size-1;
do {
lb = lbstack[ stackpos ];
rb = rbstack[ stackpos ];
stackpos--;
do {
ppos = ( lb + rb ) >> 1;
i = lb; j = rb; pivot = mass[ppos];
do {
while ( mass[i] < pivot ) i++;
while ( pivot < mass[j] ) j--;
if ( i <= j ) {
temp = mass[i]; mass[i] = mass[j]; mass[j] = temp;
i++; j--;
}
} while ( i <= j );
if ( i < ppos ) {
if ( i < rb ) {
stackpos++;
lbstack[ stackpos ] = i;
rbstack[ stackpos ] = rb;
}
rb = j;
} else {
if ( j > lb ) {
stackpos++;
lbstack[ stackpos ] = lb;
rbstack[ stackpos ] = j;
}
lb = i;
}
} while ( lb < rb );
} while ( stackpos != 0 );
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static int[][] list_of_ribs(int len, int kol)
{
int[][] mass= new int[len][];
for (int i = 0; i < len; i++)
{
mass[i] = new int[len];
}
string[] s;
int first, second;
for (int i = 0; i < kol; i++)
{
s = Console.ReadLine().Split(' ');
first =Convert.ToInt32(s[0]);
second = Convert.ToInt32(s[1]);
mass[first-1][second-1] = 1;
mass[second-1][first-1] = 1;
}
return mass;
}
public static int[][] list_of_compatibility(int len)
{
string[] s;
int sum, now;
int[][] mass= new int[len][];
for (int i = 0; i < len; i++)
{
mass[i] = new int[len];
}
for (int i = 0; i < len; i++)
{
s = Console.ReadLine().Split(' ');
sum =Convert.ToInt32(s[0]);
for (int j = 1; j <=sum; j++)
{
now = Convert.ToInt32(s[j]);
mass[i][now - 1] = 1;
mass[now - 1][i] = 1;
}
}
return mass;
}
public static int[][] incidence_matrix(int len, int reb)
{
int[][] mass= new int[len][];
int[][] mass_incid = new int[len][];
string s;
int first, second;
for (int i = 0; i < len; i++)
{
mass[i] = new int[len];
mass_incid[i] = new int[reb];
s = Console.ReadLine();
for (int j = 0; j < reb; j++)
{
if (s[j] == '1')
mass_incid[i][j] = 1;
}
}
for (int i = 0; i < reb; i++)
{
first = 0;
second = 0;
for (int j = 0; j < len; j++)
{
if (mass_incid[j][i] == 1 && first == 0)
{
first = j;
}else if (mass_incid[j][i] == 1 && first != 0)
{
second = j;
}
}
mass[first][second] = 1;
mass[second][first] = 1;
}
return mass;
}
public static int[][] adjacency_matrix(int len)
{
int[][] mass= new int[len][];
string s;
for (int i = 0; i < len; i++)
{
mass[i] = new int[len];
s = Console.ReadLine();
for (int j = 0; j < len; j++)
{
if (s[j] == '1')
mass[i][j] = 1;
else
mass[i][j] = 0;
}
}
return mass;
}
public static void test1()
{
Random rnd = new Random();
int[] mass = new int[20];
for (int i = 0; i < 20; i++)
{
mass[i] = rnd.Next(500);
}
for (int i = 0; i < 20; i++)
{
Console.Write(mass[i]+" ");
}
Console.WriteLine();
//qSortR(mass,0,mass.Length-1);
qSortI(mass,mass.Length);
for (int i = 0; i < 20; i++)
{
Console.Write(mass[i]+" ");
}
}
public static Stack<int> dfs_way(int[][] mass, int len,int start,int end)
{
Stack<int> way = new Stack<int>();
int[] visit = new int[len];
visit[start] = 1;
int now =start;
way.Push(start);
while (way.Count!=0)
{
for (int i = 0; i < len; i++)
{
if (now == end)
{
return way;
}
if (mass[now][i] == 1 && visit[i] != 1)
{
visit[i] = 1;
way.Push(i);
now = i;
break;
}
if (i == len - 1)
{
way.Pop();
if (way.Count != 0)
now = way.Peek();
else
return way;
}
}
}
return way;
}
public static int[] bfs_way(int[][] mass, int len, int start, int end)
{
int[] roots = new int[len];
int[] visit = new int[len];
visit[start] = 1;
roots[start] = -1;
Queue<int> queue = new Queue<int>();
int now;
queue.Enqueue(start);
while (queue.Count!=0)
{
now =queue.Dequeue();
for (int i = 0; i < len; i++)
{
if (now == end)
{
return roots;
}
if (mass[now][i] == 1 && visit[i] != 1)
{
visit[i] = 1;
queue.Enqueue(i);
roots[i] = now;
}
}
}
roots[start] = -2;
return roots;
}
public static void test2()
{
int[][] mass;
int num, len, reb,start,end;
Console.WriteLine("1)adjacency_matrix\n2)incidence_matrix\n3)list_of_compatibility\n4)list_of_ribs");
Console.Write("num :");
num = Convert.ToInt32(Console.ReadLine());
switch (num)
{
case 1:
Console.Write("graph vertices :");
len = Convert.ToInt32(Console.ReadLine());
mass = adjacency_matrix(len);
break;
case 2:
Console.Write("graph vertices :");
len = Convert.ToInt32(Console.ReadLine());
Console.Write("graph reb :");
reb = Convert.ToInt32(Console.ReadLine());
mass = incidence_matrix(len, reb);
break;
case 3:
Console.Write("graph vertices :");
len = Convert.ToInt32(Console.ReadLine());
mass = list_of_compatibility(len);
break;
case 4:
Console.Write("graph vertices :");
len = Convert.ToInt32(Console.ReadLine());
Console.Write("graph reb :");
reb = Convert.ToInt32(Console.ReadLine());
mass = list_of_ribs(len, reb);
break;
default:
Console.WriteLine("error");
return;
}
for (int i = 0; i < len; i++)
{
for (int j = 0; j < len; j++)
{
Console.Write(mass[i][j] +" ");
}
Console.WriteLine();
}
Console.WriteLine("1)dfs\n2)bfs");
Console.Write("num : ");
num = Convert.ToInt32(Console.ReadLine());
Console.Write("start : ");
start = Convert.ToInt32(Console.ReadLine());
Console.Write("end : ");
end = Convert.ToInt32(Console.ReadLine());
if (num == 1)
{
Stack<int> stck = dfs_way(mass, len, end-1, start-1);
if(stck.Count == 0)
Console.WriteLine("can't be way");
else
{
while (stck.Count!= 1)
{
Console.Write((stck.Pop()+1)+"->");
}
Console.WriteLine(stck.Pop()+1);
}
}
else
{
int[] roots = bfs_way(mass, len, end-1, start-1);
if(roots[end-1]==-2)
Console.WriteLine("can't be way");
else
{
reb = start-1;
while (roots[reb]!=-1)
{
Console.Write((reb+1)+"->");
reb = roots[reb];
}
Console.WriteLine($"{end}");
}
}
}
public static void Main(string[] args)
{
test2();
}
}
}
|
522b660be3e56f119603fff296baa49671e34b58
|
C#
|
Fallenstarrz/GPE340Project
|
/Assets/Scripts/Drops/DestroyAndRemoval.cs
| 2.78125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DestroyAndRemoval : MonoBehaviour
{
[Header("Timers")]
[SerializeField]
[Tooltip("Time in seconds to wait before destroying this object after spawn")]
[Range(0,120)]
private float timeBeforeDestroy;
[SerializeField]
[Tooltip("Time in seconds to wait before removing rigidbody and collider from this gameObject")]
[Range(0,5)]
private float timeBeforeRemove;
Rigidbody myRigidbody;
Collider myCollider;
// Use this for initialization
void Start()
{
}
/// <summary>
/// begin funtion is called and used the same way a start function would, but we don't want it to run on all objects, only the ones spawned by enemies,
/// so we attach this to every object and run the function when the enemy dies instead
/// </summary>
public void begin()
{
myRigidbody = GetComponent<Rigidbody>();
myCollider = GetComponent<Collider>();
Destroy(this.gameObject, timeBeforeDestroy);
StartCoroutine(removeComponents());
}
/// <summary>
/// Coroutine!!
/// This function removes sets the collider to a trigger after it removes the rigidbody from the object,
/// this is so objects cannot be pushed around after they have landed on the ground
/// </summary>
/// <returns></returns>
IEnumerator removeComponents()
{
yield return new WaitForSeconds(timeBeforeRemove);
Destroy(myRigidbody);
myCollider.isTrigger = true;
}
}
|
0b64ae2a6c965cefdb9b20cd660276e63d19a894
|
C#
|
tiffanycabernathy96/AbandonMentality
|
/Assets/Scripts/Maps.cs
| 2.84375
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Maps : MonoBehaviour {
public Image leftButton;
public Image rightButton;
public Image backButton;
public List<Image> floors; //0 is 1st, 1 is 2nd, 2 is basement
public float[] floorPositions = {1.051798f, 4.843465f, -2.823202f};
public CharacterControllerMovement character;
private int currentFloorDisplayed = -1;
public void DisplayMaps(float playerYLocation)
{
leftButton.enabled = true;
rightButton.enabled = true;
backButton.enabled = true;
//Determine What Floor the User is on.
if(System.Math.Abs(playerYLocation -floorPositions[0]) < 1e-3)
{
//First Floor
floors[0].enabled = true;
currentFloorDisplayed = 0;
}
else if(System.Math.Abs(playerYLocation - floorPositions[1]) < 1e-3)
{
//Second Floor
floors[1].enabled = true;
currentFloorDisplayed = 1;
}
else if(System.Math.Abs(playerYLocation - floorPositions[2]) < 1e-3)
{
//Basement
floors[2].enabled = true;
currentFloorDisplayed = 2;
}
}
public void HideMaps()
{
leftButton.enabled = false;
rightButton.enabled = false;
backButton.enabled = false;
foreach (Image floor in floors)
{
floor.enabled = false;
}
character.MovementController(true);
}
public void ShowNextFloor(int direction)
{
//0 is go down
//1 is go up.
floors[currentFloorDisplayed].enabled = false;
if(direction == 0)
{
currentFloorDisplayed -= 1;
if (currentFloorDisplayed < 0)
currentFloorDisplayed = 2;
}
else
{
currentFloorDisplayed += 1;
if (currentFloorDisplayed > 2)
currentFloorDisplayed = 0;
}
floors[currentFloorDisplayed].enabled = true;
}
}
|
6c4e25f303e01b202412ef38ee0941da6ab2dfe8
|
C#
|
ZohrehAnsarian/WebShop-Project
|
/Repository/EF/Repository/PageContentRepository.cs
| 2.625
| 3
|
using Model;
using Repository.EF.Base;
using System.Linq;
namespace Repository.EF.Repository
{
public class PageContentRepository : EFBaseRepository<PageContent>
{
public PageContent GetByLanguageId(int type, int languageId)
{
var pageContent = from p in Context.PageContents
where p.Type == type && p.LanguageId == languageId
select p;
return pageContent.SingleOrDefault();
}
public PageContent GetByCurrentLanguageId(int type)
{
var pageContent = from p in Context.PageContents
where p.Type == type && p.LanguageId == CurrentLanguageId
select p;
return pageContent.FirstOrDefault();
}
public void AddNewPageContent(PageContent PageContent)
{
Add(PageContent);
}
public void UpdatePageContent(PageContent PageContent)
{
var oldPageContent = (from s in Context.PageContents
where s.Type == PageContent.Type && s.LanguageId == PageContent.LanguageId
select s).FirstOrDefault();
oldPageContent.Content = PageContent.Content;
oldPageContent.Subject = PageContent.Subject;
Update(oldPageContent);
}
}
}
|
efe3db483cb6e8663d46dc25abdc08bb7556e24f
|
C#
|
scottjustin5000/MongoJobScheduler
|
/Infrastructure/Scheduling/ScheduleCollection.cs
| 3.09375
| 3
|
using System;
using Infrastructure.Collections;
namespace Infrastructure.Scheduling
{
[Serializable]
public class ScheduleCollection : CustomDictionary<string, ScheduleBase>
{
/// <summary>
/// Creates a new instance of type <see cref="ScheduleCollection"/>.
/// </summary>
public ScheduleCollection() : base(new DynamicDictionary<string, ScheduleBase>(StringComparer.OrdinalIgnoreCase)) { }
private ScheduleCollection(DictionaryBase<string, ScheduleBase> collection) : base(collection) { }
/// <summary>
/// Creates and returns a read-only version of the specified
/// collection.
/// </summary>
public static ScheduleCollection ReadOnly(ScheduleCollection collection)
{
ScheduleCollection readOnlyCollection = null;
if (collection.IsReadOnly)
{
readOnlyCollection = collection;
}
else
{
readOnlyCollection = new ScheduleCollection(DynamicDictionary<string, ScheduleBase>.ReadOnly((DynamicDictionary<string, ScheduleBase>)collection.Values));
}
return readOnlyCollection;
}
/// <summary>
/// Creates and returns a fixed-size version of the specified
/// collection.
/// </summary>
public static ScheduleCollection FixedSize(ScheduleCollection collection)
{
ScheduleCollection fixedSizeCollection = null;
if (collection.IsFixedSize)
{
fixedSizeCollection = collection;
}
else
{
fixedSizeCollection = new ScheduleCollection(DynamicDictionary<string, ScheduleBase>.FixedSize((DynamicDictionary<string, ScheduleBase>)collection.Values));
}
return fixedSizeCollection;
}
/// <summary>
/// Creates and returns a read-only version of the specified
/// collection.
/// </summary>
public static ScheduleCollection Synchronized(ScheduleCollection collection)
{
ScheduleCollection synchronizedCollection = null;
if (collection.IsSynchronized)
{
synchronizedCollection = collection;
}
else
{
synchronizedCollection = new ScheduleCollection(DynamicDictionary<string, ScheduleBase>.Synchronized((DynamicDictionary<string, ScheduleBase>)collection.Values));
}
return synchronizedCollection;
}
/// <summary>
/// Returns the key of the specified item.
/// </summary>
public override string KeyOf(ScheduleBase value)
{
return value.Name;
}
}
}
|
a26b7e84e9c609654eb3dc2b8b1fccd921345520
|
C#
|
mark-raymond/DependabotTest
|
/MyClassLibrary/MyClass.cs
| 3.828125
| 4
|
using System;
namespace MyClassLibrary
{
public static class MyClass
{
public static double Tetrate(double a, int n)
{
if (n < 0)
{
throw new NotImplementedException("Negative tetration not implemented");
}
if (n == 0)
{
return 1.0;
}
var result = a;
var logA = Math.Log(a);
n--;
while (n > 0)
{
result = Math.Exp(logA * result);
n--;
}
return result;
}
}
}
|
dd7ca380fe801aafa0b25236d491d9bea93fe7ee
|
C#
|
ozidom/SpaceRogueRevolution
|
/SpaceRogueRevolution/Models/Factory/JobFactory.cs
| 2.90625
| 3
|
using SpaceRogueRevolution.Models.GameObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SpaceRogueRevolution.Models.Factory
{
public static class JobFactory
{
/*public static Job Create(int id,string description,int desination,int value)
{
return new Job { ID = id, Description = description, DestinationID = desination, Value = value };
}*/
public static Job CreateRandomJob(int id, int numberPlanets,int currentPlanetID)
{
int value = 0;
int risk = 0;
string description = "";
Random r = new Random();
GetRandomDescriptionAndValue(out description,out value,out risk);
int destinationID = r.Next(7);
return new Job { ID = id, Description = description,OriginID = currentPlanetID, DestinationID = destinationID, Value = value,Risk=risk };
}
private static int GetRandomJobValue()
{
Random r = new Random();
return r.Next(1000);
}
private static int GetRandomDestination(List<Planet> planets)
{
Random r = new Random();
int randomIndex = r.Next(planets.Count);
return planets[randomIndex].ID;
}
public static void GetRandomDescriptionAndValue(out string description,out int value,out int risk )
{
var jobs = new [] { new {Name="Transfer of Cash",value=400,risk= 2},
new {Name="Transfer Goods",value=200,risk= 1},
new {Name="Transport of Government worker travel",value=300,risk= 2},
new {Name="Transport for a highly sought after Computer Specialist",value=400,risk= 2},
new {Name="Ensure safe passage for an intergalactice Trade Official",value=800,risk= 6},
new {Name="Take a famous Sports star to a big game",value=300,risk= 4},
new {Name="Take a family to a Bridal Party",value=200,risk= 1},
new {Name="Take a load of angry activists to a political conference",value=400,risk= 3},
new {Name="Transport a Paranoid Android",value=900,risk= 8},
new {Name="You need to transfer a Nuclear Bomb ",value=1400,risk=10}
};
Random r = new Random();
int index = r.Next(jobs.Length);
description = jobs[index].Name;
value = jobs[index].value;
risk = jobs[index].risk;
}
}
}
|
1f62f7d1421ba86474a3fb571a88cd910a4554de
|
C#
|
OpenJEVis/JEVis-C-Sharp
|
/JEAPI/JEVisAttributeType.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace JEAPI
{
public interface JEVisAttributeType : JEVisComponent, JEVisCommittable, IComparable<JEVisAttributeType> {
/**
* Returns the name of this type. The name is a unique identifier for a
* type. The name does not have to be unique in the JEVis system but has to
* be under an JEVisClass.
*
* @return
* @throws JEVisException
*/
String GetName();
/**
* Set the name for this type. The name is an unique identifier for an type.
* The name does not have to be unique in the JEVis system but has to be
* under an JEVisClass.
*
* @param name
* @throws JEVisException
*/
void SetName(String name);
/**
* Returns the primitive type.
*
* @see JEVisConstants
* @return
* @throws JEVisException
*/
int GetPrimitiveType();
/**
* Set the primitive type.
*
* @see JEVisConstants
* @param type
* @throws JEVisException
*/
void SetPrimitiveType(int type);
/**
* Returns the GUI display type. GUIs will use this type to display the
* value, for example a String could be displayed as asterisk textfield or
* clear text.
*
* @return
* @throws JEVisException
*/
String GetGUIDisplayType();
/**
* Set the GUI display type.
*
* @see JEVisConstants
* @param type
* @throws JEVisException
*/
void SetGUIDisplayType(String type);
/**
* Set the order of the input field for this type in the GUI. The Fields
* will be sorted from lowest-top to the highest-bottom.
*
* @param pos
* @throws JEVisException
*/
void SetGUIPosition(int pos);
/**
* Returns positions of this type in the GUI. The Fields will be sorted from
* lowest-top to the highest-bottom.
*
* @return
* @throws JEVisException
*/
int GetGUIPosition();
/**
* returns the JEVisClass of this type.
*
* @return JEVisClass of this type
* @throws JEVisException
*/
JEVisClass GetJEVisClass();
/**
* Returns the JEVisClass name of this type.
*
* @return
* @throws JEVisException
*/
String getJEVisClassName();
/**
* Returns the validity. The validity tells the API how to handle die
* timestamps. For example if only the last value is valid or if every
* timestamp is valid at this time.
*
* @see JEVisConstants
* @return validity of the sample
* @throws JEVisException
*/
int GetValidity();
/**
* Set the validity. The validity tells the API how to handle die
* timestamps. For example if only the last value is valid or if every
* timestamp is valid at this time.
*
* @see JEVisConstants
* @param validity
* @throws JEVisException
*/
void SetValidity(int validity);
/**
* Return the additional configuration parameter.
*
* @deprecated
* @return
* @throws JEVisException
* @deprecated This function is not in use and will be changed?!
*/
String GetConfigurationValue();
/**
* Set the additional configuration parameter.
*
* @param value
* @throws JEVisException
* @deprecated This function is not in use and will be changed?!
*/
void SetConfigurationValue(String value);
/**
* Set the expected unit for this type. All values of attributes from type
* type will be stored as this unit in the JEVisDataSource.
*
* @param unit
* @throws JEVisException
*/
void SetUnit(JEVisUnit unit);
/**
* Return the expected unit for this type. All values of attributes from
* type type will be stored as this unit in the JEVisDataSource.
*
* @return
* @throws JEVisException
*/
JEVisUnit GetUnit();
/**
* Get the alternative Symbol for the Unit of this type
*
* @return
* @throws JEVisException
*/
String GetAlternativeSymbol();
/**
* Set an alternative symbols for the unit of this type
*
* @param symbol
* @throws JEVisException
*/
void SetAlternativeSymbol(String symbol);
/**
* Returns the human description for the type. The function may be replaced
* with a localized version.
*
* @deprecated
* @return
* @throws JEVisException
*/
String GetDescription();
/**
* Set the human description for the type.
*
* @param discription
* @throws JEVisException
*/
void SetDescription(String discription);
/**
* Delete this type from the JEVisDataSource. This function does not need a
* commit;
*
* @deprecated use JEVIsClass.DeleteType
* @return
* @throws JEVisException
*/
bool Delete();
/**
* return true if this type is inherited from an other class
*
* @return
* @throws JEVisException
*/
bool IsInherited();
/**
* Set if this Type is inherited from an other class
*
* @param inherited
* @throws JEVisException
*/
void IsInherited(bool inherited);
}
}
|
da6d2a9d61e967ccfdd0c68fc7d488504dabdc0c
|
C#
|
Kaos1105/Etour
|
/backend-app/Application/HelperCodes/Edit.cs
| 2.5625
| 3
|
using System;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Application.Errors;
using Domain;
using FluentValidation;
using MediatR;
using Persistence;
namespace Application.HelperCodes
{
public class Edit
{
public class Command : IRequest
{
//command properties
public Guid Id { get; set; }
public string CodeType { get; set; }
public string CodeName { get; set; }
public string CodeValue { get; set; }
public string CodeContent { get; set; }
}
public class CommandValidator : AbstractValidator<Command>
{
public CommandValidator()
{
}
}
public class Handler : IRequestHandler<Command>
{
private readonly DataContext _context;
public Handler(DataContext context)
{
this._context = context;
}
public async Task<Unit> Handle(Command request, CancellationToken cancellationToken)
{
//handler logic
var code = await _context.HelperCodes.FindAsync(request.Id);
if (code == null)
throw new RestException(HttpStatusCode.NotFound, new { HelperCode = "Not found" });
code.CodeContent = request.CodeContent ?? code.CodeContent;
code.CodeName = request.CodeName ?? code.CodeName;
code.CodeType = request.CodeType ?? code.CodeType;
code.CodeValue = request.CodeValue ?? code.CodeValue;
code.IsActive = code.IsActive ? code.IsActive : true;
//return result
var isSuccess = await _context.SaveChangesAsync() > 0;
if (isSuccess) return Unit.Value;
throw new Exception("Problem saving changes");
}
}
}
}
|
414dfc2887d60714d3cf1de776f09ae68fdde2ce
|
C#
|
Dzuke911/PVT.Dzukes.Money
|
/PVT.Money.Business/MoneyClasses/Money.cs
| 3.0625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace PVT.Money.Business
{
[Serializable]
public sealed class Money
{
public decimal Amount { get; private set; }
public Currency Curr { get; private set; }
[NonSerialized]
private ExchangeRates exchangeRates;
public Money(decimal amount, Currency curr)
{
if (amount < 0)
throw new ArgumentException(ExceptionMessages.MoneyAmountNotLessZero());
Amount = amount;
Curr = curr;
exchangeRates = new ExchangeRates();
}
public void Convert(Currency curr)
{
Amount *= exchangeRates.GetRate(Curr, curr);
Curr = curr;
}
public void AddMoney(Money mon)
{
if (mon == null)
throw new ArgumentException(ExceptionMessages.MoneyAdditionNullFail());
Money buffer = new Money(mon.Amount, mon.Curr);
buffer.AdjustExchangeRate(mon.Curr, Curr, GetExchangeRate(mon.Curr,Curr));
buffer.Convert(Curr);
Amount += buffer.Amount;
}
public void SubtractMoney(Money mon)
{
if (mon == null)
throw new ArgumentException(ExceptionMessages.MoneySubtractionNullFail());
if (IsEnoughMoney(mon))
{
Amount -= mon.Amount / exchangeRates.GetRate(Curr, mon.Curr);
}
else
throw new InvalidOperationException(ExceptionMessages.MoneySubtractionLessThanSubtractedFail());
}
public bool IsEnoughMoney(Money mon, Money mon2, Money mon3)
{
decimal sum = 0;
if (mon == null || mon2 == null || mon3 == null)
throw new ArgumentException(ExceptionMessages.MoneyComparisonWithNullFail());
sum += mon2.Amount / exchangeRates.GetRate(Curr, mon2.Curr);
sum += mon3.Amount / exchangeRates.GetRate(Curr, mon3.Curr);
sum += mon.Amount / exchangeRates.GetRate(Curr, mon.Curr);
if (Amount < sum)
return false;
else
return true;
}
public bool IsEnoughMoney(Money mon, Money mon2)
{
return IsEnoughMoney(mon, mon2, new Money(0, Curr));
}
public bool IsEnoughMoney(Money mon)
{
return IsEnoughMoney(mon, new Money(0, Curr), new Money(0, Curr));
}
public void AdjustExchangeRate(Currency currFrom, Currency currTo, decimal coefficient)
{
if (currFrom != currTo)
exchangeRates.AdjustExchangeRate(currFrom, currTo, coefficient);
}
public decimal GetExchangeRate(Currency currFrom, Currency currTo)
{
if (currFrom == currTo)
return 1;
else
return exchangeRates.GetRate(currFrom, currTo);
}
}
}
|