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
|
|---|---|---|---|---|---|---|
ca90f199e8c4fbfdca5f8220d33a3bdc6b18d95c
|
C#
|
lumberjackchester/HammerCreekBrewery
|
/HammerCreekBrewing.Models/UnitOfWork.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using HammerCreekBrewing.Data.Models;
using System.Threading.Tasks;
namespace HammerCreekBrewing.Data
{
public class UnitOfWork : IUnitOfWork, IDisposable
{
private readonly IDictionary<Type, object> _repositories;
public UnitOfWork(HCBContext context)
{
DbContext = context;
SetDbContextProperties();
_repositories = new Dictionary<Type, object>();
}
#region Repositories
// HammerCreekBrewing repositories
public IRepository<Beer> Beers { get { return GetRepository<Beer>(); } }
public IRepository<BeerStyle> BeerStyles { get { return GetRepository<BeerStyle>(); } }
public IRepository<Brewery> Breweries { get { return GetRepository<Brewery>(); } }
public IRepository<Location> Locations { get { return GetRepository<Location>(); } }
#endregion
// context
public HCBContext DbContext { get; set; }
#region Get Repository Methods
/// <summary>
/// Get or create-and-cache a repository of type T.
/// </summary>
/// <typeparam name="T">
/// Type of the repository, typically a custom repository interface.
/// </typeparam>
/// <remarks>
/// Looks for the requested repository in its cache, returning if found.
/// If not found, makes a new one and returns it.
/// </remarks>
public virtual IRepository<T> GetRepository<T>() where T : class
{
// Look for T dictionary cache under typeof(T).
object repoObj;
_repositories.TryGetValue(typeof(T), out repoObj);
if (repoObj != null)
{
return repoObj as IRepository<T>;
}
// Not found or null; make one, add to dictionary cache, and return it.
var repo = new Repository<T>(this.DbContext);
_repositories.Add(typeof(T), repo);
return repo;
}
#endregion
/// <summary>
/// Save pending changes to the database
/// </summary>
public void Commit()
{
//System.Diagnostics.Debug.WriteLine("Committed");
this.DbContext.SaveChanges();
}
/// <summary>
/// Save pending changes asynchronously to the database
/// </summary>
public async Task<int> CommitAsync()
{
//System.Diagnostics.Debug.WriteLine("Committed");
return await this.DbContext.SaveChangesAsync();
}
protected void SetDbContextProperties()
{
// this.DbContext = new HCBContext(System.Configuration.ConfigurationManager.AppSettings["DatabaseContextConnectionName"]);
// Do NOT enable proxied entities, else serialization fails
this.DbContext.Configuration.ProxyCreationEnabled = false;
// Load navigation properties explicitly (avoid serialization trouble)
this.DbContext.Configuration.LazyLoadingEnabled = false;
// Because Web API will perform validation, we don't need/want EF to do so
this.DbContext.Configuration.ValidateOnSaveEnabled = false;
// this.DbContext.Configuration.AutoDetectChangesEnabled = false;
// We won't use this performance tweak because we don't need
// the extra performance and, when autodetect is false,
// we'd have to be careful. We're not being that careful.
}
#region IDisposable
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposing) return;
if (DbContext != null)
{
DbContext.Dispose();
}
}
#endregion
}
}
|
3c03ab350970a645408bc407cfcf7cac5ce0ba14
|
C#
|
suzdorf/spublisher
|
/SPublisher.DBManagement/DataProviders/MySqlDataProvider.cs
| 2.578125
| 3
|
using System.Collections.Generic;
using MySql.Data.MySqlClient;
using SPublisher.Core;
using SPublisher.Core.DbManagement;
using SPublisher.DBManagement.Models;
namespace SPublisher.DBManagement.DataProviders
{
public class MySqlDataProvider : ISqlServerDataProvider
{
private readonly IConnectionAccessor _connectionAccessor;
public MySqlDataProvider(IConnectionAccessor connectionAccessor)
{
_connectionAccessor = connectionAccessor;
}
public bool DataBaseExists(string databaseName)
{
using (var connection = new MySqlConnection(_connectionAccessor.ConnectionString))
{
using (var command = new MySqlCommand(SqlHelpers.MySql.FindDatabaseScript(databaseName), connection))
{
connection.Open();
return command.ExecuteScalar() != null;
}
}
}
public void CreateDataBase(IDatabase database)
{
ExecuteNonQuery(SqlHelpers.CreateDatabaseScript(database.DatabaseName));
}
public void RestoreDatabase(IDatabase database)
{
throw new System.NotImplementedException();
}
public void ExecuteScript(string script, string databaseName)
{
ExecuteNonQuery(
string.IsNullOrEmpty(databaseName) ?
script :
SqlHelpers.UseDatabaseScript(script, databaseName));
}
public void CreateHashInfoTableIfNotExists(string databaseName)
{
ExecuteNonQuery(SqlHelpers.UseDatabaseScript(SqlHelpers.MySql.CreateHashInfoTableScript(), databaseName));
}
public IScriptHashInfo[] GetHashInfoList(string databaseName)
{
var result = new List<IScriptHashInfo>();
using (var connection = new MySqlConnection(_connectionAccessor.ConnectionString))
{
using (var command = new MySqlCommand(SqlHelpers.UseDatabaseScript(SqlHelpers.GetHashInfoScript(), databaseName), connection))
{
connection.Open();
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
result.Add(new ScriptHashModel { Hash = reader["Hash"].ToString() });
}
}
}
}
return result.ToArray();
}
public void SaveHashInfo(string databaseName, IFile hashInfo)
{
ExecuteNonQuery(SqlHelpers.UseDatabaseScript(SqlHelpers.SaveHashInfoScript(hashInfo), databaseName));
}
private void ExecuteNonQuery(string script)
{
using (var connection = new MySqlConnection(_connectionAccessor.ConnectionString))
{
using (var command = new MySqlCommand(script, connection))
{
connection.Open();
command.ExecuteNonQuery();
}
}
}
}
}
|
c67647964f91a1c25b8539cb672bc397a3d4f698
|
C#
|
david-evip/TodoWebApp
|
/Layers/Repositories/RepositoryBase.cs
| 2.921875
| 3
|
using Entities;
using Layers.IRepositories;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Layers
{
public class RepositoryBase<T> : IRepositoryBase<T> where T : class
{
protected RepositoryContext RepositoryContext { get; set; }
public RepositoryBase(RepositoryContext repositoryContext)
{
RepositoryContext = repositoryContext;
}
public virtual async Task<IEnumerable<T>> FindAllAsync()
{
return await RepositoryContext.Set<T>().ToListAsync();
}
public virtual async Task<T> FindByIdAsync(int id)
{
return await RepositoryContext.Set<T>().FindAsync(id);
}
public virtual void Create(T entity)
{
RepositoryContext.Set<T>().Add(entity);
}
public virtual void Update(T entity)
{
RepositoryContext.Set<T>().Update(entity);
}
public virtual void Delete(T entity)
{
RepositoryContext.Set<T>().Remove(entity);
}
public virtual Task SaveChangesAsync()
{
return RepositoryContext.SaveChangesAsync();
}
}
}
|
28a815352857d4b5559e45d96e2f33234f6eae23
|
C#
|
shendongnian/download4
|
/code8/1350876-36488368-115167177-2.cs
| 3.328125
| 3
|
public string replace(string input)
{
StringBuilder sb = new StringBuilder();
Dictionary<char, char> map = new Dictionary<char, char>();
map.Add('2', '₂');
map.Add('3', '₃');
map.Add('4', '₄');
map.Add('5', '₅');
map.Add('6', '₆');
map.Add('7', '₇');
char tmp;
foreach(char c in repl)
{
if (map.TryGetValue(c, out tmp))
sb.Append(tmp);
else
sb.Append(c);
}
return sb.ToString();
}
|
3808dec575facf5aa2c3cf112f40941ffc18f7c2
|
C#
|
markand911/movieChallenge
|
/WebJetAPI/API/Provider/FilmWorldProvider.cs
| 2.703125
| 3
|
using API.Interface;
using API.Models;
using AutoMapper;
using Newtonsoft.Json;
using System.Threading.Tasks;
namespace API.Provider
{
public class FilmWorldProvider : IMovieProvider
{
private readonly IMapper _mapper;
private readonly IProviderHelper _providerHelper;
public FilmWorldProvider(IMapper mapper, IProviderHelper providerHelper)
{
_mapper = mapper;
_providerHelper = providerHelper;
}
public async Task<Movie> GetMovie(string Id)
{
string RequestUrl = $"{Properties.Settings.Default.MoviesAPIPath}/api/{MovieProviderEnum.filmworld}/movie/{Id}";
string result = await _providerHelper.RestAPICall(RequestUrl);
FilmWorldMovieResponse filmMovies = JsonConvert.DeserializeObject<FilmWorldMovieResponse>(result);
Movie movies = _mapper.Map<Movie>(filmMovies);
return movies;
}
public async Task<MoviesResponse> GetMovies()
{
string RequestUrl = $"{Properties.Settings.Default.MoviesAPIPath}/api/{MovieProviderEnum.filmworld}/movies";
string result = await _providerHelper.RestAPICall(RequestUrl);
FilmWorldMoviesResponse filmMovies = JsonConvert.DeserializeObject<FilmWorldMoviesResponse>(result);
MoviesResponse movies = _mapper.Map<MoviesResponse>(filmMovies);
return movies;
}
}
}
|
c3ea3d0809673c9ce2d7053e0b952984d5889f81
|
C#
|
StormDevelopmentSoftware/Lana
|
/Lana/Entities/Lavalink/TrackInfo.cs
| 2.828125
| 3
|
using System;
using DSharpPlus.Entities;
using DSharpPlus.Lavalink;
namespace Lana.Entities.Lavalink
{
public class TrackInfo : IEquatable<TrackInfo>
{
public TrackInfo(DiscordChannel chn, DiscordUser usr, LavalinkTrack track)
{
this.Channel = chn;
this.User = usr;
this.Track = track;
}
public DiscordChannel Channel { get; private set; }
public DiscordUser User { get; private set; }
public LavalinkTrack Track { get; private set; }
public override int GetHashCode()
{
return this.Track.GetHashCode();
}
public override bool Equals(object obj)
{
return this.Equals(obj as TrackInfo);
}
public bool Equals(TrackInfo other)
{
if (other is null)
return false;
if (ReferenceEquals(other, this))
return true;
return this.Channel == other.Channel
&& this.User == other.User
&& this.Track == other.Track;
}
public static bool operator ==(TrackInfo t1, TrackInfo t2)
=> Equals(t1, t2);
public static bool operator !=(TrackInfo t1, TrackInfo t2)
=> !(t1 == t2);
}
}
|
7f9aa30fbdf8fd4a1383cfe96117fa08848694d7
|
C#
|
shendongnian/download4
|
/first_version_download2/258883-20633899-53821057-2.cs
| 2.84375
| 3
|
public class MembershipSetting
{
/// <summary>
/// Gets or sets the name of the setting.
/// </summary>
public string SettingName { get; set; }
/// <summary>
/// Gets or sets the setting value.
/// </summary>
public string SettingValue { get; set; }
}
private List<MembershipSetting> GetMembershipSetting()
{
List<MembershipSetting> settings = new List<MembershipSetting>
{
new MembershipSetting {SettingName = "Dafult Membership Provider", SettingValue = Membership.Provider.ToString() },
new MembershipSetting {SettingName = "Minimum Required Password Length", SettingValue = Membership.MinRequiredPasswordLength.ToString(CultureInfo.InvariantCulture) },
new MembershipSetting {SettingName = "Minimum Required Non Alphanumeric Characters",SettingValue = Membership.MinRequiredNonAlphanumericCharacters.ToString(CultureInfo.InvariantCulture)},
new MembershipSetting {SettingName = "Password reset enabled", SettingValue = Membership.EnablePasswordReset.ToString()},
new MembershipSetting {SettingName = "Maximum Invalid Password Attempts",SettingValue = Membership.MaxInvalidPasswordAttempts.ToString(CultureInfo.InvariantCulture) },
new MembershipSetting {SettingName = "Attempt windows",SettingValue = Membership.PasswordAttemptWindow.ToString(CultureInfo.InvariantCulture)},
new MembershipSetting {SettingName = "applicationName",SettingValue = Membership.ApplicationName.ToString(CultureInfo.InvariantCulture)}
};
return settings;
}
|
4de87a2c8eee46181d4d63a175255d2e4c347b47
|
C#
|
xszaboj/euler
|
/23_Abundant/Abundant/AbundantNumbers.cs
| 3.609375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Abundant
{
public class AbundantNumbers
{
public List<int> GetDivisiorsOfNumber(int number)
{
List<int> divisiors = new List<int>();
for (int i = 1; i < number; i++)
{
if (number % i == 0)
{
divisiors.Add(i);
}
}
return divisiors;
}
public int GetDivisorsSum(int number)
{
var sum = 0;
var numbers = GetDivisiorsOfNumber(number);
foreach (var num in numbers)
{
sum += num;
}
return sum;
}
public bool IsAbundant(int number)
{
var sum = GetDivisorsSum(number);
return sum > number;
}
public List<int> GetAbundatnNumbers(int toNumber)
{
List<int> numbers = new List<int>();
for (int i = 1; i < toNumber; i++)
{
if (IsAbundant(i))
{
numbers.Add(i);
}
}
return numbers;
}
public bool IsCombination(List<int> abundantNumbers,List<int> oddAbundantNumbers, int number)
{
bool isEven = number % 2 == 0;
//Even numbers
if (isEven)
{
return IsCombinationForEvenumbers(abundantNumbers, number);
}
//Odd numbers
else
{
return IsCombinationForOddNumbers(abundantNumbers, oddAbundantNumbers, number);
}
}
public long SumOfNonAbundant(int upperlimit, List<int> abundantNumbers)
{
var a = new AbundantNumbers();
var numbers = new List<int>();
var odds = abundantNumbers.Where(n => n % 2 != 0).ToList();
for (int i = 1; i < upperlimit; i++)
{
var lowerNumbers = abundantNumbers.Where(n => n < i).ToList();
var lowerOddNumbers = odds.Where(n => n < i).ToList();
if (lowerNumbers.Count == 0)
{
numbers.Add(i);
}
else
{
var isCombination = a.IsCombination(lowerNumbers, lowerOddNumbers, i);
if (!isCombination)
{
numbers.Add(i);
}
}
}
return numbers.Sum();
}
private bool IsCombinationForEvenumbers(List<int> abundantNumbers, int number)
{
List<int> combinations = new List<int>();
if (abundantNumbers.Count == 1)
{
combinations.Add(abundantNumbers[0] + abundantNumbers[0]);
}
else
{
for (int i = 0; i < abundantNumbers.Count; i++)
{
var firstNumber = abundantNumbers[i];
for (int j = (abundantNumbers.Count - 1); j >= 0; j--)
{
var secondNumber = abundantNumbers[j];
var combination = firstNumber + secondNumber;
combinations.Add(combination);
if (combination < number)
{
break;
}
}
if (combinations.Contains(number))
{
return true;
}
}
}
return false;
}
private bool IsCombinationForOddNumbers(List<int> evenAbundantNumbers, List<int> oddAbundantNumbers, int number)
{
//Idea is that even + even so there is no point to count these combinations
//Se we are interested only in even + odd and there is just few odd abundant numbers
List<int> combinations = new List<int>();
if (oddAbundantNumbers.Count == 0)
{
return false;
}
else
{
for (int i = 0; i < oddAbundantNumbers.Count; i++)
{
var firstNumber = oddAbundantNumbers[i];
for (int j = (evenAbundantNumbers.Count - 1); j >= 0; j--)
{
var secondNumber = evenAbundantNumbers[j];
var combination = firstNumber + secondNumber;
combinations.Add(combination);
if (combination < number)
{
//No point to continue this combination will be always less
break;
}
}
if (combinations.Contains(number))
{
return true;
}
}
}
return false;
}
}
}
|
6b6077c3a84fc58902e20a5a60191c90cc69ee19
|
C#
|
2kingmartians/Astron-End
|
/Astron End/Assets/AT SCRIPTS/Inventory/EquipManager.cs
| 2.703125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EquipManager : MonoBehaviour {
#region Singleton
public static EquipManager instance;
private void Awake()
{
if(instance != null)
{
Debug.LogError("There is more than 1 equipmentManager in the scene");
return;
}
instance = this;
}
#endregion
public delegate void OnUnEquip();
public OnUnEquip onUnEquipCallBack;
public GameObject currentlyEquiped;
public Transform equiedItemHolder;
public Item item;
public bool EquipItem(Item _item)
{
item = _item;
if(item.equipedModel == null)
{
Debug.LogWarning("There is no equip model for: " + item.name);
return false;
}
if(currentlyEquiped == null)
{
currentlyEquiped = Instantiate(item.equipedModel, equiedItemHolder.position, item.equipedModel.transform.rotation);
currentlyEquiped.transform.SetParent(equiedItemHolder);
}
else if(currentlyEquiped != null)
{
UnEquip();
item = _item;
currentlyEquiped = Instantiate(item.equipedModel, equiedItemHolder.position, item.equipedModel.transform.rotation);
currentlyEquiped.transform.SetParent(equiedItemHolder);
}
Debug.Log("Equip: " + item.name);
return true;
}
public void UnEquip()
{
if(currentlyEquiped != null)
{
Destroy(currentlyEquiped);
item = null;
if(onUnEquipCallBack != null)
{
onUnEquipCallBack.Invoke();
}
currentlyEquiped = null;
}
else
{
Debug.Log("Nothing To Unequip");
}
}
}
|
7298d931301eb1854146d90dbd5c900e91eb1a80
|
C#
|
burakpols/ReCapProjectCamp
|
/DataAccess/Concrete/InMemory/InMemoryCarDal.cs
| 2.953125
| 3
|
using DataAccess.Abstract;
using Entities.Concrete;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace DataAccess.Concrete.InMemory
{
public class InMemoryCarDal : ICarDal
{
private List<Car> _carList;
public InMemoryCarDal(List<Car> carList)
{
_carList = new List<Car>
{
new Car{ Id=1,BrandId=1,ColorId=4,DailyPrice=140,ModelYear=2014,Descriptions="1 Nolu Araç Açıklaması" },
new Car{ Id=2,BrandId=2,ColorId=3,DailyPrice=125,ModelYear=2012,Descriptions="2 Nolu Araç Açıklaması" },
new Car{ Id=3,BrandId=3,ColorId=5,DailyPrice=150,ModelYear=2015,Descriptions="3 Nolu Araç Açıklaması" },
new Car{ Id=4,BrandId=4,ColorId=4,DailyPrice=210,ModelYear=2018,Descriptions="4 Nolu Araç Açıklaması" },
new Car{ Id=5,BrandId=5,ColorId=8,DailyPrice=180,ModelYear=2016,Descriptions="5 Nolu Araç Açıklaması" }
};
}
public void Add(Car car)
{
_carList.Add(car);
}
public void Delete(Car car)
{
Car deletedCar = _carList.SingleOrDefault(c => c.Id == car.Id);
_carList.Remove(deletedCar);
}
public Car Get(Expression<Func<Car, bool>> filter)
{
return null;
}
public List<Car> GetAll(Expression<Func<Car, bool>> filter = null)
{
return null;
}
public void Update(Car car)
{
Car _updateToCar = _carList.FirstOrDefault(c => c.Id == car.Id);
_updateToCar.BrandId = car.BrandId;
_updateToCar.ColorId = car.ColorId;
_updateToCar.DailyPrice = car.DailyPrice;
_updateToCar.ModelYear = car.ModelYear;
_updateToCar.Descriptions = car.Descriptions;
}
}
}
|
92552b98d8153cb39ffe98c0b6f91b9eea08663e
|
C#
|
gelanq/BeerTap-V2.0
|
/MyBeerTap.BusinessServices/TapServices.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using AutoMapper;
using MyBeerTap.BusinessServices;
using MyBeerTap.Data.Models;
using MyBeerTap.Data.UnitOfWork;
using MyBeerTap.Model;
namespace MyBeerTap.Services
{
public class TapServices: ITapServices
{
private readonly UnitOfWork _unitOfWork;
/// <summary>
/// Public constructor.
/// </summary>
public TapServices()
{
_unitOfWork = new UnitOfWork();
}
/// <summary>
/// Fetches Tap details by id
/// </summary>
/// <param name="tapId"></param>
/// <returns></returns>
public Tap GetTapById(int tapId)
{
var tap = _unitOfWork.TapRepository.GetByID(tapId);
if (tap != null)
{
Mapper.CreateMap<TapEntity, Tap>().ConvertUsing<TapEntityToTapConverter>();
var tapModel = Mapper.Map<TapEntity, Tap>(tap);
return tapModel;
}
return null;
}
/// <summary>
/// Fetches all the taps in an office.
/// </summary>
/// <param name="officeId"></param>
/// <returns></returns>
public IEnumerable<Tap> GetAllTapsByOfficeId(int officeId)
{
var items = _unitOfWork.TapRepository.GetWithInclude(t => t.OfficeId == officeId, "Keg").ToList();
Mapper.CreateMap<TapEntity, Tap>().ConvertUsing<TapEntityToTapConverter>();
var itemsModel = Mapper.Map<List<TapEntity>, List<Tap>>(items);
return itemsModel;
}
public int CreateTap(Tap tap)
{
throw new NotImplementedException();
}
public Office UpdateTap(int tapId, Tap tap)
{
throw new NotImplementedException();
}
public bool DeleteTap(int tapId)
{
throw new NotImplementedException();
}
public Tap ReplaceKeg(int tapId, Keg keg)
{
//Get tap by Id
TapEntity tapEntity = _unitOfWork.TapRepository.GetByID(tapId);
if (tapEntity != null)
{
using (var scope = new TransactionScope())
{
//Get Keg by TapId
var oldKeg = _unitOfWork.KegRepository.GetFirst(k => k.TapId == tapId);
if (oldKeg != null)
{
//Update the Old Keg
oldKeg.TapId = null;
_unitOfWork.KegRepository.Update(oldKeg);
}
//Update the Tap with the new Keg
Mapper.CreateMap<Keg, KegEntity>();
var kegModel = Mapper.Map<Keg, KegEntity>(keg);
tapEntity.Keg = kegModel;
//Add new Keg
_unitOfWork.KegRepository.Insert(kegModel);
_unitOfWork.Save();
scope.Complete();
}
}
return GetTapById(tapId);
}
public Tap GetBeer(int tapId, Glass glass)
{
//Get Keg by TapId
KegEntity kegEntity = _unitOfWork.KegRepository.GetFirst(k => k.TapId == tapId);
if (kegEntity.Remaining < glass.AmountToPour)
throw new Exception("Not enough beer in this Tap!!!!!");
if (kegEntity != null)
{
using (var scope = new TransactionScope())
{
kegEntity.Remaining -= glass.AmountToPour;
_unitOfWork.KegRepository.Update(kegEntity);
Mapper.CreateMap<Glass, GlassEntity>();
var glassModel = Mapper.Map<Glass, GlassEntity>(glass);
_unitOfWork.GlassRepository.Insert(glassModel);
_unitOfWork.Save();
scope.Complete();
}
}
var tap = _unitOfWork.TapRepository.GetByID(tapId);
return GetTapById(tapId);
}
}
}
|
b91f2dade8b39cbbce9ff216c5b10374d2891338
|
C#
|
thomasnilsson/winprog2016
|
/Diagram_WinProg2016/Diagram_WinProg2016/Commands/AddClassCommand.cs
| 2.5625
| 3
|
using Diagram_WinProg2016.Model;
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Diagram_WinProg2016.Commands
{
//
// Class used to add ClassBox's to the Grid
//
public class AddClassCommand : IUndoRedoCommand
{
private ObservableCollection<Class>Classes;
private Class NewClass;
public AddClassCommand(ObservableCollection<Class> _Classes)
{
this.Classes = _Classes;
NewClass = new Class();
}
public void Execute()
{
Classes.Add(NewClass);
}
public void UnExecute()
{
Classes.Remove(NewClass);
}
}
}
|
51dfc9a86f5e86a4bd69fe4fe57f543fd4a759e4
|
C#
|
MarceloCorreaADS/BeginReality
|
/GameLibrary/GameLibrary/Utils/TurnManager.cs
| 2.65625
| 3
|
using System;
using UnityEngine;
using System.Collections.Generic;
using System.Collections;
using Character;
namespace Utils {
public class TurnManager : MonoBehaviour {
public List<String> moves;
public String teamTurn;
public bool turnActive;
[SerializeField]
public List<Player> players = new List<Player>();
public WinningConditions winningConditions;
public Player getPlayer(String playerName) {
Player player = null;
String objectName = moves[0];
GameObject gameObject = getGameObject(playerName);
if (objectName == "Ally" && gameObject != null) {
this.teamTurn = objectName;
this.turnActive = true;
Debug.Log("batatadoce");
player = gameObject.GetComponent<Player>();
player.turnFinished = false;
player.move.resetParameters("iwanttoresetmove");
if (players.Find(p => p.name == player.name) == null)
players.Add(player);
}
return player;
}
private GameObject getFirstGameObject() {
return GameObject.Find(moves[0]) as GameObject;
}
private GameObject getGameObject(String objectName) {
return GameObject.Find(objectName) as GameObject;
}
public void EnemyTurn() {
String objectName = moves[0];
if (objectName == "Enemy") {
enemyAction();
}
}
private void enemyAction() {
this.teamTurn = moves[0];
List<GameObject> enemyObjects = new List<GameObject>(GameObject.FindGameObjectsWithTag(teamTurn));
new Task(EnemyTurn(enemyObjects), true);
}
private IEnumerator EnemyTurn(List<GameObject> enemyObjects) {
List<GameObject> playerObjects = new List<GameObject>(GameObject.FindGameObjectsWithTag("Enemy"));
playerObjects.AddRange(GameObject.FindGameObjectsWithTag("Ally"));
foreach (GameObject enemyObject in enemyObjects) {
Player enemy = enemyObject.GetComponent<Player>();
if (players.Find(p => p.name == enemy.name) == null)
players.Add(enemy);
enemy.move.resetParameters("iwanttoresetmove");
winningConditions.checkCondition();
if (winningConditions.checkVictory()) {
break;
}
if (!enemy.status.isDead) {
GameIA.ArtificialIntelligence gameIa = new GameIA.ArtificialIntelligence(enemy, playerObjects, GetComponent<Board.Grid>());
Task artificialIntelligenceTask = null;
try {
artificialIntelligenceTask = new Task(gameIa.CalcularPossibleAttacks(), true);
} catch (Exception) {
Debug.Log("Ta dando erro na IA");
}
yield return new WaitWhile(() => artificialIntelligenceTask.Running);
}
this.turnActive = true;
}
Task task = new Task(NextTurn(), true);
yield return new WaitWhile(() => task.Running);
this.teamTurn = null;
this.turnActive = false;
yield break;
}
public void next() {
ActionOrder.getInstance().resetActionOrder();
String name = moves[0];
this.moves.Remove(name);
this.moves.Add(name);
Debug.Log("alahuakbar");
if (winningConditions.checkVictory()) {
return;
}
String objectName = moves[0];
if (objectName == "Enemy") {
enemyAction();
}
}
public IEnumerator NextTurn() {
ActionOrder actionOrder = ActionOrder.getInstance();
yield return new WaitWhile(() => actionOrder.QtyOrder > actionOrder.ActualOrder);
if (players != null && players.Count > 0) {
winningConditions.checkCondition();
foreach (Player player in players) {
player.status.resetActionPoints();
player.turnFinished = true;
}
}
next();
}
}
}
|
89cf64dd214918a8687a8d3f5425c66504079a7b
|
C#
|
cjmaier2/LoLinfo
|
/LoLInfo/LoLInfo/Views/SummonerSearchView.xaml.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using LoLInfo.ViewModels;
using Xamarin.Forms;
namespace LoLInfo.Views
{
public class SummonerSearchViewBase : BaseView<SummonerSearchViewModel> { }
public partial class SummonerSearchView : SummonerSearchViewBase
{
public SummonerSearchView()
{
InitializeComponent();
foreach (var region in ViewModel.Regions)
{
regionPicker.Items.Add(region);
}
regionPicker.SelectedIndex = 0;
}
protected override async void OnAppearing()
{
base.OnAppearing();
searchInput.Text = string.Empty;
}
async void OnSearchClicked(object sender, EventArgs args)
{
var searchText = searchInput.Text;
if (!string.IsNullOrWhiteSpace(searchText))
{
var matchHistory = await ViewModel.GetMatchHistory(searchText, regionPicker.Items[regionPicker.SelectedIndex]);
if (matchHistory == null)
{
await DisplayAlert("Error", "Failed to retrieve match history", "OK");
}
else
{
var matchHistoryView = new MatchHistoryView(matchHistory);
matchHistoryView.Title = searchInput.Text;
await Navigation.PushAsync(matchHistoryView);
}
}
}
async void OnMyMatchHistoryClicked(object sender, EventArgs args)
{
var matchHistory = await ViewModel.GetMyMatchHistory();
if (matchHistory == null)
{
await DisplayAlert("Error", "Failed to retrieve match history", "OK");
}
else
{
var matchHistoryView = new MatchHistoryView(matchHistory);
matchHistoryView.Title = "My Matches";
await Navigation.PushAsync(matchHistoryView);
}
}
}
}
|
e73a1a8159aeadc22157a7f8529c9f04bd2c411c
|
C#
|
nielsgolstein/Patterns
|
/StatePattern/StatePattern/StatePattern/States/BaseState.cs
| 3.359375
| 3
|
namespace StatePattern.StatePattern.States.StateTypes
{
public class BaseState<TObjectType>
{
/// <summary>
/// Sets the new state end exits the old one (if exists)
/// </summary>
/// <param name="newState">The new state we want to enter</param>
/// <param name="oldState">The old state we want to exit (Optional)</param>
/// <returns>The entered state</returns>
public IState<TObjectType> SetState(IState<TObjectType> newState, IState<TObjectType> oldState = null)
{
if(oldState != null)
oldState.ExitState();
newState.EnterState();
return newState;
}
}
}
|
ebc99a30899f3ddf0b391a963899e1675eadf711
|
C#
|
tralezab/Barotrauma
|
/Barotrauma/BarotraumaClient/Source/Characters/Jobs/JobPrefab.cs
| 2.59375
| 3
|
using Microsoft.Xna.Framework;
namespace Barotrauma
{
partial class JobPrefab
{
public GUIFrame CreateInfoFrame()
{
int width = 500, height = 400;
GUIFrame backFrame = new GUIFrame(Rectangle.Empty, Color.Black * 0.5f);
backFrame.Padding = Vector4.Zero;
GUIFrame frame = new GUIFrame(new Rectangle(GameMain.GraphicsWidth / 2 - width / 2, GameMain.GraphicsHeight / 2 - height / 2, width, height), "", backFrame);
frame.Padding = new Vector4(30.0f, 30.0f, 30.0f, 30.0f);
new GUITextBlock(new Rectangle(0, 0, 100, 20), Name, "", Alignment.TopLeft, Alignment.TopLeft, frame, false, GUI.LargeFont);
var descriptionBlock = new GUITextBlock(new Rectangle(0, 40, 0, 0), Description, "", Alignment.TopLeft, Alignment.TopLeft, frame, true, GUI.SmallFont);
new GUITextBlock(new Rectangle(0, 40 + descriptionBlock.Rect.Height + 20, 100, 20), TextManager.Get("Skills") + ": ", "", Alignment.TopLeft, Alignment.TopLeft, frame, false, GUI.LargeFont);
int y = 40 + descriptionBlock.Rect.Height + 50;
foreach (SkillPrefab skill in Skills)
{
string skillDescription = Skill.GetLevelName((int)skill.LevelRange.X);
string skillDescription2 = Skill.GetLevelName((int)skill.LevelRange.Y);
if (skillDescription2 != skillDescription)
{
skillDescription += "/" + skillDescription2;
}
new GUITextBlock(new Rectangle(0, y, 100, 20),
" - " + skill.Name + ": " + skillDescription, "", Alignment.TopLeft, Alignment.TopLeft, frame, false, GUI.SmallFont);
y += 20;
}
new GUITextBlock(new Rectangle(250, 40 + descriptionBlock.Rect.Height + 20, 0, 20), TextManager.Get("Items") + ": ", "", Alignment.TopLeft, Alignment.TopLeft, frame, false, GUI.LargeFont);
y = 40 + descriptionBlock.Rect.Height + 50;
foreach (string itemName in ItemNames)
{
new GUITextBlock(new Rectangle(250, y, 100, 20),
" - " + itemName, "", Alignment.TopLeft, Alignment.TopLeft, frame, false, GUI.SmallFont);
y += 20;
}
return backFrame;
}
}
}
|
329da18b801faffdfd4495284c61281e6ffdd77b
|
C#
|
727175929/.net_study
|
/C#语法学习/DateTime转化String等/DateTime/Program.cs
| 3.109375
| 3
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DateTime1
{
class Program
{
static void Main(string[] args)
{
String a = "2017/9/15 12:00";
Console.WriteLine("String类型的时间为"+a);
DateTime aa;
aa = Convert.ToDateTime(a);
Console.WriteLine("DateTime类型的时间为" + aa);
DateTime bb;
bb = aa.AddDays(-5);
Console.WriteLine("DateTime减去3天的时间为" + bb);
Console.ReadLine();
}
}
}
|
7134d63ccd3f5042448cf956b845d81109ea9bbf
|
C#
|
czcz1024/czlib
|
/CZLib/CZLib.Config/THZConfigBase.cs
| 3.09375
| 3
|
namespace CZLib.Config
{
using System;
using System.Linq.Expressions;
/// <summary>
/// 自定义配置基类
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class THZConfigBase<T> : Singleton<T>
{
/// <summary>
/// 检测是否已经创建配置
/// </summary>
/// <returns>
/// <c>true</c> if this instance has config; otherwise, <c>false</c>.
/// </returns>
public abstract bool HasConfig();
/// <summary>
/// 从已经创建的配置中读取成配置对象
/// </summary>
/// <returns></returns>
public abstract T Load();
/// <summary>
/// 新建一个配置对象
/// </summary>
/// <returns></returns>
public abstract T Create();
/// <summary>
/// 保存配置对象
/// </summary>
public abstract void Save(T obj);
/// <summary>
/// 保存默认值
/// </summary>
/// <param name="obj">The obj.</param>
public abstract void SaveDefault(T obj);
/// <summary>
/// 重置为默认
/// </summary>
/// <param name="field"></param>
public abstract void ResetToDefault(Expression<Func<T, object>> field);
}
}
|
9f51f882c2efd67f8227ff3d70579d78822074fc
|
C#
|
punkcpp/FNP
|
/PatternMining/SubgraphIsomorphism.cs
| 3.125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PatternMining
{
class SubgraphIsomorphism
{
public Graph g1;
public Graph g2;
public int R;
public List<int>[] Nodes1;
public List<int>[] Nodes2;
public int[] Map;
public bool Isomorphic;
public bool[] Used;
public SubgraphIsomorphism(Graph g1, Graph g2, int R)
{
this.g1 = g1;
this.g2 = g2;
this.R = R;
Nodes1 = new List<int>[R];
Nodes2 = new List<int>[R];
for (int i = 0; i < R; ++i)
{
Nodes1[i] = new List<int>();
Nodes2[i] = new List<int>();
}
Map = new int[g2.n];
Isomorphic = false;
Used = new bool[g1.n];
}
public bool checkEdges()
{
for (int u = 0; u < g2.n; ++u)
{
int u1 = Map[u];
for (int v = u + 1; v < g2.n; ++v)
{
int v1 = Map[v];
if (!(g2.adj[u].Contains(v) && g1.adj[u1].Contains(v1)))
return false;
}
}
return true;
}
public List<List<int>> findPotential()
{
List<List<int>> potential = new List<List<int>>();
for (int u = 0; u < g2.n; ++u)
{
potential.Add(new List<int>());
}
for (int i = 0; i < R; ++i)
{
for (int i1 = 0; i1 < Nodes1[i].Count; ++i1)
{
int u = Nodes1[i][i1];
for (int i2 = 0; i2 < Nodes2[i].Count; ++i2)
{
int v = Nodes2[i][i2];
if (g2.getLabel(v).Equals(g1.getLabel(u)))
potential[v].Add(u);
}
}
}
return potential;
}
public void dfs(List<List<int>> potential, int index)
{
if (index >= potential.Count)
{
if (checkEdges())
Isomorphic = true;
return;
}
for (int i = 0; i < potential[index].Count; ++i)
{
int u = potential[index][i];
if (!Used[u])
{
Map[index] = u;
Used[u] = true;
dfs(potential, index + 1);
if (Isomorphic)
return;
Used[u] = false;
}
}
}
public bool containPattern()
{
Isomorphic = false;
if (g1.n < g2.n) return false;
int pivot_g = g1.pivot;
int pivot_p = g2.pivot;
bool[] vis = new bool[g1.n];
for (int i = 0; i < vis.Length; ++i)
{
vis[i] = false;
}
int[] que = new int[g1.n];
int front =0, rear = 0;
que[rear++] = pivot_g;
vis[pivot_g] = true;
int step = 0;
for (int i = 0; i < Nodes1.Length; ++i)
{
Nodes1[i].Clear();
}
while (front < rear)
{
int tmp_rear = rear;
while (front < tmp_rear)
{
int u = que[front++];
Nodes1[step].Add(u);
for (int i = 0; i < g1.adj[u].Count; ++i)
{
int v = g1.adj[u][i];
if (vis[v] == false)
{
vis[v] = true;
que[rear++] = v;
}
}
}
step++;
if (step >= R)
break;
}
for (int i = 0; i < vis.Length; ++i)
{
vis[i] = false;
}
front = rear = 0;
que[rear++] = pivot_p;
vis[pivot_p] = true;
step = 0;
for (int i = 0; i < Nodes2.Length; ++i)
{
Nodes2[i].Clear();
}
while (front < rear)
{
int tmp_rear = rear;
while (front < tmp_rear)
{
int u = que[front++];
Nodes2[step].Add(u);
for (int i = 0; i < g2.adj[u].Count; ++i)
{
int v = g2.adj[u][i];
if (vis[v] == false)
{
vis[v] = true;
que[rear++] = v;
}
}
}
step++;
if (step >= R)
break;
}
List<List<int>> potential = findPotential();
for (int i = 0; i < potential.Count; ++i)
{
if (potential[i].Count == 0)
return false;
}
for (int i = 0; i < g1.n; ++i)
{
Used[i] = false;
}
dfs(potential, 0);
return Isomorphic;
}
}
}
|
de697b766e942b8095c4fe08ce0234d9b339a2dc
|
C#
|
dkwkekzz/Test
|
/SpeakingLanguage/old/Services/NWorkspace/PageLoader.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpeakingLanguage.Command.NWorkspace
{
class PageLoader
{
private WorkerPool _pool;
private PageStreamer _pageStreamer;
public PageLoader(WorkerPool pool, Book book)
{
_pool = pool;
_pageStreamer = new PageStreamer(book);
}
public async void Load(string owner)
{
var page = await _work(owner);
_pool.OnCompletedWork(owner);
}
private Task<Page> _work(string owner)
{
return Task<Page>.Factory.StartNew(() =>
{
return _pageStreamer.Open(owner);
});
}
}
}
|
7fde0ecb7bc302f4965acb195ab1544e8a214ee0
|
C#
|
ojmakhura/andromda
|
/andromda-etc/andromda-dotnet/AndroMDA.VS80AddIn/AndroMDA.VS80AddIn/Solution Wizard Files/SchemaExport/SchemaExport.cs
| 2.734375
| 3
|
//
// SchemaExport
//
#region Using Statements
using System;
using System.IO;
using System.Configuration;
using NHibernate;
using AndroMDA.NHibernateSupport;
#endregion
namespace ${wizard.solution.name}.SchemaExport
{
class Program
{
public static void Main(string[] args)
{
// Initialize Log4Net
log4net.Config.XmlConfigurator.Configure();
// Get the schema files
string createSchemaFile = ConfigurationManager.AppSettings["schema.create.file"];
string dropSchemaFile = ConfigurationManager.AppSettings["schema.drop.file"];
if (createSchemaFile == null || createSchemaFile.Trim().Length == 0)
{
createSchemaFile = "schema-create.sql";
}
if (dropSchemaFile == null || dropSchemaFile.Trim().Length == 0)
{
dropSchemaFile = "schema-drop.sql";
}
// Show usage information
string usage =
@"Usage:
SchemaExport [-o|-e]
-o = outputs DDL to the console
-e = exports schema to the database
The following example will display the DDL, AND change the database schema:
SchemaExport -o -e
The following example will display the DDL, but NOT change the database schema:
SchemaExport -o
";
string msg = String.Empty;
// Initialize parameters for SchemaExport
bool outputSchemaScriipt = false;
bool exportToDatabase = false;
foreach (string arg in args)
{
switch (arg.ToLower().Trim())
{
case "-o":
outputSchemaScriipt = true;
break;
case "-e":
exportToDatabase = true;
break;
}
}
//They need to enter one of the switches, otherwise we'll kick them out.
if (!exportToDatabase && !outputSchemaScriipt)
{
Console.WriteLine(usage);
return;
}
string outScript = String.Empty;
if (exportToDatabase)
{
try
{
using (DbSupport dbSupport = new DbSupport())
{
outScript = dbSupport.RegenerateDatabase(createSchemaFile, dropSchemaFile);
}
TestDataManager.InsertTestData();
Console.WriteLine("SchemaExport: Export successful. Schema create and drop files saved to '{0}' and '{1}'.", createSchemaFile, dropSchemaFile);
}
catch (Exception e)
{
Console.WriteLine("SchemaExport: Export failed (" + e.Message + ")\n");
throw (e);
}
}
else
{
// Get the create and drop scripts so we can output them to the console
using (DbSupport dbSupport = new DbSupport())
{
string[] dropSql = dbSupport.GenerateDropSQL();
string[] createSql = dbSupport.GenerateCreateSQL();
outScript += String.Join(Environment.NewLine, dropSql);
outScript += String.Join(Environment.NewLine, createSql);
File.WriteAllLines(createSchemaFile, createSql);
File.WriteAllLines(dropSchemaFile, dropSql);
}
}
if (outputSchemaScriipt)
{
Console.WriteLine(outScript);
}
}
}
}
|
a306e37314547a19338e854028dd0d64734ca4d0
|
C#
|
karthikpandiyan/at
|
/JCI.CAM.Provisioning.Core/Utilities/ConfigurationHelper.cs
| 2.609375
| 3
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ConfigurationHelper.cs" company="Microsoft">
// Copyright (c) 2014. All rights reserved.
// </copyright>
// <summary>
// Helper class to read from the Config files
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace JCI.CAM.Provisioning.Core.Configuration
{
using System;
using System.Configuration;
using JCI.CAM.Common.Logging;
/// <summary>
/// Helper class to read from the Config files
/// </summary>
internal static class ConfigurationHelper
{
#region Public Static Members
/// <summary>
/// Helper method to return the a value define in the config file.
/// </summary>
/// <param name="key">The key of the value to return</param>
/// <returns>Value of the key requested</returns>
public static string Get(string key)
{
string returnValue = string.Empty;
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException(PCResources.Exception_Message_EmptyString_Arg, "key");
}
try
{
if (ConfigurationManager.AppSettings[key] != null)
{
returnValue = ConfigurationManager.AppSettings.Get(key);
}
return returnValue;
}
catch (ConfigurationErrorsException ex)
{
LogHelper.LogError(ex, LogEventID.ExceptionHandling, null);
throw;
}
}
#endregion
}
}
|
6968a168fe8b9d5173ca7ca28b0193b472e56ad4
|
C#
|
llenroc/datastructures
|
/DataStructures/Exercises/AlgoExpert/AlgoExpertFindThreeLargestNumbers.cs
| 3.640625
| 4
|
namespace DataStructures.Exercises.AlgoExpert
{
public class AlgoExpertFindThreeLargestNumbers
{
public AlgoExpertFindThreeLargestNumbers()
{
var results = FindThreeLargestNumbers(new[] { 141, 1, 17, -7, -17, -27, 18, 541, 8, 7, 7 });
}
public int[] FindThreeLargestNumbers(int[] arr)
{
int[] numbers = new int[3];
for (int i = 0; i < arr.Length; i++)
{
Shift(numbers, arr[i]);
}
return numbers;
}
public void Shift(int[] numbers, int num)
{
if (numbers[2] < num)
{
ShiftAndUpdate(numbers, 2, num);
}
else if (numbers[1] < num)
ShiftAndUpdate(numbers, 1, num);
else if (numbers[0] < num)
ShiftAndUpdate(numbers, 0, num);
}
public void ShiftAndUpdate(int[] numbers, int idx, int num)
{
for (int i = 0; i <= idx; i++)
{
if (i == idx)
{
numbers[i] = num;
}
else
numbers[i] = numbers[i + 1];
}
}
}
}
|
5c74dcb00079584536a49443a6f9777e2ab34b08
|
C#
|
mssogamosog/OOPChallenge
|
/OOPChallenge/Address.cs
| 3.328125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OOPChallenge
{
public class Address
{
private int id;
private string lineOne;
private string lineTwo;
private string city;
private string country;
private bool billingAddress;
public Address(int id, string lineOne, string lineTwo, string city, string country, bool billingAddress)
{
this.id = id;
this.lineOne = lineOne;
this.lineTwo = lineTwo;
this.city = city;
this.country = country;
this.billingAddress = billingAddress;
}
public string getAddress()
{
StringBuilder str = new StringBuilder();
str.Append(this.lineOne).Append(" ").Append(this.lineTwo).Append(", ").Append(this.city).Append(" (").Append(this.country).Append(")");
return str.ToString();
}
}
}
|
5bef88a39893430a839ad0d2faabdeab45d95bd6
|
C#
|
ExterminatorX99/DissonanceEngine
|
/Src/Core/Structures/Vector3.cs
| 2.96875
| 3
|
using System;
using System.Runtime.InteropServices;
namespace Dissonance.Engine
{
public struct Vector3
{
public const float kEpsilon = 0.00001F;
public const float kEpsilonNormalSqrt = 1e-15F;
public static readonly int SizeInBytes = Marshal.SizeOf(typeof(Vector3));
public static readonly Vector3 Zero = default;
public static readonly Vector3 One = new(1f, 1f, 1f);
public static readonly Vector3 UnitX = new(1f, 0f, 0f);
public static readonly Vector3 UnitY = new(0f, 1f, 0f);
public static readonly Vector3 UnitZ = new(0f, 0f, 1f);
public static readonly Vector3 Up = new(0f, 1f, 0f);
public static readonly Vector3 Down = new(0f, -1f, 0f);
public static readonly Vector3 Left = new(-1f, 0f, 0f);
public static readonly Vector3 Right = new(1f, 0f, 0f);
public static readonly Vector3 Forward = new(0f, 0f, 1f);
public static readonly Vector3 Backward = new(0f, 0f, -1f);
public float X;
public float Y;
public float Z;
public float Magnitude => MathF.Sqrt(X * X + Y * Y + Z * Z);
public float SqrMagnitude => X * X + Y * Y + Z * Z;
public bool HasNaNs => float.IsNaN(X) || float.IsNaN(Y) || float.IsNaN(Z);
public Vector2 XY {
get => new(X, Y);
set {
X = value.X;
Y = value.Y;
}
}
public Vector2 XZ {
get => new(X, Z);
set {
X = value.X;
Z = value.Y;
}
}
public Vector2 YZ {
get => new(Y, Z);
set {
Y = value.X;
Z = value.Y;
}
}
public Vector3 Normalized {
get {
float mag = Magnitude;
if (mag != 0f) {
return this * (1f / mag);
}
return this;
}
}
public float this[int index] {
get => index switch
{
0 => X,
1 => Y,
2 => Z,
_ => throw new IndexOutOfRangeException($"Indices for {nameof(Vector3)} run from 0 to 2 (inclusive)."),
};
set {
switch (index) {
case 0:
X = value;
return;
case 1:
Y = value;
return;
case 2:
Z = value;
return;
default:
throw new IndexOutOfRangeException($"Indices for {nameof(Vector3)} run from 0 to 2 (inclusive).");
}
}
}
public Vector3(float x, float y, float z)
{
X = x;
Y = y;
Z = z;
}
public Vector3(float xyz) : this(xyz, xyz, xyz) { }
public Vector3(Vector2 xy, float z) : this(xy.X, xy.Y, z) { }
public override int GetHashCode()
=> X.GetHashCode() ^ Y.GetHashCode() << 2 ^ Z.GetHashCode() >> 2;
public override bool Equals(object other)
=> other is Vector3 vector && X == vector.X && Y == vector.Y && Z == vector.Z;
public override string ToString()
=> $"[{X}, {Y}, {Z}]";
public float[] ToArray()
=> new[] { X, Y, Z };
public void Normalize()
{
float mag = Magnitude;
if (mag != 0f) {
float num = 1f / mag;
X *= num;
Y *= num;
Z *= num;
}
}
public void Normalize(out float magnitude)
{
magnitude = Magnitude;
if (magnitude != 0f) {
float num = 1f / magnitude;
X *= num;
Y *= num;
Z *= num;
}
}
public void NormalizeEuler()
{
//TODO: Rewrite without loops, sigh.
while (X >= 360f) {
X -= 360f;
}
while (X < 0f) {
X += 360f;
}
while (Y >= 360f) {
Y -= 360f;
}
while (Y < 0f) {
Y += 360f;
}
while (Z >= 360f) {
Z -= 360f;
}
while (Z < 0f) {
Z += 360f;
}
}
//TODO: Rewrite without matrices.
public Vector3 Rotate(Vector3 rot) => Matrix4x4.CreateRotation(rot) * this;
public Vector3 RotatedBy(Vector3 vec) => Matrix4x4.CreateRotation(-vec.X, vec.Y, -vec.Z) * this;
public Vector3 RotatedBy(float x, float y, float z) => Matrix4x4.CreateRotation(-x, y, -z) * this;
public static Vector3 Min(Vector3 a, Vector3 b)
{
return new Vector3(Math.Min(a.X, b.X), Math.Min(a.Y, b.Y), Math.Min(a.Z, b.Z));
}
public static Vector3 Max(Vector3 a, Vector3 b)
{
return new Vector3(Math.Max(a.X, b.X), Math.Max(a.Y, b.Y), Math.Max(a.Z, b.Z));
}
public static Vector3 StepTowards(Vector3 val, Vector3 goal, float step)
{
return new Vector3(
MathHelper.StepTowards(val.X, goal.X, step),
MathHelper.StepTowards(val.Y, goal.Y, step),
MathHelper.StepTowards(val.Z, goal.Z, step)
);
}
public static Vector3 EulerToDirection(Vector3 euler)
{
float pitch = euler.X * MathHelper.Deg2Rad;
float yaw = euler.Y * MathHelper.Deg2Rad;
float cX = MathF.Cos(pitch);
float sX = MathF.Sin(pitch);
float cY = MathF.Cos(yaw);
float sY = MathF.Sin(yaw);
return new Vector3(
cX * sY,
-sX,
cX * cY
);
}
public static Vector3 DirectionToEuler(Vector3 direction)
{
float xzLength = MathF.Sqrt(direction.X * direction.X + direction.Z * direction.Z);
float pitch = MathF.Atan2(xzLength, direction.Y) - MathHelper.HalfPI;
float yaw = MathF.Atan2(direction.X, direction.Z);
return new Vector3(
pitch * MathHelper.Rad2Deg,
yaw * MathHelper.Rad2Deg,
0f
);
}
public static Vector3 Repeat(Vector3 vec, float length) => new(
vec.X - MathF.Floor(vec.X / length) * length,
vec.Y - MathF.Floor(vec.Y / length) * length,
vec.Z - MathF.Floor(vec.Z / length) * length
);
public static Vector3 Rotate(Vector3 vec, Vector3 rot)
=> Matrix4x4.CreateRotation(rot) * vec;
public static Vector3 Normalize(Vector3 vec)
{
float mag = vec.Magnitude;
if (mag != 0f) {
vec *= 1f / mag;
}
return vec;
}
public static Vector3 Floor(Vector3 vec)
{
vec.X = MathF.Floor(vec.X);
vec.Y = MathF.Floor(vec.Y);
vec.Z = MathF.Floor(vec.Z);
return vec;
}
public static Vector3 Ceil(Vector3 vec)
{
vec.X = MathF.Ceiling(vec.X);
vec.Y = MathF.Ceiling(vec.Y);
vec.Z = MathF.Ceiling(vec.Z);
return vec;
}
public static Vector3 Round(Vector3 vec)
{
vec.X = MathF.Round(vec.X);
vec.Y = MathF.Round(vec.Y);
vec.Z = MathF.Round(vec.Z);
return vec;
}
public static Vector3 Lerp(Vector3 from, Vector3 to, float t)
{
t = MathHelper.Clamp01(t);
return new Vector3(from.X + (to.X - from.X) * t, from.Y + (to.Y - from.Y) * t, from.Z + (to.Z - from.Z) * t);
}
public static Vector3 LerpAngle(Vector3 from, Vector3 to, float t)
{
// Could be sped up.
return new Vector3(
MathHelper.LerpAngle(from.X, to.X, t),
MathHelper.LerpAngle(from.Y, to.Y, t),
MathHelper.LerpAngle(from.Z, to.Z, t)
);
}
public static void Cross(ref Vector3 left, ref Vector3 right, out Vector3 result)
{
result = new Vector3(
left.Y * right.Z - left.Z * right.Y,
left.Z * right.X - left.X * right.Z,
left.X * right.Y - left.Y * right.X
);
}
public static Vector3 Cross(Vector3 left, Vector3 right)
{
Cross(ref left, ref right, out var result);
return result;
}
public static float Dot(Vector3 left, Vector3 right)
=> left.X * right.X + left.Y * right.Y + left.Z * right.Z;
public static float Angle(Vector3 from, Vector3 to)
{
float denominator = MathF.Sqrt(from.SqrMagnitude * to.SqrMagnitude);
if (denominator < kEpsilonNormalSqrt) {
return 0f;
}
float dot = MathHelper.Clamp(Dot(from, to) / denominator, -1F, 1F);
return MathF.Acos(dot) * MathHelper.Rad2Deg;
}
public static float Distance(Vector3 a, Vector3 b)
=> (a - b).Magnitude;
public static float SqrDistance(Vector3 a, Vector3 b)
=> (a - b).SqrMagnitude;
// Operations
// Vector3
public static Vector3 operator *(Vector3 a, Vector3 b) => new(a.X * b.X, a.Y * b.Y, a.Z * b.Z);
public static Vector3 operator /(Vector3 a, Vector3 b) => new(a.X / b.X, a.Y / b.Y, a.Z / b.Z);
public static Vector3 operator +(Vector3 a, Vector3 b) => new(a.X + b.X, a.Y + b.Y, a.Z + b.Z);
public static Vector3 operator -(Vector3 a, Vector3 b) => new(a.X - b.X, a.Y - b.Y, a.Z - b.Z);
public static Vector3 operator -(Vector3 a) => new(-a.X, -a.Y, -a.Z);
public static bool operator ==(Vector3 a, Vector3 b) => (a - b).SqrMagnitude < 9.99999944E-11f;
public static bool operator !=(Vector3 a, Vector3 b) => (a - b).SqrMagnitude >= 9.99999944E-11f;
// Float
public static Vector3 operator *(Vector3 a, float d) => new(a.X * d, a.Y * d, a.Z * d);
public static Vector3 operator *(float d, Vector3 a) => new(a.X * d, a.Y * d, a.Z * d);
public static Vector3 operator /(Vector3 a, float d) => new(a.X / d, a.Y / d, a.Z / d);
// Casts
// float*
public static unsafe implicit operator float*(Vector3 vec) => (float*)&vec;
// System.Numerics.Vector3
public static implicit operator Vector3(System.Numerics.Vector3 value) => new(value.X, value.Y, value.Z);
public static implicit operator System.Numerics.Vector3(Vector3 value) => new(value.X, value.Y, value.Z);
// BulletSharp.Math.Vector3
public static implicit operator BulletSharp.Math.Vector3(Vector3 value) => new(value.X, value.Y, value.Z);
public static implicit operator Vector3(BulletSharp.Math.Vector3 value) => new(value.X, value.Y, value.Z);
}
}
|
f962ce501e0eb049f1ae96339d548e50af809444
|
C#
|
JachuPL/TicketReservation
|
/Application/TicketReservation.Application/Reservations/Implementations/ReservationsQuerier.cs
| 2.59375
| 3
|
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TicketReservation.Application.Common.Database;
using TicketReservation.Application.Reservations.Interfaces;
using TicketReservation.Application.Reservations.Models;
using TicketReservation.Application.Reservations.Requests;
using TicketReservation.Domain.Reservations;
using TicketReservation.Domain.Shows;
namespace TicketReservation.Application.Reservations.Implementations
{
internal sealed class ReservationsQuerier : IQueryReservations
{
private readonly TicketReservationContext _ctx;
public ReservationsQuerier(TicketReservationContext ctx)
{
_ctx = ctx;
}
public async Task<ReservationOffer> GetReservationOffer(ReservationOfferRequest request)
{
Show show = await _ctx.Shows.Include(s => s.Reservations).FirstOrDefaultAsync(s => s.Id == request.ShowId);
if (IsAnyPlaceReservedAlready(request, show))
{
throw new Exception($"One or more of requested places are already reserved.");
}
Dictionary<Ticket, int> requestedTickets = request.Places.GroupBy(x => x.Ticket).ToDictionary(x => x.Key, x => x.Count());
decimal price = show.EvaluateReservationPrice(requestedTickets);
return new ReservationOffer()
{
OfferRequest = request,
Price = price
};
}
private static bool IsAnyPlaceReservedAlready(ReservationOfferRequest request, Show show)
{
return request.Places.Any(p => show.IsPlaceReserved(p.Row, p.Seat));
}
public async Task<IEnumerable<Place>> GetAvailableSeats(Guid showId)
{
Show show = await _ctx.Shows.Include(x => x.Reservations).ThenInclude(y => y.ReservedSeats).FirstOrDefaultAsync(x => x.Id == showId);
if (show is null)
{
throw new KeyNotFoundException(nameof(showId));
}
var allReservedSeats = show.Reservations.SelectMany(x => x.ReservedSeats);
return GetAvailableSeats(allReservedSeats);
}
private static List<Place> GetAvailableSeats(IEnumerable<ReservedSeat> reservedSeats)
{
var allPossiblePlaces = from row in Enumerable.Range(1, ReservedSeat.NumberOfRows)
from seat in Enumerable.Range(1, ReservedSeat.NumberOfSeatsPerRow)
select new { row, seat };
var availableSeats = allPossiblePlaces.Where(x => reservedSeats.Any(z => z.Row != x.row && z.Seat != x.seat));
return availableSeats.Select(x => new Place
{
Row = x.row,
Seat = x.seat
}).ToList();
}
}
}
|
b565c993232203fd9455cfd407d91f016417c315
|
C#
|
norbertkadar/Lab5_Movie
|
/Lab3Movie/Models/MoviesDbSeeder.cs
| 2.890625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Lab3Movie.Models
{
public class MoviesDbSeeder
{
public static void Initialize(MoviesDbContext context)
{
context.Database.EnsureCreated();
// Look for any movies.
if (context.Movies.Any())
{
return; // DB has been seeded
}
context.Movies.AddRange(
new Movie
{
Title = "Movie1",
Description = "Description1",
Genre = Genre.action,
DurationInMinutes = 120,
YearOfRelease = 2017,
Director = "Director1",
Rating = 10,
Watched = Watched.yes
},
new Movie
{
Title = "Movie2",
Description = "Description2",
Genre = Genre.comedy,
DurationInMinutes = 110,
YearOfRelease = 2018,
Director = "Director2",
Rating = 9,
Watched = Watched.no
}
);
context.SaveChanges();
}
}
}
|
34801c3f7f803f50ad5fa3482f10a9931f796264
|
C#
|
georg-jung/FluentDegiro
|
/FluentDegiro/Infrastructure/ApiMethodBuilder.cs
| 2.6875
| 3
|
using FluentDegiro.Abstractions.Infrastructure;
using FluentDegiro.Infrastructure.Extensions;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Net.Http;
using System.Text;
namespace FluentDegiro.Infrastructure
{
/// <summary>
/// Builder-style implementation of the abstract ApiMethodBase that is created using a "parent" IRequestBuilderFactory providing
/// the context this method is called in. The specific attributes of this api method can be configured using the builder-style
/// api this class provides.
/// </summary>
internal class ApiMethodBuilder : ApiMethodBase, IRequestBuilderFactory
{
private protected IRequestBuilderFactory Context { get; }
protected dynamic QueryStringParameters { get; } = new ExpandoObject();
protected IDictionary<string, object> QueryStringParametersDict => (IDictionary<string, object>)QueryStringParameters;
protected object Body { get; }
protected Dictionary<string, string> Headers { get; set; } = new Dictionary<string, string>();
protected HttpMethod Method { get; set; }
internal ApiMethodBuilder(IRequestBuilderFactory context)
{
Context = context;
}
protected ApiMethodBuilder(IRequestBuilderFactory context, ExpandoObject queryStringParameters, object body) : this(context)
{
if (queryStringParameters != null)
QueryStringParameters = queryStringParameters;
Body = body;
}
IRequestBuilder IRequestBuilderFactory.CreateRequestBuilder()
=> CreateRequestBuilder();
protected override IRequestBuilder CreateRequestBuilder()
{
var builder = Context.CreateRequestBuilder();
builder.Method = Method ?? HttpMethod.Get;
builder.QueryStringParameters.SetValues((ExpandoObject)QueryStringParameters);
if (Body != null) {
if (builder.Body != null)
throw new InvalidOperationException("This request's body is already set.");
builder.Body = Body;
}
builder.Headers.SetValues(Headers);
return builder;
}
internal static ApiMethodBuilder Create(IRequestBuilderFactory context, ExpandoObject queryStringParameters = null, object body = null)
=> Create(context, HttpMethod.Get, queryStringParameters, body);
internal static ApiMethodBuilder Create(
IRequestBuilderFactory context,
HttpMethod method,
ExpandoObject queryStringParameters = null,
object body = null)
{
var meth = new ApiMethodBuilder(context, queryStringParameters, body)
{
Method = method
};
return meth;
}
}
}
|
b02e27106d204d363808a676bbb34edbbf7a04e0
|
C#
|
shendongnian/download4
|
/code7/1268275-33938352-105032784-4.cs
| 2.515625
| 3
|
private void panel1_Paint(object sender, PaintEventArgs e)
{
var hs = (HatchStyle[])Enum.GetValues(typeof(HatchStyle));
for (int i = 0; i < hs.Length; i++)
using (HatchBrush hbr = new HatchBrush(hs[i], Color.GreenYellow))
using (HatchBrush hbr2 = new HatchBrush(hs[i], Color.LightCyan))
{
e.Graphics.FillRectangle(hbr, new Rectangle(i * 20, 10,16,60));
using (TextureBrush tbr = TBrush(hbr2))
{
e.Graphics.FillRectangle(tbr, new Rectangle(i * 20, 80, 16, 60));
tbr.ScaleTransform(2, 2);
e.Graphics.FillRectangle(tbr, new Rectangle(i * 20, 150, 16, 60));
tbr.ResetTransform();
tbr.ScaleTransform(3,3);
e.Graphics.FillRectangle(tbr, new Rectangle(i * 20, 220, 16, 60));
}
}
}
|
5a2d9c939da7a3db21414a26404ed3507b2c2194
|
C#
|
olivergrimes/GameOfLife
|
/GameOfLife/NeighbourState.cs
| 3.53125
| 4
|
using System;
namespace GameOfLife
{
public class NeighbourState : INeighbourState
{
private readonly bool[,] _currentState;
private readonly int _x;
private readonly int _y;
public NeighbourState(bool[,] currentState, int x, int y)
{
_currentState = currentState ?? throw new ArgumentNullException(nameof(currentState));
_x = x;
_y = y;
}
public int AliveNeighbours()
{
var aliveCount = 0;
aliveCount += IsAlive(-1, 0);
aliveCount += IsAlive(-1, -1);
aliveCount += IsAlive(-1, 1);
aliveCount += IsAlive(0, -1);
aliveCount += IsAlive(0, 1);
aliveCount += IsAlive(1, 0);
aliveCount += IsAlive(1, -1);
aliveCount += IsAlive(1, 1);
return aliveCount;
}
private int IsAlive(int offsetX, int offsetY)
{
var x = _x + offsetX;
var y = _y + offsetY;
if (x < _currentState.GetLowerBound(0) || x > _currentState.GetUpperBound(0) ||
y < _currentState.GetLowerBound(1) || y > _currentState.GetUpperBound(1))
{
return 0;
}
return _currentState[x, y] ? 1 : 0;
}
}
}
|
938c82f153ad6e36cc51e3d66ecd30f6b41bdff0
|
C#
|
DanielaPopova/TelerikAcademy_Homeworks
|
/Unit Testing/Workshop - Academy/Academy/Core/Providers/CommandParser.cs
| 3.1875
| 3
|
using Academy.Commands.Contracts;
using Academy.Core.Contracts;
using Academy.Core.Factories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Academy.Core.Providers
{
public class CommandParser : IParser
{
public ICommand ParseCommand(string fullCommand)
{
// Takes the command name from the string
var commandName = fullCommand.Split(' ')[0];
// Tries to find a class that matches that command
var commandTypeInfo = this.FindCommand(commandName);
// Creates an instance of that classes and passes to the constructor:
// The singleton instance of the AcademyFactory class
// The singleton instance of the Engine class
// Then it casts the whole thing from object to ICommand
var command = Activator.CreateInstance(commandTypeInfo, AcademyFactory.Instance, Engine.Instance) as ICommand;
return command;
}
public IList<string> ParseParameters(string fullCommand)
{
// Takes the parameters from the string
var commandParts = fullCommand.Split(' ').ToList();
commandParts.RemoveAt(0);
// If there are no params, return an empty list
// This violates part of the Command-Querry Seperation principle
// Made this way to keep things simple
if (commandParts.Count() == 0)
{
return new List<string>();
}
return commandParts;
}
private TypeInfo FindCommand(string commandName)
{
// Gets the current assembly (visual studio project)
Assembly currentAssembly = this.GetType().GetTypeInfo().Assembly;
// Gets a list of all the defined classes in the current assembly
// Then filters only the classes that implement the interface ICommand
// Then filters only the classes that contain the passed command name within it's name with the suffix command
// Then takes the class that it has found or takes null
var commandTypeInfo = currentAssembly.DefinedTypes
.Where(type => type.ImplementedInterfaces.Any(inter => inter == typeof(ICommand)))
.Where(type => type.Name.ToLower() == (commandName.ToLower() + "command"))
.SingleOrDefault();
// If it has not found the class, an exception is thrown
if (commandTypeInfo == null)
{
throw new ArgumentException("The passed command is not found!");
}
return commandTypeInfo;
}
}
}
|
2186ccf432ce1644fc19d06d29014a84449d247b
|
C#
|
arkadiusz-gorecki/3D-Shape-Editor
|
/Camera.cs
| 2.796875
| 3
|
using _3DShapeEditor.Shapes;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace _3DShapeEditor
{
public class Camera: MatrixOperations
{
public float Fov { get; } = 90;// field of view
public float Near { get; } = 1; // przednia płaszczyzna obcinania
public float Far { get; } = 10;// tylnia płaszczyzna obcinania
private float aspect = (float)16 / 9;
public float Aspect { get => aspect; }
private Vertex P; // pozycja kamery
private Vertex T; // punkt na który skierowana jest kamera
private Matrix4x4 viewMatrix;
private Matrix4x4 projMatrix;
private float cameraMovementSpeed = 0.2f;
private float cameraRotationSpeed = 0.005f;
private bool mouseHolding;
private Point lastMousePosition;
private Point currentMousePosition;
public Matrix4x4 GetViewMatrix { get => viewMatrix;}
public Matrix4x4 GetProjectionMatrix { get => projMatrix; }
public Vertex GetPosition { get => P; }
public void SetMouseHolding(bool holding, Point mousePosition)
{
if (mouseHolding = holding)
lastMousePosition = mousePosition;
}
public void SetMousePosition(Point mousePosition)
{
currentMousePosition = mousePosition;
}
public Camera(Vertex P, Vertex T, float aspect, Point mousePosition)
{
this.P = P;
this.T = T;
this.aspect = aspect;
currentMousePosition = mousePosition;
ChangeProperties(P, T);
UpdateProjectionMatrix();
}
public Camera(Vertex P, Vertex T, float aspect, float fov, float n, float f, Point mousePosition)
{
this.P = P;
this.T = T;
Fov = fov;
Near = n;
Far = f;
this.aspect = aspect;
currentMousePosition = mousePosition;
ChangeProperties(P, T);
UpdateProjectionMatrix();
}
public void Move()
{
MovePosition();
Rotate();
UpdateViewMatrix();
}
private void MovePosition()
{
// przemieszczenie punktów P i T
float dx = P.X - T.X;
float dz = P.Z - T.Z;
float dy = P.Y - T.Y;
float len = (float)Math.Sqrt(dx * dx + dy * dy + dz * dz);
// podział prędkości kamery pomiędzy każdą współrzędną
float xCam = cameraMovementSpeed * dx / len;
float yCam = cameraMovementSpeed * dy / len;
float zCam = cameraMovementSpeed * dz / len;
if (Keyboard.IsKeyDown(Constants.KEY_FORWARD_CAMERA))
{
P.X -= xCam; P.Y -= yCam; P.Z -= zCam;
T.X -= xCam; T.Y -= yCam; T.Z -= zCam;
return; // żeby nie było sytuacji że kilka przycisków na raz można przycisnąć (oznacza to że nie da się iść na ukos)
}
if (Keyboard.IsKeyDown(Constants.KEY_BACKWARD_CAMERA))
{
P.X += xCam; P.Y += yCam; P.Z += zCam;
T.X += xCam; T.Y += yCam; T.Z += zCam;
return;
}
// podział prędkości tylko pomiędzy x i z bo strafe porusza tylko wzdłuż płaszczyzny XZ (bo nie ma w programie obracania kamery (roll))
len = (float)Math.Sqrt(dx * dx + dz * dz);
xCam = cameraMovementSpeed * dx / len;
zCam = cameraMovementSpeed * dz / len;
if (Keyboard.IsKeyDown(Constants.KEY_STRAFELEFT_CAMERA))
{
P.X -= zCam; P.Z += xCam;
T.X -= zCam; T.Z += xCam;
}
else if (Keyboard.IsKeyDown(Constants.KEY_STRAFERIGHT_CAMERA))
{
P.X += zCam; P.Z -= xCam;
T.X += zCam; T.Z -= xCam;
}
}
private void Rotate()
{
if (!mouseHolding)
return;
float dx = currentMousePosition.X - lastMousePosition.X;
float dy = currentMousePosition.Y - lastMousePosition.Y;
lastMousePosition.X = currentMousePosition.X;
lastMousePosition.Y = currentMousePosition.Y;
float len = (float)Math.Sqrt((dx * dx) + (dy * dy));
if (len == 0)
return;
float yawAngle = cameraRotationSpeed * (dx); // obracanie kamery na boki
float pitchAngle = -cameraRotationSpeed * (dy); // obracanie kamery do góry do dołu
RotateYawn(yawAngle);
RotatePitch(pitchAngle);
}
private void RotatePitch(float pitchAngle)
{
Matrix4x4 T1 = GetTranslationMatrix(-P.X, -P.Y, -P.Z);
Matrix4x4 T2 = GetTranslationMatrix(P.X, P.Y, P.Z);
T = Transform(T1, T);
float alignToXYPlaneAngle = -(float)Math.Atan2(T.Z, T.X);
Matrix4x4 Ry1 = GetRotationYMatrix(alignToXYPlaneAngle);
T = Transform(Ry1, T);
float angleRemaining = (float)Math.Abs(Math.Atan(T.X / T.Y)); // jak dużo możemy jeszcze obrócić kamerę do góry (lub do dołu) żeby nie przekręcić jej "za siebie"
if (pitchAngle > 0 && T.Y > 0 && pitchAngle > angleRemaining) // do góry obracasz kamerę
{
if (angleRemaining < (Math.PI / 180) * 1) // jeden stopień w radianach (nie można bardziej pionowo niż 89 stopni)
pitchAngle = 0;
else
pitchAngle = angleRemaining - (float)(Math.PI / 180) * 1;
}
else if (pitchAngle < 0 && T.Y < 0 && -pitchAngle > angleRemaining) // do dołu obracasz kamerę
{
if (angleRemaining < (Math.PI / 180) * 1)
pitchAngle = 0;
else
pitchAngle = -angleRemaining + (float)(Math.PI / 180) * 1;
}
Matrix4x4 Rz = GetRotationZMatrix(pitchAngle);
Matrix4x4 Ry2 = GetRotationYMatrix(-alignToXYPlaneAngle);
T = Transform(T2 * Ry2 * Rz, T);
}
private void RotateYawn(float yawAngle)
{
Matrix4x4 T1 = GetTranslationMatrix(-P.X, -P.Y, -P.Z);
Matrix4x4 Ry = GetRotationYMatrix(yawAngle);
Matrix4x4 T2 = GetTranslationMatrix(P.X, P.Y, P.Z);
Matrix4x4 TRT = T2 * Ry * T1;
T = Transform(TRT, T);
}
private void Rotate_FastAlgorithm()
{
if (!mouseHolding)
return;
float dx = currentMousePosition.X - lastMousePosition.X;
float dy = currentMousePosition.Y - lastMousePosition.Y;
lastMousePosition.X = currentMousePosition.X;
lastMousePosition.Y = currentMousePosition.Y;
float len = (float)Math.Sqrt((dx * dx) + (dy * dy));
if (len == 0)
return;
float yawAngle = cameraRotationSpeed * (dx); // obracanie kamery na boki
float pitchAngle = -cameraRotationSpeed * (dy); // obracanie kamery do góry do dołu
Matrix4x4 T1 = GetTranslationMatrix(-P.X, -P.Y, -P.Z);
T = Transform(T1, T);
float alignToXYPlaneAngle = -(float)Math.Atan2(T.Z, T.X);
Matrix4x4 Ry1 = GetRotationYMatrix(alignToXYPlaneAngle);
T = Transform(Ry1, T);
float angleRemaining = (float)Math.Abs(Math.Atan(T.X / T.Y)); // jak dużo możemy jeszcze obrócić kamerę do góry żeby nie przekręcić jej "za siebie" (lub do dołu)
if (pitchAngle > 0 && T.Y > 0 && pitchAngle > angleRemaining) // do góry przekręcasz kamerę
{
if (angleRemaining < (Math.PI / 180) * 1) // jeden stopień w radianach (nie można bardziej pionowo niż 89 stopni)
pitchAngle = 0;
else
pitchAngle = angleRemaining - (float)(Math.PI / 180) * 1;
}
else if (pitchAngle < 0 && T.Y < 0 && -pitchAngle > angleRemaining) // do dołu
{
if (angleRemaining < (Math.PI / 180) * 1) // jeden stopień w radianach
pitchAngle = 0;
else
pitchAngle = -angleRemaining + (float)(Math.PI / 180) * 1;
}
Matrix4x4 Rz = GetRotationZMatrix(pitchAngle);
Matrix4x4 Ry2 = GetRotationYMatrix(-alignToXYPlaneAngle);
Matrix4x4 Ry = GetRotationYMatrix(yawAngle);
Matrix4x4 T2 = GetTranslationMatrix(P.X, P.Y, P.Z);
T = Transform(T2 * Ry * Ry2 * Rz, T);
}
public void ChangeProperties(Vertex P, Vertex T)
{
this.P = P;
this.T = T;
UpdateViewMatrix();
}
public void ChangeAspect(float aspect)
{
this.aspect = aspect;
UpdateProjectionMatrix();
}
private void UpdateViewMatrix()
{
Vector3 Uworld = new Vector3(0, 1, 0);
Vector3 D = new Vector3(P.X - T.X, P.Y - T.Y, P.Z - T.Z);
D = Vector3.Normalize(D);
Vector3 R = Vector3.Cross(Uworld, D);
R = Vector3.Normalize(R);
Vector3 U = Vector3.Cross(D, R);
U = Vector3.Normalize(U);
Matrix4x4 mat = new Matrix4x4(R.X, R.Y, R.Z, 0,
U.X, U.Y, U.Z, 0,
D.X, D.Y, D.Z, 0,
0, 0, 0, 1);
Matrix4x4 cam = new Matrix4x4(1, 0, 0, -P.X,
0, 1, 0, -P.Y,
0, 0, 1, -P.Z,
0, 0, 0, 1);
viewMatrix = mat * cam;
}
public void UpdateProjectionMatrix()
{
projMatrix = new Matrix4x4(1 / ((float)Math.Tan(Fov / 2) * Aspect), 0, 0, 0,
0, 1 / (float)Math.Tan(Fov / 2), 0, 0,
0, 0, -(Far + Near) / (Far - Near), -(2 * Far * Near) / (Far - Near),
0, 0, -1, 0);
}
}
}
|
eeadf00a2541d586e369e1cb86b3abd56886cf92
|
C#
|
migellemertens/C-Sharp-Essentials-TIN
|
/h06/Exercise06/MainWindow.xaml.cs
| 3.078125
| 3
|
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace Exercise06
{
public partial class MainWindow : Window
{
private DispatcherTimer timer = new DispatcherTimer();
private Rectangle _secondsRectangle;
private Rectangle _minutesRectangle;
private int _secondsCounter = 0;
public MainWindow()
{
InitializeComponent();
timer.Interval = TimeSpan.FromMilliseconds(1000);
timer.Tick += timer_Tick;
timer.Start();
DrawRectangle();
}
private void timer_Tick(object sender, EventArgs e)
{
_secondsCounter++;
secondsLabel.Content = _secondsCounter;
UpdateRectangle();
}
private void DrawRectangle()
{
_minutesRectangle = new Rectangle()
{
Width = 0,
Height = 50,
Margin = new Thickness(0, 40, 0, 0),
Fill = new SolidColorBrush(Colors.LightSeaGreen)
};
paperCanvas.Children.Add(_minutesRectangle);
_secondsRectangle = new Rectangle()
{
Width = 0,
Height = 50,
Margin = new Thickness(0, 120, 0, 0),
Fill = new SolidColorBrush(Colors.LightSeaGreen)
};
paperCanvas.Children.Add(_secondsRectangle);
}
private void UpdateRectangle()
{
if(_secondsCounter == 3600)
{
_minutesRectangle.Width = 0;
return;
}
if(_secondsCounter % 60 == 0)
{
_minutesRectangle.Width += 10;
_secondsRectangle.Width = 0;
}
else
{
_secondsRectangle.Width += 10;
}
}
}
}
|
7e72a0ffec116565b3ee9502e7e6e7299a874846
|
C#
|
KATESTYLES333/LabsOnCSharp
|
/Delegate1/Delegate1/Program.cs
| 3.59375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Delegate1
{
public class del<RetType> where RetType : new()
{
private List<Func<RetType>> methods = new List<Func<RetType>>();
public del(Func<RetType> fMethod)
{
methods.Add(fMethod);
}
public void AddMethod(Func<RetType> method)
{
methods.Add(method);
}
public RetType Invoke()
{
RetType res = new RetType();
foreach (var method in methods)
{
res = method.Invoke();
}
return res;
}
public static del<RetType> operator +(del<RetType> del, Func<RetType> method)
{
del.AddMethod(method);
return del;
}
}
class Program
{
static object TestMethod()
{
return 10;
}
static object TestMethod2()
{
return 11;
}
static void Main(string[] args)
{
del<object> del = new del<object>(TestMethod);
del += TestMethod2;
Console.WriteLine(del.Invoke());
Console.ReadLine();
}
}
}
|
b2ac304fdc09141f6031d31253658aa14d79c19c
|
C#
|
tropensturm/-BET-.Playground
|
/]BET[.Playground.Core/Assembly.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Reflection;
namespace _BET_.Playground.Core
{
public static class AssemblyLocator
{
public static Dictionary<string, Assembly> assemblies;
public static void Init(AppDomain domain)
{
assemblies = new Dictionary<string, Assembly>();
domain.AssemblyLoad += new AssemblyLoadEventHandler(AssemblyLoad);
domain.AssemblyResolve += new ResolveEventHandler(AssemblyResolve);
}
static Assembly AssemblyResolve(object sender, ResolveEventArgs args)
{
Assembly assembly = null;
assemblies.TryGetValue(args.Name, out assembly);
return assembly;
}
static void AssemblyLoad(object sender, AssemblyLoadEventArgs args)
{
Assembly assembly = args.LoadedAssembly;
if(assemblies == null)
assemblies = new Dictionary<string, Assembly>();
if (!assemblies.ContainsKey(assembly.FullName))
assemblies.Add(assembly.FullName, assembly);
}
}
}
|
1436e81d4c3eaf2fa212616b1bac3484b4faad87
|
C#
|
cvele89/TaxiDispatcher
|
/TaxiDispatcher.App/Scheduler.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
namespace TaxiDispatcher.App
{
public enum RideType
{
City,
InterCity
}
public class Scheduler
{
protected static TaxiCompany taxiCompany_Naxi = new TaxiCompany { CompanyName = "Naxi", PriceModifier = 10 };
protected static TaxiCompany taxiCompany_Alfa = new TaxiCompany { CompanyName = "Alfa", PriceModifier = 15 };
protected static TaxiCompany taxiCompany_Gold = new TaxiCompany { CompanyName = "Gold", PriceModifier = 13 };
protected List<Taxi> taxiDrivers = new List<Taxi>
{
new Taxi { DriverId = 1, DriverName = "Predrag", Company = taxiCompany_Naxi, CurrentLocation = 1 },
new Taxi { DriverId = 2, DriverName = "Nenad", Company = taxiCompany_Naxi, CurrentLocation = 4 },
new Taxi { DriverId = 3, DriverName = "Dragan", Company = taxiCompany_Alfa, CurrentLocation = 6 },
new Taxi { DriverId = 4, DriverName = "Goran", Company = taxiCompany_Gold, CurrentLocation = 7 }
};
public void OrderRide(int startLocation, int endLocation, RideType rideType, DateTime time)
{
Console.WriteLine($"Ordering ride from {startLocation} to {endLocation}...");
try
{
var ride = CreateRide(startLocation, endLocation, rideType, time);
Console.WriteLine("Ride ordered, price: " + ride.Price.ToString());
AcceptRide(ride);
}
catch (Exception e)
{
if (e.Message == "There are no available taxi vehicles!")
{
Console.WriteLine(e.Message);
Console.WriteLine("");
}
else
throw;
}
}
public void PrintDriverEarnings(int driverId)
{
Console.WriteLine($"Driver with ID = {driverId} earned today:");
int total = 0;
foreach (var ride in GetRideList(driverId))
{
total += ride.Price;
Console.WriteLine("Price: " + ride.Price);
}
Console.WriteLine("Total: " + total);
}
private Ride CreateRide(int startLocation, int endLocation, RideType rideType, DateTime time)
{
return new Ride
{
TaxiInfo = FindNearestTaxi(startLocation),
StartLocation = startLocation,
EndLocation = endLocation,
RideType = rideType,
Time = time
};
}
private void AcceptRide(Ride ride)
{
InMemoryRideDataBase.SaveRide(ride);
ride.TaxiInfo.CurrentLocation = ride.EndLocation;
Console.WriteLine("Ride accepted, waiting for driver: " + ride.TaxiInfo.DriverName);
Console.WriteLine("");
}
private List<Ride> GetRideList(int driverId)
{
List<Ride> rides = new List<Ride>();
List<int> ids = InMemoryRideDataBase.GetRideIds();
foreach (int id in ids)
{
Ride ride = InMemoryRideDataBase.GetRide(id);
if (ride != null && ride.TaxiInfo.DriverId == driverId)
rides.Add(ride);
}
return rides;
}
private Taxi FindNearestTaxi(int startLocation)
{
Taxi nearestTaxi = null;
int min_distance = int.MaxValue;
foreach (var taxi in taxiDrivers)
{
if (Math.Abs(taxi.CurrentLocation - startLocation) < min_distance)
{
nearestTaxi = taxi;
min_distance = Math.Abs(taxi.CurrentLocation - startLocation);
}
}
if (min_distance > 15)
throw new Exception("There are no available taxi vehicles!");
return nearestTaxi;
}
public class Taxi
{
public int DriverId { get; set; }
public string DriverName { get; set; }
public int CurrentLocation { get; set; }
public TaxiCompany Company { get; set; }
}
public class Ride
{
public int Id { get; set; }
public Taxi TaxiInfo { get; set; }
public int StartLocation { get; set; }
public int EndLocation { get; set; }
public RideType RideType { get; set; }
public DateTime Time { get; set; }
private int _price = -1;
public int Price
{
get
{
if (_price < 0)
{
_price = TaxiInfo.Company.PriceModifier * Math.Abs(StartLocation - EndLocation);
if (RideType == RideType.InterCity)
_price *= 2;
if (Time.Hour < 6 || Time.Hour > 22)
_price *= 2;
}
return _price;
}
}
}
public class TaxiCompany
{
public string CompanyName { get; set; }
public int PriceModifier { get; set; } = 1;
}
}
}
|
41a5852bca611f295defc84d074beefccbf88f90
|
C#
|
notpatrick/MyQuizMobile
|
/MyQuizMobile/MyQuizMobile/MyQuizMobile/Converters/DateTimeConverter.cs
| 2.5625
| 3
|
using System;
using System.Globalization;
using Xamarin.Forms;
namespace MyQuizMobile {
public class DateTimeConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value != null ? DateTime.Parse(value.ToString()).TimeOfDay : new TimeSpan(9, 0, 0); }
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value?.ToString(); }
}
}
|
ee3f360369d3f98846a8e7fae8b9d20efaa37558
|
C#
|
mwhelanj/TaxNumberValidation
|
/TaxFileNumberValidationApp/Services/ValidationService.cs
| 3.125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TaxFileNumberValidationApp
{
public class ValidationService : IValidationService
{
public bool ValidateTFN(string tfn)
{
//validate only digits
if (!IsNumeric(tfn)) return false;
//validate length
if (tfn.Length != 9 && tfn.Length != 8) return false;
int[] digits = Array.ConvertAll(tfn.ToArray(), c => (int)Char.GetNumericValue(c));
//do the calcs
var sum = (digits[0] * 10)
+ (digits[1] * 7)
+ (digits[2] * 8)
+ (digits[3] * 4)
+ (digits[4] * 6)
+ (digits[5] * 3)
+ (digits[6] * 5)
+ (digits[(tfn.Length - 1)] * 1);
sum += tfn.Length == 9 ? (digits[7] * 2) : sum;
var remainder = sum % 11;
return (remainder == 0);
}
private bool IsNumeric(string s)
{
float output;
return float.TryParse(s, out output);
}
}
}
|
7af7c527f4d4e8e4414b6da52a6e36cbfc9d2475
|
C#
|
kevindavis-gd/BinaryConverter
|
/Binary Calculator/MainForm.cs
| 3.328125
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics.Tracing;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Binary_Calculator
{
public partial class mainForm : Form
{
public mainForm()
{
InitializeComponent();
}
private void ConvertButton_Click(object sender, EventArgs e)
{
//store the input as a string
string textBoxText = "";
textBoxText += binaryInput.Text;
if (textBoxText == "")
textBoxText = "0";
//check if all characters are 1 or 0, if not throw error
if (!isbinary(textBoxText))
{
MessageBox.Show("Insert Binary Numbers Only", "Error");
return;
}
//check the number of digits to be processed
int repeat = textBoxText.Length;
//convert string to int
int binaryNum = Int32.Parse(textBoxText);
int remainder = 0;
int decimalNum = 0;
//keep tract of base of the right most number (128, 64, 32, 16, 8, 4, 2, 1)
int baseVal = 1;
//perform this operating for every digit
for (int x = 0; x < repeat; x++)
{ //store the right most number
remainder = binaryNum % 10;
// remove the right most number from the binary number
binaryNum = binaryNum / 10;
// multiply the binary number by the base and add it to the devimal value
decimalNum = decimalNum + remainder * baseVal;
// multiply the base value by 2 to get the correct value
baseVal = baseVal * 2;
}
// print output to invisible lable
Output.Text += " \n\n The Binary Number is : " + textBoxText;
Output.Text += "\n Its Decimal Equivalent is : " + decimalNum;
}
private void ClearButton_Click(object sender, EventArgs e)
{
//clear the screen
Output.Text = "";
}
static bool isbinary(string s)
{
//loop through every character
foreach (var c in s)
//if the character isnt 0 or 1 return false
if (c != '0' && c != '1')
return false;
return true;
}
}
}
|
f92de80f636c4c14159617d0810b124ae14783dd
|
C#
|
jamessantiago/GetNet
|
/src/getnet.web/ExtensionMethods.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Net;
using getnet.Model;
using Newtonsoft.Json;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace getnet
{
public static class ExtensionMethods
{
public static bool IsLocal(this HttpRequest req)
{
var connection = req.HttpContext.Connection;
if (connection.RemoteIpAddress != null)
{
if (connection.LocalIpAddress != null)
{
return connection.RemoteIpAddress.Equals(connection.LocalIpAddress);
}
else
{
return IPAddress.IsLoopback(connection.RemoteIpAddress);
}
}
// for in memory TestServer or when dealing with default connection info
if (connection.RemoteIpAddress == null && connection.LocalIpAddress == null)
{
return true;
}
return false;
}
public static List<SnackMessage> GetSnackMessages(this ISession session)
{
try
{
var messages = JsonConvert.DeserializeObject<List<SnackMessage>>(session.GetString("SnackMessages"));
session.Remove("SnackMessages");
return messages;
} catch
{
return new List<SnackMessage>();
}
}
public static void AddSnackMessage(this ISession session, string message, params object[] args)
{
var snack = new SnackMessage() { message = args != null ? string.Format(message, args) : message };
session.AddSnackMessage(snack);
}
public static void AddSnackMessage(this ISession session, SnackMessage message)
{
var messages = session.GetSnackMessages();
messages.Add(message);
if (messages.Count > 1)
{
messages = PaginateSnacks(messages);
}
session.SetString("SnackMessages", JsonConvert.SerializeObject(messages));
}
private static List<SnackMessage> PaginateSnacks(List<SnackMessage> messages)
{
var pagedMessages = new List<SnackMessage>();
for (int i = 0; i < messages.Count;i++)
{
var snack = messages[i];
snack.message = Regex.Replace(snack.message, @" \(\d+/\d+\)", "");
snack.message += string.Format(" ({0}/{1})", i + 1, messages.Count);
pagedMessages.Add(snack);
}
return pagedMessages;
}
public static bool IsAjaxRequest(this HttpRequest request)
{
return request != null && request.Headers["X-Requested-With"] == "XMLHttpRequest";
}
public static SelectList EnumToSelectList(this Type e) {
var values = Enum.GetValues(e);
var names = Enum.GetNames(e);
var items = new List<SelectListItem>();
for (int i = 0; i < names.Count(); i++)
{
items.Add(new SelectListItem
{
Text = names[i],
Value = ((int)values.GetValue(i)).ToString()
});
}
return new SelectList(items);
}
public static SelectList ToSelectList<T>(this IEnumerable<T> itemsToMap, Func<T, string> textProperty, Func<T, string> valueProperty)
{
var result = new List<SelectListItem>();
foreach (var item in itemsToMap)
{
result.Add(new SelectListItem
{
Value = valueProperty(item),
Text = textProperty(item)
});
}
return new SelectList(result);
}
public static ModelErrorCollection ErrorsFor(this ModelStateDictionary modelState, string key)
{
var keypair = modelState.Where(d => d.Key == key).FirstOrDefault();
if (keypair.Value != null)
return keypair.Value.Errors;
else
return null;
}
}
}
|
a1747a71d6183a8731590031efd391ef0e4fa1f2
|
C#
|
HearthSim/Hearthstone-Deck-Tracker
|
/Hearthstone Deck Tracker/Utility/RegistryHelper.cs
| 2.671875
| 3
|
using System;
using System.Windows;
using Hearthstone_Deck_Tracker.Utility.Logging;
using Microsoft.Win32;
namespace Hearthstone_Deck_Tracker.Utility
{
public static class RegistryHelper
{
private const string KeyName = "Hearthstone Deck Tracker";
private static string _executablePath = Application.ResourceAssembly.Location;
private static string? _args;
private static RegistryKey GetRunKey() => Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
public static void SetRunKey()
{
if(string.IsNullOrEmpty(_executablePath))
return;
var path = $"\"{_executablePath}\"";
if(!string.IsNullOrEmpty(_args))
path += " " + _args;
try
{
using(var key = GetRunKey())
key?.SetValue(KeyName, path);
Log.Info("Set AutoRun path to " + path);
}
catch(Exception e)
{
Log.Error(e);
}
}
public static void DeleteRunKey()
{
try
{
using(var key = GetRunKey())
key?.DeleteValue(KeyName, false);
Log.Info("Deleted AutoRun key");
}
catch(Exception e)
{
Log.Error(e);
}
}
internal static void SetExecutablePath(string executablePath) => _executablePath = executablePath;
internal static void SetExecutableArgs(string args) => _args = args;
}
}
|
1d9f40e1738597e9daa6547af2f328eba3b59b7e
|
C#
|
charlesj/Archimedes
|
/app/Archimedes.Common/Extensions/TimeSpanExtensions.cs
| 2.984375
| 3
|
namespace Archimedes.Common.Extensions
{
using System;
public static class TimeSpanExtensions
{
public static int InMilliseconds(this TimeSpan ts)
{
return (int)ts.TotalMilliseconds;
}
public static DateTime Ago(this TimeSpan ts)
{
return DateTime.Now - ts;
}
public static DateTime FromNow(this TimeSpan ts)
{
return DateTime.Now + ts;
}
}
}
|
415cc890c709eb82022cfa8f1797e5592a48813a
|
C#
|
lizhen325/MIT-Data-Structures-And-Algorithms
|
/MIT/InsertionSortAndMergeSort/InsertionSortAndMergeSort/InsertionSort.cs
| 3.359375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InsertionSortAndMergeSort
{
public class InsertionSort
{
public static int[] InsertionSorting(int[] nums)
{
for(int i=1; i<nums.Length; i++)
{
for(int j=i; j>0; j--)
{
if(nums[j] < nums[j-1])
{
int temp = nums[j];
nums[j] = nums[j - 1];
nums[j - 1] = temp;
}
}
}
return nums;
}
}
}
|
1abc79d859142455778b903970c5ffbcf5c9438e
|
C#
|
govmeeting/govmeeting
|
/src/Application/Configuration_Lib/BuildConfig.cs
| 2.53125
| 3
|
using GM.Utilities;
using Microsoft.Extensions.Configuration;
using System.IO;
namespace GM.Application.Configuration
{
public static class BuildConfig
{
public static void Build(IConfigurationBuilder config, string environment)
{
// The SECRETS" folder is outside of our Github repo. In this folder is:
// appsettings.Secrets.json - secrets used in both production and development.
// appsettings.Production.json - production-only settings
// appsettings.Development.json and appsettings.Staging.jaon are stored in solution root.
// They are read by both WebApp & WorkflowApp.
// Appsettings that are set later override earlier ones.
// https://andrewlock.net/including-linked-files-from-outside-the-project-directory-in-asp-net-core/
if (environment != "Development") // Production and Staging
{
// For production, the appsettings files are in the deployment folder.
config
.AddJsonFile("appsettings.Secrets.json", optional: true)
.AddJsonFile($"appsettings.{environment}.json", optional: true);
}
else
{
// For development & staging, get the appsettings files from the SECRETS and solution folders.
// string solutionFolder = GMFileAccess.GetSolutionFolder();
string secretsFolder = GMFileAccess.GetSecretsFolder();
config
// .AddJsonFile(Path.Combine(solutionFolder, "appsettings.Development.json"), optional: true)
.AddJsonFile("appsettings.Development.json", optional: true)
.AddJsonFile(Path.Combine(secretsFolder, "appsettings.Secrets.json"), optional: true);
// if (environment == "Staging")
// {
// // The Staging build run WebApp, clientapp and the database in separate docker containers.
// config.AddJsonFile(Path.Combine(solutionFolder, "appsettings.Staging.json"), optional: true);
// }
}
// Allow appsettings to be overidden by an optional "appsettings.json" file in the project or deployment folder.
// Currently, neither WebApp nor WorkflowApp have one.
config.AddJsonFile("appsettings.json", optional: true);
// Environment settings override all else.
config.AddEnvironmentVariables();
}
}
}
|
b66eabc4df3e0fa90577341faace1c89343e75ef
|
C#
|
Dominoz251/Checkers
|
/Warcaby/Pages/Gameplay/GameplayWindow.xaml.cs
| 2.640625
| 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.Shapes;
using Newtonsoft.Json;
using Warcaby.Messages;
namespace Warcaby.Pages.Gameplay
{
/// <summary>
/// Logika interakcji dla klasy GameplayWindow.xaml
/// </summary>
public partial class GameplayWindow : Window
{
public delegate void WantMoveEventHandler(string message);
public event WantMoveEventHandler WantMove;
public delegate void MoveEventHandler(string message);
public event MoveEventHandler Move;
public delegate void DeletePawnEventHandler(string message);
public event DeletePawnEventHandler DeletePawn;
public Button[,] fields;
public Ellipse[] whitePawns;
public Ellipse[] redPawns;
public GameplayWindow()
{
WindowStartupLocation = WindowStartupLocation.CenterScreen;
InitializeComponent();
fields = new Button[8, 8] {
{A1Button, B1Button, C1Button, D1Button, E1Button, F1Button, G1Button, H1Button},
{A2Button, B2Button, C2Button, D2Button, E2Button, F2Button, G2Button, H2Button},
{A3Button, B3Button, C3Button, D3Button, E3Button, F3Button, G3Button, H3Button},
{A4Button, B4Button, C4Button, D4Button, E4Button, F4Button, G4Button, H4Button},
{A5Button, B5Button, C5Button, D5Button, E5Button, F5Button, G5Button, H5Button},
{A6Button, B6Button, C6Button, D6Button, E6Button, F6Button, G6Button, H6Button},
{A7Button, B7Button, C7Button, D7Button, E7Button, F7Button, G7Button, H7Button},
{A8Button, B8Button, C8Button, D8Button, E8Button, F8Button, G8Button, H8Button}
};
whitePawns = new Ellipse[12] { W1, W2, W3, W4, W5, W6, W7, W8, W9, W10, W11, W12 };
redPawns = new Ellipse[12] { R1, R2, R3, R4, R5, R6, R7, R8, R9, R10, R11, R12 };
}
//ewent wywolywany w momencie wskazania popla na ktore ma sie ruszyc pionek
protected virtual void OnWantMove(string message)
{
if (WantMove != null)
WantMove(message);
}
protected virtual void OnMove(string message)
{
List<PawnToDelete> pawnsToDelete = DeletePawns();
if (pawnsToDelete.Count > 0)
{
var pawnsToDeleteStr = JsonConvert.SerializeObject(pawnsToDelete);
OnDeletePawn(pawnsToDeleteStr);
}
if (Move != null)
Move(message);
}
protected virtual void OnDeletePawn(string message)
{
if (DeletePawn != null)
DeletePawn(message);
}
private List<PawnToDelete> DeletePawns()
{
List<PawnToDelete> pawnToDelete = new List<PawnToDelete>();
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.GreenYellow)
{
pawnToDelete.Add(new PawnToDelete(i, j));
}
}
}
return pawnToDelete;
}
private bool canMove()
{
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.LightGreen)
{
return false;
}
}
}
return true;
}
private void A1Button_Click(object sender, RoutedEventArgs e)
{
if (A1Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 0, 0);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[0, 0].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(0, 0);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void A2Button_Click(object sender, RoutedEventArgs e)
{
if (A2Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 1, 0);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[1,0].Background==Brushes.LightYellow)
{
WantMove pawn = new WantMove(1, 0);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void A3Button_Click(object sender, RoutedEventArgs e)
{
if (A3Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 2, 0);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[2, 0].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(2, 0);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void A4Button_Click(object sender, RoutedEventArgs e)
{
if (A4Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 3, 0);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[3, 0].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(3, 0);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void A5Button_Click(object sender, RoutedEventArgs e)
{
if (A5Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 4, 0);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[4, 0].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(4, 0);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void A6Button_Click(object sender, RoutedEventArgs e)
{
if (A6Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 5, 0);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[5, 0].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(5, 0);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void A7Button_Click(object sender, RoutedEventArgs e)
{
if (A7Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 6, 0);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[6, 0].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(6, 0);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void A8Button_Click(object sender, RoutedEventArgs e)
{
if (A8Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 7, 0);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[7, 0].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(7, 0);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void B1Button_Click(object sender, RoutedEventArgs e)
{
if (B1Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 0, 1);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[0, 1].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(0, 1);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void B2Button_Click(object sender, RoutedEventArgs e)
{
if (B2Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 1, 1);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[1, 1].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(1, 1);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void B3Button_Click(object sender, RoutedEventArgs e)
{
if (B3Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 2, 1);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[2, 1].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(2, 1);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void B4Button_Click(object sender, RoutedEventArgs e)
{
if (B4Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 3, 1);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[3, 1].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(3, 1);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void B5Button_Click(object sender, RoutedEventArgs e)
{
if (B5Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 4, 1);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[4, 1].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(4, 1);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void B6Button_Click(object sender, RoutedEventArgs e)
{
if (B6Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 5, 1);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[5, 1].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(5, 1);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void B7Button_Click(object sender, RoutedEventArgs e)
{
if (B7Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 6, 1);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[6, 1].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(6, 1);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void B8Button_Click(object sender, RoutedEventArgs e)
{
if (B8Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 7, 1);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[7, 1].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(7, 1);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void C1Button_Click(object sender, RoutedEventArgs e)
{
if (C1Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 0, 2);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[0, 2].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(0, 2);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void C2Button_Click(object sender, RoutedEventArgs e)
{
if (C2Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 1, 2);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[1, 2].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(1, 2);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void C3Button_Click(object sender, RoutedEventArgs e)
{
if (C3Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 2, 2);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[2, 2].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(2, 2);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void C4Button_Click(object sender, RoutedEventArgs e)
{
if (C4Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 3, 2);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[3, 2].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(3, 2);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void C5Button_Click(object sender, RoutedEventArgs e)
{
if (C5Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 4, 2);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[4, 2].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(4, 2);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void C6Button_Click(object sender, RoutedEventArgs e)
{
if (C6Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 5, 2);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[5, 2].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(5, 2);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void C7Button_Click(object sender, RoutedEventArgs e)
{
if (C7Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 6, 2);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[6, 2].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(6, 2);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void C8Button_Click(object sender, RoutedEventArgs e)
{
if (C8Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 7, 2);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[7, 2].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(7, 2);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void D1Button_Click(object sender, RoutedEventArgs e)
{
if (D1Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 0, 3);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[0, 3].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(0, 3);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void D2Button_Click(object sender, RoutedEventArgs e)
{
if (D2Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 1, 3);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[1, 3].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(1, 3);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void D3Button_Click(object sender, RoutedEventArgs e)
{
if (D3Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 2, 3);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[2, 3].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(2, 3);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void D4Button_Click(object sender, RoutedEventArgs e)
{
if (D4Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 3, 3);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[3, 3].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(3, 3);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void D5Button_Click(object sender, RoutedEventArgs e)
{
if (D5Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 4, 3);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[4, 3].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(4, 3);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void D6Button_Click(object sender, RoutedEventArgs e)
{
if (D6Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 5, 3);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[5, 3].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(5, 3);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void D7Button_Click(object sender, RoutedEventArgs e)
{
if (D7Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 6, 3);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[6, 3].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(6, 3);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void D8Button_Click(object sender, RoutedEventArgs e)
{
if (D8Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 7, 3);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[7, 3].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(7, 3);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void E1Button_Click(object sender, RoutedEventArgs e)
{
if (E1Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 0, 4);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[0, 4].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(0, 4);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void E2Button_Click(object sender, RoutedEventArgs e)
{
if (E2Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 1, 4);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[1, 4].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(1, 4);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void E3Button_Click(object sender, RoutedEventArgs e)
{
if (E3Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 2, 4);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[2, 4].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(2, 4);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void E4Button_Click(object sender, RoutedEventArgs e)
{
if (E4Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 3, 4);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[3, 4].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(3, 4);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void E5Button_Click(object sender, RoutedEventArgs e)
{
if (E5Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 4, 4);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[4, 4].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(4, 4);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void E6Button_Click(object sender, RoutedEventArgs e)
{
if (E6Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 5, 4);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[5, 4].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(5, 4);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void E7Button_Click(object sender, RoutedEventArgs e)
{
if (E7Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 6, 4);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[6, 4].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(6, 4);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void E8Button_Click(object sender, RoutedEventArgs e)
{
if (E8Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 7, 4);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[7, 4].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(7, 4);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void F1Button_Click(object sender, RoutedEventArgs e)
{
if (F1Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 0, 5);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[0, 5].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(0, 5);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void F2Button_Click(object sender, RoutedEventArgs e)
{
if (F2Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 1, 5);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[1, 5].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(1, 5);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void F3Button_Click(object sender, RoutedEventArgs e)
{
if (F3Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 2, 5);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[2, 5].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(2, 5);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void F4Button_Click(object sender, RoutedEventArgs e)
{
if (F4Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 3, 5);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[3, 5].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(3, 5);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void F5Button_Click(object sender, RoutedEventArgs e)
{
if (F5Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 4, 5);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[4, 5].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(4, 5);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void F6Button_Click(object sender, RoutedEventArgs e)
{
if (F6Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 5, 5);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[5, 5].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(5, 5);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void F7Button_Click(object sender, RoutedEventArgs e)
{
if (F7Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 6, 5);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[6, 5].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(6, 5);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void F8Button_Click(object sender, RoutedEventArgs e)
{
if (F8Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 7, 5);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[7, 5].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(7, 5);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void G1Button_Click(object sender, RoutedEventArgs e)
{
if (G1Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 0, 6);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[0, 6].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(0, 6);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void G2Button_Click(object sender, RoutedEventArgs e)
{
if (G2Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 1, 6);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[1, 6].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(1, 6);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void G3Button_Click(object sender, RoutedEventArgs e)
{
if (G3Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 2, 6);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[2, 6].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(2, 6);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void G4Button_Click(object sender, RoutedEventArgs e)
{
if (G4Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 3, 6);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[3, 6].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(3, 6);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void G5Button_Click(object sender, RoutedEventArgs e)
{
if (G5Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 4, 6);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[4, 6].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(4, 6);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void G6Button_Click(object sender, RoutedEventArgs e)
{
if (G6Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 5, 6);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[5, 6].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(5, 6);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void G7Button_Click(object sender, RoutedEventArgs e)
{
if (G7Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 6, 6);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[6, 6].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(6, 6);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void G8Button_Click(object sender, RoutedEventArgs e)
{
if (G8Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 7, 6);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[7, 6].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(7, 6);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void H1Button_Click(object sender, RoutedEventArgs e)
{
if (H1Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 0, 7);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[0, 7].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(0, 7);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void H2Button_Click(object sender, RoutedEventArgs e)
{
if (H2Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 1, 7);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[1, 7].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(1, 7);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void H3Button_Click(object sender, RoutedEventArgs e)
{
if (H3Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 2, 7);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[2, 7].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(2, 7);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void H4Button_Click(object sender, RoutedEventArgs e)
{
if (H4Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 3, 7);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[3, 7].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(3, 7);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void H5Button_Click(object sender, RoutedEventArgs e)
{
if (H5Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 4, 7);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[4, 7].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(4, 7);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void H6Button_Click(object sender, RoutedEventArgs e)
{
if (H6Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 5, 7);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[5, 7].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(5, 7);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void H7Button_Click(object sender, RoutedEventArgs e)
{
if (H7Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 6, 7);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[6, 7].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(6, 7);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
private void H8Button_Click(object sender, RoutedEventArgs e)
{
if (H8Button.Background == Brushes.Blue)
{
Move move;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (fields[i, j].Background == Brushes.Yellow)
{
move = new Move(i, j, 7, 7);
string moveStr = JsonConvert.SerializeObject(move);
OnMove(moveStr);
}
}
}
}
else if (canMove() || fields[7, 7].Background == Brushes.LightYellow)
{
WantMove pawn = new WantMove(7, 7);
var pawnStr = JsonConvert.SerializeObject(pawn);
OnWantMove(pawnStr);
}
}
}
}
|
a913f3baad94a6e65b9a75a5ad0cbd88edd4a89f
|
C#
|
dungnguyentien0409/competitive-programming
|
/C#/940. Distinct Subsequences II.cs
| 3.375
| 3
|
// Link: https://leetcode.com/problems/distinct-subsequences-ii/
// Author: Dung Nguyen Tien (Chris)
public class Solution {
public int DistinctSubseqII(string S) {
// dp[i] is the total of subset from S having the len i
var dp = createDP(S);
var last = createLast();
int max = 1000000007;
// the empty string
dp[0] = 1;
for (var i = 1; i <= S.Length; i++) {
dp[i] = dp[i - 1] * 2 % max;
// if the character is duplicate, then substract
var iLast = S[i - 1] - 'a';
if (last[iLast] >= 0) {
dp[i] -= dp[last[iLast] - 1];
}
dp[i] %= max;
last[iLast] = i;
Console.WriteLine(dp[i]);
}
// substract the empty string
dp[S.Length] -= 1;
if (dp[S.Length] < 0) dp[S.Length] += max;
return dp[S.Length];
}
int[] createDP(string S) {
var dp = new int[S.Length + 1];
for (var i = 1; i <= S.Length; i++) {
dp[i] = 0;
}
return dp;
}
int[] createLast() {
var last = new int[27];
for (var i = 0; i < 27; i++) {
last[i] = -1;
}
return last;
}
}
|
86d0ed8bd13f4a5d45e0ff7a0234467706ee6890
|
C#
|
RobsonAdorno/TrabalhoBiblioteca
|
/Biblioteca/Biblioteca/DAL/VendedorDAO.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Biblioteca.Model;
namespace Biblioteca.DAL
{
class VendedorDAO
{
private static Context ctx = SingletonContext.GetInstance();
public static Vendedor BuscarVendedorPorCPF(Vendedor v)
{
return ctx.Vendedores.FirstOrDefault(x => x.CPF.Equals(v.CPF));
}
public static Vendedor BuscarVendedorPorLogin(Vendedor v)
{
return ctx.Vendedores.FirstOrDefault(x => x.Login.Equals(v.Login));
}
public static bool ValidarCPF(Vendedor v)
{
if (BuscarVendedorPorCPF(v) != null)
{
return false;
}else if (BuscarVendedorPorLogin(v) != null)
{
return false;
}
return true;
}
public static bool Cadastrar(Vendedor v)
{
if (!ValidarCPF(v))
{
return false;
}
ctx.Vendedores.Add(v);
ctx.SaveChanges();
return true;
}
public static List<Vendedor> Listagem()
{
return ctx.Vendedores.ToList();
}
public static bool EfetuarLogin(string login, string senha)
{
Vendedor a = ctx.Vendedores.FirstOrDefault(x => x.Login.Equals(login));
Vendedor b = ctx.Vendedores.FirstOrDefault(x => x.Senha.Equals(senha));
if (a != null && b != null)
{
return true;
}
return false;
}
}
}
|
7159a4b1cd0cdbb1272c67a39f9f40a0c9a1fdda
|
C#
|
InvaderZim85/AppzManagerV4
|
/AppzManagerV4/Business/FormManager.cs
| 2.546875
| 3
|
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using AppzManagerV4.DataObjects;
using AppzManagerV4.Forms;
using AppzManagerV4.Global;
using TAFactory.IconPack;
namespace AppzManagerV4.Business
{
public static class FormManager
{
/// <summary>
/// Contains the data maanger
/// </summary>
private static readonly DataManager DataManager = new DataManager();
/// <summary>
/// Creates the listview for the apps
/// </summary>
/// <param name="listView">The list view</param>
/// <param name="appList">The app list</param>
/// <param name="imgList">The image list</param>
public static void CreateListView(ref ListView listView, ref List<AppModel> appList, ImageList imgList)
{
if (!appList.Any())
return;
var deletedList = new List<AppModel>();
var count = imgList.Images.Count;
listView.Items.Clear();
foreach (var app in appList.OrderBy(o => o.Name))
{
var addEntry = true;
var error = false;
if (!File.Exists(app.Path))
{
if (MessageBox.Show(
$"Der Pfad der Anwedung \"{app.Name}\" (Pfad: {app.Path}) konnte nicht gefunden werden. Soll der Eintrag entfernt werden?",
"Anwendung - Fehler", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
deletedList.Add(app);
addEntry = false;
}
error = true;
app.Error = true;
}
if (!addEntry)
continue;
listView.Items.Add(CreateListViewItem(GlobalEnums.RegionType.App, listView, app, error, imgList, count));
count++;
}
foreach (var entry in deletedList)
{
appList.Remove(entry);
DataManager.DeleteApp(entry);
}
}
/// <summary>
/// Creates the listview for the folders
/// </summary>
/// <param name="listView">The list viewq</param>
/// <param name="folderList">The folder list</param>
/// <param name="imageList">The image list</param>
public static void CreateListView(ref ListView listView, ref List<FolderModel> folderList, ImageList imageList)
{
if (!folderList.Any())
return;
var deleteList = new List<FolderModel>();
var count = imageList.Images.Count;
listView.Items.Clear();
foreach (var folder in folderList)
{
var addEntry = true;
var error = false;
if (!Directory.Exists(folder.Path))
{
if (MessageBox.Show(
$"Der Pfad des Ordners {folder.Name} (Pfad: {folder.Path}) konnte nicht gefunden werden. Soll der Eintrag entfernt werden?",
"Ordner", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
deleteList.Add(folder);
addEntry = false;
}
error = true;
folder.Error = true;
}
if (addEntry)
{
listView.Items.Add(CreateListViewItem(GlobalEnums.RegionType.Folder, listView, folder, error, imageList, count));
count++;
}
}
foreach (var entry in deleteList)
{
folderList.Remove(entry);
DataManager.DeleteFolder(entry);
}
}
/// <summary>
/// Creates the listview for the files
/// </summary>
/// <param name="listView">The list view</param>
/// <param name="fileList">The file list</param>
/// <param name="imageList">The image list</param>
public static void CreateListView(ref ListView listView, ref List<FileModel> fileList, ImageList imageList)
{
if (!fileList.Any())
return;
var deleteList = new List<FileModel>();
var count = imageList.Images.Count;
listView.Items.Clear();
foreach (var file in fileList)
{
var addEntry = true;
var error = false;
if (!File.Exists(file.Path))
{
if (MessageBox.Show(
$"Der Pfad der Datei {file.Name} (Pfad: {file.Path}) konnte nicht gefunden werden. Soll der Eintrag entfernt werden?",
"Ordner", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
deleteList.Add(file);
addEntry = false;
}
error = true;
file.Error = true;
}
if (addEntry)
{
listView.Items.Add(CreateListViewItem(GlobalEnums.RegionType.File, listView, file, error, imageList,
count));
count++;
}
}
foreach (var entry in deleteList)
{
fileList.Remove(entry);
DataManager.DeleteFile(entry);
}
}
/// <summary>
/// Creates a new list view entry
/// </summary>
/// <param name="region">The region</param>
/// <param name="listView">The list view</param>
/// <param name="entry">The current entry</param>
/// <param name="error">true if the entry has an error, otherwise false</param>
/// <param name="imgList">The image list</param>
/// <param name="count">The current count</param>
/// <returns>The new list view item</returns>
private static ListViewItem CreateListViewItem(GlobalEnums.RegionType region, ListView listView, dynamic entry,
bool error, ImageList imgList, int count)
{
var name = entry.Name;
if (region == GlobalEnums.RegionType.App && entry.Autostart)
name += "*";
var item = new ListViewItem(name) {Tag = entry};
item.SubItems.Add(string.IsNullOrEmpty(entry.Shortcut) ? "" : $"STRG + {entry.Shortcut}");
if (region == GlobalEnums.RegionType.App)
item.SubItems.Add(entry.Version);
item.SubItems.Add(entry.Comment);
item.SubItems.Add(entry.Path);
if (region == GlobalEnums.RegionType.App)
{
item.SubItems.Add(entry.ExecuteIn);
item.SubItems.Add(entry.Parameter);
}
item.SubItems.Add(entry.ShowInContextMenu ? "Ja" : "Nein");
if (region == GlobalEnums.RegionType.App)
item.SubItems.Add(entry.Autostart ? "Ja" : "Nein");
if (error)
{
imgList.Images.Add(Properties.Resources.error);
item.ImageIndex = count;
item.ForeColor = Color.Red;
}
else
{
if (region == GlobalEnums.RegionType.App)
{
imgList.Images.Add(string.IsNullOrEmpty(entry.IconPath)
? Functions.ExtractIcon(entry.Path)
: Image.FromFile(entry.IconPath));
}
else if (region == GlobalEnums.RegionType.Folder)
{
imgList.Images.Add(string.IsNullOrEmpty(entry.IconPath)
? Properties.Resources.Folder
: Image.FromFile(entry.IconPath));
}
else if (region == GlobalEnums.RegionType.File)
{
imgList.Images.Add(Functions.GetFileIcon(entry.Path));
}
item.ImageIndex = count;
entry.ImageIndex = count;
}
item.ToolTipText = entry.Name;
if (!string.IsNullOrEmpty(entry.Comment))
item.ToolTipText += $"\r\nBeschreibung: {entry.Comment}";
if (!string.IsNullOrEmpty(entry.Shortcut))
item.ToolTipText += $"\r\nShortcut: {entry.Shortcut}";
// Get the group
foreach (var group in listView.Groups.OfType<ListViewGroup>())
{
var groupEntry = group.Tag as GroupModel;
if (groupEntry != null)
{
if (groupEntry.Id == entry.GroupId)
item.Group = group;
}
}
return item;
}
/// <summary>
/// Creates the context menu for the notify icon
/// </summary>
/// <param name="contextMenu">The context menu</param>
/// <param name="appList">The app list</param>
/// <param name="folderList">The folder list</param>
/// <param name="groupList">The group list</param>
/// <param name="imgList">The image list</param>
/// <param name="fileList">The file list</param>
/// <param name="icon">The icon</param>
public static void CreateNotifyIcon(ref ContextMenuStrip contextMenu, List<AppModel> appList,
List<FolderModel> folderList, List<FileModel> fileList, List<GroupModel> groupList, ImageList imgList, Icon icon)
{
contextMenu.Items.Clear();
var headerItem = new ToolStripMenuItem("AppzManager V4")
{
Name = "HeaderItem",
ToolTipText = "AppzManager",
Image = icon.ToBitmap()
};
contextMenu.Items.Add(headerItem);
foreach (var group in groupList)
{
var tmpAppList = appList.Where(w => w.GroupId == group.Id && w.ShowInContextMenu && !w.Error).ToList();
if (tmpAppList.Any())
{
if (contextMenu.Items.Count > 0)
contextMenu.Items.Add(new ToolStripSeparator());
var items = CreateItems(GlobalEnums.RegionType.App, tmpAppList, imgList);
if (items != null)
contextMenu.Items.AddRange(items);
}
var tmpFolderList =
folderList.Where(w => w.GroupId == group.Id && w.ShowInContextMenu && !w.Error).ToList();
if (tmpFolderList.Any())
{
if (contextMenu.Items.Count > 0)
contextMenu.Items.Add(new ToolStripSeparator());
var items = CreateItems(GlobalEnums.RegionType.Folder, tmpFolderList, imgList);
if (items != null)
contextMenu.Items.AddRange(items);
}
var tmpFileList = fileList.Where(w => w.GroupId == group.Id && w.ShowInContextMenu && !w.Error).ToList();
if (tmpFileList.Any())
{
if (contextMenu.Items.Count > 0)
contextMenu.Items.Add(new ToolStripSeparator());
var items = CreateItems(GlobalEnums.RegionType.File, tmpFileList, imgList);
if (items != null)
contextMenu.Items.AddRange(items);
}
}
contextMenu.Items.AddRange(CreateMainMenuItems());
}
/// <summary>
/// Creates new items for the context menu
/// </summary>
/// <param name="region">The region</param>
/// <param name="entryList">The entry list</param>
/// <param name="imgList">The image list</param>
/// <returns>An array with the items</returns>
private static ToolStripItem[] CreateItems(GlobalEnums.RegionType region, object entryList, ImageList imgList)
{
if (region == GlobalEnums.RegionType.App)
{
var tmpList = entryList as List<AppModel>;
if (tmpList == null)
return null;
var result = new ToolStripItem[tmpList.Count];
var count = 0;
foreach (var entry in tmpList)
{
var menuItem = new ToolStripMenuItem(entry.Autostart
? $"{entry.Name}*"
: entry.Name)
{
Tag = entry,
Image = imgList.Images[entry.ImageIndex],
ToolTipText =
string.IsNullOrEmpty(entry.Comment) ? entry.Name : $"{entry.Name} - {entry.Comment}"
};
if (entry.ColorCode != "255,255,255")
menuItem.BackColor = entry.ColorCode.ToColor();
menuItem.ForeColor = Functions.GetContrastColor(entry.ColorCode.ToColor());
result[count++] = menuItem;
}
return result;
}
if (region == GlobalEnums.RegionType.Folder)
{
var tmpList = entryList as List<FolderModel>;
if (tmpList == null)
return null;
var result = new ToolStripItem[tmpList.Count];
var count = 0;
foreach (var entry in tmpList)
{
var menuItem = new ToolStripMenuItem(entry.Name)
{
Tag = entry,
Image = imgList.Images[entry.ImageIndex],
ToolTipText =
string.IsNullOrEmpty(entry.Comment) ? entry.Name : $"{entry.Name} - {entry.Comment}"
};
if (entry.ColorCode != "255,255,255")
menuItem.BackColor = entry.ColorCode.ToColor();
menuItem.ForeColor = Functions.GetContrastColor(entry.ColorCode.ToColor());
result[count++] = menuItem;
}
return result;
}
if (region == GlobalEnums.RegionType.File)
{
var tmpList = entryList as List<FileModel>;
if (tmpList == null)
return null;
var result = new ToolStripItem[tmpList.Count];
var count = 0;
foreach (var entry in tmpList)
{
var menuItem = new ToolStripMenuItem(entry.Name)
{
Tag = entry,
Image = imgList.Images[entry.ImageIndex],
ToolTipText =
string.IsNullOrEmpty(entry.Comment) ? entry.Name : $"{entry.Name} - {entry.Comment}"
};
if (entry.ColorCode != "255,255,255")
menuItem.BackColor = entry.ColorCode.ToColor();
menuItem.ForeColor = Functions.GetContrastColor(entry.ColorCode.ToColor());
result[count++] = menuItem;
}
return result;
}
return null;
}
/// <summary>
/// Creates the "main" menu for the context menu
/// </summary>
/// <returns>An array with the items</returns>
private static ToolStripItem[] CreateMainMenuItems()
{
var result = new ToolStripItem[3];
var newItem = new ToolStripMenuItem("Neuer Eintrag")
{
Tag = null,
Image = Properties.Resources.Plus,
ToolTipText = "Neuer Eintrag",
Name = "NewItem"
};
var newApp = new ToolStripMenuItem("Anwendung")
{
Tag = null,
Image = Properties.Resources.Plus,
ToolTipText = "Neuer Eintrag - Anwendung",
Name = "NewAppItem"
};
var newFolder = new ToolStripMenuItem("Ordner")
{
Tag = null,
Image = Properties.Resources.Plus,
ToolTipText = "Neuer Eintrag - Ordner",
Name = "NewFolderItem"
};
var newFile = new ToolStripMenuItem("Datei")
{
Tag = null,
Image = Properties.Resources.Plus,
ToolTipText = "Neuer Eintrag - Datei",
Name = "NewFileItem"
};
var closeItem = new ToolStripMenuItem("Beenden")
{
Tag = null,
Image = Properties.Resources.Close,
ToolTipText = "Beendet das Programm",
Name = "CloseItem"
};
newItem.DropDownItems.AddRange(new ToolStripItem[] { newApp, newFolder, newFile });
result[0] = new ToolStripSeparator();
result[1] = newItem;
result[2] = closeItem;
return result;
}
/// <summary>
/// Creates a new entry
/// </summary>
/// <param name="region">The region</param>
/// <param name="entryList">The entry list</param>
/// <param name="filepathList">The filepath list</param>
public static void CreateNewEntry(GlobalEnums.RegionType region, object entryList,
List<string> filepathList = null)
{
var addForm = new FormAdd(region, entryList);
if (filepathList == null)
addForm.ShowDialog();
else
{
filepathList.ForEach(entry =>
{
addForm.Path = entry;
addForm.ShowDialog();
});
}
}
/// <summary>
/// Edits an existing entry
/// </summary>
/// <param name="region">The region</param>
/// <param name="entryList">The entry list</param>
/// <param name="entry">The entry</param>
/// <returns>true if successful, otherwise false</returns>
public static bool EditEntry(GlobalEnums.RegionType region, object entryList, object entry)
{
if (entry == null)
return false;
var addForm = new FormAdd(region, entryList, entry);
return addForm.ShowDialog() != DialogResult.Cancel;
}
}
}
|
bce825ddea730d8c2fd29acd4952d66a4409a91b
|
C#
|
92-Theo/demo-xamarin
|
/signalr-chat/SignalRChatDemo/Sample.WebSocket/Models/EventArgs.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Text;
namespace Sample.WebSocket.Models
{
public class ReceivedMessageEventArgs : System.EventArgs
{
public string IP { get; set; }
public string Message { get; set; }
public override string ToString()
{
return $"[{IP}]{Message}";
}
}
public class ChangedSockStateEventArgs : System.EventArgs
{
public string IP { get; set; }
public WebSocketState NewState { get; set; }
public WebSocketState OldState { get; set; }
public override string ToString()
{
return $"[{IP}] {OldState} >>> {NewState}";
}
}
public class OccuredErrorEventArgs : EventArgs
{
public enum ErrorCode
{
Default, Exception
}
public Exception Exception { get; set; }
public string Message { get; set; }
public ErrorCode Code { get; set; } = ErrorCode.Default;
}
}
|
db1f93e30a92f090fd1a3142adeb78a485144f6c
|
C#
|
jaskarans-optimus/Induction
|
/Dot Net Induction/Design Patterns/MVC/MVCusingWinForms/MVCusingWinForms/Models/SystemModel.cs
| 2.828125
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MVCusingWinForms.Views;
namespace MVCusingWinForms.Models
{
public class SystemModel
{
private ArrayList views = new ArrayList();
public SystemModel(string name, float minRam, float minDisk, float CpuSpeed)
{
MinRam = minRam;
MinDisk = minDisk;
this.CpuSpeed = CpuSpeed;
Name = name;
Ram = minRam;
Disk = minDisk;
}
public string Name { get; set; }
public float Ram { get; set; }
public float Disk { get; set; }
public float MinRam { get; set; }
public float MinDisk { get; set; }
public float CpuSpeed { get; set; }
public void UpdateModel(float ram, float disk, float cpuSpeed)
{
Ram += ram;
Disk += disk;
CpuSpeed += cpuSpeed;
this.NotifyObservers();
}
public void AddObserver(SystemView view)
{
views.Add(view);
}
public void RemoveObserver(SystemView view)
{
views.Remove(view);
}
public void NotifyObservers()
{
foreach (SystemView view in views)
{
view.Update(this);
}
}
}
}
|
ce84e58e39f2acf114e11ca990f4d3e9a8c7d03d
|
C#
|
RattsDen/Brainfarm
|
/BrainfarmService/LoginTokenManager.cs
| 2.953125
| 3
|
using BrainfarmService.Data;
using JWT;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;
namespace BrainfarmService
{
/*
* This class handles the generation and validation of JSON Web Tokens (JWTs)
* used to validate the user with the service.
*
* JWTs store the session information (UserID) inside themselves and are stored
* client side. This allows multiple instances of the service to be created
* without needing to share user session data between them, because the client
* is storing it themselves.
*
* JWTs can be stored on the client side safely because they are given a
* cryptographic signature by the server, ensuring that the token was created
* by an instance of the service.
*
* In exchange for scalability, the use of JWTs removes some control over
* sessions from the server side. For instance: logging out simply means having
* the client discard their token - the token will still remain valid until it
* expires. It also means that "keep me signed in" just means having a long
* expiration time (because a token that can never expire is *super* insecure)
*/
public static class LoginTokenManager
{
private static DateTime unixEpoch = new DateTime(1970, 1, 1);
private static int shortExpireTime = int.Parse(ConfigurationManager.AppSettings["shortExpireTime"]);
private static int shortRefreshTime = int.Parse(ConfigurationManager.AppSettings["shortRefreshTime"]);
private static int longExpireTime = int.Parse(ConfigurationManager.AppSettings["longExpireTime"]);
private static int longRefreshTime = int.Parse(ConfigurationManager.AppSettings["longRefreshTime"]);
private static string secret = ConfigurationManager.AppSettings["jwtSecret"];
public static string GenerateToken(int userID, bool isPersistent)
{
int exp, refreshExp;
if (isPersistent)
{
exp = longExpireTime;
refreshExp = longRefreshTime;
}
else
{
exp = shortExpireTime;
refreshExp = shortRefreshTime;
}
Dictionary<string, object> claims = new Dictionary<string,object>();
claims.Add("UserID", userID);
claims.Add("IsPersistent", isPersistent);
// Store time as seconds since unix epoch, as is JWT standard (for some reason)
claims.Add("exp", (int)(DateTime.UtcNow.AddMinutes(exp) - unixEpoch).TotalSeconds);
claims.Add("refreshExp", (int)(DateTime.UtcNow.AddMinutes(refreshExp) - unixEpoch).TotalSeconds);
return JsonWebToken.Encode(claims, secret, JwtHashAlgorithm.HS256);
}
public static int ValidateToken(string token)
{
if(token == "")
{
throw new EmptyTokenException();
}
try
{
Dictionary<string, object> claims
= JsonWebToken.DecodeToObject<Dictionary<string, object>>(token, secret, true);
// Check that token is not expired
DateTime exp = unixEpoch.AddSeconds((int)claims["exp"]);
if (exp < DateTime.UtcNow)
throw new TokenExpiredException();
return (int)claims["UserID"];
}
catch
{
throw new MalformedTokenException();
}
}
// If token is not expired, return the same token
// If token is expired and valid for refresh, return new token
// If token is not valid for refresh, throw exception
public static string RenewToken(string token)
{
try
{
Dictionary<string, object> claims
= JsonWebToken.DecodeToObject<Dictionary<string, object>>(token, secret, true);
// Check whether or not the token is expired
DateTime exp = unixEpoch.AddSeconds((int)claims["exp"]);
if (exp < DateTime.UtcNow)
{
// If the token is expired, see if it can be refreshed
DateTime refreshExp = unixEpoch.AddSeconds((int)claims["refreshExp"]);
if (refreshExp >= DateTime.UtcNow)
{
int userID = (int)claims["UserID"];
bool isPersistent = (bool)claims["IsPersistent"];
return GenerateToken(userID, isPersistent);
}
else
{
throw new TokenExpiredException();
}
}
else
{
// Token is not expired, return original token
return token;
}
}
catch
{
throw new MalformedTokenException();
}
}
}
public class TokenExpiredException : Exception { }
public class MalformedTokenException : Exception { }
public class EmptyTokenException : Exception { }
}
|
091db9b13bc9aad70720a67671c433d0d10de5df
|
C#
|
static-motion/Softuni
|
/Algorithms-Exam-Preparation/Sticks/Program.cs
| 3.484375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Sticks
{
class Program
{
static void Main()
{
int sticks = int.Parse(Console.ReadLine());
int stickPlacings = int.Parse(Console.ReadLine());
Dictionary<int, HashSet<int>> reverseGraph = new Dictionary<int, HashSet<int>>();
BuildGraphs(sticks, stickPlacings, reverseGraph);
List<int> removed = RemoveOrphanNodes(reverseGraph);
if (removed.Count < sticks)
{
Console.WriteLine("Cannot lift all sticks");
}
Console.WriteLine(string.Join(" ", removed));
}
private static List<int> RemoveOrphanNodes(Dictionary<int, HashSet<int>> reverseGraph)
{
var itemToRemove = reverseGraph
.Where(x => x.Value.Count == 0)
.OrderByDescending(x => x.Key)
.FirstOrDefault();
List<int> removed = new List<int>();
while (!itemToRemove.Equals(default(KeyValuePair<int, HashSet<int>>)))
{
reverseGraph.Remove(itemToRemove.Key);
foreach (var node in reverseGraph)
{
node.Value.Remove(itemToRemove.Key);
}
removed.Add(itemToRemove.Key);
itemToRemove = reverseGraph
.Where(x => x.Value.Count == 0)
.OrderByDescending(x => x.Key)
.FirstOrDefault();
}
return removed;
}
private static void BuildGraphs(int sticks, int stickPlacings, Dictionary<int, HashSet<int>> reverseGraph)
{
for (int i = 0; i < sticks; i++)
{
reverseGraph.Add(i, new HashSet<int>());
}
for (int i = 0; i < stickPlacings; i++)
{
int[] connections = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
reverseGraph[connections[1]].Add(connections[0]);
}
}
}
}
|
e221ff809827d9842ea6fcdfb9bff0e8f9a78b51
|
C#
|
henriTai/TrafficSystem
|
/Scripts/WaypointTool/TrafficAIScripts/StraightRoadTrafficLightUpdater.cs
| 2.546875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// A patch script for unfinished traffic light / crosswalk system. Attach this script to a straight road-object with
/// crosswalks and traffic lights. This simply handles updating traffic light controller (which is usually handled by
/// intersection controller).
/// </summary>
public class StraightRoadTrafficLightUpdater : MonoBehaviour
{
/// <summary>
/// Traffic light controller attached to this gameobject.
/// </summary>
private ICTrafficLightController trafficLightController;
/// <summary>
/// Is there a traffic light controller attached to this gameobject?
/// </summary>
bool active = false;
// Start is called before the first frame update
void Start()
{
trafficLightController = GetComponent<ICTrafficLightController>();
if (trafficLightController != null)
{
active = true;
}
}
// Update is called once per frame
void Update()
{
if (active)
{
trafficLightController.UpdateActiveController(Time.deltaTime);
}
}
}
|
ac203ac039ef072cfbb875ef5b557cf6f637a41d
|
C#
|
Opiumtm/DvachBrowser3
|
/DvachBrowser3.Core/Engines/Common/HttpPostEngineOperationBase.cs
| 2.65625
| 3
|
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Windows.Web.Http;
namespace DvachBrowser3.Engines
{
/// <summary>
/// Операция движка HTTP POST.
/// </summary>
/// <typeparam name="T">Тип результата.</typeparam>
/// <typeparam name="TParam">Тип параметра.</typeparam>
public abstract class HttpPostEngineOperationBase<T, TParam> : HttpEngineOperationBase<T, TParam>
{
/// <summary>
/// Конструктор.
/// </summary>
/// <param name="parameter">Параметр.</param>
/// <param name="services">Сервисы.</param>
protected HttpPostEngineOperationBase(TParam parameter, IServiceProvider services)
: base(parameter, services)
{
}
/// <summary>
/// Выполнить операцию.
/// </summary>
/// <param name="client">Клиент.</param>
/// <param name="token">Токен отмены.</param>
/// <returns>Операция.</returns>
protected sealed override async Task<T> DoComplete(HttpClient client, CancellationToken token)
{
var uri = GetRequestUri();
var content = await GetPostContent();
var operation = client.PostAsync(uri, content).AsTask(token, new Progress<HttpProgress>(HttpOperationProgress));
using (var message = await operation)
{
return await DoComplete(message, token);
}
}
/// <summary>
/// Получить контент для постинга.
/// </summary>
/// <returns>Контент.</returns>
protected abstract Task<IHttpContent> GetPostContent();
/// <summary>
/// Выполнить операцию.
/// </summary>
/// <param name="message">Сообщение.</param>
/// <param name="token">Токен отмены.</param>
/// <returns>Операция.</returns>
protected abstract Task<T> DoComplete(HttpResponseMessage message, CancellationToken token);
}
}
|
acd6bc093d6e336288a7645c226652c9b883ed14
|
C#
|
sermetk/XFOouiSignalRSample
|
/OouiSignalRSample/Behaviors/ListViewScrollBehavior.cs
| 2.578125
| 3
|
using System.Linq;
using Xamarin.Forms;
namespace OouiSignalRSample.Behaviors
{
public class ListViewScrollBehaviour : Behavior<ListView>
{
protected override void OnAttachedTo(ListView bindable)
{
base.OnAttachedTo(bindable);
bindable.ItemAppearing += OnItemAppearing;
}
protected override void OnDetachingFrom(ListView bindable)
{
base.OnDetachingFrom(bindable);
bindable.ItemAppearing -= OnItemAppearing;
}
private void OnItemAppearing(object sender, ItemVisibilityEventArgs e)
{
var listView = (ListView)sender;
if (listView.ItemsSource != null)
{
var lastItem = listView.ItemsSource.Cast<object>().LastOrDefault();
listView.ScrollTo(lastItem, ScrollToPosition.End, false);
}
}
}
}
|
1c6ae9c84ce5a9f2530b748ce043b89b634b3efc
|
C#
|
penma/sdbprof
|
/sdbprof/AssemblyInfo.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace sdbprof
{
class AssemblyInfo
{
public String name;
public String location;
/* TODO more fields? */
public String GoodFilename
{
get
{
if (location.StartsWith("data-"))
{
return String.Format("{0} ({1})", location, name);
}
else
{
return String.Format("{0} ({1})", Path.GetFileName(location), location);
}
}
}
/* TODO: Equals for checking the methodId behind it, so that method infos compare properly
* (methodIds are supposed to be unique across a debugging session)
*/
/* Queries the debugger for information about this method ID */
public static AssemblyInfo Query(UInt32 assemblyId)
{
AssemblyInfo ai = new AssemblyInfo();
AssemblyGetNameReply reName = Program.sdb.SendPacketToStreamSync(new AssemblyGetNameRequest(assemblyId)) as AssemblyGetNameReply;
ai.name = reName.assemblyName;
AssemblyGetLocationReply reLocation = Program.sdb.SendPacketToStreamSync(new AssemblyGetLocationRequest(assemblyId)) as AssemblyGetLocationReply;
ai.location = reLocation.location;
return ai;
}
/* Cached method info */
private static Dictionary<UInt32, AssemblyInfo> assemblyInfos = new Dictionary<uint, AssemblyInfo>();
public static AssemblyInfo GetOrQueryAssemblyInfo(UInt32 assemblyId)
{
if (!assemblyInfos.ContainsKey(assemblyId))
{
assemblyInfos[assemblyId] = Query(assemblyId);
}
return assemblyInfos[assemblyId];
}
}
}
|
bb9e05413caa8ca8994c4b2a6e0601be64259879
|
C#
|
fasteddys/Birdie.Tesseract
|
/tvn-cosine.ai/tvn-cosine.ai/environment/wumpusworld/WumpusCave.cs
| 3.09375
| 3
|
using tvn.cosine.collections;
using tvn.cosine.collections.api;
using tvn.cosine.exceptions;
namespace tvn.cosine.ai.environment.wumpusworld
{
/**
* Artificial Intelligence A Modern Approach (3rd Edition): page 236.<br>
* <br>
* The <b>wumpus world</b> is a cave consisting of rooms connected by
* passageways. The rooms are always organized into a grid. See Figure 7.2 for
* an example.
*
* @author Federico Baron
* @author Alessandro Daniele
* @author Ciaran O'Reilly
*/
public class WumpusCave
{
private int caveXDimension; // starts bottom left -> right
private int caveYDimension; // starts bottom left ^ up
private ISet<AgentPosition> allowedPositions = CollectionFactory.CreateSet<AgentPosition>();
/**
* Default Constructor. Create a Wumpus Case of default dimensions 4x4.
*/
public WumpusCave()
: this(4, 4)
{ }
/**
* Create a grid of rooms of dimensions x and y, representing the wumpus's
* cave.
*
* @param caveXDimension
* the cave's x dimension.
* @param caveYDimension
* the cave's y dimension.
*/
public WumpusCave(int caveXDimension, int caveYDimension)
: this(caveXDimension, caveYDimension, defaultAllowedPositions(caveXDimension, caveYDimension))
{ }
/**
* Create a grid of rooms of dimensions x and y, representing the wumpus's
* cave.
*
* @param caveXDimension
* the cave's x dimension.
* @param caveYDimension
* the cave's y dimension.
* @param allowedPositions
* the set of legal agent positions that can be reached within
* the cave.
*/
public WumpusCave(int caveXDimension, int caveYDimension,
ISet<AgentPosition> allowedPositions)
{
if (caveXDimension < 1)
{
throw new IllegalArgumentException("Cave must have x dimension >= 1");
}
if (caveYDimension < 1)
{
throw new IllegalArgumentException("Case must have y dimension >= 1");
}
this.caveXDimension = caveXDimension;
this.caveYDimension = caveYDimension;
this.allowedPositions.AddAll(allowedPositions);
}
public int getCaveXDimension()
{
return caveXDimension;
}
public int getCaveYDimension()
{
return caveYDimension;
}
public ICollection<AgentPosition> getLocationsLinkedTo(AgentPosition fromLocation)
{
int x = fromLocation.getX();
int y = fromLocation.getY();
AgentPosition.Orientation orientation = fromLocation.getOrientation();
ICollection<AgentPosition> result = CollectionFactory.CreateQueue<AgentPosition>();
AgentPosition currentForwardNorth = new AgentPosition(x, y + 1,
AgentPosition.Orientation.FACING_NORTH);
AgentPosition currentForwardSouth = new AgentPosition(x, y - 1,
AgentPosition.Orientation.FACING_SOUTH);
AgentPosition currentForwardEast = new AgentPosition(x + 1, y,
AgentPosition.Orientation.FACING_EAST);
AgentPosition currentForwardWest = new AgentPosition(x - 1, y,
AgentPosition.Orientation.FACING_WEST);
AgentPosition currentNorth = new AgentPosition(x, y,
AgentPosition.Orientation.FACING_NORTH);
AgentPosition currentSouth = new AgentPosition(x, y,
AgentPosition.Orientation.FACING_SOUTH);
AgentPosition currentEast = new AgentPosition(x, y,
AgentPosition.Orientation.FACING_EAST);
AgentPosition currentWest = new AgentPosition(x, y,
AgentPosition.Orientation.FACING_WEST);
if (orientation.Equals(AgentPosition.Orientation.FACING_NORTH))
{
addIfAllowed(currentForwardNorth, result);
addIfAllowed(currentEast, result);
addIfAllowed(currentWest, result);
}
else if (orientation.Equals(AgentPosition.Orientation.FACING_SOUTH))
{
addIfAllowed(currentForwardSouth, result);
addIfAllowed(currentEast, result);
addIfAllowed(currentWest, result);
}
else if (orientation.Equals(AgentPosition.Orientation.FACING_EAST))
{
addIfAllowed(currentNorth, result);
addIfAllowed(currentSouth, result);
addIfAllowed(currentForwardEast, result);
}
else if (orientation.Equals(AgentPosition.Orientation.FACING_WEST))
{
addIfAllowed(currentNorth, result);
addIfAllowed(currentSouth, result);
addIfAllowed(currentForwardWest, result);
}
return result;
}
private static ISet<AgentPosition> defaultAllowedPositions(int caveXDimension, int caveYDimension)
{
ISet<AgentPosition> allowedPositions = CollectionFactory.CreateSet<AgentPosition>();
// Create the default set of allowed positions within the cave that
// an agent may occupy.
for (int x = 1; x <= caveXDimension; x++)
{
for (int y = 1; y <= caveYDimension; y++)
{
foreach (AgentPosition.Orientation orientation in AgentPosition.Orientation.values())
{
allowedPositions.Add(new AgentPosition(x, y, orientation));
}
}
}
return allowedPositions;
}
private void addIfAllowed(AgentPosition position, ICollection<AgentPosition> positions)
{
if (allowedPositions.Contains(position))
{
positions.Add(position);
}
}
}
}
|
f15fcdd866e38fc7be37d3713de9e5345a4d1754
|
C#
|
sumtotal-services/OAuth2ODataSample
|
/OAuth2ODataSample/B2BGrantOauth.cs
| 2.71875
| 3
|
using Newtonsoft.Json;
using System;
using System.Configuration;
using System.IO;
using System.Net;
namespace OAuth2ODataSample
{
//Reads configuration settings from App.Config.
//Contains methods relating to obtaining an Access Token via the Client Credential grant type.
public class B2BGrantOauth
{
// Production OAuth server endpoints.
public readonly static string env = ConfigurationManager.AppSettings.Get("Environment");
public readonly static string redirect = ConfigurationManager.AppSettings.Get("RedirectUri");
public readonly static string clientId = ConfigurationManager.AppSettings.Get("ClientId");
public readonly static string clientSecret = ConfigurationManager.AppSettings.Get("ClientSecret");
private readonly string AuthorizationUri = env + "/apisecurity/connect/authorize"; // Authorization code endpoint
private readonly string RefreshUri = env + "/apisecurity/connect/token"; // Get tokens endpoint
private readonly string CodeQueryString = "?client_id={0}&client_secret={1}&scope=allapis&response_type=code";
private readonly string AccessBody = "client_id={0}&client_secret={1}&grant_type=client_credentials";
private readonly string _clientId = null;
private readonly string _clientSecret = null;
private readonly string _uri = null;
public string AccessToken { get; private set; } = null;
public string RefreshToken { get; private set; } = null;
public int Expiration { get; private set; }
public string Error { get; private set; } = null;
public B2BGrantOauth(string clientId)
{
if (string.IsNullOrEmpty(clientId))
{
Console.WriteLine("An Error occured:");
Console.WriteLine("The client ID is missing.");
Console.ReadKey();
}
this._clientId = clientId;
this._clientSecret = clientSecret;
this._uri = string.Format(this.AuthorizationUri + this.CodeQueryString, this._clientId, this._clientSecret);
}
public string GetAccessToken()
{
try
{
var accessTokenRequestBody = string.Format(this.AccessBody, this._clientId, this._clientSecret);
AccessTokens tokens = GetTokens(this.RefreshUri, accessTokenRequestBody);
this.AccessToken = tokens.AccessToken;
this.RefreshToken = tokens.RefreshToken;
this.Expiration = tokens.Expiration;
}
catch (WebException)
{
this.Error = "GetAccessToken failed likely due to an invalid client ID, client secret, or authorization code";
}
return this.AccessToken;
}
private static AccessTokens GetTokens(string uri, string body)
{
try
{
AccessTokens tokens = null;
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.Accept = "application/json";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = body.Length;
using (Stream requestStream = request.GetRequestStream())
{
StreamWriter writer = new StreamWriter(requestStream);
writer.Write(body);
writer.Close();
}
var response = (HttpWebResponse)request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
string json = reader.ReadToEnd();
reader.Close();
tokens = JsonConvert.DeserializeObject(json, typeof(AccessTokens)) as AccessTokens;
}
return tokens;
}
catch (Exception ex)
{
Console.WriteLine("An Error occured:");
Console.WriteLine(ex.Message);
Console.ReadKey();
return null;
}
}
}
}
|
9bdc441fde431a580d095c8085a01549a893a237
|
C#
|
shendongnian/download4
|
/code6/1080073-28374134-83235531-2.cs
| 2.796875
| 3
|
private class AsyncExceptionHandlingInterceptor : IInterceptor
{
private static readonly MethodInfo handleAsyncMethodInfo = typeof(AsyncExceptionHandlingInterceptor).GetMethod("HandleAsyncWithResult", BindingFlags.Instance | BindingFlags.NonPublic);
private readonly IExceptionHandler _handler;
public AsyncExceptionHandlingInterceptor(IExceptionHandler handler)
{
_handler = handler;
}
public void Intercept(IInvocation invocation)
{
var delegateType = GetDelegateType(invocation);
if (delegateType == MethodType.Synchronous)
{
_handler.HandleExceptions(() => invocation.Proceed());
}
if (delegateType == MethodType.AsyncAction)
{
invocation.Proceed();
invocation.ReturnValue = HandleAsync((Task)invocation.ReturnValue);
}
if (delegateType == MethodType.AsyncFunction)
{
invocation.Proceed();
ExecuteHandleAsyncWithResultUsingReflection(invocation);
}
}
private void ExecuteHandleAsyncWithResultUsingReflection(IInvocation invocation)
{
var resultType = invocation.Method.ReturnType.GetGenericArguments()[0];
var mi = handleAsyncMethodInfo.MakeGenericMethod(resultType);
invocation.ReturnValue = mi.Invoke(this, new[] { invocation.ReturnValue });
}
private async Task HandleAsync(Task task)
{
await _handler.HandleExceptions(async () => await task);
}
private async Task<T> HandleAsyncWithResult<T>(Task<T> task)
{
return await _handler.HandleExceptions(async () => await task);
}
private MethodType GetDelegateType(IInvocation invocation)
{
var returnType = invocation.Method.ReturnType;
if (returnType == typeof(Task))
return MethodType.AsyncAction;
if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task<>))
return MethodType.AsyncFunction;
return MethodType.Synchronous;
}
private enum MethodType
{
Synchronous,
AsyncAction,
AsyncFunction
}
}
|
49cf849832b10683aa36c7c94c06539541c86aec
|
C#
|
houssemDevs/msdn-code-gallery-community-a-c
|
/C Sharp (C#) Jigsaw Puzzle Game/[C#]-C Sharp (C#) Jigsaw Puzzle Game/C#/Jigsaw1/Code/GameSettings.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
namespace MinThantSin.OpenSourceGames
{
public static class GameSettings
{
public static readonly string BACKGROUND_PICTURE_NAME = "background_tile.bmp";
public static readonly int MIN_PIECE_WIDTH = 50; // Minimum width of jigsaw piece in pixels.
public static readonly int MIN_PIECE_HEIGHT = 50; // Minimum height of jigsaw piece in pixels.
// It's recommended to set the number of rows and columns to be the same, otherwise,
// the pieces may appear out of proportion.
public static readonly int NUM_ROWS = 4;
public static readonly int NUM_COLUMNS = 4;
public static readonly int SNAP_TOLERANCE = 15;
public static readonly byte GHOST_PICTURE_ALPHA = 127;
public static readonly int PIECE_OUTLINE_WIDTH = 4;
public static readonly bool DRAW_PIECE_OUTLINE = true;
public static readonly int DROP_SHADOW_DEPTH = 3;
public static readonly Color DROP_SHADOW_COLOR = Color.FromArgb(50, 50, 50);
}
}
|
5b2a5e73ab5eb8c7219e49b79f4fc83e6dfa0f45
|
C#
|
KieranBond/swiftsuspenders-sharp
|
/src/swiftsuspenders/mapping/MappingId.cs
| 2.78125
| 3
|
using System;
namespace SwiftSuspenders.Mapping
{
public struct MappingId
{
private Type _type;
private object _key;
public Type type
{
get
{
return _type;
}
}
public object key
{
get
{
return _key;
}
}
public MappingId (Type type, object key)
{
_type = type;
_key = key;
}
public MappingId (Type type)
{
_type = type;
_key = null;
}
/*
public override bool Equals (object obj)
{
if (obj is MappingId)
{
MappingId other = (MappingId)obj;
return other.type == type && other.key == key;
}
return base.Equals (obj);
}
public override int GetHashCode ()
{
if (key != null)
return key.GetHashCode ();
if (type != null)
return type.GetHashCode ();
return 0;
int hashcode = 0;
if (type != null)
hashcode += type.GetHashCode ();
if (key != null)
hashcode += key.GetHashCode ();
return hashcode;
}
*/
public override string ToString ()
{
return string.Format ("[MappingId: type={0}, key={1}]", type, key);
}
}
}
|
96970e0817de28e463dfb23b1dfbc40b1b6a0fb1
|
C#
|
caofangsheng93/JsonDataWithJquery
|
/JsonDataWithJqueryReview/Controllers/BlogController.cs
| 2.890625
| 3
|
using JsonDataWithJqueryReview.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace JsonDataWithJqueryReview.Controllers
{
public class BlogController : Controller
{
private EFDataContext db;
public BlogController()
{
db = new EFDataContext();
//检测到循环引用可以加上这句
db.Configuration.ProxyCreationEnabled = false;
}
public ActionResult Index()
{
//创建下拉框的方式二
List<SelectListItem> categories = new List<SelectListItem>();
//创建一个默认选项
categories.Add(new SelectListItem() { Text = "--请选择--", Value = "0", Selected = true });
//查询所有的分类
var lstCategories = db.BlogCategories.ToList();
//循环添加到下拉框中
foreach (var item in lstCategories)
{
categories.Add(new SelectListItem()
{
Text = item.CategoryName,
Value = item.CategoryId.ToString()
});
}
ViewBag.CategoryList = categories;
return View();
}
/// <summary>
/// 根据产品分类找
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public JsonResult GetBlogByCategoryId(int id)
{
var data = db.Bolgs.Where(s => s.CategoryId == id).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
}
}
|
a1badcb2b1be71c5d288a28f559ae0e96b3bb8a5
|
C#
|
yamachi4416/ChatApp
|
/src/ChatApp/Services/GMailSender.cs
| 2.9375
| 3
|
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
namespace ChatApp.Services
{
public class MailOptions
{
public string Host { get; set; }
public int Port { get; set; }
public string Email { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public MailAddress FromAddress => new MailAddress(Email, UserName);
public NetworkCredential Credentials => new NetworkCredential(Email, Password);
}
public class GMailSender : IEmailSender
{
public MailOptions Options { get; }
public GMailSender(IOptions<MailOptions> options)
{
Options = options.Value;
}
public async Task SendEmailAsync(string email, string subject, string message)
{
using (var sc = new SmtpClient(Options.Host, Options.Port))
using (var msg = new MailMessage(Options.FromAddress, new MailAddress(email)))
{
//SMTPサーバーを設定する
sc.DeliveryMethod = SmtpDeliveryMethod.Network;
//ユーザー名とパスワードを設定する
sc.Credentials = Options.Credentials;
//SSLを使用する
sc.EnableSsl = true;
// HTML形式
msg.IsBodyHtml = true;
// 件名を設定
msg.Subject = subject;
// メッセージを設定
msg.Body = message;
//メッセージを送信する
await sc.SendMailAsync(msg);
}
}
}
}
|
d613d41a9b49676b0cc256cc0446791dc70c439e
|
C#
|
jacksonrakena/human-date-parser
|
/HumanDateParser/Tokenisation/Tokens/LiteralDayOfWeekToken.cs
| 3.078125
| 3
|
using System;
namespace HumanDateParser.Tokenisation.Tokens
{
internal class LiteralDayOfWeekToken : IParseToken
{
public DayOfWeek DayOfWeek { get; }
internal LiteralDayOfWeekToken(DayOfWeek dayOfWeek)
{
DayOfWeek = dayOfWeek;
}
public static DayOfWeek? ParseDayOfWeek(string text)
{
if (!Enum.TryParse<DayOfWeek>(text, true, out var day)) return null;
return day;
}
}
}
|
a203d487551edd38fb7a705eb4e9afb34c472a3a
|
C#
|
OrPolyzos/interactive-systems
|
/Assets/MazeGame/Scripts/MazeManager.cs
| 2.625
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityStandardAssets.Characters.FirstPerson;
public class MazeManager : MonoBehaviour
{
public string sceneName;
public GameObject timeCanvas;
public GameObject gameOverCanvas;
public AudioSource WinSound;
public GameObject player;
public float timeLeftInSec = 5 * 60;
public bool hasWon = false;
// Start is called before the first frame update
void Start()
{
InvokeRepeating("CountDown", 0.0F, 1.0F);
}
// Update is called once per frame
void Update()
{
TimeSpan timeSpan = TimeSpan.FromSeconds(timeLeftInSec);
string time = string.Format("{0:D2}m:{1:D2}s",
timeSpan.Minutes,
timeSpan.Seconds);
timeCanvas.GetComponent<Text>().text = time;
if (timeLeftInSec <= 0)
{
player.GetComponent<FirstPersonController>().enabled = false;
gameOverCanvas.GetComponent<Text>().text = "<b>You Lost!</b>\n<color=\"White\"> Press R to play again</color>\n<color=\"Red\">Press ESC to go back</color>";
gameOverCanvas.SetActive(true);
if (Input.GetKey(KeyCode.Escape))
{
SceneManager.LoadScene("RoomScene", LoadSceneMode.Single);
}
else if (Input.GetKey(KeyCode.R))
{
SceneManager.LoadScene(sceneName, LoadSceneMode.Single);
}
return;
}
else if (hasWon)
{
player.GetComponent<FirstPersonController>().enabled = false;
gameOverCanvas.GetComponent<Text>().text = "<b>Congratulations! You Won!</b>\n<color=\"White\"> Press R to play again</color>\n<color=\"Red\">Press ESC to go back</color>";
gameOverCanvas.SetActive(true);
if (Input.GetKey(KeyCode.Escape))
{
SceneManager.LoadScene("RoomScene", LoadSceneMode.Single);
}
else if (Input.GetKey(KeyCode.R))
{
SceneManager.LoadScene(sceneName, LoadSceneMode.Single);
}
return;
}
}
void CountDown()
{
if (timeLeftInSec > 0)
{
timeLeftInSec--;
}
}
public void IncreaseTime(float seconds)
{
this.timeLeftInSec += seconds;
}
public void DecreaseTime(float seconds)
{
this.timeLeftInSec -= seconds;
}
}
|
1818d53d06115d3634c16d58beb714482c3d2a12
|
C#
|
jp701/College_Event_Management_Portal
|
/College_Event_Management_Portal_CE084/CoreApplication2/Models/SQLRegEventRepository.cs
| 2.703125
| 3
|
using CoreApplication2.Data;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CoreApplication2.Models
{
public class SQLRegEventRepository:IRegEventRepository
{
private readonly ApplicationDbContext context;
public SQLRegEventRepository(ApplicationDbContext context)
{
this.context = context;
}
RegEvent IRegEventRepository.GetRegEvent(int Id)
{
return context.RegEvents.Include(r => r.Event).FirstOrDefault(r => r.Id == Id);
}
IEnumerable<RegEvent> IRegEventRepository.GetAllRegEvents()
{
return context.RegEvents.Include(r => r.Event).Include(r => r.User);
}
IEnumerable<RegEvent> IRegEventRepository.GetRegEventsWithUserId(string Id)
{
return context.RegEvents.Include(r => r.Event).Where(r => r.UserId == Id);
}
RegEvent IRegEventRepository.AddRegEvent(RegEvent regEvent)
{
context.RegEvents.Add(regEvent);
context.SaveChanges();
return regEvent;
}
RegEvent IRegEventRepository.DeleteRegEvent(int Id)
{
RegEvent regEvent = context.RegEvents.Find(Id);
if (regEvent != null)
{
context.RegEvents.Remove(regEvent);
context.SaveChanges();
}
return regEvent;
}
}
}
|
d2c37e403aa647f8fe8c23dbc181f2fc2c6bae52
|
C#
|
j-karls/P4-CrawlProgrammingLanguage
|
/src/libcompiler/CrawlCompilerConfiguration.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
namespace libcompiler
{
public class CrawlCompilerConfiguration
{
//TODO: Non insane way of having this be a tuple of (path, Stream)
public List<string> Files { get; } = new List<string>();
public List<string> Assemblies { get; } = new List<string>{ "mscorlib.dll"};
public TargetStage TargetStage { get; set; } = TargetStage.Compile;
public HashSet<string> Optimizations { get; } = new HashSet<string>();
public bool PrintHelp { get; set; }
public string OutputFile { get; set; }
public bool ForceSingleThreaded { get; set; }
public static readonly string Instructions =
/*
1 2 3 4 5 6 7 8
12345678901234567890123456789012345678901234567890123456789012345678901234567890*/
"-h --help Print this help message and exit\n" +
"\n" +
"Compiler options:" +
" --output=file Save output to file\n" +
"-o --optimize Optimize compiled exe\n" +
" --optimize=optimization1[,...] Turn on specific optimizations\n" +
" --force-single-thread Forces the compiler to do all compilation on a single thread\n" +
"\n" +
"Diagnostic information:\n" +
"-a --print-ast Print all abstract syntax tree\n" +
"-t --tree Print all parse trees\n";
public static CrawlCompilerConfiguration Parse(string[] args)
{
CrawlCompilerConfiguration configuration = new CrawlCompilerConfiguration();
TargetStage defaultTargetStage = configuration.TargetStage;
configuration.TargetStage = (TargetStage) (-1);
for (int index = 0; index < args.Length; index++)
{
string arg = args[index];
if (arg.StartsWith("--"))
{
string longarg = arg.Substring(2);
SwitchOnLongargs(configuration, longarg);
}
else if (arg.StartsWith("-"))
{
string multiargs = arg.Substring(1);
foreach (char c in multiargs)
{
SwitchOnCharargs(configuration, c);
}
}
else
{
configuration.Files.Add(arg);
}
}
if (configuration.TargetStage < 0)
configuration.TargetStage = defaultTargetStage;
if (args.Length == 0)
configuration.PrintHelp = true;
return configuration;
}
private static void SwitchOnCharargs(CrawlCompilerConfiguration crawlCompilerConfiguration, char c)
{
switch (c)
{
case 'h':
crawlCompilerConfiguration.PrintHelp = true;
break;
case 'p':
SetStage(crawlCompilerConfiguration, TargetStage.ParseTree);
break;
case 'a':
SetStage(crawlCompilerConfiguration, TargetStage.AbstractSyntaxTree);
break;
default:
throw new UnknownOption(c.ToString());
}
}
private static void SwitchOnLongargs(CrawlCompilerConfiguration crawlCompilerConfiguration, string longarg)
{
string[] parts = longarg.Split('=');
try
{
switch (parts[0])
{
case "help":
crawlCompilerConfiguration.PrintHelp = true;
break;
case "print-ast":
SetStage(crawlCompilerConfiguration, TargetStage.AbstractSyntaxTree);
break;
case "print-pt":
SetStage(crawlCompilerConfiguration, TargetStage.ParseTree);
break;
case "typecheck":
SetStage(crawlCompilerConfiguration, TargetStage.TypeCheck);
break;
case "optimize":
if (parts.Length == 1)
crawlCompilerConfiguration.Optimizations.Add("*");
else
foreach (string optimiaztion in parts[1].Split(','))
crawlCompilerConfiguration.Optimizations.Add(optimiaztion);
break;
case "assembly":
crawlCompilerConfiguration.Assemblies.Add(parts[1]);
break;
case "output":
crawlCompilerConfiguration.OutputFile = parts[1];
break;
case "force-single-thread":
crawlCompilerConfiguration.ForceSingleThreaded = true;
break;
default:
throw new UnknownOption(parts[0]);
}
}
catch (IndexOutOfRangeException)
{
throw new RequiresArgumentException(parts[0]);
}
}
private static void SetStage(CrawlCompilerConfiguration crawlCompilerConfiguration, TargetStage stage)
{
if(crawlCompilerConfiguration.TargetStage >= 0)
throw new MutalExcluseiveOptionsException(crawlCompilerConfiguration.TargetStage.ToString(), stage.ToString());
crawlCompilerConfiguration.TargetStage = stage;
}
public class MutalExcluseiveOptionsException : Exception
{
public string FirstOption { get; }
public string SecondOption { get; }
public MutalExcluseiveOptionsException(string firstOption, string secondOption)
{
FirstOption = firstOption;
SecondOption = secondOption;
}
}
public class UnknownOption : Exception
{
public UnknownOption(string message) : base(message)
{
}
}
public class RequiresArgumentException : Exception
{
public RequiresArgumentException(string option) : base(option)
{
}
}
}
public enum TargetStage
{
ParseTree,
AbstractSyntaxTree,
//Rest of this is "Probably this order"
ScopeCheck,
TypeCheck,
OptimizedAbstractSyntaxTree,
Compile
}
}
|
81d9dcd2dc238df7a6214c82f30eefd798fdaf41
|
C#
|
Houheshuai/SDWxPro
|
/SDWxPro.Tool/CsvUtil.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Odbc;
using System.Linq;
using System.Text;
namespace SDWxPro.Tool
{
public class CsvUtil
{
/// <summary>
/// 读取CSV文件内容
/// </summary>
/// <param name="filePath">文件路径,如:F:\\data\\</param>
/// <param name="fileName">文件名称,如:001.csv</param>
/// <returns>返回DataTable</returns>
public static DataTable GetCsvDataTable(string filePath, string fileName)
{
string strConn = @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=";
strConn += filePath;//这个地方只需要目录就可以了
strConn += ";Extensions=asc,csv,tab,txt;";
OdbcConnection objConn = new OdbcConnection(strConn);
try
{
string strSQL = "select * from " + fileName;//文件名,不要带目录
OdbcDataAdapter da = new OdbcDataAdapter(strSQL, objConn);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
catch (Exception ex)
{
throw ex;
}
}
}
}
|
a0f2e77ccd5ca3ace6a67b3e0296f9d1753c3098
|
C#
|
mizg/ConsoleAppl_Day6_Lab
|
/ConsoleAppl_Day6_Lab/Program.cs
| 3.59375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleAppl_Day6_Lab
{
class Program
{
static void Main(string[] args)
{
string str = "";
List<Ninjas> squad = new List<Ninjas>();
do
{
Console.WriteLine("Please enter the name of a student.");
squad.Add(new Ninjas(Console.ReadLine()));
Console.WriteLine("Press enter to add another student or press any key then enter to move forward.");
str = Console.ReadLine();
} while (string.IsNullOrEmpty(str));
for (int x = 0; x < squad.Count(); x++ )
{
Console.WriteLine("{0} Please enter the number of programs you've completed.", squad[x].Name);
int prog = int.Parse(Console.ReadLine());
squad[x].levelUp(prog);
Console.WriteLine("{0} Please enter the number of people you've helped.", squad[x].Name);
prog = int.Parse(Console.ReadLine()) * 2;
squad[x].levelUp(prog);
}
for (int x = 0; x < squad.Count(); x++ )
{
squad[x].print();
}
}
}
class Ninjas
{
public string Name { get; set; }
int level = 0;
string rank;
public Ninjas(string n)
{
rank = "Beginner";
level = 0;
Name = n;
}
public void levelUp(int c)
{
level += c;
getRank(level);
}
private void getRank(int lvl)
{
if (lvl > 0 && lvl < 5)
{
rank = "Beginner";
}
else if (lvl >= 5 && lvl < 10)
{
rank = "Grasshopper";
}
else if (lvl >= 10 && lvl < 15)
{
rank = "Journeyman";
}
else if (lvl >= 15 && lvl < 20)
{
rank = "RockStar";
}
else if (lvl >= 20 && lvl < 25)
{
rank = "Ninja";
}
else if (lvl >= 25)
{
rank = "Jedi";
}
}
public void print()
{
Console.WriteLine("Name: {0} Level: {1} Rank: {2}", Name, level, rank);
}
}
}
|
0379a53622bd86d4906c9ad1b9a63044a1f3c700
|
C#
|
sethjdev/FunctionsLab
|
/FunctionsLab/Program.cs
| 3.359375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FunctionsLab
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("What Level Manager Are You?");
var managerLevel = Console.ReadLine();
CheckLevel(managerLevel);
Console.ReadLine();
}
private static void CheckLevel(string managerLevel)
{
if (managerLevel == "First")
{
Console.WriteLine("What is the price of the item?");
var priceInput = Console.ReadLine();
int itemPrice = Convert.ToInt32(priceInput);
if (itemPrice < 250)
{
Console.WriteLine("What is the description of the item?");
var itemDesc = Console.ReadLine();
invalidTerm(itemDesc);
}
else
{
Console.WriteLine("Please Escalate to Second Level Manager");
}
}
else if (managerLevel == "Second")
{
Console.WriteLine("What is the price of the item?");
var priceInput = Console.ReadLine();
int itemPrice = Convert.ToInt32(priceInput);
if (itemPrice < 500)
{
Console.WriteLine("What is the description of the item?");
var itemDesc = Console.ReadLine();
invalidTerm(itemDesc);
}
else
{
Console.WriteLine("Please Escalate to Director");
}
}
else if (managerLevel == "Director")
{
Console.WriteLine("What is the price of the item?");
var priceInput = Console.ReadLine();
int itemPrice = Convert.ToInt32(priceInput);
if ((itemPrice > 1000) && itemPrice < 5000)
{
Console.WriteLine("Are you buying hardware?");
var hardwareAnswer = Console.ReadLine();
if (hardwareAnswer == "yes")
{
Console.WriteLine("Approved");
}
else
{
Console.WriteLine("Sorry you can only approve expenses above $1000 on hardware purchases");
}
}
else if (itemPrice < 1000)
{
Console.WriteLine("What is the description of the item?");
var itemDesc = Console.ReadLine();
invalidTerm(itemDesc);
}
else
{
Console.WriteLine("Please Escalate to CEO");
}
}
else if (managerLevel == "CEO")
{
Console.WriteLine("You are the CEO You can Approve Anything You Want!");
}
}
private static void invalidTerm(string itemDesc)
{
if (itemDesc.Contains("entertainment") || itemDesc.Contains("towncar") || itemDesc.Contains("towncars") || itemDesc.Contains("hardware"))
{
Console.WriteLine("Rejected");
}
else
{
Console.WriteLine("Approved");
}
}
}
}
|
f97928c8d2037b9d572efeefc733f3befbdfd4ae
|
C#
|
JJauss/Katas
|
/NET452Katas/NET452Katas/ExcelToNumber/ExcelToNumber.cs
| 3.03125
| 3
|
using System;
using System.Linq;
namespace NET452Katas.ExcelToNumber
{
public class ExcelToNumber
{
public static long TitleToNumber(string title) {
string titleReverse = new string(title.Reverse().ToArray());
long sum = 0;
for (int index = 0; index < titleReverse.Length; index++) {
int number = titleReverse[index] - 64;
sum += number * (long)Math.Pow(26 , index);
}
return sum;
}
}
}
|
27b6e956b9a3aec5b7062d196fcde360d8ceb52d
|
C#
|
ibensonr/ticketsystem
|
/TicketSystem/src/BusinessServices/UserServices.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using BusinessEntities;
using DataModel;
using DataModel.UnitOfWork;
namespace BusinessServices
{
public class UserServices : IUserServices
{
private readonly UnitOfWork _unitOfWork;
public UserServices()
{
_unitOfWork = new UnitOfWork();
}
public int CreateUser(UserEntity userEntity)
{
throw new NotImplementedException();
}
public bool DeleteUser(int userId)
{
throw new NotImplementedException();
}
public IEnumerable<UserEntity> GetAllUsers()
{
throw new NotImplementedException();
}
public UserEntity GetUserById(int userId)
{
var user = _unitOfWork.UserRepository.GetByID(userId);
if (user != null)
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<tbluser, UserEntity>();
//cfg.AddProfile()... etc...
});
var mapper = config.CreateMapper();
var userModel = mapper.Map<tbluser, UserEntity>(user);
return userModel;
}
return null;
}
public bool UpdateUser(int userId, UserEntity userEntity)
{
throw new NotImplementedException();
}
}
}
|
fc319cf650dcadf681f33b6a9925638e32e13594
|
C#
|
guih2127/praticas-de-programacao
|
/listas/lista04matrizes/exercicio03/exercicio03/Program.cs
| 3.765625
| 4
|
using System;
namespace exercicio03
{
class Program
{
static void Main(string[] args)
{
int[,] myArray = new int[2, 3];
int maiorNumero = 0;
int menorNumero = 100000;
string posicaoMenor = "";
string posicaoMaior = "";
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
Console.WriteLine("Digite os números da primeira linha (3 numeros) e segunda linha (3 numeros): ");
myArray[i, j] = Convert.ToInt32(Console.ReadLine());
if (myArray[i, j] < menorNumero && myArray[i, j] > maiorNumero)
{
maiorNumero = myArray[i, j];
menorNumero = myArray[i, j];
posicaoMaior = Convert.ToString("Linha " + i + ", Coluna " + j);
posicaoMenor = Convert.ToString("Linha " + i + ", Coluna " + j);
}
else if (myArray[i, j] > maiorNumero) {
maiorNumero = myArray[i, j];
posicaoMaior = Convert.ToString( "Linha " + i + ", Coluna " + j );
}
else if (myArray[i, j] < menorNumero)
{
menorNumero = myArray[i, j];
posicaoMenor = Convert.ToString( "Linha " + i + ", Coluna " + j );
}
}
}
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write(myArray[i, j] + " ");
}
Console.WriteLine();
}
Console.WriteLine("O maior número da Array é {0}", maiorNumero);
Console.WriteLine("A posição do maior número é: {0}", posicaoMaior);
Console.WriteLine("O menor número da Array é {0}", menorNumero);
Console.WriteLine("A posição do menor número é {0}", posicaoMenor);
Console.ReadKey();
}
}
}
|
537b482455c6ae29e2c01bc2fdc9912ce99c4cfe
|
C#
|
ariusbronte-portfolio/web-wallet
|
/src/WebWallet.Domain/Enums/Currency.cs
| 2.9375
| 3
|
using System.Diagnostics.CodeAnalysis;
// The number of currencies is deliberately reduced.
namespace WebWallet.Domain.Enums
{
/// <summary>
/// The codes and qualifiers of the currency.
/// </summary>
/// <remarks>ISO-4217</remarks>
[SuppressMessage("ReSharper", "InconsistentNaming")]
[SuppressMessage("ReSharper", "UnusedMember.Global")]
public enum Currency
{
/// <summary>
/// US Dollar.
/// </summary>
USD = 840,
/// <summary>
/// Yen.
/// </summary>
JPY = 392,
/// <summary>
/// Bulgarian Lev.
/// </summary>
BGN = 975,
/// <summary>
/// Czech Koruna.
/// </summary>
CZK = 203,
/// <summary>
/// Danish Krone.
/// </summary>
DKK = 208,
/// <summary>
/// Russian Ruble.
/// </summary>
RUB = 643,
/// <summary>
/// Turkish Lira.
/// </summary>
TRY = 949,
/// <summary>
/// Rand.
/// </summary>
ZAR = 710,
}
}
|
509f561c7c943797e293b2bb2435422f40e5c3aa
|
C#
|
SinxHe/Sinx.UnitTest
|
/Sinx.Refactor.Tests/03 MovieRental Refactor - 多态代替条件/Movie03.cs
| 2.859375
| 3
|
namespace Sinx.Refactor.Tests
{
internal class Movie03
{
public const int CHILDRENS = 2;
public const int REGULAR = 0;
public const int NEW_RELEASE = 1;
private Price03 _priceCode;
public int PriceCode
{
get => _priceCode.GetPriceCode();
set
{
switch (value)
{
// NOTICE: 不要在别人的对象属性上使用SWITCH
case Movie03.REGULAR:
_priceCode = new RegularPrice03();
break;
case Movie03.NEW_RELEASE:
_priceCode = new NewReleasePrice03();
break;
case Movie03.CHILDRENS:
_priceCode = new ChildrensPrice03();
break;
default:
throw new System.ArgumentException();
}
}
}
public string Title { get; }
public Movie03(string title, int priceCode)
{
PriceCode = priceCode;
Title = title;
}
// NOTICE: 这里用到Rental类的DaysRented和Movie的类型
// 之所以传递DaysRented而不是Movie的类型是因为Movie类型
// 是一个很可能增加的类型, 要控制此改变的影响
public double GetCharge(int daysRenged)
{
return _priceCode.GetCharge(daysRenged);
}
public int GetFrequentRenterPoints(int daysRented)
{
return _priceCode.GetFrequentRenterPoints(daysRented);
}
}
}
|
c05f20285caadabe2c6b24f1e8d65225f1081ec5
|
C#
|
EduardoCma/Canada-game
|
/UTIMA_TENTATIVA/Assets/scripts/Dialog.cs
| 2.578125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Dialog : MonoBehaviour {
public Text textDisplay;
public string[] sentences;
private int index;
public float typeSpeed;
public GameObject objective;
public GameObject image;
public GameObject continueButtom;
private void Start()
{
StartCoroutine(Type());
Time.timeScale = 0.3f;
}
private void Update()
{
if (textDisplay.text == sentences[index])
{
continueButtom.SetActive(true);
}
}
IEnumerator Type() {
foreach (char letter in sentences[index].ToCharArray()) {
textDisplay.text += letter;
yield return new WaitForSeconds(typeSpeed);
}
}
public void NextSentence() {
continueButtom.SetActive(false);
image.SetActive(true);
if (index < sentences.Length - 1)
{
index++;
textDisplay.text = "";
StartCoroutine(Type());
Time.timeScale = 0.3f;
}
else
{
textDisplay.text = "";
continueButtom.SetActive(false);
image.SetActive(false);
Instantiate(objective, transform.position, Quaternion.identity);
Time.timeScale = 1f;
}
}
}
|
b145ca2cfd3d565b6c86365c4add0740c22e7a0b
|
C#
|
inkton/sample.wppod
|
/Client/WPPodManager/WPPodManager/WPPodManager/Views/MenuItemPage.xaml.cs
| 2.65625
| 3
|
using System;
using Xamarin.Forms;
using WPPod.Models;
namespace WPPodManager.Views
{
public partial class MenuItemPage : ContentPage
{
public WPPod.Models.MenuItem Item { get; set; }
public MenuItemPage()
{
InitializeComponent();
Item = new WPPod.Models.MenuItem
{
Title = "Menu Item title",
Description = "This is a nice description",
Price = 0,
PhotoURL = "path to menu item image"
};
BindingContext = this;
FoodType.SelectedIndex = 0;
}
public string[] FoodTypes
{
get
{
return Enum.GetNames(typeof(FoodType));
}
}
async void Save_Clicked(object sender, EventArgs e)
{
Item.FoodType = (FoodType)Enum.Parse(typeof(FoodType),
FoodType.SelectedItem as string);
MessagingCenter.Send(this, "AddItem", Item);
await Navigation.PopToRootAsync();
}
}
}
|
ad29e4196ec49fc6445780d8606deb36ba078c0f
|
C#
|
RumeysaBukecik/Calismalar
|
/DersNotlari/For detaylı/ConsoleApplication25/Program.cs
| 3.078125
| 3
|
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication25
{
enum KurumTipi : byte { Devlet, Özel, Vakıf }
enum OzelKursAlanı : byte { Yazılım, Muhasebe, YabancıDil, Ehliyet, Yüzme }
class EgitimKurumu
{
public string KurumAdi;
public string KurumAdresi;
public KurumTipi KurumTipik;
public EgitimKurumu(string kurumadi, string kurumadresi, KurumTipi kurumtipik)
{
KurumAdi=kurumadi;
KurumAdresi=kurumadresi;
KurumTipi KurumTipik = kurumtipik;
}
}
class OzelKurs : EgitimKurumu
{
public string OzelKursSahibi;
public OzelKursAlanı OzelKursAlanik;
public ArrayList EgitmenListesi= new ArrayList();
public OzelKurs(string ozelkurssahibi, OzelKursAlanı ozelkursalanik, string kurumadi, string kurumadresi, KurumTipi kurumtipik) : base(kurumadi, kurumadresi, kurumtipik)
{
this.OzelKursSahibi = ozelkurssahibi;
this.OzelKursAlanik = ozelkursalanik;
EgitmenEkle();
}
public void EgitmenEkle()
{
Console.Write("Eğitmen sayısı giriniz: ");
int esayisi = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < esayisi; i++)
{
Console.Write("TC giriniz: ");
int tc = Convert.ToInt32(Console.ReadLine());
EgitmenListesi.Add(tc);
Console.Write("Adınızı ve soyadınızı giriniz: ");
string adsoy = Console.ReadLine();
EgitmenListesi.Add(adsoy);
}
EgitmenListele();
}
public void EgitmenListele()
{
for (int i = 0; i < EgitmenListesi.Count; i+=2)
{
Console.WriteLine("Tc : "+EgitmenListesi[i] +" Ad Soyad: "+EgitmenListesi[i+1]);
}
}
public string EgitmenBul(int tc)
{
Console.WriteLine();
int isimsiz = EgitmenListesi.IndexOf(tc); //Tcyi bulduğu yeri gösteriyor
return ($"Tc: " + EgitmenListesi[isimsiz] + " Adsoy:" +EgitmenListesi[isimsiz+1]);
}
}
class Program
{
static void Main(string[] args)
{
OzelKurs SmartPro = new OzelKurs("Rümeysa Bükecik", OzelKursAlanı.Yazılım, "SmartPro", "Kadıköy", KurumTipi.Özel);
Console.WriteLine(SmartPro.EgitmenBul(404));
Console.Read();
}
}
}
|
209ae86fc338aca96be7215ad5af48f9092a1769
|
C#
|
szymonk663/SZPNUW
|
/Base/SZPNUW.Base/Utils/Extensions.cs
| 2.546875
| 3
|
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.Net;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Force.DeepCloner;
using System.Security.Principal;
namespace SZPNUW.Base
{
public static class Extensions
{
public static string GetFirstError(this ModelStateDictionary modelState)
{
if(modelState != null && modelState.ErrorCount > 0)
{
return WebUtility.HtmlEncode(modelState.Keys.SelectMany(x => modelState[x].Errors).Select(x => x.ErrorMessage).First());
}
else
{
return string.Empty;
}
}
public static bool AnyLazy<T>(this IEnumerable<T> collection)
{
return collection != null && collection.Any();
}
public static bool HasValue(this string value)
{
return value != null && value.Any();
}
public static string WithFormatExtesion(this string value, object[] args)
{
return string.Format(value, args);
}
public static T Clone<T>(this T item) where T : class, new()
{
return item != null ? item.DeepClone() : default(T);
}
public static bool IsLogedIn(this IPrincipal principal)
{
try
{
return principal.Identity.IsAuthenticated;
}
catch
{
return false;
}
}
}
}
|
0674fd04834ae52e9e112c4fb55ed185ca007a87
|
C#
|
Serega-SPb/Test_tasks
|
/GZipTest/GZipTest/FileHelper.cs
| 3.015625
| 3
|
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Threading;
namespace GZipTest
{
public class FileHelper
{
private Logger _logger = Logger.Instance;
private Thread _readingThread;
private Thread _writeingThread;
private int _amountBlocks;
private bool _isStoped;
public bool ReadingEnd { get; private set; }
public int BlockSize { get; } = 1000000;
public void ReadFile(string sourceFile, ProducerConsumerQueue<Block> inputBlocks,bool withSize = false)
{
_readingThread = new Thread(() =>
{
_logger.Wrapper(() =>
{
using (var readingStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read))
{
_logger.OnLogEvent($"Start reading\t\t{DateTime.Now.TimeOfDay}");
ReadingEnd = false;
var index = _amountBlocks = 0;
while (readingStream.CanRead)
{
if (_isStoped)
{
readingStream.Close();
return;
}
var size = BlockSize;
if (withSize)
{
var sizebBytes = new byte[4];
if (readingStream.Read(sizebBytes, 0, 4) == 0)
break;
size = BitConverter.ToInt32(sizebBytes, 0);
}
var bytes = new byte[size];
var c = readingStream.Read(bytes, 0, size);
if (c == 0)
break;
var block = new Block(index, bytes)
{
BlockSize = size
};
inputBlocks.Add(block);
index++;
_amountBlocks++;
}
_logger.OnLogEvent($"Read has finished\t{DateTime.Now.TimeOfDay}", ConsoleColor.Yellow);
ReadingEnd = true;
}
});
});
_readingThread.Start();
}
public void WriteFile(string sourceFile, ProducerConsumerQueue<Block> outputBlocks, bool checkLastBlock = false)
{
_writeingThread = new Thread(() =>
{
_logger.Wrapper(() =>
{
using (var writingStream = new FileStream(sourceFile, FileMode.Create, FileAccess.Write))
{
_logger.OnLogEvent($"Start writing\t\t{DateTime.Now.TimeOfDay}");
var index = 0;
do
{
if (_isStoped)
{
writingStream.Close();
return;
}
var block = outputBlocks.Take();
var writeLength = block.BlockBytes.Length;
if (checkLastBlock && ReadingEnd && _amountBlocks == index+1)
{
for (var i = writeLength - 1; i >= 0; i--)
{
if (block.BlockBytes[i] == 0) continue;
writeLength = i;
break;
}
}
writingStream.Write(block.BlockBytes, 0, writeLength);
index++;
_logger.OnProgressEvent(_amountBlocks, index);
} while (!ReadingEnd || outputBlocks.Count>0 || _amountBlocks > index);
_logger.OnLogEvent($"Write has finished\t{DateTime.Now.TimeOfDay}", ConsoleColor.Yellow);
}
});
});
_writeingThread.Start();
}
public void Stop()
{
_isStoped = true;
}
}
}
|
113a928cdadeee30fe983ca82cead4f43ba8726f
|
C#
|
dobrinsky/AngularDefault
|
/RaportareOTR/CommonCode/Validation/CodesValidationMethods.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SIGAD.CommonCode.Validation
{
public class CodesValidationMethods
{
public static bool VerificaCod(string input)
{
bool rezultatValidareCod = true;
if (input == "" || (input.Length > 10 && input.Length != 13))
{
rezultatValidareCod = false;
}
else if (input != "" && input.Length == 13)
{
if (!VerificaCNP(input))
{
rezultatValidareCod = false;
}
}
else if (input != "" && input.Length <= 10)
{
if (!verificaCIF(input))
{
rezultatValidareCod = false;
}
}
return rezultatValidareCod;
}
private static bool VerificaCNP(string cnp)
{
if (cnp.Length != 13)
return false;
const string a = "279146358279";
long j = 0;
if (!long.TryParse(cnp, out j))
return false;
long suma = 0;
for (int i = 0; i < 12; i++)
suma += long.Parse(cnp.Substring(i, 1)) * long.Parse(a.Substring(i, 1));
long rest = suma - 11 * (int)(suma / 11);
rest = rest == 10 ?
1 : rest;
if (long.Parse(cnp.Substring(12, 1)) != rest)
return false;
return true;
}
private static bool verificaCIF(string cif)
{
bool rezultatParse = true;
string justNumbers = new String(cif.Where(Char.IsDigit).ToArray());
long reallyJustNumbers = 0;
rezultatParse = long.TryParse(justNumbers, out reallyJustNumbers);
if (!rezultatParse) return false;
long controlNumber = 753217532;
int cifraControl = (int)reallyJustNumbers % 10;
reallyJustNumbers = (long)reallyJustNumbers / 10;
double temp = 0.0;
while (reallyJustNumbers > 0)
{
temp += (reallyJustNumbers % 10) * (controlNumber % 10);
reallyJustNumbers = (long)reallyJustNumbers / 10;
controlNumber = (long)controlNumber / 10;
}
double c = temp * 10 % 11;
if (c == 10) c = 0;
return cifraControl == c;
}
}
}
|
0e085a82412ef9be696621b1827e16fb09935e68
|
C#
|
ancantho/Espera
|
/Espera/Espera.Core/YoutubeSong.cs
| 2.671875
| 3
|
using Espera.Core.Audio;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using YoutubeExtractor;
using AudioType = Espera.Core.Audio.AudioType;
namespace Espera.Core
{
public sealed class YoutubeSong : Song
{
private readonly bool isStreaming;
/// <summary>
/// Initializes a new instance of the <see cref="YoutubeSong"/> class.
/// </summary>
/// <param name="path">The path of the song.</param>
/// <param name="audioType">The audio type.</param>
/// <param name="duration">The duration of the song.</param>
/// <param name="isStreaming">if set to true, the song streams from YouTube, instead of downloading.</param>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
public YoutubeSong(string path, AudioType audioType, TimeSpan duration, bool isStreaming)
: base(path, audioType, duration)
{
this.isStreaming = isStreaming;
}
/// <summary>
/// Gets or sets the description that was entered by the uploader of the YouTube video.
/// </summary>
public string Description { get; set; }
public override bool HasToCache
{
get { return !this.isStreaming; }
}
/// <summary>
/// Gets or sets the average rating.
/// </summary>
/// <value>
/// The average rating. <c>null</c>, if the rating is unknown.
/// </value>
public double? Rating { get; set; }
/// <summary>
/// Gets or sets the thumbnail source.
/// </summary>
public Uri ThumbnailSource { get; set; }
/// <summary>
/// Gets or sets the number of views for the YouTube video.
/// </summary>
public int Views { get; set; }
public override void LoadToCache()
{
this.IsCaching = true;
try
{
string tempPath = Path.GetTempFileName();
VideoInfo video = GetVideoInfoForDownload(this.OriginalPath);
this.DownloadAudioTrack(video, tempPath);
this.StreamingPath = tempPath;
this.IsCached = true;
}
catch (IOException)
{
this.OnCachingFailed(EventArgs.Empty);
}
catch (WebException)
{
this.OnCachingFailed(EventArgs.Empty);
}
catch (VideoNotAvailableException)
{
this.OnCachingFailed(EventArgs.Empty);
}
catch (YoutubeParseException)
{
this.OnCachingFailed(EventArgs.Empty);
}
catch (AudioExtractionException)
{
this.OnCachingFailed(EventArgs.Empty);
}
finally
{
this.IsCaching = false;
}
}
internal override AudioPlayer CreateAudioPlayer()
{
if (this.isStreaming)
{
VideoInfo video = GetVideoInfoForStreaming(this.OriginalPath);
this.StreamingPath = video.DownloadUrl;
}
return this.isStreaming ? (AudioPlayer)new YoutubeAudioPlayer(this) : new LocalAudioPlayer(this);
}
private static VideoInfo GetVideoInfoForDownload(string youtubeLink)
{
IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(youtubeLink);
VideoInfo video = videoInfos
.Where(info => info.CanExtractAudio && info.AudioType == YoutubeExtractor.AudioType.Mp3)
.OrderByDescending(info => info.AudioBitrate)
.First();
return video;
}
private static VideoInfo GetVideoInfoForStreaming(string youtubeLink)
{
IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(youtubeLink);
// For now, we select the lowest resolution to avoid buffering, later we let the user decide which quality he prefers
VideoInfo video = videoInfos
.Where(info => info.VideoType == VideoType.Mp4 && !info.Is3D)
.OrderBy(info => info.Resolution)
.First();
return video;
}
private void DownloadAudioTrack(VideoInfo video, string tempPath)
{
var downloader = new AudioDownloader(video, tempPath);
// We need a factor at which the downlaod progress is preferred to the audio extraction progress
const double factor = 0.95;
downloader.DownloadProgressChanged += (sender, args) =>
{
this.CachingProgress = (int)(args.ProgressPercentage * factor);
};
downloader.AudioExtractionProgressChanged += (sender, args) =>
{
this.CachingProgress = (int)(factor * 100) + (int)(args.ProgressPercentage * (1 - factor));
};
downloader.Execute();
}
}
}
|
8c55e3d6cf713165eb63552c7024ed10b4f420b0
|
C#
|
rozabto/HotelReservation
|
/src/Infrastructure/Common/CheckoutService.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using Application.Common.Interfaces;
namespace Infrastructure.Common
{
public class CheckoutService : ICheckoutService
{
private static readonly char[] HEXADECIMAL = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
private const string ENCODING = "UTF-8";
public string GenerateCheckout(Dictionary<string, string> parameters, string marchantKey)
{
const string pppUrl = "https://ppp-test.safecharge.com/ppp/purchase.do?";
parameters.Add("checksum", CalculateChecksum(parameters, marchantKey));
var encoded_params = EncodeParameters(parameters);
return pppUrl + encoded_params;
}
public string CalculateChecksum(Dictionary<string, string> parameters, string merchantKey, bool firstKey = true)
{
var allVals = new StringBuilder();
if (firstKey)
allVals.Append(merchantKey);
foreach (var param in parameters)
allVals.Append(param.Value);
if (!firstKey)
allVals.Append(merchantKey);
return GetHash(allVals.ToString());
}
public string GetHash(string text)
{
const string MESSAGE_DIGEST = "SHA256";
byte[] bytes;
using (var md = HashAlgorithm.Create(MESSAGE_DIGEST))
{
if (md == null)
{
Console.Error.WriteLine("SHA256 implementation not found.");
return null;
}
byte[] encoded;
try
{
encoded = Encoding.GetEncoding(ENCODING).GetBytes(text);
}
catch (EncoderFallbackException ex)
{
Console.Error.WriteLine("Cannot encode text into bytes: " + ex.Message);
return null;
}
bytes = md.ComputeHash(encoded);
}
var sb = new StringBuilder(2 * bytes.Length);
for (var i = 0; i < bytes.Length; i++)
{
var low = bytes[i] & 0x0f;
var high = (bytes[i] & 0xf0) >> 4;
sb.Append(HEXADECIMAL[high]);
sb.Append(HEXADECIMAL[low]);
}
return sb.ToString();
}
private string EncodeParameters(Dictionary<string, string> parameters)
{
var postData = new StringBuilder();
foreach (var param in parameters)
{
if (postData.Length != 0)
postData.Append("&");
postData.Append(HttpUtility.UrlEncode(param.Key, Encoding.GetEncoding(ENCODING)));
postData.Append("=");
postData.Append(HttpUtility.UrlEncode(param.Value, Encoding.GetEncoding(ENCODING)));
}
return postData.ToString();
}
}
}
|
12206add4d3cd3b43df9142b180bbb1458471f52
|
C#
|
genI3/TaskListAppTest
|
/src/Converters/StringIsNullOrWhiteSpaceToVisibiltyConverter.cs
| 2.921875
| 3
|
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace TaskListAppTest.Converters
{
/// <summary>
/// Конвертирует объект <see cref="string"/>
/// в состояние отображения элемента <see cref="Visibility"/>.
/// Реализует интерфейс <seealso cref="IValueConverter"/>
/// </summary>
[ValueConversion(typeof(string), typeof(Visibility))]
public class StringIsNullOrWhiteSpaceToVisibiltyConverter : IValueConverter
{
/// <inheritdoc/>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is string str)
{
return string.IsNullOrWhiteSpace(str) ? Visibility.Visible : Visibility.Hidden;
}
return DependencyProperty.UnsetValue;
}
/// <inheritdoc/>
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => DependencyProperty.UnsetValue;
}
}
|
de88c82aa93c80096861496afecce5f9fcfab146
|
C#
|
JoeJoeWalters/TNDStudios.Web.Blogs.Core
|
/TNDStudios.Web.Blogs/ViewModels/Properties/BlogViewDisplaySettings.cs
| 3.1875
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace TNDStudios.Web.Blogs.Core.ViewModels
{
/// <summary>
/// Enumeration to indicate the viewport size
/// </summary>
public enum BlogViewSize
{
ExtraSmall = 0,
Small = 1,
Medium = 2,
Large = 3
}
/// <summary>
/// Settings dependant on the size of the display
/// (Roughly analagous to Bootstrap viewport size)
/// </summary>
public class BlogViewSizeSettings
{
/// <summary>
/// How many columns are visible in the given port size
/// </summary>
public Int16 Columns { get; set; }
}
/// <summary>
/// The options for how the templates should render the data
/// </summary>
public class BlogViewDisplaySettings
{
/// <summary>
/// How dates should be displayed
/// </summary>
public String DateFormat { get; set; }
/// <summary>
/// Definitions for the viewports based on the size of the screen
/// e.g. how many columns will be visible for large viewports
/// </summary>
public Dictionary<BlogViewSize, BlogViewSizeSettings> ViewPorts { get; set; }
/// <summary>
/// Default Constructor
/// </summary>
public BlogViewDisplaySettings()
{
DateFormat = "dd MMM yyyy HH:mm"; // The default date format
// Set the default values for the viewports
ViewPorts = new Dictionary<BlogViewSize, BlogViewSizeSettings>();
ViewPorts.Add(BlogViewSize.ExtraSmall, new BlogViewSizeSettings() { Columns = 1 });
ViewPorts.Add(BlogViewSize.Small, new BlogViewSizeSettings() { Columns = 1 });
ViewPorts.Add(BlogViewSize.Medium, new BlogViewSizeSettings() { Columns = 2 });
ViewPorts.Add(BlogViewSize.Large, new BlogViewSizeSettings() { Columns = 3 });
}
}
}
|
294beed90d7b0145503e8e0580f17da455cdde95
|
C#
|
Alex-D-Green/Translator
|
/Translator/TranslatorBase.cs
| 3.078125
| 3
|
using System;
using System.Text;
using System.Threading.Tasks;
using Translator.CommonData;
namespace Translator
{
/// <summary>
/// An abstract translator.
/// </summary>
internal abstract class TranslatorBase
{
/// <summary>
/// Translation service name.
/// </summary>
public abstract string TranslationBy { get; }
/// <summary>
/// Translate the word asynchronously.
/// </summary>
/// <param name="word">A word in English for translation to Russian.</param>
/// <returns>A task that return translation result.</returns>
public abstract Task<string> TranslateAsync(string word);
/// <summary>
/// Translate the word synchronously.
/// </summary>
/// <param name="word">A word in English for translation to Russian.</param>
/// <param name="timeout">Operation timeout.</param>
/// <returns>A task that return translation result.</returns>
public string Translate(string word, int timeout = -1)
{
var task = TranslateAsync(word);
task.Wait(timeout);
return task.Result;
}
/// <summary>
/// Format translation output.
/// </summary>
/// <param name="word">A word for translation.</param>
/// <param name="clause">Relevant dictionary clause.</param>
/// <returns>Text output.</returns>
protected virtual string FormatClause(string word, DictionaryClause clause)
{
var ret = new StringBuilder("");
ret.AppendFormat("{0}:{1}", word, Environment.NewLine);
int i = 0;
foreach(TranslationClause translate in clause.Translations)
ret.AppendFormat(" {0}: {1} ({2});{3}", ++i, translate.Translation,
translate.Type.ToShortFormString(), Environment.NewLine);
return ret.ToString();
}
}
}
|
37577d907dc888607ee3556ecf099dee7f878405
|
C#
|
domoticz/domoticz-xamarin
|
/NL.HNOGames.Domoticz/NL.HNOGames.Domoticz/Helpers/UsefulBits.cs
| 2.921875
| 3
|
using Plugin.DeviceInfo;
using System;
using System.Text;
using System.Text.RegularExpressions;
using Xamarin.Forms;
namespace NL.HNOGames.Domoticz.Helpers
{
/// <summary>
/// Defines the <see cref="UsefulBits" />
/// </summary>
public static class UsefulBits
{
#region Public
/// <summary>
/// check if is numeric
/// </summary>
/// <param name="s">The s<see cref="string"/></param>
/// <returns>The <see cref="bool"/></returns>
public static bool IsNumeric(this string s)
{
return float.TryParse(s, out float output);
}
/// <summary>
/// Get device id
/// </summary>
/// <returns></returns>
public static String GetDeviceID()
{
return CrossDeviceInfo.Current.Id;
}
/// <summary>
/// Get the MD5 string
/// </summary>
/// <param name="input">The input<see cref="string"/></param>
/// <returns>The <see cref="String"/></returns>
public static String GetMD5String(string input)
{
if (string.IsNullOrEmpty(input))
return null;
return XLabs.Cryptography.MD5.GetMd5String(input);
}
/// <summary>
/// Check if a string is base64 encoded
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static bool IsBase64Encoded(string input)
{
if (string.IsNullOrEmpty(input))
return false;
return Regex.Match(input, "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$").Success;
}
internal static string getMd5String(string input)
{
// Use input string to calculate MD5 hash
using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
{
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hashBytes = md5.ComputeHash(inputBytes);
// Convert the byte array to hexadecimal string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("X2"));
}
return sb.ToString();
}
}
/// <summary>
/// Decode base 64 string
/// </summary>
/// <param name="input">The input<see cref="string"/></param>
/// <returns>The <see cref="string"/></returns>
public static string DecodeBase64String(string input)
{
if (string.IsNullOrEmpty(input))
return null;
byte[] plain = Convert.FromBase64String(input);
return (Encoding.GetEncoding("UTF-8")).GetString(plain);
}
/// <summary>
/// Get hex value of string
/// </summary>
/// <param name="color"></param>
/// <param name="withAlpha">The withAlpha<see cref="bool"/></param>
/// <returns></returns>
public static string GetHexString(Color color, bool withAlpha = false)
{
var red = (int)(color.R * 255);
var green = (int)(color.G * 255);
var blue = (int)(color.B * 255);
var alpha = (int)(color.A * 255);
if (withAlpha)
return $"{alpha:X2}{red:X2}{green:X2}{blue:X2}";
else
return $"{red:X2}{green:X2}{blue:X2}";
}
#endregion
}
}
|
018e93a6568ad849d94133501ee52534ce7906b6
|
C#
|
robotron2084/eat-sleep-rave-repeat
|
/ESRR/Assets/GameJamStarterKit/Core/Scripts/Utility/TimeSince.cs
| 3.0625
| 3
|
using UnityEngine;
// https://garry.tv/2018/01/16/timesince/
namespace GameJamStarterKit
{
/// <summary>
/// Measures time since this struct was initialized. Implicitly converts to a float.
/// <para>Example: TimeSince timeSinceStart = 0f will measure the time since the moment timeSinceStart was initialized</para>
/// <para>Usage: if ( timeSinceStart > 10f ) { // it's been more than 10 seconds! };</para>
/// </summary>
public struct TimeSince
{
private float _time;
public static implicit operator float(TimeSince ts)
{
return Time.time - ts._time;
}
public static implicit operator TimeSince(float ts)
{
return new TimeSince {_time = Time.time - ts};
}
}
/// <summary>
/// Measures unscaled time since this struct was initialized. Implicitly converts to a float.
/// <para>Example: UnscaledTimeSince timeSinceStart = 0f will measure the unscaled time since the moment timeSinceStart was initialized</para>
/// <para>Usage: ( timeSinceStart > 10f ) { // it's been more than 10 unscaled seconds! };</para>
/// </summary>
public struct UnscaledTimeSince
{
private float _time;
public static implicit operator float(UnscaledTimeSince ts)
{
return Time.unscaledTime - ts._time;
}
public static implicit operator UnscaledTimeSince(float ts)
{
return new UnscaledTimeSince {_time = Time.unscaledTime - ts};
}
}
}
|
9a889477bcd5153620f294911b0e12e378fd8838
|
C#
|
StasStrezh/EYTestTask1
|
/EYTask1/Merging.cs
| 3.125
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EYTask1
{
public class Merging
{
public static int counter = 0;
public static void MergeFiles(string comb)
{
var path = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
string[] txtFiles = Directory.GetFiles(path, "*.txt");
using (StreamWriter writer = new StreamWriter("all.txt"))
{
for (int i = 0; i < txtFiles.Length; i++)
{
if (!txtFiles[i].Contains("all.txt"))
{
using (StreamReader reader = File.OpenText(txtFiles[i]))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (comb != "" && line.Contains(comb))
{
counter++;
continue;
}
writer.WriteLine(line);
}
}
System.IO.File.Delete(txtFiles[i]);
}
}
}
}
}
}
|
d63736008306500a3faa1f43f46ce21d69ec96cd
|
C#
|
AmireddyAjaykumar/HackerRank
|
/HackerRank/IntroToChallenges.cs
| 3.390625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HackerRank
{
public static class IntroToChallenges
{
static int introTutorial(int V, int[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == V)
{
return i;
}
}
return 0;
}
public static void GetIndex()
{
int V = Convert.ToInt32(Console.ReadLine());
int n = Convert.ToInt32(Console.ReadLine());
int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), arrTemp => Convert.ToInt32(arrTemp));
int result = introTutorial(V, arr);
Console.WriteLine(result);
}
}
}
|
8c7841a1d9415853b5cf5f41a456d8c3bd8e37c5
|
C#
|
LykkeCity/bitcoinservice
|
/src/LkeServices/Helpers/Retry.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Common.Log;
namespace LkeServices.Helpers
{
public class Retry
{
public static async Task<T> Try<T>(Func<Task<T>> action, Func<Exception, bool> exceptionFilter, int tryCount, ILog logger)
{
int @try = 0;
while (true)
{
try
{
return await action();
}
catch (Exception ex)
{
@try++;
if (!exceptionFilter(ex) || @try >= tryCount)
throw;
await logger.WriteErrorAsync("Retry", "Try", null, ex);
}
}
}
public static async Task Try(Func<Task> action, Func<Exception, bool> exceptionFilter, int tryCount, ILog logger)
{
int @try = 0;
while (true)
{
try
{
await action();
return;
}
catch (Exception ex)
{
@try++;
if (!exceptionFilter(ex) || @try >= tryCount)
throw;
await logger.WriteErrorAsync("Retry", "Try", null, ex);
}
}
}
}
}
|
f8022056fc70ee2f1e9480851b65fa13e5f510a1
|
C#
|
chelseamgp01/Array
|
/2 Demension.cs
| 2.953125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _2Demesion
{
class Program
{
static void Main(string[] args)
{
double[,] temperture = new double[,]
{
{12.50,10.45,12.30,14.60,17.70,11.20,12.50},
{12.22,11.00,10.00,20.00,21.00,14.00,15.50},
{13.00,14.00,14.50,14.60,12.30,14.00,14.60}
};
Random random = new Random();
int a = random.Next(0, 2);
int b = random.Next(0, 6);
Console.WriteLine(temperture[a,b]);
Console.ReadLine();
}
}
}
|
bf2624ea513a5f762f7ee076b1589863a553a5d3
|
C#
|
allsources/WordAutoComplete
|
/WordAutoComplete/Classes/Word.cs
| 3.40625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WordAutoComplete.Classes
{
/// <summary>
/// Represents a word object.
/// </summary>
public class Word
{
#region "Public members"
/// <summary>
/// A word.
/// </summary>
public string Value { get; set; }
/// <summary>
/// A number that defines how many times the word occurs in the text.
/// </summary>
public int Count { get; set; }
#endregion "Public members"
#region ".ctor"
public Word()
{
}
public Word(string word, int count)
{
Value = word;
Count = count;
}
#endregion ".ctor"
}
}
|
bf43b152a5fffc6eded21247900a9ccb1e33f8b4
|
C#
|
didatzi/TechModule
|
/Ex_DataTypesAndVariables/P14_IntegerToHexAndBinary/P14_IntegerToHexAndBinary.cs
| 3.328125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace P14_IntegerToHexAndBinary
{
class P14_IntegerToHexAndBinary
{
static void Main(string[] args)
{
int number = int.Parse(Console.ReadLine());
string toHex = Convert.ToString(number, 16).ToUpper();
string toBinary = Convert.ToString(number, 2);
Console.WriteLine(toHex);
Console.WriteLine(toBinary);
}
}
}
|
eeba6c2cf434b95ec0e0f503666494e8f2cb12b6
|
C#
|
shendongnian/download4
|
/first_version_download2/69481-4366607-9207796-2.cs
| 2.734375
| 3
|
for (
int i = 0;
i < argsin.Length;
i++
)
{
Console.WriteLine("Argument: {0}", argsin[i]);
}
Console.ReadLine();
return -1;
|
4e757082ff7852bd0e73cb1b150e3bf5a6db53d6
|
C#
|
hahorro/bleakwind-buffet
|
/Data/Menu.cs
| 2.828125
| 3
|
/*
* Author: Hans Ahorro
* Class name: Menu.cs
* Purpose: Static class used to represent the menu of items
*/
using System;
// using System.Reflection;
using System.Collections.Generic;
using BleakwindBuffet.Data.Entrees;
using BleakwindBuffet.Data.Sides;
using BleakwindBuffet.Data.Drinks;
using BleakwindBuffet.Data.Enums;
namespace BleakwindBuffet.Data
{
/// <summary>
/// A static class representing the menu of items.
/// </summary>
public static class Menu
{
/// <summary>
/// Gets the possible order types
/// </summary>
public static string[] OrderTypes
{
get => new string[]
{
"Entree",
"Side",
"Drink"
};
}
/// <summary>
/// Returns a list of entrees.
/// </summary>
/// <returns>The list of entrees.</returns>
public static IEnumerable<IOrderItem> Entrees()
{
//var classes = Assembly.GetExecutingAssembly().GetTypes();
var entrees = new List<IOrderItem>
{
new BriarheartBurger(),
new DoubleDraugr(),
new GardenOrcOmelette(),
new PhillyPoacher(),
new SmokehouseSkeleton(),
new ThalmorTriple(),
new ThugsTBone()
};
//var entrees = new List<IOrderItem>();
//foreach(Type t in classes)
//{
// if (t.Namespace == "BleakwindBuffet.Data.Entrees")
// {
// if (typeof(Entree).IsAssignableFrom(t))
// {
// entrees.Add(t as IOrderItem);
// }
// }
//}
return entrees;
}
/// <summary>
/// Returns a list of sides.
/// </summary>
/// <returns>The list of sides.</returns>
public static IEnumerable<IOrderItem> Sides()
{
var sides = new List<IOrderItem>
{
// Without object initializer, the size defaults to small.
new DragonbornWaffleFries(),
new DragonbornWaffleFries() { Size = Size.Medium },
new DragonbornWaffleFries() { Size = Size.Large },
new FriedMiraak(),
new FriedMiraak() { Size = Size.Medium },
new FriedMiraak() { Size = Size.Large },
new MadOtarGrits(),
new MadOtarGrits() { Size = Size.Medium },
new MadOtarGrits() { Size = Size.Large },
new VokunSalad(),
new VokunSalad() { Size = Size.Medium },
new VokunSalad() { Size = Size.Large }
};
return sides;
}
/// <summary>
/// Returns a list of drinks.
/// </summary>
/// <returns>The list of drinks.</returns>
public static IEnumerable<IOrderItem> Drinks()
{
var drinks = new List<IOrderItem>
{
// Without object initializer, the size defaults to small.
// Soda flavor defaults to cherry if not specified inside
// the object initializer.
new AretinoAppleJuice(),
new AretinoAppleJuice() { Size = Size.Medium },
new AretinoAppleJuice() { Size = Size.Large },
new CandlehearthCoffee(),
new CandlehearthCoffee() { Size = Size.Medium },
new CandlehearthCoffee() { Size = Size.Large },
new MarkarthMilk(),
new MarkarthMilk() { Size = Size.Medium },
new MarkarthMilk() { Size = Size.Large },
new SailorSoda(),
new SailorSoda() { Flavor = SodaFlavor.Blackberry },
new SailorSoda() { Flavor = SodaFlavor.Grapefruit },
new SailorSoda() { Flavor = SodaFlavor.Lemon },
new SailorSoda() { Flavor = SodaFlavor.Peach },
new SailorSoda() { Flavor = SodaFlavor.Watermelon },
new SailorSoda() { Size = Size.Medium },
new SailorSoda() { Size = Size.Medium, Flavor = SodaFlavor.Blackberry },
new SailorSoda() { Size = Size.Medium, Flavor = SodaFlavor.Grapefruit },
new SailorSoda() { Size = Size.Medium, Flavor = SodaFlavor.Lemon },
new SailorSoda() { Size = Size.Medium, Flavor = SodaFlavor.Peach },
new SailorSoda() { Size = Size.Medium, Flavor = SodaFlavor.Watermelon },
new SailorSoda() { Size = Size.Large },
new SailorSoda() { Size = Size.Large, Flavor = SodaFlavor.Blackberry },
new SailorSoda() { Size = Size.Large, Flavor = SodaFlavor.Grapefruit },
new SailorSoda() { Size = Size.Large, Flavor = SodaFlavor.Lemon },
new SailorSoda() { Size = Size.Large, Flavor = SodaFlavor.Peach },
new SailorSoda() { Size = Size.Large, Flavor = SodaFlavor.Watermelon },
new WarriorWater(),
new WarriorWater() { Size = Size.Medium },
new WarriorWater() { Size = Size.Large },
};
return drinks;
}
/// <summary>
/// Returns a list of all items.
/// </summary>
/// <returns>The list of all items.</returns>
public static IEnumerable<IOrderItem> FullMenu()
{
var fullMenu = new List<IOrderItem>();
foreach(IOrderItem item in Entrees())
{
fullMenu.Add(item);
}
foreach (IOrderItem item in Sides())
{
fullMenu.Add(item);
}
foreach (IOrderItem item in Drinks())
{
fullMenu.Add(item);
}
return fullMenu;
}
/// <summary>
/// Searches the menu for matching items
/// </summary>
/// <param name="menu">The collection of menu items</param>
/// <param name="terms">The terms to search for</param>
/// <returns>A collection of menu items</returns>
public static IEnumerable<IOrderItem> Search(IEnumerable<IOrderItem> menu, string terms)
{
var results = new List<IOrderItem>();
// Return all menu items if search is blank
if (terms == null) return menu;
// Check ToString method return value
foreach (IOrderItem item in menu)
{
if (item.ToString().Contains(terms, StringComparison.InvariantCultureIgnoreCase))
{
results.Add(item);
}
}
return results;
}
/// <summary>
/// Filters range of calories
/// </summary>
/// <param name="movies">The collection of menu items</param>
/// <param name="min">The minimum range value</param>
/// <param name="max">The maximum range value</param>
/// <returns>The filtered menu item collection</returns>
public static IEnumerable<IOrderItem> FilterByCalories(IEnumerable<IOrderItem> menu, int? min, int? max)
{
if (min == null && max == null) return menu;
var results = new List<IOrderItem>();
// check for proper range applied
if (min > max) return results;
// only a maximum specified
if (min == null)
{
foreach (IOrderItem item in menu)
{
if (item.Calories <= max) results.Add(item);
}
return results;
}
// only a minimum specified
if (max == null)
{
foreach (IOrderItem item in menu)
{
if (item.Calories >= min) results.Add(item);
}
return results;
}
// Both minimum and maximum specified
foreach (IOrderItem item in menu)
{
if (item.Calories >= min && item.Calories <= max)
{
results.Add(item);
}
}
return results;
}
/// <summary>
/// Filters range of prices
/// </summary>
/// <param name="movies">The collection of menu items</param>
/// <param name="min">The minimum range value</param>
/// <param name="max">The maximum range value</param>
/// <returns>The filtered menu item collection</returns>
public static IEnumerable<IOrderItem> FilterByPrice(IEnumerable<IOrderItem> menu, double? min, double? max)
{
if (min == null && max == null) return menu;
var results = new List<IOrderItem>();
// check for proper range applied
if (min > max) return results;
// only a maximum specified
if (min == null)
{
foreach (IOrderItem item in menu)
{
if (item.Price <= max) results.Add(item);
}
return results;
}
// only a minimum specified
if (max == null)
{
foreach (IOrderItem item in menu)
{
if (item.Price >= min) results.Add(item);
}
return results;
}
// Both minimum and maximum specified
foreach (IOrderItem item in menu)
{
if (item.Price >= min && item.Price <= max)
{
results.Add(item);
}
}
return results;
}
}
}
|
587e3d6f95f390d295bd797688407f73786001d3
|
C#
|
AkiraTakahashi0906/KGroupWorkSystem
|
/KGroupWorkSystem.Infrastructure/SQLServer/SQLServerHelper.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KGroupWorkSystem.Infrastructure.SQLServer
{
internal static class SQLServerHelper
{
internal readonly static string ConnectionString;
static SQLServerHelper()
{
//pass00000000
var builder = new SqlConnectionStringBuilder();
builder.DataSource = @"DESKTOP-8B0KCU1\SQLEXPRESS";
builder.InitialCatalog = "KGWS";
builder.IntegratedSecurity = true;
ConnectionString = builder.ConnectionString;
}
internal static void Query(
string sql,
SqlParameter[] parameters,
Action<SqlDataReader> action)
{
using (var connection = new SqlConnection(ConnectionString))
using (var command = new SqlCommand(sql, connection))
{
connection.Open();
if (parameters != null)
{
command.Parameters.AddRange(parameters);
}
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
action(reader);
}
}
}
}
internal static void Execute(
string sql,
SqlParameter[] parameters)
{
using (var connection =
new SqlConnection(ConnectionString))
using (var command = new SqlCommand(sql, connection))
{
connection.Open();
if (parameters != null)
{
command.Parameters.AddRange(parameters);
}
command.ExecuteNonQuery();
}
}
}
}
|
76d0dd6ae0fd9c15f89e28d8dcf356348eed585a
|
C#
|
VirginiaPereiro/Csharp_ej6_Empleados
|
/EmpleoEF/RepositorioEmpleados.cs
| 3.09375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EmpleoEF.Model;
namespace EmpleoEF
{
public class RepositorioEmpleados
{
private EmpleoEntities db = new EmpleoEntities();
public void Alta(Empleado emple)
{
db.Empleado.Add(emple);
db.SaveChanges();
}
public Empleado GetById(int id)
{
// Find busca por clave primaria, sólo podrá haber un resultado
return db.Empleado.Find(id);
}
public IEnumerable<Empleado> GetBySalario(double salario)
{
//que el objeto recibido sea mayor o igual al salario introducido
return db.Empleado.Where(o => o.salario >= salario);
}
public void DarBaja(Empleado emple)
{
db.Empleado.Remove(emple);
db.SaveChanges();
}
public double SalarioMedioEmpleados()
{
return db.Empleado.Average(o => o.salario);
}
public IEnumerable<Empleado> EmpleadosProyecto(int id)
{
var datos = db.Proyecto.First(o => o.id == id).Empleado;
return datos;
}
public IEnumerable<Proyecto> ProyectoEmpleados(int id)
{
var datos =db.Empleado.First(o => o.id == id).Proyecto;
return datos;
}
public String[] EmpleadosNombre()
{
var nombres = db.Empleado.Select(o => o.nombre);
return nombres.ToArray();
}
public IEnumerable<Empleado> EmpleadosPorNombre(String nombre)
{
return db.Empleado.Where(o => o.nombre.Contains(nombre));
}
}
}
|
b0287bdf703f39e10a63f543f195033a02b35d5d
|
C#
|
ansabha2612datastructures/Tutort_DSA
|
/ClassAssignments/PairSum.cs
| 3.3125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassAssignments
{
class PairSum
{
bool isSumPair(int[] arr, int target)
{
int diff = 0;
HashSet<int> h = new HashSet<int>();
int len = arr.Length;
for (int i = 0; i < len; i++)
{
h.Add(arr[i]);
}
for (int i = 0; i < len; i++)
{
diff = target - arr[i];
if (h.contains(diff))
return true;
}
return false;
}
}
}
|
10b3b726b2b89338a2824ebe212307cc4c535692
|
C#
|
shikimiya/Unity-SDP
|
/Assets/Scripts/SDP/time_description.cs
| 3.203125
| 3
|
using System;
using System.Collections.Generic;
namespace sdp
{
// TimeDescriptionは、セッションの開始時刻と停止時刻、
// およびスケジュールされたセッションの繰り返し間隔と期間を指定するために使用される、
// セッション記述の「t =」、「r =」フィールドを記述します。
public class TimeDescription
{
// t=<start-time> <stop-time>
// https://tools.ietf.org/html/rfc4566#section-5.9
public Timing Timing;
// r=<repeat interval> <active duration> <offsets from start-time>
// https://tools.ietf.org/html/rfc4566#section-5.10
public List<RepeatTime> RepeatTime;
public TimeDescription()
{
Timing = new Timing();
RepeatTime = new List<RepeatTime>();
}
}
//タイミングは、開始時間と停止時間の「t =」フィールドの構造化表現を定義します。
public class Timing
{
public ulong StartTime;
public ulong StopTime;
public Timing()
{
StartTime = 0;
StopTime = 0;
}
public string String()
{
var output = Convert.ToString(StartTime);
output += " " + Convert.ToString(StopTime);
return output;
}
}
// RepeatTimeは、繰り返されるスケジュールされたセッションの間隔と
// 期間を表すセッション記述の「r =」フィールドを記述します。
public class RepeatTime
{
public long Interval;
public long Duration;
public List<long> Offsets;
public RepeatTime()
{
Interval = 0;
Duration = 0;
Offsets = new List<long>();
}
public string String()
{
var fields = new List<string>();
fields.Add(Convert.ToString(Interval));
fields.Add(Convert.ToString(Duration));
foreach (var value in Offsets)
{
fields.Add(Convert.ToString(value));
}
return string.Join(" ", fields);
}
}
}
|