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
|
|---|---|---|---|---|---|---|
ef8533c22387e2801b216981358271d3c1462bae
|
C#
|
DiegoSullon/Moanso2020
|
/SysRestaurantNorte/Controller/ClientController.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Entity;
using Data;
namespace Controller
{
public class ClientController
{
#region singleton
private static readonly ClientController _instancia = new ClientController();
public static ClientController Instancia
{
get { return ClientController._instancia; }
}
#endregion singleton
public List<Client> listarSectors()
{
return ClientData.Instancia.listar();
}
public void insertarSector(Client SEC)
{
try
{
ClientData.Instancia.insertar(SEC);
}
catch(Exception e )
{ throw e;
}
}
public void editarSector(Client SEC)
{
try
{
ClientData.Instancia.editar(SEC);
}
catch (Exception e)
{
throw e;
}
}
public void eliminarSector(int id)
{
try
{
ClientData.Instancia.eliminar(id);
}
catch (Exception e)
{
throw e;
}
}
}
}
|
66320815b2c8306e03b774cf8258f9fb1081f6e6
|
C#
|
daria-teremkova/2_semester_2018
|
/Graphs_13/Node.cs
| 2.953125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace Graphs_13
{
public class Node
{
public class Edge
{
public int A { get; set; }
public int NumNode { get; set; }
public int PrevNode { get; set; }
public Color color { get; set; }
public int length { get; set; }
public int value { get; set; }
public Node Neighbour { get; set; }
public bool build { get; set; }
public bool visited = false;
}
public int Distance { get; set; } // для кратчайшего расстояния
public string name { get; set; }
public string city { get; set; }
public List<Edge> edge;
public int numVisit { get; set; }
public bool visit { get; set; }
public int x { get; set; }
public int y { get; set; }
public Color color = Color.Pink;
public bool chosen { get; set; }
//public bool periphery { get; set; }
public Node(int ex, int ey, string number)
{
name = number.ToString();
x = ex; y = ey;
edge = new List<Edge>();
}
}
}
|
ce0c28c3f975949def384c33dc69c746b48f0fb7
|
C#
|
siddhesh-vartak98/Fire-Detection-Using-Infrared-Images
|
/AForge.Imaging/AForge/Imaging/Filters/Difference.cs
| 2.578125
| 3
|
namespace AForge.Imaging.Filters
{
using AForge.Imaging;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
public sealed class Difference : BaseInPlaceFilter2
{
private Dictionary<PixelFormat, PixelFormat> formatTranslations;
public Difference()
{
this.formatTranslations = new Dictionary<PixelFormat, PixelFormat>();
this.InitFormatTranslations();
}
public Difference(UnmanagedImage unmanagedOverlayImage) : base(unmanagedOverlayImage)
{
this.formatTranslations = new Dictionary<PixelFormat, PixelFormat>();
this.InitFormatTranslations();
}
public Difference(Bitmap overlayImage) : base(overlayImage)
{
this.formatTranslations = new Dictionary<PixelFormat, PixelFormat>();
this.InitFormatTranslations();
}
private void InitFormatTranslations()
{
this.formatTranslations[PixelFormat.Format8bppIndexed] = PixelFormat.Format8bppIndexed;
this.formatTranslations[PixelFormat.Format24bppRgb] = PixelFormat.Format24bppRgb;
this.formatTranslations[PixelFormat.Format32bppRgb] = PixelFormat.Format32bppRgb;
this.formatTranslations[PixelFormat.Format32bppArgb] = PixelFormat.Format32bppArgb;
this.formatTranslations[PixelFormat.Format16bppGrayScale] = PixelFormat.Format16bppGrayScale;
this.formatTranslations[PixelFormat.Format48bppRgb] = PixelFormat.Format48bppRgb;
this.formatTranslations[PixelFormat.Format64bppArgb] = PixelFormat.Format64bppArgb;
}
protected override unsafe void ProcessFilter(UnmanagedImage image, UnmanagedImage overlay)
{
int num3;
PixelFormat pixelFormat = image.PixelFormat;
int width = image.Width;
int height = image.Height;
switch (pixelFormat)
{
case PixelFormat.Format8bppIndexed:
case PixelFormat.Format24bppRgb:
case PixelFormat.Format32bppRgb:
case PixelFormat.Format32bppArgb:
{
int num4 = (pixelFormat == PixelFormat.Format8bppIndexed) ? 1 : ((pixelFormat == PixelFormat.Format24bppRgb) ? 3 : 4);
int num5 = width * num4;
int num6 = image.Stride - num5;
int num7 = overlay.Stride - num5;
byte* numPtr = (byte*) image.ImageData.ToPointer();
byte* numPtr2 = (byte*) overlay.ImageData.ToPointer();
for (int j = 0; j < height; j++)
{
int num9 = 0;
while (num9 < num5)
{
num3 = numPtr[0] - numPtr2[0];
numPtr[0] = (num3 < 0) ? ((byte) -num3) : ((byte) num3);
num9++;
numPtr++;
numPtr2++;
}
numPtr += num6;
numPtr2 += num7;
}
return;
}
}
int num10 = (pixelFormat == PixelFormat.Format16bppGrayScale) ? 1 : ((pixelFormat == PixelFormat.Format48bppRgb) ? 3 : 4);
int num11 = width * num10;
int stride = image.Stride;
int num13 = overlay.Stride;
int num14 = (int) image.ImageData.ToPointer();
int num15 = (int) overlay.ImageData.ToPointer();
for (int i = 0; i < height; i++)
{
ushort* numPtr3 = (ushort*) (num14 + (i * stride));
ushort* numPtr4 = (ushort*) (num15 + (i * num13));
int num17 = 0;
while (num17 < num11)
{
num3 = numPtr3[0] - numPtr4[0];
numPtr3[0] = (num3 < 0) ? ((ushort) -num3) : ((ushort) num3);
num17++;
numPtr3++;
numPtr4++;
}
}
}
public override Dictionary<PixelFormat, PixelFormat> FormatTranslations
{
get
{
return this.formatTranslations;
}
}
}
}
|
d3e12d6995fdd22ecf5a6196c7ba0a7c6ddc7382
|
C#
|
berlamont/BluetoothBear
|
/BluetoothBear/IBleDevice.cs
| 2.546875
| 3
|
// The MIT License (MIT)
//
// Copyright (c) 2015 Liquimind Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BluetoothBear
{
/// <summary>
/// Bluetooth LE connection states.
/// </summary>
public enum BleConnectionState
{
/// <summary>
/// The device is not currently connected.
/// </summary>
Disconnected,
/// <summary>
/// The device is not currently connected.
/// </summary>
Disconnecting,
/// <summary>
/// The device is connected but no services have been discovered so it cannot be used.
/// </summary>
Connected,
/// <summary>
/// The device is in the process of creating a connection
/// </summary>
Connecting,
/// <summary>
/// The device has been connected and all the services have been enumerated.
/// </summary>
ConnectedWithServices
};
/// <summary>
/// Interface that defines the basic operations of Bluetooth LE Device
/// </summary>
public interface IBleDevice
{
/// <summary>
/// Occurs when connection state changed.
/// </summary>
event BleDeviceConnectionStateChangedEventHandler ConnectionStateChanged;
/// <summary>
/// Occurs when characteristic changed.
/// </summary>
event BleDeviceCharacteristicChangedEventHandler CharacteristicChanged;
/// <summary>
/// Occurs when characteristic read.
/// </summary>
event BleDeviceCharacteristicReadEventHandler CharacteristicRead;
/// <summary>
/// Occurs when characteristic write.
/// </summary>
event BleDeviceCharacteristicWriteEventHandler CharacteristicWrite;
/// <summary>
/// Occurs when descriptor read.
/// </summary>
event BleDeviceDescriptorReadEventHandler DescriptorRead;
/// <summary>
/// Occurs when descriptor write.
/// </summary>
event BleDeviceDescriptorWriteEventHandler DescriptorWrite;
/// <summary>
/// Occurs when read remote rssi.
/// </summary>
event BleDeviceReadRemoteRssiEventHandler ReadRemoteRssi;
/// <summary>
/// Occurs when reliable write completed.
/// </summary>
event BleDeviceReliableWriteCompletedEventHandler ReliableWriteCompleted;
/// <summary>
/// Occurs when services discovered.
/// </summary>
event BleDeviceServicesDiscoveredEventHandler ServicesDiscovered;
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
string Name { get; }
/// <summary>
/// Gets the ID. In Android and Windows this is a Mac Address on IOS this is a UUID
/// </summary>
/// <value>The UUI.</value>
string ID { get; }
/// <summary>
/// Gets the state of the connection.
/// </summary>
/// <value>The state of the connection.</value>
BleConnectionState ConnectionState { get; }
/// <summary>
/// Gets a value indicating whether this instance has performed service discovered.
/// </summary>
/// <value><c>true</c> if this instance is service discovered; otherwise, <c>false</c>.</value>
bool IsServiceDiscovered { get; }
/// <summary>
/// Connect to this device.
/// </summary>
void Connect();
/// <summary>
/// Disconnect this device.
/// </summary>
void Disconnect();
/// <summary>
/// Gets the characteristic.
/// </summary>
/// <returns>The characteristic.</returns>
/// <param name="id">Identifier.</param>
object GetCharacteristic(Guid id);
/// <summary>
/// Gets the characteristic.
/// </summary>
/// <returns>The characteristic.</returns>
/// <param name="id">Identifier.</param>
object GetCharacteristic(UInt16 id);
/// <summary>
/// Enables the notifications on a characteristic.
/// </summary>
/// <returns><c>true</c>, if notifications was enabled, <c>false</c> otherwise.</returns>
/// <param name="characteristic">Characteristic.</param>
/// <param name="enabled">If set to <c>true</c> enabled.</param>
bool EnableNotifications(object characteristic, bool enabled);
/// <summary>
/// Reads the characteristic.
/// </summary>
/// <param name="characteristic">Characteristic.</param>
void ReadCharacteristic(object characteristic);
/// <summary>
/// Writes the characteristic.
/// </summary>
/// <param name="characteristic">Characteristic.</param>
/// <param name="value">Value.</param>
/// <param name="isReliable">If set to <c>true</c> is reliable.</param>
void WriteCharacteristic(object characteristic, byte[] value, bool isReliable);
void DiscoverServices();
/// <summary>
/// Raises the connection state changed event.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">E.</param>
void OnConnectionStateChanged(IBleDevice sender, BleConnectionStateChangedEventArgs e);
/// <summary>
/// Raises the characteristic read event.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">E.</param>
void OnCharacteristicRead(IBleDevice sender, BleCharacteristicReadEventArgs e);
/// <summary>
/// Raises the characteristic write event.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">E.</param>
void OnCharacteristicWrite(IBleDevice sender, BleCharacteristicWriteEventArgs e);
/// <summary>
/// Raises the characteristic changed event.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">E.</param>
void OnCharacteristicChanged(IBleDevice sender, BleCharacteristicChangedEventArgs e);
/// <summary>
/// Raises the descriptor read event.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">E.</param>
void OnDescriptorRead(IBleDevice sender, BleDescriptorReadEventArgs e);
/// <summary>
/// Raises the descriptor write event.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">E.</param>
void OnDescriptorWrite(IBleDevice sender, BleDescriptorWriteEventArgs e);
/// <summary>
/// Raises the read remote rssi event.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">E.</param>
void OnReadRemoteRssi(IBleDevice sender, BleReadRemoteRssiEventArgs e);
/// <summary>
/// Raises the reliable write completed event.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">E.</param>
void OnReliableWriteCompleted(IBleDevice sender, BleReliableWriteCompletedEventArgs e);
/// <summary>
/// Raises the services discovered event.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">E.</param>
void OnServicesDiscovered(IBleDevice sender, BleServicesDiscoveredEventArgs e);
}
}
|
63ef295123f60df9b863edcb5dfb5f158fd7ea7e
|
C#
|
FlamingoLab/TheLostFire
|
/Assets/Voidless/Scripts/Behavior Trees/Composites/BehaviorTreeComposite.cs
| 2.8125
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Voidless
{
public abstract class BehaviorTreeComposite<T> : BehaviorTreeComponent<T>, IAgentComposite<T, IEnumerator<TreeState>> where T : IComponentAgent<T, IEnumerator<TreeState>>
{
private List<IAgentComponent<T, IEnumerator<TreeState>>> _children; /// <summary>Composite's Children.</summary>
/// <summary>Gets and Sets children property.</summary>
public List<IAgentComponent<T, IEnumerator<TreeState>>> children
{
get { return _children; }
set { _children = value; }
}
/// <summary>BehaviorTreeComposite default constructor.</summary>
/// <param name="_children">Children to add to this Composite.</param>
public BehaviorTreeComposite(params IAgentComponent<T, IEnumerator<TreeState>>[] _children)
{
children = new List<IAgentComponent<T, IEnumerator<TreeState>>>(_children.Length);
this.AddChildren(_children);
}
/// <summary>Ticks the component.</summary>
/// <param name="_agent">Component's Agent to tick.</param>
/// <returns>Tick's result.</returns>
public override abstract IEnumerator<TreeState> Tick(T _agent);
}
}
|
4b88323dfe43fdadf85ae5510eb8657cd135acd3
|
C#
|
GabGuerra/GerenciamentoIdentidadeCore
|
/GerenciamentoIdentidadeCore2/Repositories/LoginRepository.cs
| 2.71875
| 3
|
using GerenciamentoIdentidadeCore2.Models;
using GerenciamentoIdentidadeCore2.Models.Login;
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GerenciamentoIdentidadeCore2.Repositories
{
public class LoginRepository : MySqlRepository<UsuarioVD>, ILoginRepository
{
public LoginRepository(IConfiguration config) : base(config)
{}
public UsuarioVD RealizarLogin(string email, string senha)
{
string sql = @"SELECT
U.NOME_USUARIO,
U.CPF,
L.*
FROM
USUARIO U
INNER JOIN LOGIN L ON U.CPF = L.CPF_USUARIO
WHERE
L.SENHA = @SENHA
AND L.EMAIL = @EMAIL";
using (var cmd = new MySqlCommand(sql))
{
cmd.Parameters.AddWithValue("@SENHA", senha);
cmd.Parameters.AddWithValue("@EMAIL", email);
UsuarioVD usuario = ObterRegistro(cmd);
if(usuario !=null)
usuario.Login = new LoginVD(email, senha);
return usuario;
}
}
public void RealizarLogout()
{
}
public override UsuarioVD PopularDados(MySqlDataReader dr)
{
return new UsuarioVD
{
Cpf = dr["CPF"].ToString(),
Nome = dr["NOME_USUARIO"].ToString()
};
}
}
}
|
ad3564510f365c5a431d39add930712ce4f6f51e
|
C#
|
zetanove/programmare_con_csharp8
|
/Capitolo 03/SintassiBase/Program.cs
| 3.71875
| 4
|
/*
* Programmare con C# 8 guida completa
* Autore: Antonio Pelleriti
* Capitolo 3: sintassi di base
*/
using System;
namespace SintassiBase
{
class Program
{
static void Main(string[] args)
{
//Commenti
//commento su una linea
/*
* commento
* su più
* linee
*/
/* commento delimitato */
//dichiarazioni di variabili
int numero; //ok
int _numero; //ok
int numero1; //ok
string straße; //ok
string état = "état"; //ok
//errore, non può iniziare per numero
//int 1numero;
//un tipo primitivo è un oggetto
int i = 123;
string str = i.ToString(); //restituisce la sequenza di caratteri "123"
Console.WriteLine(str);
//variabili implicite
var str2 = "hello"; //implicitamente di tipo string
var ij = 0;
Console.WriteLine(str2.Length);
}
}
}
|
885c74143233080167b3af509cbced6ac0c5b308
|
C#
|
Ainslay/RPG
|
/RPG.API/Commands/PlayerCommands/AddPlayerCommandHandler.cs
| 2.703125
| 3
|
using System;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using RPG.API.Database;
using RPG.API.Model;
namespace RPG.API.Commands.PlayerCommands
{
public class AddPlayerCommandHandler : IRequestHandler<AddPlayerCommand, Guid>
{
private ApplicationDbContext _context;
public AddPlayerCommandHandler(ApplicationDbContext context)
{
_context = context;
}
public async Task<Guid> Handle(AddPlayerCommand command, CancellationToken cancellationToken)
{
var player = new Player(command.Name, command.Proffesion, command.Level,
command.Experience, command.Strength, command.Dexterity, command.Intelligence);
_context.Players.Add(player);
await _context.SaveChangesAsync();
return player.PlayerId;
}
}
}
|
f219f7fa0d479c1fd02fdf851ddd74d67ccc8890
|
C#
|
1-designer-1/Pract-11
|
/Pract 11/Form1.cs
| 3.140625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace Pract_11
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void выходToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void оПрограммеToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Практическая работа № 11\n" +
"Серегин Денис \n" +
"ИСП-31\n" +
"Задание 1 \n" +
"Дана строка '23 2+3 2++3 2+++3 445 677'. Напишите регулярное выражение, которое найдет строки 23, 2+3, 2++3, 2+++3, не захватив остальные. \n" +
"Задание 2 \n" +
"Дана строка '*+ *q+ *qq+ *qqq+ *qqq qqq+'. Напишите регулярное выражение, которое найдет строки *+, *q+, *qq+, *qqq+, не захватив остальные. ", "О программе", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
private void получитьОтветToolStripMenuItem_Click(object sender, EventArgs e)
{
Regex regex1 = new Regex("2[+]*3");
Regex regex2 = new Regex("[*][q]*[+]");
MatchCollection matches1 = regex1.Matches(textBox1.Text);
MatchCollection matches2 = regex2.Matches(textBox2.Text);
for (int i = 0; i < matches1.Count; i++)
{
textBox3.Text += matches1[i].Value + " ";
}
for (int j = 0; j < matches2.Count; j++)
{
textBox4.Text += matches2[j].Value + " ";
}
}
private void удалитьToolStripMenuItem_Click(object sender, EventArgs e)
{
textBox3.Clear();
textBox4.Clear();
}
}
}
|
8b6b70753e86bca266916b7b19ac82f33d3a9a68
|
C#
|
user1311/SportsStore
|
/SportsStore/Models/ViewModels/ProductCategoryViewModel.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace SportsStore.Models.ViewModels
{
public class ProductCategoryViewModel
{
//[Required(ErrorMessage = "You must provide product name"), MinLength(3), MaxLength(40)]
//public string ProductName { get; set; }
//[MaxLength(20, ErrorMessage = "Maximum of 20 characters"), MinLength(5, ErrorMessage = "Minumum 5 charachters")]
//public string QuantityPerUnit { get; set; }
//[Column(TypeName = "Money")]
//public decimal UnitPrice { get; set; }
//[Required]
//public int? UnitsInStock { get; set; }
//[Required]
//public int? UnitsOnOrder { get; set; }
//[Required]
//public int? ReorderLevel { get; set; }
//[Required]
//public bool Discounted { get; set; }
//[Required(ErrorMessage ="Category must be selected")]
//public int CategoryID { get; set; }
public Product Product { get; set; }
public IEnumerable<Category> Categories { get; set; }
}
}
|
65f73278264869254749df5f43237e3be805344a
|
C#
|
shendongnian/download4
|
/latest_version_download2/64246-11730711-27385074-2.cs
| 3.140625
| 3
|
public sealed class PlaceHolderAttribute:ValidationAttribute
{
private readonly string _placeholderValue;
public override bool IsValid(object value)
{
var stringValue = value.ToString();
if (stringValue == _placeholderValue)
{
ErrorMessage = string.Format("Please fill out {0}", _placeholderValue);
return false;
}
return true;
}
public PlaceHolderAttribute(string placeholderValue)
{
_placeholderValue = placeholderValue;
}
}
|
431d791bfbfa806713188dc585b34f98f0e9a229
|
C#
|
alexoah/CSharpPlayground
|
/W3School-CSExercises/CS-Classes_Objects/csClasses_ObjectsE4.cs
| 3.734375
| 4
|
/**
* from C# Classes/Objects: Exercise 4 ( https://www.w3schools.com/cs/exercise.asp?filename=exercise_classes4 )
*
* question:
* Call the fullThrottle() method from the object:
*
* class Car
* {
* public void fullThrottle()
* {
* Console.WriteLine("The car is going as fast as it can!");
* }
*
* static void Main(string[] args)
* {
* Car myObj = new Car();
* _____._______________
* }
* }
*
*/
class Car
{
public void fullThrottle()
{
Console.WriteLine("The car is going as fast as it can!");
}
static void Main(string[] args)
{
Car myObj = new Car();
myObj.fullThrottle();
}
}
|
0a650d4d7203e26b189e223e48501097f6c3c1c3
|
C#
|
jhmartin404/RPGHeroPrototype
|
/RPGHero/Assets/Scripts/InventoryItemDetails.cs
| 2.65625
| 3
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class InventoryItemDetails : MonoBehaviour
{
private InventoryItem item;
private Text itemText;
public InventoryItem Item
{
get
{
return item;
}
}
// Use this for initialization
void Start ()
{
itemText = gameObject.GetComponentInChildren<Text>();
}
public void SetItem(InventoryItem itm, bool equipped)
{
item = itm;
if(item != null)
{
itemText = gameObject.GetComponentInChildren<Text>();
gameObject.GetComponentsInChildren<Image> () [1].enabled = true;
gameObject.GetComponentsInChildren<Image> () [1].sprite = item.GetItemImage ();
if(equipped)
itemText.text = "Equipped\n\n"+item.ToString();
else if(!equipped)
itemText.text = item.ToString();
}
else
{
itemText = gameObject.GetComponentInChildren<Text>();
gameObject.GetComponentsInChildren<Image> () [1].enabled = false;
itemText.text = "No Item";
}
}
}
|
140684ca4302e48b9d3cb4f0ca399e0c12015f99
|
C#
|
robdavey555/Demo
|
/Eintech.Data/EintechContext.cs
| 2.8125
| 3
|
using Eintech.Data.Extensions;
using Eintech.Data.ModelConfiguration;
using Eintech.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
namespace Eintech.Data
{
[ExcludeFromCodeCoverage]
public class EintechContext : DbContext
{
public EintechContext(DbContextOptions options) : base(options)
{
}
public DbSet<Person> People { get; set; }
public DbSet<Group> Groups { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//set database config using FluentAPI
modelBuilder.ApplyConfiguration(new GroupConfiguration());
modelBuilder.ApplyConfiguration(new PersonConfiguration());
//always seed data for this demo
modelBuilder.Seed();
}
public override int SaveChanges()
{
//get entities that have been added where _Base class is inherited
var entries = ChangeTracker
.Entries()
.Where(e => e.Entity is _Base && (e.State == EntityState.Added));
//loop added enities
foreach (var entityEntry in entries)
{
((_Base)entityEntry.Entity).CreatedOn = DateTime.Now; //automatically ensure that date is set
}
return base.SaveChanges();
}
}
}
|
e4c2ac17da401c966f5a2d1c79fe512111996ad8
|
C#
|
bastienmurot/AltDotNet_2016_01_RPN
|
/RPN_Test/RPNTest.cs
| 3.3125
| 3
|
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace RPN_Test
{
public class RPN
{
public static int Compute(string input)
{
var stack = new Stack<int>();
foreach (var data in input.Split(' '))
{
int value;
if (int.TryParse(data, out value))
{
stack.Push(value);
}
else
{
var op1 = stack.Pop();
var op2 = stack.Pop();
switch (data)
{
case "+":
stack.Push(op2 + op1);
break;
case "-":
stack.Push(op2 - op1);
break;
case "*":
stack.Push(op2 * op1);
break;
case "/":
stack.Push(op2 / op1);
break;
}
}
}
return stack.Peek();
}
}
[TestClass]
public class RPNTest
{
[TestMethod]
public void Test_Only_One_Operand()
{
var result = RPN.Compute("5");
Assert.AreEqual(result, 5);
}
[TestMethod]
public void Test_Two_Operand_Single_Add()
{
var result = RPN.Compute("5 4 +");
Assert.AreEqual(result, 9);
}
[TestMethod]
public void Test_Three_Operand_Double_Add()
{
var result = RPN.Compute("5 4 1 + +");
Assert.AreEqual(result, 10);
}
[TestMethod]
public void Test_Three_Operand_Double_Add_Other()
{
var result = RPN.Compute("5 4 + 1 +");
Assert.AreEqual(result, 10);
}
[TestMethod]
public void Test_Two_Operand_Single_Soustract()
{
var result = RPN.Compute("5 4 -");
Assert.AreEqual(result, 1);
}
[TestMethod]
public void Test_Three_Operand_Double_Soustract()
{
var result = RPN.Compute("5 4 1 - -");
Assert.AreEqual(result, 2);
}
[TestMethod]
public void Test_Three_Operand_Double_Soustract_Other()
{
var result = RPN.Compute("5 4 - 1 -");
Assert.AreEqual(result, 0);
}
[TestMethod]
public void Test_Two_Operand_Single_Multiply()
{
var result = RPN.Compute("5 4 *");
Assert.AreEqual(result, 20);
}
[TestMethod]
public void Test_Two_Operand_Single_Divide()
{
var result = RPN.Compute("20 4 /");
Assert.AreEqual(result, 5);
}
[TestMethod]
public void Test_Complex_Operation()
{
var result = RPN.Compute("5 1 2 + 4 * + 3 -");
Assert.AreEqual(result, 14);
}
}
}
|
21a2b7dfe025f6870a56846d98800e22b9a3d19a
|
C#
|
mlstroud/rock-paper-scissors
|
/RockPaperScissors/Models/RockPaperScissors.cs
| 3.203125
| 3
|
using System;
using System.Collections.Generic;
namespace Game.Models
{
public class RockPaperScissors
{
public string UserChoice { get; set; }
public string ComputerChoice { get; set; }
public static string[] _computerChoices = { "rock", "paper", "scissors" };
public static Dictionary<string, string> winList = new Dictionary<string, string>
{
{ "rock", "scissors" },
{ "scissors", "paper" },
{ "paper", "rock" }
};
public RockPaperScissors(string userChoice)
{
UserChoice = userChoice;
Random rand = new Random();
ComputerChoice = _computerChoices[rand.Next(_computerChoices.Length)];
}
public string GetGameResult()
{
string result = "";
if (UserChoice == ComputerChoice)
{
result = "draw";
}
else if (winList.ContainsKey(UserChoice) && winList[UserChoice] == ComputerChoice)
{
result = "win";
}
else
{
result = "loss";
}
return result;
}
}
}
|
73a86a9a1b0965f61a31d7ea238da97b313f5926
|
C#
|
xy19xiaoyu/TG
|
/Patentquery_TLC/BLL/Authority.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
using TLC.DataAccessLayer;
namespace TLC.BusinessLogicLayer
{
/// <summary>
/// Ȩ
/// </summary>
public class Authority
{
/*** ֶ̬ ***/
private int _AuthorityId;
private byte _Types;
private string _Url;
private string _Title;
private string _Note;
/*** 캯 ***/
//Authority
public Authority(int authorityId, byte types, string url, string title, string note)
{
if (String.IsNullOrEmpty(title))
throw (new NullReferenceException("title"));
_AuthorityId = authorityId;
_Types = types;
_Url = url;
_Title = title;
_Note = note;
}
/*** ***/
//ȨID
public int AuthorityId
{
get { return _AuthorityId; }
set { _AuthorityId = value; }
}
//
public byte Types
{
get { return _Types; }
set { _Types = value; }
}
//ַ
public string Url
{
get
{
if (String.IsNullOrEmpty(_Url))
return string.Empty;
else
return _Url;
}
set { _Url = value; }
}
//
public string Title
{
get
{
if (String.IsNullOrEmpty(_Title))
return string.Empty;
else
return _Title;
}
set { _Title = value; }
}
//
public string Note
{
get
{
if (String.IsNullOrEmpty(_Note))
return string.Empty;
else
return _Note;
}
set { _Note = value; }
}
/*** ***/
/// <summary>
/// ָȨϢ
/// </summary>
/// <returns></returns>
public bool Save()
{
DataAccess DALLayer = DataAccessHelper.GetDataAccess();
if (_AuthorityId <= DefaultValues.GetAuthorityIdMinValue())
{
int TempId = DALLayer.CreateNewAuthority(this);
if (TempId > 0)
{
_AuthorityId = TempId;
return true;
}
else
return false;
}
else
return (DALLayer.UpdateAuthority(this));
}
/// <summary>
/// ɾȨ
/// </summary>
/// <returns></returns>
public bool Delete()
{
DataAccess DALLayer = DataAccessHelper.GetDataAccess();
return DALLayer.DeleteAuthority(this.AuthorityId);
}
/*** ̬ ***/
/// <summary>
/// Ȩ
/// </summary>
/// <returns></returns>
public static int InsertAuthority(byte types, string url, string title, string note)
{
if (String.IsNullOrEmpty(title))
throw (new NullReferenceException("title"));
Authority insertAuthority = new Authority(0, types, url, title, note);
if (insertAuthority.Save())
{
return insertAuthority.AuthorityId;
}
else
{
return 0;
}
}
/// <summary>
/// ɾָȨIDȨ
/// </summary>
/// <param name="authorityId"></param>
/// <returns></returns>
public static bool DeleteAuthority(int authorityId)
{
DataAccess DALLayer = DataAccessHelper.GetDataAccess();
return (DALLayer.DeleteAuthority(authorityId));
}
/// <summary>
/// ָȨIDȨ
/// </summary>
/// <param name="AuthorityId"></param>
/// <returns></returns>
public static bool UpdateAuthority(int authorityId, byte types, string url, string title, string note)
{
if (String.IsNullOrEmpty(title))
throw (new NullReferenceException("title"));
Authority updateAuthority = Authority.GetAuthorityByAuthorityId(authorityId);
if (updateAuthority != null)
{
updateAuthority.Types = types;
updateAuthority.Url = url;
updateAuthority.Title = title;
updateAuthority.Note = note;
return (updateAuthority.Save());
}
else
return false;
}
/// <summary>
/// ȡеȨб
/// </summary>
/// <returns></returns>
public static List<Authority> GetAllAuthoritys()
{
DataAccess DALLayer = DataAccessHelper.GetDataAccess();
return (DALLayer.GetAllAuthoritys());
}
/// <summary>
/// ȡȨIDȨ
/// </summary>
/// <param name="authorityId"></param>
/// <returns></returns>
public static Authority GetAuthorityByAuthorityId(int authorityId)
{
DataAccess DALLayer = DataAccessHelper.GetDataAccess();
return (DALLayer.GetAuthorityByAuthorityId(authorityId));
}
/// <summary>
/// ȡַָȨ
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static Authority GetAuthorityByUrl(string url)
{
DataAccess DALLayer = DataAccessHelper.GetDataAccess();
return (DALLayer.GetAuthorityByUrl(url));
}
}
}
|
8d57651456f0800f1fa998eb0fbc0c971e934d7d
|
C#
|
etking19/icon600
|
/WindowsMain/WindowsFormServer/FormLicense.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormClient
{
public partial class FormLicense : Form
{
private delegate void DelegateUI(int counter);
private int mCounter;
private BackgroundWorker worker;
public FormLicense()
{
InitializeComponent();
}
private void FormLicense_Load(object sender, EventArgs e)
{
this.FormClosed += FormLicense_FormClosed;
buttonOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.AcceptButton = buttonOK;
mCounter = 60;
labelLicense.Text = "No license found. Please make sure you plug in the license dongle.";
labelCounter.Text = "Application will close in 60 seconds";
// create a counter
worker = new BackgroundWorker();
worker.WorkerSupportsCancellation = true;
worker.DoWork += worker_DoWork;
worker.RunWorkerAsync();
}
void FormLicense_FormClosed(object sender, FormClosedEventArgs e)
{
worker.CancelAsync();
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
while(true)
{
// change the counter
SetMessage(mCounter--);
Thread.Sleep(1000);
}
}
public void SetMessage(int counter)
{
if(this.InvokeRequired)
{
this.Invoke(new DelegateUI(SetMessage), counter);
return;
}
labelCounter.Text = String.Format("Application will close in {0} seconds", counter);
if (counter <= 0)
{
this.DialogResult = System.Windows.Forms.DialogResult.OK;
this.Close();
}
}
}
}
|
6fc22bf4b5d900a8304cebf5b9f0fdf757e52289
|
C#
|
dawidkomorowski/geisha
|
/src/Geisha.Editor/Core/EventBus.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using NLog;
namespace Geisha.Editor.Core
{
public interface IEvent
{
}
public interface IEventBus
{
void RegisterEventHandler<TEvent>(Action<TEvent> handler) where TEvent : IEvent;
void SendEvent<TEvent>(TEvent @event) where TEvent : IEvent;
}
public sealed class EventBus : IEventBus
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private static readonly EventBus DefaultInstance = new();
private readonly Dictionary<Type, object> _eventHandlers = new();
public static IEventBus Default => DefaultInstance;
public void RegisterEventHandler<TEvent>(Action<TEvent> handler) where TEvent : IEvent
{
_eventHandlers.Add(typeof(TEvent), handler);
}
public void SendEvent<TEvent>(TEvent @event) where TEvent : IEvent
{
Logger.Debug("Event sent: {0}.", typeof(TEvent));
if (_eventHandlers.TryGetValue(typeof(TEvent), out var eventHandler))
{
((Action<TEvent>)eventHandler).Invoke(@event);
}
else
{
Logger.Warn("No event handler registered for event of type {0}.", typeof(TEvent));
}
}
}
}
|
d76b7fa0deb3f3b8bfdae47b8a9a617a0981d11d
|
C#
|
SimpleLonely/NJUMSCBot
|
/NJUMSCBot/Data/Data.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using NJUMSCBot.Models;
namespace NJUMSCBot.Data
{
public static class Data
{
static Data()
{
Constants = Read<StringConstants>(nameof(StringConstants));
DepartmentInfo = Read<Info<Department>>("DepartmentInfo");
BenefitInfo = Read<Info<Item>>("BenefitInfo");
ActivityInfo = Read<Info<Item>>("ClubActivityInfo");
CompetitionInfo = Read<Info<Item>>("CompetitionInfo");
ClubIntro = Read<ClubIntroduction>("ClubIntroduction");
}
public static StringConstants Constants { get; private set; }
public static Info<Department> DepartmentInfo { get; private set; }
public static Info<Item> BenefitInfo { get; private set; }
public static Info<Item> ActivityInfo { get; private set; }
public static Info<Item> CompetitionInfo { get; private set; }
public static ClubIntroduction ClubIntro { get; private set; }
/// <summary>
/// Fetch data from json files
/// </summary>
/// <typeparam name="TReturn">Type of return value</typeparam>
/// <returns>deserialized data in json files of type TReturn </returns>
private static TReturn Read<TReturn>(string fileName)
{
string content = Properties.Resources.ResourceManager.GetString(fileName);
return JsonConvert.DeserializeObject<TReturn>(content);
}
public static void ForEach<T>(this IEnumerable<T> array, Action<T> action)
{
foreach(T a in array)
{
action(a);
}
}
}
}
|
a382d559537addcacee5f919e18a715c3eb25c05
|
C#
|
MarcelloMello2/DxgiScreenCapture
|
/DxgiScreenCapture/DXGIOutputDuplication.cs
| 2.671875
| 3
|
using SharpDX;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
using SharpDX.Mathematics.Interop;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace DxgiScreenCapture
{
class DXGIOutputDuplication
{
Adapter _adapter;
SharpDX.Direct3D11.Device _device;
SharpDX.Direct3D11.DeviceContext _deviceContext;
OutputDuplication _outputDuplication;
OutputDescription _description;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern bool GetMonitorInfo(IntPtr hMonitor, ref MonitorInfoEx lpmi);
public DXGIOutputDuplication(Adapter adapter,
SharpDX.Direct3D11.Device device,
OutputDuplication outputDuplication, OutputDescription description)
{
_adapter = adapter;
_device = device;
_deviceContext = _device.ImmediateContext;
_outputDuplication = outputDuplication;
_description = description;
}
public Rectangle DesktopCoordinates
{
get
{
RawRectangle rect = _description.DesktopBounds;
return new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);
}
}
internal bool IsPrimary()
{
MonitorInfoEx monitorInfo = new MonitorInfoEx();
monitorInfo.Size = Marshal.SizeOf(monitorInfo);
GetMonitorInfo(_description.MonitorHandle, ref monitorInfo);
return (monitorInfo.Flags & MONITORINFOF_PRIMARY) == MONITORINFOF_PRIMARY;
}
// size of a device name string
private const int CCHDEVICENAME = 32;
private const uint MONITORINFOF_PRIMARY = 1;
/// <summary>
/// The MONITORINFOEX structure contains information about a display monitor.
/// The GetMonitorInfo function stores information into a MONITORINFOEX structure or a MONITORINFO structure.
/// The MONITORINFOEX structure is a superset of the MONITORINFO structure. The MONITORINFOEX structure adds a string member to contain a name
/// for the display monitor.
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal struct MonitorInfoEx
{
/// <summary>
/// The size, in bytes, of the structure. Set this member to sizeof(MONITORINFOEX) (72) before calling the GetMonitorInfo function.
/// Doing so lets the function determine the type of structure you are passing to it.
/// </summary>
public int Size;
/// <summary>
/// A RECT structure that specifies the display monitor rectangle, expressed in virtual-screen coordinates.
/// Note that if the monitor is not the primary display monitor, some of the rectangle's coordinates may be negative values.
/// </summary>
public RectStruct Monitor;
/// <summary>
/// A RECT structure that specifies the work area rectangle of the display monitor that can be used by applications,
/// expressed in virtual-screen coordinates. Windows uses this rectangle to maximize an application on the monitor.
/// The rest of the area in rcMonitor contains system windows such as the task bar and side bars.
/// Note that if the monitor is not the primary display monitor, some of the rectangle's coordinates may be negative values.
/// </summary>
public RectStruct WorkArea;
/// <summary>
/// The attributes of the display monitor.
///
/// This member can be the following value:
/// 1 : MONITORINFOF_PRIMARY
/// </summary>
public uint Flags;
/// <summary>
/// A string that specifies the device name of the monitor being used. Most applications have no use for a display monitor name,
/// and so can save some bytes by using a MONITORINFO structure.
/// </summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCHDEVICENAME)]
public string DeviceName;
public void Init()
{
this.Size = 40 + 2 * CCHDEVICENAME;
this.DeviceName = string.Empty;
}
}
internal void Dispose()
{
if (_outputDuplication != null)
{
_outputDuplication.Dispose();
_outputDuplication = null;
}
if (_device != null)
{
_device.Dispose();
_device = null;
}
if (_deviceContext != null)
{
_deviceContext.Dispose();
_deviceContext = null;
}
if (_adapter != null)
{
_adapter.Dispose();
_adapter = null;
}
}
internal bool AcquireNextFrame(int timeout, Action<Surface1, Rectangle, Action<IntPtr, int, Rectangle>> copyAction, Action<IntPtr, int, Rectangle> copyFrameBuffer)
{
SharpDX.DXGI.Resource desktopResource;
try
{
_outputDuplication.AcquireNextFrame(timeout, out OutputDuplicateFrameInformation fi, out desktopResource);
}
catch (SharpDXException e)
{
if (e.ResultCode == DXGIError.DXGI_ERROR_ACCESS_LOST)
{
throw;
}
return false;
}
if (desktopResource == null)
{
return false;
}
try
{
using (Texture2D textureResource = desktopResource.QueryInterface<Texture2D>())
{
Texture2DDescription desc = textureResource.Description;
Texture2DDescription textureDescription = desc;
textureDescription.MipLevels = 1;
textureDescription.ArraySize = 1;
textureDescription.SampleDescription.Count = 1;
textureDescription.SampleDescription.Quality = 0;
textureDescription.Usage = ResourceUsage.Staging;
textureDescription.BindFlags = 0;
textureDescription.CpuAccessFlags = CpuAccessFlags.Read;
textureDescription.OptionFlags = ResourceOptionFlags.None;
using (Texture2D d3d11Texture2D = new Texture2D(_device, textureDescription))
{
_device.ImmediateContext.CopyResource(textureResource, d3d11Texture2D);
using (Surface1 surface = d3d11Texture2D.QueryInterface<Surface1>())
{
copyAction(surface, this.DesktopCoordinates, copyFrameBuffer);
return true;
}
}
}
}
finally
{
if (desktopResource != null)
{
desktopResource.Dispose();
}
_outputDuplication.ReleaseFrame();
}
}
/// <summary>
/// The RECT structure defines the coordinates of the upper-left and lower-right corners of a rectangle.
/// </summary>
/// <see cref="http://msdn.microsoft.com/en-us/library/dd162897%28VS.85%29.aspx"/>
/// <remarks>
/// By convention, the right and bottom edges of the rectangle are normally considered exclusive.
/// In other words, the pixel whose coordinates are ( right, bottom ) lies immediately outside of the the rectangle.
/// For example, when RECT is passed to the FillRect function, the rectangle is filled up to, but not including,
/// the right column and bottom row of pixels. This structure is identical to the RECTL structure.
/// </remarks>
[StructLayout(LayoutKind.Sequential)]
public struct RectStruct
{
/// <summary>
/// The x-coordinate of the upper-left corner of the rectangle.
/// </summary>
public int Left;
/// <summary>
/// The y-coordinate of the upper-left corner of the rectangle.
/// </summary>
public int Top;
/// <summary>
/// The x-coordinate of the lower-right corner of the rectangle.
/// </summary>
public int Right;
/// <summary>
/// The y-coordinate of the lower-right corner of the rectangle.
/// </summary>
public int Bottom;
}
}
}
|
d0e74c4e71d46144b8433fc3bfb8a6712cd773b5
|
C#
|
Baari125/downloading-files
|
/kopiowanie/Kopiowanie/Kopiowanie/Conversion.cs
| 2.5625
| 3
|
using System.Text;
using System;
using System.IO;
using Spire.Doc;
using Spire.Pdf;
using Spire.Xls;
using System.Net;
namespace Kopiowanie
{
class Conversion
{
private static string DirectoryPath = Directory.GetCurrentDirectory();
public Conversion() { }
~Conversion() { GC.Collect(); }
public void ConvertFromDoc(string link, string path, string file)
{
Document document = new Document();
WebClient Client = new WebClient();
Client.DownloadFile(link, Path.Combine(DirectoryPath, "Plik\\DocFile.doc"));
document.LoadFromFile(Path.Combine(DirectoryPath, "Plik\\DocFile.doc"));
document.SaveToFile(Path.Combine(DirectoryPath, "Plik\\1.txt"), Spire.Doc.FileFormat.Txt);
string content = File.ReadAllText(Path.Combine(DirectoryPath, "Plik\\1.txt"));
JsonFile jf = new JsonFile();
jf.CreatJson(link, content, Path.Combine(path, file));
}
public void ConvertFromPdf(string link, string path, string file)
{
PdfDocument pdfDocument = new PdfDocument();
WebClient Client = new WebClient();
Client.DownloadFile(link, Path.Combine(DirectoryPath, "Plik\\PdfFile.pdf"));
pdfDocument.LoadFromFile(Path.Combine(DirectoryPath, "Plik\\PdfFile.pdf"));
pdfDocument.SaveToFile(Path.Combine(DirectoryPath, "Plik\\DocFile.doc"), Spire.Pdf.FileFormat.DOC);
Document document = new Document();
document.LoadFromFile(Path.Combine(DirectoryPath, "Plik\\DocFile.doc"));
document.SaveToFile(Path.Combine(DirectoryPath, "Plik\\1.txt"), Spire.Doc.FileFormat.Txt);
string content = File.ReadAllText(Path.Combine(DirectoryPath, "Plik\\1.txt"));
JsonFile jf = new JsonFile();
jf.CreatJson(link, content, Path.Combine(path, file));
}
public void ConvertFromXls(string link, string path, string file)
{
Workbook workbook = new Workbook();
WebClient Client = new WebClient();
Client.DownloadFile(link, Path.Combine(DirectoryPath, "Plik\\XlsFile.xls"));
workbook.LoadFromFile(Path.Combine(DirectoryPath, "Plik\\XlsFile.xls"));
Worksheet sheet = workbook.Worksheets[0];
sheet.SaveToFile(Path.Combine(DirectoryPath, "Plik\\1.txt"), " ", Encoding.UTF8);
string content = File.ReadAllText(Path.Combine(DirectoryPath, "Plik\\1.txt"));
JsonFile jf = new JsonFile();
jf.CreatJson(link, content, Path.Combine(path, file));
}
}
}
|
aa3335448281d2d71ca2fcb844d4f08d46832be0
|
C#
|
MustaqHussain/UcbManagementInformation
|
/UcbManagementInformation.Server.DataAccess/Repositories/DataAccessUtilities.cs
| 2.984375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UcbManagementInformation.Server.IoC.ServiceLocation;
using UcbManagementInformation.Server.DataAccess.Repositories;
namespace UcbManagementInformation.Server.DataAccess
{
public class DataAccessUtilities
{
private DataAccessUtilities()
{ }
public static T RepositoryLocator<T>(IObjectContext context)
{
Dictionary<string, object> contextHolder = new Dictionary<string, object>();
contextHolder.Add("context", context);
return SimpleServiceLocator.Instance.Get<T>(contextHolder);
}
public static T RepositoryLocator<T>()
{
return RepositoryLocator<T>(new NullObjectContext());
}
public static string GetSystemParameterByName(string Name)
{
IUcbManagementInformationRepository<MCSystemParameter> systemParameterRepository = DataAccessUtilities.RepositoryLocator<IUcbManagementInformationRepository<MCSystemParameter>>();
MCSystemParameter parameter = systemParameterRepository.Find(x => x.Name == Name).FirstOrDefault();
if (parameter != null)
{
return parameter.ParameterValue;
}
else
{
return null;
}
}
/// <summary>
/// A comparer to allow sorting / grouping by period when considering a date value
/// </summary>
public class DatePeriodComparer : IEqualityComparer<DateTime>
{
public bool Equals(DateTime x, DateTime y)
{
return ConvertDateToPeriod(x) == ConvertDateToPeriod(y);
}
public int GetHashCode(DateTime obj)
{
return ConvertDateToPeriod(obj).GetHashCode();
}
}
/// <summary>
/// Takes a date and returns the corresponding Period value
/// </summary>
/// <param name="dateToConvert">DateTime to find the period of</param>
/// <returns>string representing Period value</returns>
public static string ConvertDateToPeriod(DateTime dateToConvert)
{
int Year = dateToConvert.Year;
int Month = dateToConvert.Month;
if (Month == 12) Month = 0;
Month += 2 - (Month % 3);
string FormattedDate = Year.ToString() + Month.ToString().PadLeft(2, '0');
return FormattedDate;
}
}
}
|
c90fb413c960d0befe3662e07b264cf4d05f6171
|
C#
|
calumjs/DateCalculator
|
/DateCalculator/Date.cs
| 3.6875
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace DateCalculator
{
public class Date : IComparable<Date>
{
public int Days { get; set; }
public int Months { get; set; }
public int Years { get; set; }
public Date(int year, int month, int day)
{
this.Years = year;
this.Months = month;
this.Days = day;
}
public int CompareTo(Date other)
{
if (this.Years < other.Years)
{
return -1;
}
else if (this.Years > other.Years)
{
return 1;
}
else if (this.Months < other.Months)
{
return -1;
}
else if (this.Months > other.Months)
{
return 1;
}
else if (this.Days < other.Days)
{
return -1;
}
else if (this.Days > other.Days)
{
return 1;
}
else
{
return 0;
}
}
public static bool operator <(Date one, Date two)
{
return one.CompareTo(two) < 0;
}
public static bool operator >(Date one, Date two)
{
return two.CompareTo(one) < 0;
}
public static bool operator ==(Date one, Date two)
{
return one.CompareTo(two) == 0;
}
public static bool operator !=(Date one, Date two)
{
return one.CompareTo(two) != 0;
}
}
}
|
26bd67c69b48df31cc93b1737240274108563e34
|
C#
|
AbhishekAzad08/ToyRobot
|
/ToyRobotEngine/Handlers/CommandHandler.cs
| 3.578125
| 4
|
using System;
using System.Collections.Generic;
using System.Text;
using ToyRobotEngine.Enums;
namespace ToyRobotEngine.Handlers
{
public class CommandHandler
{
/// <summary>
/// Gets the input string provided by the user and returns a command object
/// </summary>
/// <param name="cmd"></param>
/// <returns></returns>
public static Command GetCommands(string cmd)
{
Command command = new Command();
Direction dir = new Direction();
cmd = cmd.ToUpper();
string[] commands = cmd.Split(' ');
try
{
if (commands.Length > 1)
{
string[] commandParam = commands[1].Split(',');
if (commandParam.Length < 2)
return command;
command.NextPosition = new Position(
Convert.ToInt32(commandParam[0]), Convert.ToInt32(commandParam[1]));
if (commandParam.Length > 2)
{
try
{
dir.CurrentDirection = (Directions)Enum.Parse(typeof(Directions), commandParam[2]);
command.Direction = dir;
}
catch (ArgumentException)
{
Console.WriteLine($"{commandParam[2]} is not a valid direction. Please enter a valid direction.");
return new Command();//return empty command in case of exception. Validity check in the next step will return false.
}
}
}
command.NextCommand = (Commands)Enum.Parse(typeof(Commands), commands[0]);
}
catch (FormatException)
{
Console.WriteLine($"Input not in a correct format.");
return new Command(); //return empty command in case of exception. Validity check in the next step will return false.
}
catch (ArgumentException)
{
Console.WriteLine($"{commands[0]} is not a valid command. Please enter a valid command.");
return new Command(); //return empty command in case of exception. Validity check in the next step will return false.
}
return command;
}
}
}
|
68a7dfa34d68da1209f144307f8eb319098eb81e
|
C#
|
SherlockPei/CodeProject
|
/Compress/Compressor/SharpCompressor.cs
| 2.765625
| 3
|
/*************************************************************************
* Copyright © 2020 Mogoson. All rights reserved.
*------------------------------------------------------------------------
* File : SharpCompressor.cs
* Description : Sharp compressor.
*------------------------------------------------------------------------
* Author : Mogoson
* Version : 1.0
* Date : 5/30/2020
* Description : Initial development version.
*************************************************************************/
using MGS.DesignPattern;
using SharpCompress.Archives;
using SharpCompress.Common;
using System;
using System.Collections.Generic;
using System.IO;
namespace MGS.Compress
{
/// <summary>
/// Sharp compressor.
/// </summary>
public class SharpCompressor : Singleton<SharpCompressor>, ICompressor
{
#region Private Method
/// <summary>
/// Constructor.
/// </summary>
private SharpCompressor() { }
#endregion
#region Public Method
/// <summary>
/// Compress entrie[File or Directory] to dest file.
/// </summary>
/// <param name="entrie">Target entrie[File or Directory].</param>
/// <param name="destFile">The dest file.</param>
/// <param name="progressCallback">Progress callback.</param>
/// <param name="completeCallback">Complete callback.</param>
/// <param name="errorCallback">Error callback.</param>
public void Compress(string entrie, string destFile,
Action<float> progressCallback = null,
Action<string> completeCallback = null,
Action<string> errorCallback = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Compress entrie[Files or Directories] to dest file.
/// </summary>
/// <param name="entries">Target entrie[Files or Directories].</param>
/// <param name="destFile">The dest file.</param>
/// <param name="progressCallback">Progress callback.</param>
/// <param name="completeCallback">Complete callback.</param>
/// <param name="errorCallback">Error callback.</param>
public void Compress(IEnumerable<string> entries, string destFile,
Action<float> progressCallback = null,
Action<string> completeCallback = null,
Action<string> errorCallback = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Decompress file to dest dir [Support zip, rar, tar, gzip, 7z].
/// </summary>
/// <param name="filePath">Target file.</param>
/// <param name="destDir">The dest decompress directory.</param>
/// <param name="clear">Clear the dest dir before decompress.</param>
/// <param name="progressCallback">Progress callback.</param>
/// <param name="completeCallback">Complete callback.</param>
/// <param name="errorCallback">Error callback.</param>
public void Decompress(string filePath, string destDir, bool clear = false,
Action<float> progressCallback = null,
Action<string> completeCallback = null,
Action<string> errorCallback = null)
{
if (!File.Exists(filePath))
{
var error = string.Format("Decompress file error: Can not find the file in the path {0}", filePath);
errorCallback?.Invoke(error);
return;
}
if (string.IsNullOrEmpty(destDir))
{
var error = "Decompress file error: The dest directory can not be null or empty.";
errorCallback?.Invoke(error);
return;
}
try
{
if (clear)
{
if (Directory.Exists(destDir))
{
Directory.Delete(destDir, true);
}
}
using (var archive = ArchiveFactory.Open(filePath))
{
var totalSize = archive.TotalUncompressSize;
long unzipSize = 0;
archive.EntryExtractionEnd += (s, e) =>
{
unzipSize += e.Item.Size;
var progress = (float)unzipSize / totalSize;
progressCallback?.Invoke(progress);
};
var options = new ExtractionOptions()
{
Overwrite = true,
ExtractFullPath = true,
PreserveFileTime = false,
PreserveAttributes = false
};
foreach (var entry in archive.Entries)
{
if (!entry.IsDirectory)
{
entry.WriteToDirectory(destDir, options);
}
}
}
completeCallback?.Invoke(destDir);
}
catch (Exception ex)
{
var error = string.Format("Decompress file exception: {0}\r\n{1}", ex.Message, ex.StackTrace);
errorCallback?.Invoke(error);
}
}
#endregion
}
}
|
8be8d75ac60e3b5c8b75e15f63964642323033f1
|
C#
|
DUWENINK/NETCORE_3_HELP
|
/DUWENINK.Core/DUWENINK.Core.Weixin.SDK/Card/Special/LuckyMoneyAPI.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Http;
using Codeplex.Data;
namespace DUWENINK.Core.Weixin.SDK.Card.Special
{
/// <summary>
/// 特殊卡票接口=> 红包
/// 商户调用接口创建会员卡获取card_id,并将会员卡下发给用户,用户领取后需激活/绑定update会员卡编号及积分信息。会员卡暂不支持转赠。
/// </summary>
public class LuckyMoneyAPI
{
/// <summary>
/// 更新红包金额
/// 支持领取红包后通过调用“更新红包”接口update红包余额。
/// </summary>
/// <param name="access_token"></param>
/// <param name="code">红包的序列号</param>
/// <param name="card_id">自定义code的卡券必填。非自定义code可不填。</param>
/// <param name="balance">红包余额</param>
/// <returns>
/// {
///"errcode":0,
///"errmsg":"ok"
///}
///</returns>
public static dynamic UpdateUserBalance(string access_token, string code, string card_id, int balance)
{
var url = string.Format("https://api.weixin.qq.com/card/luckymoney/updateuserbalance?access_token={0}", access_token);
var client = new HttpClient();
var sb = new StringBuilder();
sb.Append("{")
.Append('"' + "code" + '"' + ":").Append(code)
.Append('"' + "card_id" + '"' + ":").Append(card_id)
.Append('"' + "balance" + '"' + ":").Append(balance)
.Append("}");
var result = client.PostAsync(url, new StringContent(sb.ToString())).Result;
if (result.IsSuccessStatusCode) return string.Empty;
return DynamicJson.Parse(result.Content.ReadAsStringAsync().Result);
}
}
}
|
736f67f0fd33b2f2f6936468bb20dec6e87318a9
|
C#
|
shendongnian/download4
|
/first_version_download2/346215-29396460-87177757-1.cs
| 3.296875
| 3
|
class Program
{
static void Main(string[] args)
{
var classType = typeof (Class1);
foreach (var prop in classType.GetProperties().Where(p => p.CanWrite))
{
Console.WriteLine(prop.Name);
}
foreach (var field in classType.GetFields())
{
Console.WriteLine(field.Name);
}
}
}
public class Class1
{
public string ABC { get; set; }
public string DEF { get; set; }
public string GHI { get; set; }
public string JLK { get; set; }
public string CantWrite { get { return ""; } }
public string Field = "";
}
|
edf4d5d315cfcd289a7d23d685ae29307bd8b21b
|
C#
|
agapkinadiana/OOP-3
|
/lab13/lab13/Program.cs
| 3.078125
| 3
|
using System;
using static System.Console;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Serialization;
//using System.Runtime.Serialization.Formatters.Soap;
using System.Runtime.Serialization.Json;
using System.Xml;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Linq;
namespace lab13
{
class Program
{
static void Main(string[] args)
{
Point point = new Point(5, 9);
Point point_2 = new Point(7, 23);
Point[] points = { point, point_2 };
WriteLine("_________Бинарная сериализация_________");
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream fs = new FileStream("point.dat", FileMode.OpenOrCreate))
{
formatter.Serialize(fs, point);
WriteLine("Объект сериализован");
formatter.Serialize(fs, points);
WriteLine("Объект(массив) сериализован");
}
using (FileStream fs = new FileStream("point.dat", FileMode.OpenOrCreate))
{
Point newPoint = (Point)formatter.Deserialize(fs);
WriteLine("Объект десериализован");
WriteLine($"X: {newPoint.X}, Y: {newPoint.Y}");
Point[] newPoint2 = (Point[])formatter.Deserialize(fs);
WriteLine("Объект(массив) десериализован");
foreach (Point p in newPoint2)
{
WriteLine($"X: {p.X}, Y: {p.Y}");
}
}
WriteLine("_________Сериализация в XML_________");
XmlSerializer serializer = new XmlSerializer(typeof(Point));
XmlSerializer serializer1 = new XmlSerializer(typeof(Point[]));
using (FileStream fs = new FileStream("point2.xml", FileMode.OpenOrCreate))
{
serializer.Serialize(fs, point);
WriteLine("Объект сериализован");
}
using (FileStream fs = new FileStream("point2.xml", FileMode.OpenOrCreate))
{
Point newPoint = (Point)serializer.Deserialize(fs);
WriteLine("Объект десериализован");
WriteLine($"X: {newPoint.X}, Y: {newPoint.Y}");
}
using (FileStream fs = new FileStream("point3.xml", FileMode.OpenOrCreate))
{
serializer1.Serialize(fs, points);
WriteLine("Объект(массив) сериализован");
}
using (FileStream fs = new FileStream("point3.xml", FileMode.OpenOrCreate))
{
Point[] newPoint2 = (Point[])serializer1.Deserialize(fs);
WriteLine("Объект(массив) десериализован");
foreach (Point p in newPoint2)
{
WriteLine($"X: {p.X}, Y: {p.Y}");
}
}
WriteLine("_________Сериализация в JSON_________");
Person person1 = new Person("Tom", 29);
Person person2 = new Person("Will", 25);
Person[] people = { person1, person2 };
DataContractJsonSerializer jsonFormatter = new DataContractJsonSerializer(typeof(Person[]));
using (FileStream fs = new FileStream("people.json", FileMode.OpenOrCreate))
{
jsonFormatter.WriteObject(fs, people);
}
using (FileStream fs = new FileStream("people.json", FileMode.OpenOrCreate))
{
Person[] newpeople = (Person[])jsonFormatter.ReadObject(fs);
foreach (Person p in newpeople)
{
WriteLine("Имя: {0} --- Возраст: {1}", p.Name, p.Age);
}
}
WriteLine("_________Linq to XML_________");
//создание документа
XDocument xdoc = new XDocument(new XElement("users",
new XElement("user",
new XAttribute("name", "Bill Gates"),
new XElement("company", "Microsoft"),
new XElement("age", "48")),
new XElement("user",
new XAttribute("name", "Larry Page"),
new XElement("company", "Google"),
new XElement("price", "42"))));
xdoc.Save("users.xml");
IEnumerable<XElement> elements = xdoc.Descendants("user"); //получаем отдельный эл-т
foreach (XElement e in elements)
WriteLine("Элемент {0} : значение = {1}", e.Name, e.Value);
IEnumerable<XElement> elements2 = xdoc
.Descendants("user")
.Where(e => ((string)e.Element("company")) == "Microsoft");
foreach (XElement e in elements2)
WriteLine("Элемент {0} : значение = {1}", e.Name, e.Value);
WriteLine("_________XPath_________");
XmlDocument xml = new XmlDocument();
xml.Load("users.xml");
//только компании, все узлы корневого элемента
XmlElement xRoot = xml.DocumentElement;
XmlNodeList list = xRoot.SelectNodes("//user/company");
foreach (XmlNode nodes in list)
{
WriteLine(nodes.InnerText);
}
//узел, у которого вложенный элемент "company" имеет значение "Microsoft"
XmlNode childnode = xRoot.SelectSingleNode("user[company='Microsoft']");
if (childnode != null)
WriteLine(childnode.OuterXml);
}
}
}
|
08982e59d8811b6a4a48354031fd7e89abd77a99
|
C#
|
prateekbansalind/cSharp-OOP-01-PropertiesTypeExercise
|
/ConsoleUI/AddressModel.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleUI
{
class AddressModel
{
public string Street { get; set; }
public string City { get; set; }
public string Region { get; set; }
public string Country { get; set; }
public string ZipCode { get; set; }
private string _address;
public string Address
{
get { return $"{Street}, {City}, {Region}, {Country}, {ZipCode}"; }
}
}
}
|
ce405575e726405091b42fdc608ae6f8debff4fd
|
C#
|
minhtan2302/CodeWeb
|
/BT1/BT1/Program.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BT1
{
class Program
{
static void Main(string[] args)
{
HCN hcn = new HCN();
hcn.CongThuc();
Console.WriteLine("Chu vi hinh chu nhat la :" + hcn.ChuViHCN());
Console.WriteLine("Dien tich hinh chu nhat la :" + hcn.DienTichHCN());
Console.ReadLine();
//HCN.CongThuc();
//Console.WriteLine("Chu vi hinh chu nhat la :" + ChuViHCN());
//Console.WriteLine("Dien tich hinh chu nhat la :" + DienTichHCN());
//Console.ReadLine();
//Point p1 = new Point(3, 4);
//Point p2 = new Point(5, 7);
//double distance = p1.DistanceTo(p2);
}
}
}
|
4f51d3bd473369e95b2fbfdf41fd6da0067dba36
|
C#
|
DHIteration/INVedit
|
/GUI/BookForm.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace INVedit
{
public partial class BookForm : Form
{
private string _BookText;
public string BookText
{
get { return _BookText; }
set { _BookText = value; }
}
public BookForm()
{
InitializeComponent();
//Have to do it this way cause some how SharpDevelop Screwed the Resources.
pictureBox1.Image = INVedit.Resources.book;
}
private void BookForm_Load(object sender, EventArgs e)
{
BookText = parseText(BookText);
webBrowser1.Navigate("about: <html><body bgcolor=\"#fdf8ec\">" + BookText + "</body></html>");
}
private void webBrowser1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private string parseText(string Text)
{
string parsedText = Text;
parsedText = parsedText.Replace("§r", "</font></b></i></s></u>");
parsedText = parsedText.Replace("§k", "[RndLtrs]");
parsedText = parsedText.Replace("§l", "<b>");
parsedText = parsedText.Replace("§m", "<s>");
parsedText = parsedText.Replace("§n", "<u>");
parsedText = parsedText.Replace("§o", "<i>");
parsedText = parsedText.Replace("§0", "<font color=\"#000000\">");
parsedText = parsedText.Replace("§1", "<font color=\"#0000AA\">");
parsedText = parsedText.Replace("§2", "<font color=\"#00AA00\">");
parsedText = parsedText.Replace("§3", "<font color=\"#00AAAA\">");
parsedText = parsedText.Replace("§4", "<font color=\"#AA0000\">");
parsedText = parsedText.Replace("§5", "<font color=\"#AA00AA\">");
parsedText = parsedText.Replace("§6", "<font color=\"#FFAA00\">");
parsedText = parsedText.Replace("§7", "<font color=\"#AAAAAA\">");
parsedText = parsedText.Replace("§8", "<font color=\"#555555\">");
parsedText = parsedText.Replace("§9", "<font color=\"#5555FF\">");
parsedText = parsedText.Replace("§a", "<font color=\"#55FF55\">");
parsedText = parsedText.Replace("§b", "<font color=\"#55FFFF\">");
parsedText = parsedText.Replace("§c", "<font color=\"#FF5555\">");
parsedText = parsedText.Replace("§d", "<font color=\"#FF55FF\">");
parsedText = parsedText.Replace("§e", "<font color=\"#FFFF55\">");
parsedText = parsedText.Replace("§f", "<font color=\"#FFFFFF\">");
parsedText = parsedText.Replace("\r\n", "<br>");
parsedText = parsedText.Replace("\n", "<br>");
return parsedText;
}
}
}
|
e5fc53bf66ece132fa4ebcdbb5035229ae906aab
|
C#
|
romerotg/LeetCodeProblems
|
/LeetCodeProblems/Anagrams.cs
| 3.546875
| 4
|
using System;
using System.Collections.Generic;
using System.IO;
namespace LeetCodeProblems
{
public class Anagrams
{
public List<string> GetAnagrams(string w)
{
List<string> result = new List<string>();
char[] chars = w.ToCharArray();
Array.Sort(chars);
string ordered = new string(chars);
string[] words = File.ReadAllLines(@"D:\Workspace\LeetCodeProblems\LeetCodeProblems\palavrinhas.txt");
for (int i = 0; i < words.Length; i++)
{
char[] currentChars = words[i].ToCharArray();
Array.Sort(currentChars);
if (ordered == new string(currentChars))
result.Add(words[i]);
}
return result;
}
}
}
|
19de1e7931291f3715a91316fe8dd32514e9b014
|
C#
|
dlannan/modelthulhu
|
/code/PreResultModel.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using Modelthulhu.Math3D;
using Modelthulhu.UserModel;
namespace Modelthulhu.Triangulated
{
public class PreResultModel
{
protected List<PreResultTriangle> triangles = new List<PreResultTriangle>();
protected List<Vec3> uniqueVerts = new List<Vec3>();
protected List<int[]> prohibitedEdges = new List<int[]>();
public PreResultModel()
{
}
// Function to add a list of triangles, given the triangles' verts (grouped by 3's)
public void AddTriangles(List<BasicModelVert> verts)
{
if (verts.Count == 0)
return;
for (int i = 0; i < verts.Count; i += 3)
{
PreResultTriangle tri = new PreResultTriangle();
for (int j = 0; j < 3; j++)
{
tri.verts[j] = verts[i + j];
tri.v_indices[j] = AddVertex(tri.verts[j].position);
}
tri.Prepare();
tri.id = triangles.Count;
List<int[]> edges = tri.GetEdges();
for(int j = 0; j < 3; j++)
foreach (PreResultTriangle other in triangles)
{
int index = other.IndexOfEdge(edges[j]);
if(index != -1)
{
other.edge_neighbors[index] = tri.id;
tri.edge_neighbors[j] = other.id;
}
}
triangles.Add(tri);
}
}
// adds the specified vert if it is not yet present, and returns the new vert's index
// otherwise returns the index of the existing vert it's a duplicate of
public int AddVertex(Vec3 vert)
{
int index = uniqueVerts.FindIndex((v) => (v - vert).ComputeMagnitudeSquared() < 0.0000000001);
if (index == -1)
{
uniqueVerts.Add(vert);
return uniqueVerts.Count - 1;
}
else
return index;
}
public void ProhibitEdges(List<Vec3[]> edgeList)
{
foreach (Vec3[] edge in edgeList)
{
int[] vertex_indices = new int[] { AddVertex(edge[0]), AddVertex(edge[1]) };
prohibitedEdges.Add(vertex_indices);
}
}
protected List<List<int>> DivideIntoRegions()
{
foreach (int[] edge in prohibitedEdges)
foreach (PreResultTriangle tri in triangles)
tri.ProhibitEdge(edge);
int numTriangles = triangles.Count;
List<int> unassigned = new List<int>();
for (int i = 0; i < numTriangles; i++)
{
unassigned.Add(i);
triangles[i].Prepare();
}
List<List<int>> regions = new List<List<int>>();
while (unassigned.Count > 0)
{
List<int> currentRegion = new List<int>();
List<int> addition = new List<int>();
int selection = unassigned[0];
currentRegion.Add(selection);
addition.Add(selection);
unassigned.RemoveAt(0);
do
{
List<int> lastAddition = addition;
addition = new List<int>();
foreach (int testSpread in unassigned)
foreach (int spreader in lastAddition)
if (triangles[spreader].GetValidNeighbors().Contains(testSpread) && !addition.Contains(testSpread))
addition.Add(testSpread);
unassigned.RemoveAll((index) => addition.Contains(index));
currentRegion.AddRange(addition);
} while (addition.Count != 0);
regions.Add(currentRegion);
}
return regions;
}
public List<BasicModelVert> Trim(RegionKeepCondition keepCondition) // hypothetically, only one of keepInside or keepOutside should be true
{
List<List<int>> regions = DivideIntoRegions();
int numRegions = regions.Count;
List<BasicModelVert> result = new List<BasicModelVert>();
RegionBehavior[] behaviors = new RegionBehavior[numRegions];
for (int i = 0; i < numRegions; i++)
{
List<PreResultTriangle> regionTriangles = new List<PreResultTriangle>();
foreach(int j in regions[i])
regionTriangles.Add(triangles[j]);
RegionBehavior behavior = behaviors[i] = keepCondition(regionTriangles);
if (behavior != RegionBehavior.Delete)
{
if (behavior == RegionBehavior.Normal)
{
foreach (int index in regions[i])
result.AddRange(triangles[index].verts);
}
else
{
int[] winding = new int[] {2, 1, 0 };
int numTriangles = regions[i].Count;
for (int j = 0; j < numTriangles; j++)
{
int index = regions[i][j];
foreach(int k in winding)
{
BasicModelVert vert = triangles[regions[i][j]].verts[k];
vert.normal = -vert.normal;
result.Add(vert);
}
}
}
}
}
return result;
}
}
}
|
1aa2d029e4847396501daa32d824398a66f1415c
|
C#
|
martincostello/adventofcode
|
/src/AdventOfCode/Puzzles/Y2018/Day05.cs
| 3.046875
| 3
|
// Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.AdventOfCode.Puzzles.Y2018;
/// <summary>
/// A class representing the puzzle for <c>https://adventofcode.com/2018/day/5</c>. This class cannot be inherited.
/// </summary>
[Puzzle(2018, 05, "Alchemical Reduction", RequiresData = true, IsSlow = true)]
public sealed class Day05 : Puzzle
{
/// <summary>
/// Gets the number of remaining polymer units after the reduction.
/// </summary>
public int RemainingUnits { get; private set; }
/// <summary>
/// Gets the number of remaining polymer units after the reduction using optimization.
/// </summary>
public int RemainingUnitsOptimized { get; private set; }
/// <summary>
/// Reduces the specified polymer.
/// </summary>
/// <param name="polymer">The polymer to reduce.</param>
/// <returns>
/// The polymer remaining after reducing the specified <paramref name="polymer"/>
/// value until it can be reduced no further.
/// </returns>
public static string Reduce(string polymer)
{
var builder = new StringBuilder(polymer, polymer.Length);
while (true)
{
int before = builder.Length;
builder = ReduceOnce(builder);
if (before == builder.Length)
{
break;
}
}
return builder.ToString();
}
/// <summary>
/// Reduces the specified polymer optimally.
/// </summary>
/// <param name="polymer">The polymer to reduce optimally.</param>
/// <returns>
/// The polymer remaining after reducing the specified <paramref name="polymer"/>
/// value until it can be reduced no further with optimizations in use.
/// </returns>
public static string ReduceWithOptimization(string polymer)
{
string[] units = polymer
.Select((p) => char.ToLowerInvariant(p).ToString(CultureInfo.InvariantCulture))
.Distinct()
.Order()
.ToArray();
string optimized = units
.Select((p) => polymer.Replace(p, string.Empty, StringComparison.OrdinalIgnoreCase))
.Select(Reduce)
.OrderBy((p) => p.Length)
.First();
return optimized;
}
/// <inheritdoc />
protected override async Task<PuzzleResult> SolveCoreAsync(string[] args, CancellationToken cancellationToken)
{
string polymer = (await ReadResourceAsStringAsync(cancellationToken)).Trim('\r', '\n');
RemainingUnits = Reduce(polymer).Length;
RemainingUnitsOptimized = ReduceWithOptimization(polymer).Length;
if (Verbose)
{
Logger.WriteLine($"The number of units that remain after fully reacting the polymer is {RemainingUnits:N0}.");
Logger.WriteLine($"The number of units that remain after fully reacting the polymer with optimization is {RemainingUnitsOptimized:N0}.");
}
return PuzzleResult.Create(RemainingUnits, RemainingUnitsOptimized);
}
/// <summary>
/// Reduces the specified polymer once.
/// </summary>
/// <param name="polymer">The polymer to reduce.</param>
/// <returns>
/// The polymer remaining after reducing the specified <paramref name="polymer"/> value.
/// </returns>
private static StringBuilder ReduceOnce(StringBuilder polymer)
{
const int Shift = 'a' - 'A';
for (int i = 0; i < polymer.Length - 1; i++)
{
char x = polymer[i];
char y = polymer[i + 1];
if (Math.Abs(x - y) == Shift)
{
polymer = polymer.Remove(i, 2);
}
}
return polymer;
}
}
|
b912c7527385b850cc6eb5994d33038e31197084
|
C#
|
maxstralin/BeamingInventory.Example
|
/BeamingInventory.Example.Presentation.App/InputHandler.cs
| 3.1875
| 3
|
using System.Linq;
using System.Threading.Tasks;
using BeamingInventory.Example.Presentation.Entities.Interfaces;
using Microsoft.Extensions.Logging;
namespace BeamingInventory.Example.Presentation.App
{
public class InputHandler : IInputHandler
{
private readonly ICommandsProvider _commandsProvider;
private readonly ICommandService _commandService;
private readonly ILogger<InputHandler> _logger;
public InputHandler(ICommandsProvider commandsProvider, ICommandService commandService, ILogger<InputHandler> logger)
{
_commandsProvider = commandsProvider;
_commandService = commandService;
_logger = logger;
}
public async Task<string> ProcessInputAsync(string? input)
{
if (string.IsNullOrEmpty(input)) return "I'm afraid you didn't enter a command, please try again.";
//In this case, we know that the implementation of _commandsProvider caches the commands.
//Otherwise, it'd make sense to cache it on our end.
var commands = (await _commandsProvider.GetAsync()).ToList();
//This could be cached instead of selected on each input but OK for this scenario.
var commandStrings = commands.Select(a => a.CommandChar);
//First character of the string is the command, e.g. 'S'
var commandString = input[0];
//We'll find a command corresponding to the key input, regardless of case (see more in comments below)
var command = commands.SingleOrDefault(a => a.CommandChar == char.ToUpper(commandString));
//Let's check if it's a valid command but they seem to have entered it erroneously (i.e. lowercase)
//This example assumes we only have uppercase commands and there's no risk for 'S' and 's' to be used together as commands.
if (command != null && char.IsLower(commandString))
{
var uppercaseCommand = char.ToUpper(commandString);
_logger.LogDebug($"User possibly entered {commandString} instead of {uppercaseCommand}");
var wantedUppercase =
PromptService.BooleanPrompt($"You entered {commandString}, did you mean {uppercaseCommand}?");
if (!wantedUppercase) return "Okay, please try again.";
}
//We couldn't find a valid command
else if (command == null)
{
_logger.LogDebug($"Unknown command entered: {commandString}");
return $"I'm afraid I don't know how to process {commandString}, try again";
}
//Remaining part of the input (if any)
var param = input[1..];
var result = await _commandService.PerformAsync(command, param);
return $"{(result.Successful ? "Successful" : "Unsuccessful")}: {result.Message ?? "No details provided"}";
}
}
}
|
ad0130a3b8fc9626b5d945fd3139537930ede7d1
|
C#
|
jyce3d/3ve-walker
|
/MayeArc.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
namespace _ve_Walker
{
class MayeArc : Object3D
{
public CustomVertex.PositionColored[] m_verts;
public int m_nLong;
protected VertexBuffer m_vBuffer;
public MayeArc(int nLong, System.Drawing.Color col, string Keyname, bool Hidden)
: base(col, Keyname, Hidden)
{
m_nLong = nLong;
m_verts = new CustomVertex.PositionColored[m_nLong];
}
public void ExtrudeZ(float z, int iType, ref MayeSurface ms)
{
uint nVertCount = (uint)(m_nLong * (ms.m_nLat));
ms.m_verts = new CustomVertex.PositionColored[nVertCount];
// short[6*nSlices*(nSegments-1)]
uint nIndexCount = (uint)((6 * (m_nLong - 1) * (ms.m_nLat - 1)));
// uint nSphere_index =(uint)(((nSlices) * 3) );
ms.m_indexes = new short[nIndexCount];
// Copier les vertex buffer existants dans la mayeSurface
int ms_i = 0;
float curz;
float deltaz;
for (int i = 0; i < m_nLong; i++)
{
deltaz = (z - m_verts[i].Z) / (ms.m_nLat - 1);
if (deltaz < 0)
{
curz = m_verts[i].Z;
deltaz = -deltaz;
}
else
curz = z;
for (int j = 0; j < ms.m_nLat; j++)
{
ms.m_verts[ms_i++] = new CustomVertex.PositionColored(new Vector3(m_verts[i].X, m_verts[i].Y, curz), m_verts[i].Color);
curz -= deltaz;
}
}
// calculer les index_buffer
ms_i = 0;
for (int j = 0; j < ms.m_nLat - 1; j++)
{
for (int i = 0; i < ms.m_nLong - 1; i++)
{
// upper
ms.m_indexes[ms_i++] = (short)(i + j * ms.m_nLong);
ms.m_indexes[ms_i++] = (short)((i + 1) + (j + 1) * ms.m_nLong);
ms.m_indexes[ms_i++] = (short)(i + (j + 1) * ms.m_nLong);
//lower
ms.m_indexes[ms_i++] = (short)(i + j * ms.m_nLong);
ms.m_indexes[ms_i++] = (short)((i + 1) + j * ms.m_nLong);
ms.m_indexes[ms_i++] = (short)((i + 1) + (j + 1) * ms.m_nLong);
}
}
ms.m_nFaceCount = 2 * (m_nLong - 1) * (ms.m_nLat - 1);
}
public void ExtrudeX(float x, int iType, ref MayeSurface ms)
{
uint nVertCount = (uint)(m_nLong * (ms.m_nLat));
ms.m_verts = new CustomVertex.PositionColored[nVertCount];
// short[6*nSlices*(nSegments-1)]
uint nIndexCount = (uint)((6 * (m_nLong - 1) * (ms.m_nLat - 1)));
// uint nSphere_index =(uint)(((nSlices) * 3) );
ms.m_indexes = new short[nIndexCount];
// Copier les vertex buffer existants dans la mayeSurface
int ms_i = 0;
int i = 0;
int j = 0;
float curx;
float deltax;
float deltaz = m_verts[m_nLong - 1].Z - m_verts[0].Z;
for ( i = 0; i < m_nLong; i++)
{
deltax = (x - m_verts[i].X) / (ms.m_nLat - 1);
if (deltax < 0)
{
curx = m_verts[i].X;
deltax = -deltax;
}
else
curx = x;
for (j = 0; j < ms.m_nLat; j++)
{
ms.m_verts[ms_i].Position=new Vector3(curx, m_verts[i].Y, m_verts[i].Z);
ms.m_verts[ms_i++].Color=m_verts[i].Color;
curx -= deltax;
}
}
// calculer les index_buffer
ms_i = 0;
i = 0; j = 1;
ms.m_nFaceCount = 2 * (m_nLong - 1) * (ms.m_nLat - 1);
// for (int i = 0; i < ms.m_nLong - 1; j++)
while (ms_i<3*ms.m_nFaceCount)
{
// for (int j = 0; j < ms.m_nLat - 1; i++)
// {
// upper
// ms.m_indexes[ms_i++] = (short)(i + j * ms.m_nLong); //1
// ms.m_indexes[ms_i++] = (short)((i + 1) + (j + 1) * ms.m_nLong);//2
//ms.m_indexes[ms_i++] = (short)(i + (j + 1) * ms.m_nLong);//3
//lower
//ms.m_indexes[ms_i++] = (short)(i + j * ms.m_nLong);//1
//ms.m_indexes[ms_i++] = (short)((i + 1)+j * ms.m_nLong);//2
//ms.m_indexes[ms_i++] = (short)((i + 1) + (j + 1) * ms.m_nLong);//3
if (deltaz < 0)
{
ms.m_indexes[ms_i++] = (short)i; //1
ms.m_indexes[ms_i++] = (short)(i + ms.m_nLat); //3
ms.m_indexes[ms_i++] = (short)(i + 1); //2
ms.m_indexes[ms_i++] = (short)(i + 1); //1
ms.m_indexes[ms_i++] = (short)(i + ms.m_nLat); //3
ms.m_indexes[ms_i++] = (short)(i + ms.m_nLat + 1); //2
}
else
{
ms.m_indexes[ms_i++] = (short)i; //1
ms.m_indexes[ms_i++] = (short)(i + 1); //2
ms.m_indexes[ms_i++] = (short)(i + ms.m_nLat); //3
ms.m_indexes[ms_i++] = (short)(i + 1); //1
ms.m_indexes[ms_i++] = (short)(i + ms.m_nLat + 1); //2
ms.m_indexes[ms_i++] = (short)(i + ms.m_nLat); //3
}
i++;
if (i == (j * ms.m_nLat)-1)
{
i++;
j++;
}
// }
}
}
public void ExtrudeY(float y, int iType, ref MayeSurface ms)
{
uint nVertCount = (uint)(m_nLong * (ms.m_nLat));
ms.m_verts = new CustomVertex.PositionColored[nVertCount];
// short[6*nSlices*(nSegments-1)]
uint nIndexCount = (uint)((6 * (m_nLong - 1) * (ms.m_nLat - 1)));
// uint nSphere_index =(uint)(((nSlices) * 3) );
ms.m_indexes = new short[nIndexCount];
// Copier les vertex buffer existants dans la mayeSurface
int ms_i = 0;
float cury;
float deltay;
for (int i = 0; i < m_nLong; i++)
{
deltay = (y - m_verts[i].Y) / (ms.m_nLat - 1);
if (deltay < 0)
{
cury = m_verts[i].Y;
deltay = -deltay;
}
else
cury = y;
for (int j = 0; j < ms.m_nLat; j++)
{
ms.m_verts[ms_i++] = new CustomVertex.PositionColored(new Vector3(m_verts[i].X, cury, m_verts[i].Z), m_verts[i].Color);
cury -= deltay;
}
}
// calculer les index_buffer
ms_i = 0;
for (int j = 0; j < ms.m_nLat - 1; j++)
{
for (int i = 0; i < ms.m_nLong - 1; i++)
{
// upper
ms.m_indexes[ms_i++] = (short)(i + j * ms.m_nLong);
ms.m_indexes[ms_i++] = (short)((i + 1) + (j + 1) * ms.m_nLong);
ms.m_indexes[ms_i++] = (short)(i + (j + 1) * ms.m_nLong);
//lower
ms.m_indexes[ms_i++] = (short)(i + j * ms.m_nLong);
ms.m_indexes[ms_i++] = (short)((i + 1) + j * ms.m_nLong);
ms.m_indexes[ms_i++] = (short)((i + 1) + (j + 1) * ms.m_nLong);
}
}
ms.m_nFaceCount = 2 * (m_nLong - 1) * (ms.m_nLat - 1);
}
public override void Translate(float x, float y, float z)
{
base.Translate(x, y, z);
for (int i = 0; i < m_nLong; i++)
{
m_verts[i].X += x;
m_verts[i].Y += y;
m_verts[i].Z += z;
}
}
public override void DrawObject(Device device)
{
//Ne pas pas tre utilis plus d'une fois, une fois utilis, il est mort...
m_vBuffer = new VertexBuffer(typeof(CustomVertex.PositionColored), m_verts.Length, device, 0,
CustomVertex.PositionColored.Format, Pool.Default);
m_vBuffer.SetData(m_verts, 0, LockFlags.None);
if (m_vBuffer == null)
throw new Exception("MayeArc::DrawObject:The m_vBuffer Vertex Buffer cannot be empty");
device.Transform.World = m_matWorld;
// device.Transform.World = Matrix.Translation(0.0f, 0.0f, 0.0f);
device.SetStreamSource(0, m_vBuffer, 0);
device.VertexFormat = CustomVertex.PositionColored.Format;
try
{
device.DrawPrimitives(PrimitiveType.LineStrip, 0, m_nLong-1 );
}
catch
{
//throw new Exception("nombre de segment" + m_nLong.ToString());
}//TODO: Avoid to choke the exception due to m_nLong too long...
}
}
}
|
e5a688f36ec0ba3ee0455ee2c8d50187cf110ad4
|
C#
|
valerysntx/expressionutil
|
/ExpressionFingerprint/Conditional/ConditionalExpressionFingerprint.cs
| 2.59375
| 3
|
using System.Linq.Expressions;
namespace System.Web.Mvc.ExpressionUtil.ExpressionFingerprint.Conditional
{
using ExpressionFingerprint;
#pragma warning disable CS0659 // Type overrides Object.Equals(object o) but does not override Object.GetHashCode()
public class ConditionalExpressionFingerprint : AbstractExpressionFingerprint
#pragma warning restore CS0659 // Type overrides Object.Equals(object o) but does not override Object.GetHashCode()
{
public ConditionalExpressionFingerprint( ExpressionType nodeType, Type type ) : base(nodeType, type)
{
}
public override bool Equals( object obj )
{
ConditionalExpressionFingerprint conditionalExpressionFingerprint = obj as ConditionalExpressionFingerprint;
if (conditionalExpressionFingerprint == null)
{
return false;
}
return base.Equals(conditionalExpressionFingerprint);
}
}
}
|
2688d7a637e846d74ee58948a87bf790e1b1a730
|
C#
|
CCSI-Toolset/turb_sci_gate
|
/Master/TurbineChangePassword/Program.cs
| 2.8125
| 3
|
using CommandLine;
using CommandLine.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Text;
using Turbine.Data;
using Turbine.DataEF6;
namespace TurbineChangePassword
{
class Program
{
static Boolean verbose = false;
class Options
{
[Option('u', "username", Required = true,
HelpText = "Username")]
public string Username { get; set; }
[Option('p', "password", Required = true,
HelpText = "Password")]
public string Password { get; set; }
[Option('v', "verbose", DefaultValue = true,
HelpText = "Prints all messages to standard output.")]
public bool Verbose { get; set; }
[ParserState]
public IParserState LastParserState { get; set; }
[HelpOption]
public string GetUsage()
{
return HelpText.AutoBuild(this,
(HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current));
}
}
static bool UpdateUser(string username, string token)
{
using (ProducerContext container = new ProducerContext())
{
Turbine.Data.Entities.User user = container.Users.SingleOrDefault<Turbine.Data.Entities.User>(s => s.Name == username);
if (user == null) return false;
user.Token = token;
container.SaveChanges();
}
return true;
}
static void Main(string[] args)
{
var options = new Options();
if (CommandLine.Parser.Default.ParseArguments(args, options))
{
// Values are available here
verbose = options.Verbose;
if (verbose) Console.WriteLine("Changing Password for User: {0}", options.Username);
int saltSize = 12;
byte[] data = new byte[saltSize];
var provider = new System.Security.Cryptography.RNGCryptoServiceProvider();
provider.GetBytes(data);
string salt = System.Text.UTF8Encoding.UTF8.GetString(data);
string token = Turbine.Security.AuthenticateCredentials.
CreateFormattedToken("pbkdf2_sha256", 12000, salt, options.Password);
if (verbose) Console.WriteLine("Create Security Token: {0}", token);
if (UpdateUser(options.Username, token) == false)
{
Console.WriteLine("User {0} does not exist", options.Username);
Environment.ExitCode = 1;
}
}
}
}
}
|
8f86dcae55d1737a296ebd0929ced24821c5af08
|
C#
|
asuralove/dragonnest_src
|
/src/com.tencent.pandora/CachedFileMd5Helper.cs
| 2.546875
| 3
|
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace com.tencent.pandora
{
public class CachedFileMd5Helper
{
private static MD5CryptoServiceProvider MD5_SERVICE = new MD5CryptoServiceProvider();
public static string GetFileMd5(byte[] fileBytes)
{
if (fileBytes.Length == 0)
{
return string.Empty;
}
byte[] array = CachedFileMd5Helper.MD5_SERVICE.ComputeHash(fileBytes);
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < array.Length; i++)
{
stringBuilder.Append(array[i].ToString("X2"));
}
string str = stringBuilder.ToString();
string str2 = "pandora20151019";
byte[] bytes = Encoding.UTF8.GetBytes(str2 + str);
MemoryStream memoryStream = new MemoryStream();
memoryStream.Write(bytes, 0, bytes.Length);
memoryStream.Seek(0L, SeekOrigin.Begin);
byte[] array2 = CachedFileMd5Helper.MD5_SERVICE.ComputeHash(memoryStream);
memoryStream.Dispose();
stringBuilder = new StringBuilder();
for (int j = 0; j < array2.Length; j++)
{
stringBuilder.Append(array2[j].ToString("X2"));
}
return stringBuilder.ToString();
}
}
}
|
efdc508bae37b73648600c3c1af269457bfde110
|
C#
|
ROHITCHARDE/ProgramLibrary
|
/Development/Csharp/StaticMethodsAndClasses/Program.cs
| 3.328125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StaticMethodsAndClasses
{
public class A
{
public A()
{
Console.WriteLine("Hello normal A");
}
static A()
{
Console.WriteLine("Hello static A");
}
}
class B : A
{
public B()
{
Console.WriteLine("\n Hello normal B");
}
static B()
{
Console.WriteLine("\n Hello static B");
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
Console.WriteLine("\n\n");
B b = new B();
Console.WriteLine("\n\n");
A c = new B();
Console.WriteLine("\n\n");
// B d = (A)new A();
}
}
}
|
ccd9be174354771a4ec671355cedaa2e4dd1f9a6
|
C#
|
Zergatul/ZergatulLib
|
/Zergatul/Cryptography/Certificate/X509ExtensionsCollection.cs
| 2.65625
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zergatul.Network.Asn1.Structures.X509;
namespace Zergatul.Cryptography.Certificate
{
public class X509ExtensionsCollection : IReadOnlyList<X509Extension>
{
private List<X509Extension> _extensions;
internal X509ExtensionsCollection(IEnumerable<Extension> extensions)
{
if (extensions != null)
this._extensions = extensions.Select(e => X509Extension.Parse(e)).Where(ext => ext != null).ToList();
else
this._extensions = new List<X509Extension>();
}
public T Get<T>() where T : X509Extension
{
return _extensions.OfType<T>().SingleOrDefault();
}
#region IReadOnlyList<X509Extension>
public X509Extension this[int index] => _extensions[index];
public int Count => _extensions.Count;
public IEnumerator<X509Extension> GetEnumerator() => _extensions.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
}
}
|
beb992d92cfef54dbe73d0fa1ded82a7aebf442a
|
C#
|
lexzh/Myproject
|
/AppServer/Remoting/Remoting/RemotingDataCS.cs
| 2.609375
| 3
|
namespace Remoting
{
using System;
using System.Collections;
using System.Data;
using PublicClass;
using Library;
public class RemotingDataCS : DataBase
{
public override void Add(DataTable data)
{
try
{
if ((data != null) && (data.Rows.Count <= base._Size))
{
lock (base._PosList.SyncRoot)
{
base._PosList.Add(CompressHelper.Compress(data));
return;
}
}
this.DataDisBach(data);
}
catch (Exception exception)
{
ErrorMsg msg = new ErrorMsg("RemotingDataCS", "Add", exception.Message + exception.StackTrace);
new LogHelper().WriteError(msg);
base._PosList = new ArrayList(100);
}
}
private void DataDisBach(DataTable data)
{
if ((data != null) && (data.Rows.Count > 0))
{
DataTable table = data.Clone();
int num = 1;
for (int i = 0; i <= (data.Rows.Count - 1); i++)
{
table.Rows.Add(data.Rows[i].ItemArray);
if ((num >= base._Size) || (i == (data.Rows.Count - 1)))
{
lock (base._PosList.SyncRoot)
{
base._PosList.Add(CompressHelper.Compress(table.Copy()));
}
table.Clear();
num = 0;
}
num++;
}
}
}
}
}
|
02e27892ec99891d7214edacafa79fe383a604f5
|
C#
|
bsstahl/AIDemos
|
/HybridConferenceSchedulerDemo/AddConstraintsDemo.cs
| 2.546875
| 3
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using ConferenceScheduler.Entities;
using ConferenceScheduler.Interfaces;
using ConferenceScheduler.Exceptions;
namespace HybridConferenceScheduler
{
[TestClass]
public class AddConstraintsDemo
{
[TestMethod]
public void ScheduleByAddingConstraints()
{
bool disableTrace = true;
var engine = (null as IConferenceOptimizer).Create(disableTrace);
var sessions = new SessionsCollection();
var rooms = new List<Room>();
var timeslots = new List<Timeslot>();
#region Presenters
// No restrictions on when they present
var presenterJustinJames = Presenter.Create(10, "Justin James");
var presenterWendySteinman = Presenter.Create(12, "Wendy Steinman");
var presenterHattanShobokshi = Presenter.Create(16, "Hattan Shobokshi");
var presenterRyanMilbourne = Presenter.Create(22, "Ryan Milbourne");
var presenterIotLaboratory = Presenter.Create(27, "IOT Laboratory");
// Prefers the last 2 sessions of the day
var preferredTimeslotsMaxNodland = new int[] { 3, 4 };
var presenterMaxNodland = Presenter.Create(23, "Max Nodland", new int[] { }, preferredTimeslotsMaxNodland);
// Doesn't like morning sessions
var preferredTimeslotsBarryStahl = new int[] { 3, 4 };
var presenterBarryStahl = Presenter.Create(24, "Barry Stahl", new int[] { }, preferredTimeslotsBarryStahl);
// Doesn't like 1st session of morning & afternoon
var preferredTimeslotsJustineCocci = new int[] { 2, 4 };
var presenterJustineCocci = Presenter.Create(25, "Justine Cocci", new int[] { }, preferredTimeslotsJustineCocci);
// Prefers 1st session of the day
var preferredTimeslotsChrisGriffith = new int[] { 1 };
var presenterChrisGriffith = Presenter.Create(26, "Chris Griffith", new int[] { }, preferredTimeslotsChrisGriffith);
// Flying in and out so only available during the middle of the day
var unavailableTimeslotsScottGu = new int[] { 1, 4 };
var presenterScottGu = Presenter.Create(28, "Scott Guthrie", unavailableTimeslotsScottGu);
// Flying in together so only available toward the end of the day
var unavailableTimeslotsScottHanselman = new int[] { 1, 2 };
var presenterScottHanselman = Presenter.Create(29, "Scott Hanselman", unavailableTimeslotsScottHanselman);
var unavailableTimeslotsDamianEdwards = new int[] { 1, 2 };
var presenterDamianEdwards = Presenter.Create(30, "Damian Edwards", unavailableTimeslotsDamianEdwards);
#endregion
#region Sessions
var sessionPublicSpeaking = sessions.Add(12, "Everyone is Public Speaker", (int)Topic.None, presenterJustinJames);
var sessionTimeyWimey = sessions.Add(14, "Timey-Wimey Stuff", null, presenterWendySteinman);
var sessionBitcoin101 = sessions.Add(24, "Bitcoin 101", (int)Topic.None, presenterRyanMilbourne);
var sessionBlockchain101 = sessions.Add(25, "Blockchain 101", (int)Topic.None, presenterRyanMilbourne);
var sessionRapidRESTDev = sessions.Add(26, "Rapid REST Dev w/Node & Sails", (int)Topic.None, presenterJustinJames);
var sessionNativeMobileDev = sessions.Add(27, "Native Mobile Dev With TACO", (int)Topic.None, presenterJustinJames);
var sessionReduxIntro = sessions.Add(28, "Redux:Introduction", (int)Topic.None, presenterMaxNodland);
var sessionReactGettingStarted = sessions.Add(29, "React:Getting Started", (int)Topic.None, presenterMaxNodland);
var sessionDevSurveyOfAI = sessions.Add(30, "Devs Survey of AI", (int)Topic.None, presenterBarryStahl);
var sessionMLIntro = sessions.Add(31, "ML:Intro to Image & Text Analysis", (int)Topic.None, presenterJustineCocci);
var sessionChatbotsIntroInNode = sessions.Add(32, "ChatBots:Intro using Node", (int)Topic.None, presenterJustineCocci);
var sessionAccidentalDevOps = sessions.Add(33, "Accidental DevOps:CI for .NET", (int)Topic.None, presenterHattanShobokshi);
var sessionWhatIsIonic = sessions.Add(34, "What is Ionic", (int)Topic.None, presenterChrisGriffith);
var sessionEverythingCloud = sessions.Add(41, "Everything about Cloud", (int)Topic.None, presenterScottGu);
var sessionFunnyMobileDev = sessions.Add(42, "Funny Mobile Development", (int)Topic.None, presenterScottHanselman);
var sessionMobileForNerdz = sessions.Add(43, "Mobile for Nerdz", (int)Topic.None, presenterScottHanselman);
var sessionDotNetCoreAwesomeness = sessions.Add(44, ".NET Core Awesomeness", (int)Topic.None, presenterDamianEdwards);
var sessionDotNetStandard20 = sessions.Add(45, ".NET Standard 2.0", (int)Topic.None, presenterDamianEdwards);
#endregion
#region Session dependencies
sessionBlockchain101.AddDependency(sessionBitcoin101);
#endregion
#region Timeslots
timeslots.Add(Timeslot.Create(1, 9.5));
timeslots.Add(Timeslot.Create(2, 11));
timeslots.Add(Timeslot.Create(3, 13));
timeslots.Add(Timeslot.Create(4, 14.5));
#endregion
#region Rooms
rooms.Add(Room.Create(1, 10)); // Unex 127
rooms.Add(Room.Create(2, 10)); // Unex 126
rooms.Add(Room.Create(3, 10, new int[] { 3, 4 })); // Unex 110 -- Only available in AM
rooms.Add(Room.Create(4, 10)); // Unex 107
rooms.Add(Room.Create(5, 10)); // Unex 106
#endregion
#region Timeslots out-of-favor for each presenter
var presenterUnfavoredTimeslots = new List<Tuple<Presenter, int>>();
// This list is built separately so it maintains the order
// in which the requests were submitted. It could also be built
// by negating the list of preferred timeslots for each presenter
// Prefers the last 2 sessions of the day
presenterUnfavoredTimeslots.Add(presenterMaxNodland, 1);
presenterUnfavoredTimeslots.Add(presenterMaxNodland, 2);
// Doesn't like morning sessions
presenterUnfavoredTimeslots.Add(presenterBarryStahl, 1);
presenterUnfavoredTimeslots.Add(presenterBarryStahl, 2);
// Doesn't like 1st session of morning & afternoon
presenterUnfavoredTimeslots.Add(presenterJustineCocci, 1);
presenterUnfavoredTimeslots.Add(presenterJustineCocci, 3);
// Prefers 1st session of the day
presenterUnfavoredTimeslots.Add(presenterChrisGriffith, 2);
presenterUnfavoredTimeslots.Add(presenterChrisGriffith, 3);
presenterUnfavoredTimeslots.Add(presenterChrisGriffith, 4);
#endregion
#region Create the schedule
// Note: We want this to throw an exception here if it is infeasible
// since this is the least restrictive it could ever be.
IEnumerable<Assignment> assignments = engine.Process(sessions, rooms, timeslots);
var lastSuccessfulAssignments = assignments.Clone();
foreach (var unfavoredTimeslot in presenterUnfavoredTimeslots)
{
int currentPresenterId = unfavoredTimeslot.Item1.Id;
var currentPresenter = sessions.First(s => s.Presenters.Any(p => p.Id == currentPresenterId)).Presenters.First(p => p.Id == currentPresenterId);
int unfavoredTimeslotId = unfavoredTimeslot.Item2;
try
{
currentPresenter.UnavailableForTimeslots = currentPresenter.UnavailableForTimeslots.Add(unfavoredTimeslotId);
assignments = engine.Process(sessions, rooms, timeslots);
lastSuccessfulAssignments = assignments;
Console.WriteLine($"Successfully prevented assignment of {unfavoredTimeslot.Item1.Name} to Timeslot {unfavoredTimeslotId}");
}
catch (NoFeasibleSolutionsException nfs)
{
Console.WriteLine($"Unable to prevent assignment of {unfavoredTimeslot.Item1.Name} to Timeslot {unfavoredTimeslotId}");
lastSuccessfulAssignments.WriteSchedule(sessions);
Console.WriteLine();
currentPresenter.UnavailableForTimeslots = currentPresenter.UnavailableForTimeslots.Remove(unfavoredTimeslotId);
}
}
#endregion
// Display the results
lastSuccessfulAssignments.WriteSchedule(sessions);
}
}
}
|
e180662b166c6892148808dcd84b317bb5fad4a9
|
C#
|
alfifutuhi13/MoneyManager
|
/MoneyManager/API/Models/User.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace API.Models
{
[Table("TB_M_User")]
public class User
{
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Name should not be empty")]
public string Name { get; set; }
[Required(ErrorMessage = "Email Should not be empty"), EmailAddress(ErrorMessage = "Email format is invalid")]
public string Email { get; set; }
[Required(ErrorMessage = "Gender should not be empty")]
public string Gender { get; set; }
[Required(ErrorMessage = "BirthDate should not be empty"), DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0}:dd-MM-YYYY")]
public DateTime BirthDate { get; set; }
[Required(ErrorMessage = "Phone Number should not be empty"), RegularExpression(@"^[08][0-9]{10,11}$", ErrorMessage = "Phone number should start with '08'"), MinLength(11, ErrorMessage = "Minimum 11 characters"), MaxLength(12, ErrorMessage = "Maximum 12 characters")]
public string PhoneNumber { get; set; }
public Account Account { get; set; }
public Role Role { get; set; }
public Transaction Transaction { get; set; }
}
}
|
772f7a472c054af25d7f5a2bf70c41975dbbce9f
|
C#
|
RobertKaufman/WinFormGame
|
/WinFormGame/Weapon.cs
| 3.0625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WinFormGame;
namespace WinFormGame
{
public class Weapon
{
public int AttributeModifier { get; set; }//
public Enums.DamageTypes damageType { get; set; }
public int WeaponLevel { get; set; }//retrict the level type to not be above the current level in the program
public string WeaponName { get; set; }//prompt the user to give the weapon a name once they pick it up
Random rand = new Random();
/// <summary>
/// autoconstructor for enemy character classes
/// </summary>
public Weapon(int weaponLevel)
{
this.WeaponLevel = weaponLevel;
this.AttributeModifier = rand.Next(weaponLevel);//look at refactoring to create a method to return the level
this.damageType = StaticFunctions.setGearType();
}
/// <summary>
/// overloaded constructor for character classes
/// </summary>
/// <param name="weaponName"></param>
public Weapon(string weaponName)
{
this.WeaponName = weaponName;
this.AttributeModifier = rand.Next(this.WeaponLevel);//look at refactoring to create a method to return the level
this.damageType = StaticFunctions.setGearType();
}
/// <summary>
/// generates a weapon with a name and an initial value. Used on game start
/// </summary>
/// <param name="weaponName"></param>
/// <param name="startingValue"></param>
public Weapon(string weaponName, int startingValue)
{
this.WeaponName = weaponName;
this.AttributeModifier = startingValue;
this.damageType = StaticFunctions.setGearType();
}
/// <summary>
/// generates a weapon with full attributes. Used in loot drops
/// </summary>
/// <param name="weaponName"></param>
/// <param name="startingValue"></param>
/// <param name="damageType"></param>
public Weapon(string weaponName, int startingValue, Enums.DamageTypes damageType)
{
this.WeaponName = weaponName;
this.AttributeModifier = startingValue;
this.damageType = damageType;
}
}
}
|
f1baedf8ab9dc5fa627dcaf3ea1abb5b18152c68
|
C#
|
BenQuickDeNN/Reverse-Polish-Notation
|
/Program.cs
| 3.359375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleExpression
{
class Program
{
class BinaryTreeNode<T>
{
public uint Priority = 0;
public T Value;
public bool isLeaf = false;
public BinaryTreeNode<T> LeftChild;
public BinaryTreeNode<T> RightChild;
}
class BinaryTree<T>
{
public BinaryTreeNode<T> Root;
public BinaryTreeNode<T> PointerNode;
public BinaryTree(BinaryTreeNode<T> Root)
{
this.Root = Root;
}
public void addNode(BinaryTreeNode<T> thisNode, BinaryTreeNode<T> Node)
{
if (thisNode.Priority > Node.Priority)
{
if (thisNode.LeftChild == null)
{
thisNode.LeftChild = Node;
return;
}
if (thisNode.RightChild == null)
{
thisNode.RightChild = Node;
return;
}
if (!Node.isLeaf)
{
Node.LeftChild = thisNode.RightChild;
thisNode.RightChild = Node;
return;
}
if (!thisNode.LeftChild.isLeaf)
{
addNode(thisNode.LeftChild, Node);
}
if (!thisNode.RightChild.isLeaf)
{
addNode(thisNode.RightChild, Node);
}
}
else
{
Node.LeftChild = thisNode;
Root = Node;
return;
}
}
//后序遍历,进入队列
public void EnqueueNode(BinaryTreeNode<T> thisNode, Queue<T> queue)
{
if (thisNode.LeftChild != null) EnqueueNode(thisNode.LeftChild, queue);
if (thisNode.RightChild != null) EnqueueNode(thisNode.RightChild, queue);
queue.Enqueue(thisNode.Value);
}
}
static void Main(string[] args)
{
while (true)
{
try
{
Console.Write("Command > ");
string line = Console.ReadLine();
if (line == "exit") break;
string symbol = "";
BinaryTree<string> binaryTree = new BinaryTree<string>(new BinaryTreeNode<string>());
bool flag_isFirstSymbol = true;
for(int i = 0; i < line.Length; i++)
{
if (line.ElementAt(i) <= '9' && line.ElementAt(i) >= '0')
{
symbol += line.ElementAt(i);
}
else
{
if (symbol != "")
{
BinaryTreeNode<string> node = new BinaryTreeNode<string>();
node.Value = symbol;
node.isLeaf = true;
if (flag_isFirstSymbol)
{
binaryTree = new BinaryTree<string>(node);
flag_isFirstSymbol = false;
}
else
{
binaryTree.addNode(binaryTree.Root, node);
}
symbol = "";
}
BinaryTreeNode<string> node1 = new BinaryTreeNode<string>();
node1.Value = line.ElementAt(i).ToString();
if (node1.Value == "+" || node1.Value == "-") node1.Priority = 2;
if (node1.Value == "*" || node1.Value == "/") node1.Priority = 1;
binaryTree.addNode(binaryTree.Root, node1);
}
}
if (symbol != "")
{
BinaryTreeNode<string> node = new BinaryTreeNode<string>();
node.Value = symbol;
node.isLeaf = true;
if (flag_isFirstSymbol)
{
binaryTree = new BinaryTree<string>(node);
flag_isFirstSymbol = false;
}
else
{
binaryTree.addNode(binaryTree.Root, node);
}
symbol = "";
}
//二叉树节点按后序遍历进入队列
Queue<string> queue_letter = new Queue<string>();
binaryTree.EnqueueNode(binaryTree.Root, queue_letter);
//出队入栈,并计算
Stack<string> stack_letter = new Stack<string>();
string[] symbolC = new string[4] { "+", "-", "*", "/" };
while (queue_letter.Count > 0)
{
string letter = queue_letter.Dequeue();
if (symbolC.Contains(letter))
{
if (stack_letter.Count > 0)
{
int a = 0;
switch (letter)
{
case "+":
a = int.Parse(stack_letter.Pop());
a += int.Parse(stack_letter.Pop());
break;
case "-":
a = - int.Parse(stack_letter.Pop()) + int.Parse(stack_letter.Pop());
break;
case "*":
a = int.Parse(stack_letter.Pop());
a *= int.Parse(stack_letter.Pop());
break;
case "/":
a = int.Parse(stack_letter.Pop());
int b = int.Parse(stack_letter.Pop());
a = b / a;
break;
}
stack_letter.Push(a.ToString());
}
}
else
{
stack_letter.Push(letter);
}
}
if (stack_letter.Count > 0)
{
Console.WriteLine("result = " + stack_letter.Pop());
}
}catch(Exception e)
{
Console.Write(e.ToString() + "\n");
}
}
}
}
}
|
3a1946228d50005e58d20046199c1bf8df10a3b0
|
C#
|
Domenik/FifaRating
|
/Class/Club.cs
| 2.890625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MahApps.Metro;
namespace FifaRating
{
public class Club : ViewModelBase
{
#region Constructor
public Club()
{
ListOfPlayers = new List<Player>();
}
public Club(string name)
{
Name = name;
ListOfPlayers = new List<Player>();
}
#endregion
private string _name;
private int _id;
private List<Player> _listOfPlayers;
#region Property
public List<Player> ListOfPlayers
{
get { return _listOfPlayers; }
set
{
_listOfPlayers = value;
OnPropertyChanged("ListOfPlayers");
}
}
public int Id
{
get { return _id; }
set
{
_id = value;
OnPropertyChanged("Id");
}
}
public String Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged("Name");
}
}
#endregion
#region Methods
public override string ToString()
{
return Name;
}
#endregion
}
}
|
d9a89f89f196d258104d8460d6a361227cd7e2bc
|
C#
|
Magnusalt/NewAsyncFeaturesAndChannels
|
/Program.cs
| 3.328125
| 3
|
using System;
using System.Threading.Tasks;
using System.Linq;
namespace NewAsyncFeatures
{
class Program
{
static async Task Main(string[] args)
{
var random = new Random();
var gateway = new Gateway();
for (int i = 0; i < 10; i++)
gateway.ConnectSensorNode(new SensorNode($"node {i}", (i % 2 == 0 ? 2000 : 7000), random));
System.Console.WriteLine("Start reading first run");
await foreach (var item in gateway.GetLatestReadings())
Console.WriteLine($"{item.SensorId} - {item.Value} - {item.TimeStamp}");
System.Console.WriteLine("Done reading first run");
await Task.Delay(4000);
System.Console.WriteLine("Start reading second run");
await foreach (var item in gateway.GetLatestReadings())
Console.WriteLine($"{item.SensorId} - {item.Value} - {item.TimeStamp}");
System.Console.WriteLine("Done reading second run");
await Task.Delay(4000);
System.Console.WriteLine("Start reading third run");
await foreach (var item in gateway.GetLatestReadings().Where(reading => reading.Value > 10.0))
Console.WriteLine($"{item.SensorId} - {item.Value} - {item.TimeStamp}");
System.Console.WriteLine("Done reading third run");
Console.ReadLine();
}
}
}
|
8fcb4b62a40bbf130e3484158aca12d16b238687
|
C#
|
qbzjs/XGameFramework
|
/Assets/XFramework/Scripts/Utility/Verify/Util.Verify.cs
| 2.828125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using System;
using System.Runtime.Serialization.Formatters.Binary;
namespace XFramework.Utility
{
/// <summary>
/// 校验相关的工具类
/// </summary>
public static partial class Util
{
/// <summary>
/// 计算字符串的md5值
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static string Md5(string source)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] data = System.Text.Encoding.UTF8.GetBytes(source);
byte[] md5Data = md5.ComputeHash(data, 0, data.Length);
md5.Clear();
string destString = "";
for (int i = 0; i < md5Data.Length; i++)
{
destString += System.Convert.ToString(md5Data[i], 16).PadLeft(2, '0');
}
destString = destString.PadLeft(32, '0');
return destString;
}
/// <summary>
/// 计算文件的md5值
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public static string Md5File(string file)
{
try
{
FileStream fs = new FileStream(file, FileMode.Open);
System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] retVal = md5.ComputeHash(fs);
fs.Close();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("x2"));
}
return sb.ToString();
}
catch (Exception ex)
{
throw new Exception("md5file() fail, error:" + ex.Message);
}
}
/// <summary>
/// 字符串转byte数组
/// </summary>
/// <param name="str">字符串</param>
/// <returns></returns>
public static byte[] Utf8StringToBytes(string str)
{
return Encoding.UTF8.GetBytes(str);
}
/// <summary>
/// byte数组转字符串
/// </summary>
/// <param name="bts"></param>
/// <returns></returns>
public static string Utf8BytesToString(byte[] bts)
{
if (bts == null) return "";
return Encoding.UTF8.GetString(bts);
}
/// <summary>
/// 判断字符串是不是数字类型
/// </summary>
/// <param name="str">输入的字符串</param>
/// <returns></returns>
public static bool IsNumeric(string str)
{
if (str == null || str.Length == 0) return false;
for (int i = 0; i < str.Length; i++)
{
return Char.IsNumber(str[i]);
}
return true;
}
/// <summary>
/// 克隆一个对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="origin"></param>
/// <returns></returns>
public static T Clone<T>(T origin) where T : class
{
T result = default(T);
if (origin != null)
{
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, origin);
ms.Seek(0, SeekOrigin.Begin);
result = bf.Deserialize(ms) as T;
}
return result;
}
/// <summary>
/// 网络可用
/// </summary>
public static bool NetAvailable
{
get
{
return Application.internetReachability != NetworkReachability.NotReachable;
}
}
/// <summary>
/// 是否是无线
/// </summary>
public static bool IsWifi
{
get
{
return Application.internetReachability == NetworkReachability.ReachableViaLocalAreaNetwork;
}
}
}
}
|
ec8e9d3402e9be8767a7256ca5dd0fa4eee484b7
|
C#
|
StephenCleary/Comparers
|
/src/Nito.Comparers.Core/Util/CompoundEqualityComparer.cs
| 3.1875
| 3
|
using Nito.Comparers.Internals;
using System.Collections.Generic;
namespace Nito.Comparers.Util
{
/// <summary>
/// A equality comparer that uses another comparer if the source comparer determines the objects are equal.
/// </summary>
/// <typeparam name="T">The type of objects being compared.</typeparam>
internal sealed class CompoundEqualityComparer<T> : SourceEqualityComparerBase<T, T>
{
/// <summary>
/// The second comparer.
/// </summary>
private readonly IEqualityComparer<T> _secondSource;
/// <summary>
/// Initializes a new instance of the <see cref="CompoundEqualityComparer<T>"/> class.
/// </summary>
/// <param name="source">The source comparer. If this is <c>null</c>, the default comparer is used.</param>
/// <param name="secondSource">The second comparer. If this is <c>null</c>, the default comparer is used.</param>
public CompoundEqualityComparer(IEqualityComparer<T>? source, IEqualityComparer<T>? secondSource)
: base(source, true)
{
_secondSource = EqualityComparerHelpers.NormalizeDefault(secondSource);
}
/// <inheritdoc />
protected override int DoGetHashCode(T obj)
{
unchecked
{
var ret = Murmur3Hash.Create(Source.GetHashCode(obj!));
ret.Combine(_secondSource.GetHashCode(obj!));
return ret.HashCode;
}
}
/// <inheritdoc />
protected override bool DoEquals(T x, T y)
{
var ret = Source.Equals(x, y);
if (!ret)
return false;
return _secondSource.Equals(x, y);
}
/// <summary>
/// Returns a short, human-readable description of the comparer. This is intended for debugging and not for other purposes.
/// </summary>
public override string ToString() => $"Compound({Source}, {_secondSource})";
}
}
|
8cbeb185a6fa1288d928f3359d9ddbef05e7f79e
|
C#
|
samueldjack/ProjectEuler
|
/Problem25.cs
| 3.3125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ProjectEuler
{
[EulerProblem(25, Title = "What is the first term in the Fibonacci sequence to contain 1000 digits?")]
public class Problem25
{
public long Solve()
{
return Functional.Unfold(
new
{
Term = (IEnumerable<int>) new[] {2},
Previous = (IEnumerable<int>) new[] {1},
TermNumber = 3
},
previous => new
{
Term = previous.Term.SumNumbers(previous.Previous),
Previous = previous.Term,
TermNumber = previous.TermNumber + 1
}
)
.SkipWhile(term => term.Term.Count() < 1000)
.First()
.TermNumber;
}
}
}
|
dd5d0756cf09cd2b659566d9de9d9760659cedb8
|
C#
|
ukenov/game
|
/WinForms/Forms/Games/FindEvenAndOddNumbersGame.cs
| 2.8125
| 3
|
using System;
using System.Linq;
using System.Windows.Forms;
using WinForms.Context;
using WinForms.Forms.Account;
using WinForms.Models;
namespace WinForms.Forms.Games
{
public partial class FindEvenAndOddNumbersGame : Form
{
private readonly DefaultContext _context = new DefaultContext();
private readonly DateTime _start = DateTime.Now;
private readonly Random _random = new Random();
private int _even = 0;
private int _odd = 0;
private int _timerLeft = 0;
public FindEvenAndOddNumbersGame()
{
InitializeComponent();
AssignNumbersToSquare();
}
private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)
{
}
private void label_Click(object sender, EventArgs e)
{
int numbers = _random.Next(100);
var control = (Control)sender;
if (numbers % 2 == 0)
{
_odd++;
control.Enabled = false;
}
else
{
_even++;
}
}
void AssignNumbersToSquare()
{
for (var i = 0; i < tableLayoutPanel1.Controls.Count; i++)
{
Label label;
if (tableLayoutPanel1.Controls[i] is Label)
label = (Label)tableLayoutPanel1.Controls[i];
else
continue;
label.Text = _random.Next(1000).ToString();
}
}
private void FindEvenAndOddNumbersGame_Load(object sender, EventArgs e)
{
time.Enabled = true;
time.Stop();
}
private void startGame_button(object sender, EventArgs e)
{
_timerLeft = 15;
Timer.Text = _timerLeft.ToString();
StartGame.Enabled = false;
tableLayoutPanel1.Enabled = true;
time.Start();
}
private void Timer_tick(object sender, EventArgs e)
{
if (_timerLeft > 0)
{
_timerLeft--;
Timer.Text = _timerLeft.ToString();
}
if (_timerLeft == 0)
{
time.Stop();
var currentUser = LoginForm.LoggedUser.Id;
var use = _context.Users.FirstOrDefault(c => c.Id == currentUser);
var resultGame = new Statistic
{
Created = _start,
GameType = GameType.FindEvenAndOddNumbers,
SuccessCount = _even,
User = use,
WrongCount = _odd
};
_context.Add(resultGame);
_context.SaveChanges();
MessageBox.Show(Timer.Text = " Четные : " + _even +
"\n Нечетные : " + _odd);
Close();
}
}
private void FindEvenAndOddNumbersGame_Shown(object sender, EventArgs e)
{
_odd = 0;
_even = 0;
}
private void button1_Click_1(object sender, EventArgs e)
{
FindEvenAndOddNumbersGame findEvenAndOdd = new FindEvenAndOddNumbersGame();
findEvenAndOdd.Show();
this.Close();
}
}
}
|
5d215ece18ee42137a2dacebf7e0eaa8cd5df4a3
|
C#
|
Gabriel-Ayala/CadEscola
|
/Utils/Date.cs
| 2.921875
| 3
|
using System;
namespace CadEscola.Utils
{
public class Date
{
public static int Age(DateTime birthday)
{
var _birthday = birthday;
var age = DateTime.Today.Year - _birthday.Year;
if (birthday.Date > DateTime.Today.AddYears(-age)) age--;
return age;
}
}
}
|
0475b393c0462af3faa92dadec6ae74b966a919e
|
C#
|
esaliya/DSCToolsOld
|
/TwisterDaemonService/DaemonTestUtility/Program.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading;
using TwisterDaemonService;
namespace DaemonTestUtility
{
internal class Program
{
private const string TwisterHomeEnvVarName = @"TWISTER_HOME";
private const string JavaHomeEnvVarName = @"JAVA_HOME";
private string _classpath = string.Empty;
private string _javaHome;
private Dictionary<string, int> _nodes;
private string _twisterHome;
private TwisterProperties _twisterProperties;
private void OnStart(string[] args)
{
_twisterHome = Environment.GetEnvironmentVariable(TwisterHomeEnvVarName);
_javaHome = Environment.GetEnvironmentVariable(JavaHomeEnvVarName);
if (string.IsNullOrEmpty(_twisterHome))
{
throw new TwisterDaemonException("Unable to find " + TwisterHomeEnvVarName + " environment variable");
}
if (string.IsNullOrEmpty(_javaHome))
{
throw new TwisterDaemonException("Unable to find " + JavaHomeEnvVarName + " environment variable");
}
_twisterProperties = TwisterProperties.LoadFrom(Path.Combine(_twisterHome, @"bin\twister.properties"));
_nodes = LoadNodesFrom(Path.Combine(_twisterHome, @"bin\nodes"));
_classpath = BuildClassPath(_twisterHome);
const string javaArgs =
@"-Xmx{0} -Xms{1} -XX:SurvivorRatio={2} -classpath {3} cgl.imr.worker.TwisterDaemon {4} {5}";
var psi = new ProcessStartInfo(Path.Combine(_javaHome, @"bin\java.exe"))
{
UseShellExecute = false,
RedirectStandardOutput = false,
CreateNoWindow = false,
};
string fullHostName = Dns.GetHostEntry("").HostName.ToUpper();
int shift = _nodes[fullHostName]*_twisterProperties.DaemonsPerNode;
for (int i = 0; i < _twisterProperties.DaemonsPerNode; ++i)
{
psi.Arguments = string.Format(javaArgs, _twisterProperties.DaemonXmx, _twisterProperties.DaemonXms,
_twisterProperties.DaemonXxSurvivorRatio, _classpath, (shift+i),
_twisterProperties.WorkersPerDaemon);
Process.Start(psi);
Thread.Sleep(1000);
}
}
private string BuildClassPath(string twisterHome)
{
string twisterBin = Path.Combine(twisterHome, @"bin");
string twisterLib = Path.Combine(twisterHome, @"lib");
string path = twisterBin;
string[] jars = Directory.GetFiles(twisterLib, "*.jar", SearchOption.AllDirectories);
path += ";" + string.Join(";", jars);
return path;
}
private Dictionary<string, int> LoadNodesFrom(string nodesFile)
{
var nodes = new Dictionary<string, int>();
using (var reader = new StreamReader(nodesFile))
{
int count = 0;
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
if (!string.IsNullOrEmpty(line))
{
nodes.Add(line.Trim().ToUpper(), count);
++count;
}
}
}
return nodes;
}
public void OnStop()
{
string fullHostName = Dns.GetHostEntry("").HostName.ToUpper();
int count = _nodes[fullHostName];
const string javaArgs =
@"-Xmx260m -Xms260m -XX:SurvivorRatio=10 -classpath {0} cgl.imr.script.StopDaemons {1} {2} {3}";
var psi = new ProcessStartInfo(Path.Combine(_javaHome, @"bin\java.exe"))
{
UseShellExecute = false,
RedirectStandardOutput = false,
CreateNoWindow = false,
Arguments =
string.Format(javaArgs, _classpath, fullHostName, count,
_twisterProperties.DaemonsPerNode),
};
Process.Start(psi);
}
public static void Main(string[] args)
{
var p = new Program();
p.OnStart(args);
Console.WriteLine("Twister Daemon Started on node " + Dns.GetHostEntry("").HostName.ToUpper());
Console.WriteLine("Press any key to stop");
Console.Read();
p.OnStop();
Console.WriteLine("Twister Daemon Stopped on node " + Dns.GetHostEntry("").HostName.ToUpper());
Console.WriteLine("Press any key to exit");
/*string fullHostName = Dns.GetHostEntry("").HostName.ToUpper();
Console.WriteLine(fullHostName);
Console.WriteLine("Starting process ...");
StartProcess();
Console.WriteLine("Done.");*/
Console.Read();
}
public static void StartProcess()
{
var start = new ProcessStartInfo(@"C:\sali\pti\sub\salsa\Saliya\c#\TwisterDaemonService\SimpleConsoleApp\bin\x64\Release\SimpleConsoleApp.exe")
{
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = false,
};
Process p = Process.Start(start);
p.OutputDataReceived += ProcessOutputHandler;
p.BeginOutputReadLine();
// p.WaitForExit();
}
private static void ProcessOutputHandler(object sender, DataReceivedEventArgs dataReceivedEventArgs)
{
Console.WriteLine(dataReceivedEventArgs.Data);
}
}
}
|
40744a0e926bf593b6e51791da0fb7072ae614f1
|
C#
|
dlmufei/WIFI
|
/WIFI/Program.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Reflection;
namespace WIFI
{
static class Program
{
///
/// 应用程序的主入口点。
///
[STAThread]
static void Main(string[] Args)
{
try
{
//获得当前登录的Windows用户标示
System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
Application.SetCompatibleTextRenderingDefault(false);
Process intance = RunningIntance(); //调用检查函数
System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
//判断当前登录用户是否为管理员
if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
{
//如果是管理员,则直接运行
Application.EnableVisualStyles();
if (intance == null) //不存在相同的程序
{
Application.Run(new FormWIFI());
}
else //存在相同的程序
{
HandleRunningInstance(intance);
}
}
else
{
//创建启动对象
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
//设置运行文件
startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
//设置启动参数
startInfo.Arguments = String.Join(" ", Args);
//设置启动动作,确保以管理员身份运行
startInfo.Verb = "runas";
//如果不是管理员,则启动UAC
System.Diagnostics.Process.Start(startInfo);
//退出
System.Windows.Forms.Application.Exit();
}
}
catch
{ }
}
///
/// 监测系统中是否有相同的运行实例
///
/// 运行实例
private static Process RunningIntance()
{
Process currentProcess = Process.GetCurrentProcess();
Process[] processCollection = Process.GetProcessesByName(currentProcess.ProcessName);
foreach (Process p in processCollection)
{
if (p.Id != currentProcess.Id) //检查ID是否相同
{
//检查运行文件路径是否相同
if (Assembly.GetExecutingAssembly().Location.Replace("/",@"\") == currentProcess.MainModule.FileName)
return currentProcess;
}
}
return null;
}
///
/// 发现相同的运行实例(正常显示窗口,并将该应用窗口前置)
///
/// 运行实例
private static void HandleRunningInstance(Process instance)
{
MessageBox.Show("系统已经在运行!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
ShowWindowAsync(instance.MainWindowHandle, 1); //调用api函数,正常显示窗口
SetForegroundWindow(instance.MainWindowHandle); //将窗口放置最前端。
}
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow);
[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(System.IntPtr hWnd);
}
}
|
a94298ca15a973fe58ea51fb70a471e8e7863245
|
C#
|
kherr9/TransitSocial.ChicagoTransitAuthority
|
/src/TransitSocial.ChicagoTransitAuthority.BusTracker/BusTrackerClient.GetStops.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace TransitSocial.ChicagoTransitAuthority.BusTracker
{
public partial class BusTrackerClient
{
public IEnumerable<Stop> GetStops(string routeId, string direction)
{
var request = this.CreateRequest("/bustime/api/v1/getstops", CreateGetStopsQueryString(routeId, direction));
request.Method = "GET";
// will throw WebException if not success status
using (var response = (HttpWebResponse)request.GetResponse())
{
GetStopsResponse getStopsResponse = null;
using (var responseStream = response.GetResponseStream())
{
getStopsResponse = this.Serializer.Deserialize<GetStopsResponse>(responseStream);
}
if (getStopsResponse.Errors != null && getStopsResponse.Errors.Any())
{
throw new Exception(getStopsResponse.Errors.Select(x => x.Message).First());
}
else
{
return getStopsResponse.Stops;
}
}
}
public Task<IEnumerable<Stop>> GetStopsAsync(string routeId, string direction)
{
return this.GetStopsAsync(routeId, direction, CancellationToken.None);
}
public async Task<IEnumerable<Stop>> GetStopsAsync(string routeId, string direction, CancellationToken token)
{
var request = this.CreateRequest("/bustime/api/v1/getstops", CreateGetStopsQueryString(routeId, direction));
request.Method = "GET";
// will throw WebException if not success status
using (var response = await request.GetResponseAsync(token))
{
GetStopsResponse getStopsResponse = null;
using (var responseStream = response.GetResponseStream())
{
getStopsResponse = this.Serializer.Deserialize<GetStopsResponse>(responseStream);
}
if (getStopsResponse.Errors != null && getStopsResponse.Errors.Any())
{
throw new Exception(getStopsResponse.Errors.Select(x => x.Message).First());
}
else
{
return getStopsResponse.Stops;
}
}
}
internal static NameValueCollection CreateGetStopsQueryString(string routeId, string direction)
{
var queryString = CreateQueryStringCollection();
queryString.Add("rt", routeId);
queryString.Add("dir", direction);
return queryString;
}
}
}
|
eefb2efaaf5a3f4da59a1434326260c11e9a2062
|
C#
|
sandymane/BankAccountKata
|
/BankAccount/Withdrawal.cs
| 2.953125
| 3
|
using System;
namespace BankAccount
{
public class Withdrawal : Operation
{
public Withdrawal(Amount amount, DateTime date) : base(amount, date)
{
}
public override string ToString()
{
string withdrawValue = $"-{Amount.Value}".CompleteWithSpaces(10);
return $"WITHDRAWAL | {Date.Date.ToShortDateString()} | {withdrawValue} |";
}
}
}
|
ab7d5d7ceba586e6a4fe89f27b5430c5fc1485d3
|
C#
|
PrakharDemo/C-Programs
|
/UsingProcedures/Procedure-DuplicatesOrNot.cs
| 3.90625
| 4
|
// Using a Procedure,
// Write a program and ask the user to enter a few numbers separated by a hyphen. If the user simply
// presses Enter without supplying an input, exit immediately; otherwise, check to see if there are
// any duplicates. If so, display "Duplicate" on the console.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
Console.WriteLine("Please enter few numbers separated by a Hyuphen");
var input = Console.ReadLine();
if (String.IsNullOrWhiteSpace(input))
{
Console.WriteLine("You did not enter anything, hence exiting the program");
return;
}
if (IsDuplicate(input))
Console.WriteLine("The list does not contain any duplicate numbers");
else
Console.WriteLine("The list contains duplicates");
}
public static bool IsDuplicate (string input)
{
bool check = true;
var numbers = new List<int>();
var uniques = new List<int>();
foreach (var number in (input.Split('-')))
numbers.Add(Convert.ToInt32(number));
foreach (var number in numbers)
{
if (!(uniques.Contains(number)))
uniques.Add(number);
else
check = false;
}
return check;
}
}
|
49d64afde43d8e0dd94711d6a662bb4d1321eebd
|
C#
|
VBaricHB/AggregatedNanoparticleFilmFormation
|
/ANPaX.IO/LammpsDumpSerializer.cs
| 2.671875
| 3
|
using System;
using System.Globalization;
using System.IO;
using ANPaX.Core;
using ANPaX.Core.interfaces;
namespace ANPaX.IO
{
internal static class LammpsDumpSerializer
{
public static void SerializeParticleFilm(IParticleFilm<Aggregate> particleFilm, string filename)
{
using var outfile = new StreamWriter(filename);
outfile.Write($"ITEM: TIMESTEP{Environment.NewLine}0{Environment.NewLine}");
outfile.Write($"ITEM: NUMBER OF ATOMS{Environment.NewLine}{particleFilm.NumberOfPrimaryParticles}{Environment.NewLine}");
outfile.Write(GetBoxDimensionString(particleFilm));
outfile.Write($"ITEM: ATOMS id type aggregate cluster x y z Radius{Environment.NewLine}");
foreach (var agg in particleFilm.Particles)
{
foreach (var cluster in agg.Cluster)
{
foreach (var particle in cluster.PrimaryParticles)
{
outfile.Write(GetPrimaryParticleString(particle, cluster, agg));
}
}
}
}
private static string GetPrimaryParticleString(PrimaryParticle particle, Cluster cluster, Aggregate agg)
{
return $"{particle.Id} {particle.Type} {agg.Id} {cluster.Id} {DoubleToString(particle.Position.X)} {DoubleToString(particle.Position.Y)} {DoubleToString(particle.Position.Z)} {DoubleToString(particle.Radius)}{Environment.NewLine}";
}
private static string DoubleToString(double value)
{
return Math.Round(value, 6).ToString(CultureInfo.InvariantCulture);
}
private static string GetBoxDimensionString(IParticleFilm<Aggregate> particleFilm)
{
var xdim = $"{DoubleToString(particleFilm.SimulationBox.XDim.Lower)} {DoubleToString(particleFilm.SimulationBox.XDim.Upper)}";
var ydim = $"{DoubleToString(particleFilm.SimulationBox.YDim.Lower)} {DoubleToString(particleFilm.SimulationBox.YDim.Upper)}";
var zdim = $"{DoubleToString(particleFilm.SimulationBox.ZDim.Lower)} {DoubleToString(particleFilm.SimulationBox.ZDim.Upper)}";
return $"ITEM: BOX BOUNDS pp pp pp{Environment.NewLine}{xdim}{Environment.NewLine}{ydim}{Environment.NewLine}{zdim}{Environment.NewLine}";
}
}
}
|
ab9c72098706062e4416f08d13f2beebd3cb4ca5
|
C#
|
Streath2001/Jhon-Pe-a
|
/Jhon 1.cs
| 2.8125
| 3
|
/*
* Created by SharpDevelop.
* User: M
* Date: 03/02/2021
* Time: 10:18 p.m.
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
namespace EJERCICIO_1
{
class Program
{
public static void Main(string[] args)
{
int a, b , c;
a = 5;
b = 10;
c = 17;
Console.WriteLine("Combinacion aacb");
Console.Write(a);
Console.Write(a);
Console.Write(c);
Console.Write(b);
Console.WriteLine();
Console.WriteLine("Combinacion bca");
Console.Write(b);
Console.Write(c);
Console.Write(a);
Console.WriteLine();
Console.WriteLine("Combinacion bca");
Console.Write(b);
Console.Write(c);
Console.Write(b);
Console.Write(c);
Console.ReadKey(true);
}
}
}
|
925f8e2004427a30806eede40ff42a253754a314
|
C#
|
PatrikKolesar/MandatoryAssPatrikKolesar
|
/ConsoleApp1/Program.cs
| 3.609375
| 4
|
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using MandatoryAssignment;
namespace TCPServer
{
class Program
{
private static readonly int PORT = 7;
static void Main(string[] args)
{
IPAddress localAddress = IPAddress.Loopback;
// ip and port of server
TcpListener serverSocket = new TcpListener(localAddress, PORT);
//starting server
serverSocket.Start();
Console.WriteLine("TCP Server running on port" + PORT);
while (true) // server loop keeps it running
{
try
{
// waiting for incomming client
TcpClient client = serverSocket.AcceptTcpClient();
Console.WriteLine("incoming client");
// give service to this client
Task.Run(() => DoIt(client));
}
catch (IOException ex)
{
Console.WriteLine("exception. will continue");
}
}
}
//read what client wants
private static void DoIt(TcpClient client)
{
NetworkStream stream = client.GetStream();
//read only
StreamReader reader = new StreamReader(stream);
//write
StreamWriter writer = new StreamWriter(stream);
//end
while (true)
{
string request = reader.ReadLine();
if (request == "bye") break;
if (string.IsNullOrEmpty(request)) { break; }
Console.WriteLine("request: " + request);
string response = request; //echo
var splitRequest = request.Split();
double conversionNumber = double.Parse(splitRequest[1]);
Console.WriteLine("Converting" + conversionNumber + " to ounces:");
switch (splitRequest[0])
{
case ("converttoounces"):
Class1 Grams = new Class1();
double OunceResult = Grams.ConvertionGramToOunce(conversionNumber);
Console.WriteLine("Result: " + OunceResult + " ounces");
break;
case ("converttograms"):
Class1 Ounces = new Class1();
double GramResult = Ounces.ConvertionOunceToGram(conversionNumber);
Console.WriteLine($"Result: " + GramResult + " grams");
break;
}
Console.WriteLine(response);
writer.WriteLine(response);
writer.Flush();
}
client.Close();
}
}
}
|
03172e029a777eb224b8f44645baf5285b851c9e
|
C#
|
JasonGras/GameServer
|
/GameServer/SecurityCheck.cs
| 2.9375
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace GameServer
{
public static class SecurityCheck
{
public static bool CheckEmailPattern(string _text)
{
string pattern;
pattern = @"^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$"; // Email pattern
Regex rgx = new Regex(pattern);
if (rgx.IsMatch(_text))
{
return true;
}
else
{
return false;
}
}
public static bool CheckUserPattern(string _text)
{
string pattern;
pattern = @"^(?=.{4,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$"; // Username pattern
Regex rgx = new Regex(pattern);
if (rgx.IsMatch(_text))
{
return true;
}
else
{
return false;
}
}
public static bool CheckPasswordPattern(string _text)
{
string pattern;
pattern = @"^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})"; // Password pattern (1 Min 1 Maj 1 Numeric 1 Symbol)
Regex rgx = new Regex(pattern);
if (rgx.IsMatch(_text))
{
return true;
}
else
{
return false;
}
}
}
}
|
3d0135ee08d3449d353ca0413299abc825bfa2eb
|
C#
|
Ljubo6/SoftUni-1
|
/CSharp-OOP/Exams/Basics_16-Jul-2017_Minedraft/MinedraftExam/DraftManager.cs
| 2.921875
| 3
|
using System.Collections.Generic;
using System;
using System.Text;
using System.Linq;
public class DraftManager
{
private WorkingMode workingMode;
private double totalStoredEnergy;
private double totalMinedOre;
private List<Harvester> harvesters;
private List<Provider> providers;
private Dictionary<string, Unit> byId;
private HarvesterFactory harvesterFactory;
private ProviderFactory providerFactory;
public DraftManager()
{
this.workingMode = WorkingMode.Full;
this.harvesters = new List<Harvester>();
this.providers = new List<Provider>();
this.harvesterFactory = new HarvesterFactory();
this.providerFactory = new ProviderFactory();
this.byId = new Dictionary<string, Unit>();
}
public string RegisterHarvester(List<string> arguments)
{
try
{
var harvester = harvesterFactory.Create(arguments);
this.harvesters.Add(harvester);
this.byId.Add(arguments[1], harvester);
return $"Successfully registered {arguments[0]} Harvester - {arguments[1]}";
}
catch (Exception e)
{
return e.Message;
}
}
public string RegisterProvider(List<string> arguments)
{
try
{
var provider = providerFactory.Create(arguments);
this.providers.Add(provider);
this.byId.Add(arguments[1], provider);
return $"Successfully registered {arguments[0]} Provider - {arguments[1]}";
}
catch (Exception e)
{
return e.Message;
}
}
public string Day()
{
var dailyProducedEnergy = this.CalculateDailyProducedEnergy();
this.totalStoredEnergy += dailyProducedEnergy;
var requiredEnergyForDay = this.CalculateTotalRequiredEnergy();
double dailyOre = 0d;
if (requiredEnergyForDay <= this.totalStoredEnergy && this.workingMode != WorkingMode.Energy)
{
this.totalStoredEnergy -= requiredEnergyForDay;
dailyOre = this.CalculateDailyOre();
this.totalMinedOre += dailyOre;
}
var output = new StringBuilder();
output.AppendLine("A day has passed.");
output.AppendLine($"Energy Provided: {dailyProducedEnergy}");
output.AppendLine($"Plumbus Ore Mined: {dailyOre}");
return output.ToString().TrimEnd();
}
private double CalculateDailyOre()
{
var dailyOre = this.harvesters.Sum(h => h.OreOutput);
if(this.workingMode == WorkingMode.Half)
{
dailyOre *= 0.5;
}
return dailyOre;
}
private double CalculateDailyProducedEnergy()
{
return this.providers.Sum(p => p.EnergyOutput);
}
private double CalculateTotalRequiredEnergy()
{
var totalRequiredEnergy = this.harvesters.Sum(h => h.EnergyRequirement);
if(this.workingMode == WorkingMode.Half)
{
totalRequiredEnergy *= 0.6;
}
return totalRequiredEnergy;
}
public string Mode(List<string> arguments)
{
string mode = arguments[0];
Enum.TryParse(mode, out this.workingMode);
return $"Successfully changed working mode to {mode} Mode";
}
public string Check(List<string> arguments)
{
string id = arguments[0];
if (!this.byId.ContainsKey(id))
{
return $"No element found with id - {id}";
}
var unit = this.byId[id];
return unit.ToString();
}
public string ShutDown()
{
var info = new StringBuilder();
info.AppendLine($"System Shutdown");
info.AppendLine($"Total Energy Stored: {this.totalStoredEnergy}");
info.AppendLine($"Total Mined Plumbus Ore: {this.totalMinedOre}");
return info.ToString().TrimEnd();
}
}
|
7e4cfb1ac1af820dcdf71027e541ee44c6a0a11d
|
C#
|
DDR12/RestfulFirebase
|
/RestfulFirebase/Database/Offline/DataChanges.cs
| 2.984375
| 3
|
using RestfulFirebase.Utilities;
using System;
using System.Collections.Generic;
using System.Text;
namespace RestfulFirebase.Database.Offline
{
internal enum DataChangesType
{
Create, Update, Delete, None
}
internal class DataChanges
{
public string Blob { get; }
public DataChangesType ChangesType { get; }
public static DataChanges Parse(string data)
{
if (string.IsNullOrEmpty(data)) return null;
var deserialized = StringUtilities.Deserialize(data);
if (deserialized == null) return null;
if (deserialized.Length != 2) return null;
var changesType = DataChangesType.None;
switch (deserialized[1])
{
case "1":
changesType = DataChangesType.Create;
break;
case "2":
changesType = DataChangesType.Update;
break;
case "3":
changesType = DataChangesType.Delete;
break;
}
return new DataChanges(deserialized[0], changesType);
}
public DataChanges(string blob, DataChangesType changesType)
{
Blob = blob;
ChangesType = changesType;
}
public string ToData()
{
var changesType = "0";
switch (ChangesType)
{
case DataChangesType.Create:
changesType = "1";
break;
case DataChangesType.Update:
changesType = "2";
break;
case DataChangesType.Delete:
changesType = "3";
break;
}
return StringUtilities.Serialize(Blob, changesType);
}
}
}
|
dfd300cf8a36d70f4450f2be6442d8640e091ca2
|
C#
|
GrapeSalad/palindrome
|
/Objects/Palindrome.cs
| 3.515625
| 4
|
using System;
using System.Collections.Generic;
namespace PalindromeWork
{
public class Palindrome
{
public bool TestPalindrome(string userInput)
{
char [] standardArray = userInput.ToCharArray();
Console.WriteLine(standardArray);
Array.Reverse(standardArray);
Console.WriteLine(standardArray);
char [] input = userInput.ToCharArray();
if (input.ToString() == standardArray.ToString())
{
return true;
}
else{
return false;
}
}
public bool TestPalindromeHard(string userInput)
{
char [] userArray = userInput.ToCharArray();
Console.WriteLine(userArray);
char [] reversedUserArray;
for (var i = userArray.Length; i > 0; i --)
{
reversedUserArray[] = userArray[i];
}
Console.WriteLine(reversedUserArray);
if (reversedUserArray.ToString() == userArray.ToString())
{
return true;
}
else{
return false;
}
}
}
}
|
b6cd975c07ca6298af935e2a735f2f1b0564d54f
|
C#
|
FRee22858/ServerCluster
|
/CommonLibrarys/LibTest/Program.cs
| 2.515625
| 3
|
using CommonUtility;
using DataProperty;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LibTest
{
class Program
{
static void InitPath(string path = "")
{
string rootPath = string.Empty;
if (string.IsNullOrEmpty(path))
{
DirectoryInfo tempPath = new DirectoryInfo(Application.StartupPath);
if (tempPath.Parent.Exists)
{
rootPath = tempPath.Parent.FullName;
}
else
{
Console.WriteLine("Path is error!Please check the input path!");
}
}
else
{
rootPath = path;
}
PathMng.SetPath(rootPath);
}
static void InitData()
{
string[] files = Directory.GetFiles(PathMng.FullPathFromData("XML"), "*.xml", SearchOption.AllDirectories);
foreach (string file in files)
{
if (DataListManager.Inst.Parse(file))
{
//解析成功
}
else
{
//解析失败
Console.WriteLine("Fail:{0}", file);
}
}
}
static void InitConfig()
{
Data globalData;
DataList clusterConfig = DataListManager.Inst.GetDataList("ClusterConfig");
if (clusterConfig != null)
{
globalData = clusterConfig.GetDataByName("GlobalServer");
}
}
static void Main(string[] args)
{
InitPath();
InitData();
InitConfig();
InitServer();
}
private static void InitServer()
{
InitBattleServer();
}
private static void InitBattleServer()
{
throw new NotImplementedException();
}
}
}
|
e3648032cc3685c1be56829230f94028bbc47e4f
|
C#
|
javendano003/challengeCSharp
|
/Context/ContextDataAccess.cs
| 2.515625
| 3
|
using ChallengeLeanTechJA.Modelo;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ChallengeLeanTechJA.Context
{
public class ContextDataAccess: DbContext
{
private string _connectionString = "";
public string ConnectionString
{
get { return _connectionString; }
set { _connectionString = value; }
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
_connectionString = @"Server=DESKTOP-MSCL69Q\SQLEXPRESS;Integrated Security=true; initial catalog=challenge";
optionsBuilder.UseSqlServer(_connectionString);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Products>().HasKey(p => new { p.ProductId });
//modelBuilder.Entity<Products>().Property(p => p.ProductId).UseIdentityColumn().Metadata.SetAfterSaveBehavior(Microsoft.EntityFrameworkCore.Metadata.PropertySaveBehavior.Ignore);
}
public DbSet<Products> Products { get; set; }
}
}
|
89c64febf03468f8854fff795ec84cfdc68b63c1
|
C#
|
markusjohnsson/JSIL
|
/Examples/SimplePathtracer.cs
| 3.109375
| 3
|
// Based on http://www.coldcity.com/index.php/simple-csharp-pathtracer/
// Original license comment follows
/*
* simplepath
* A simple pathtracer for teaching purposes
*
* IainC, 2009
* License: Do WTF you want
*
* World coord system:
* Origin (0,0,0) is the center of the screen
* X increases towards right of screen
* Y increases towards top of screen
* Z increases into screen
*
* Enough vector maths to get you through:
* - The dot product of two vectors gives the cosine of the angle between them
* - Normalisation is scaling a vector to have magnitude 1: makes it a "unit vector"
* - To get a unit direction vector from point A to point B, do B-A and normalise the result
* - To move n units along a direction vector from an origin, new position = origin + (direction * n)
* - To reflect a vector in a surface with a known surface normal:
* negativeVec = -vecToReflect;
* reflectedVec = normal * (2.0f * negativeVec.Dot(normal)) - negativeVec;
*/
using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JSIL.Meta;
namespace simpleray {
public class Vector3f {
public float x, y, z;
public Vector3f(float x = 0, float y = 0, float z = 0) {
this.x = x;
this.y = y;
this.z = z;
}
// dot product -- returns the cosine of the angle between two vectors
public float Dot(Vector3f b) {
return (x * b.x + y * b.y + z * b.z);
}
// normalise -- scale magnitude of vector to 1. used a lot to construct a point on
// a unit sphere which represents a direction
public void Normalise() {
float f = (float)(1.0f / Math.Sqrt(this.Dot(this)));
x *= f;
y *= f;
z *= f;
}
// return the length of the vector
public float Magnitude() {
return (float)Math.Sqrt(x*x + y*y + z*z);
}
public static Vector3f operator -(Vector3f a, Vector3f b) {
return new Vector3f(a.x - b.x, a.y - b.y, a.z - b.z);
}
public static Vector3f operator -(Vector3f a) {
return new Vector3f(-a.x, -a.y, -a.z);
}
public static Vector3f operator *(Vector3f a, float b) {
return new Vector3f(a.x * b, a.y * b, a.z * b);
}
public static Vector3f operator /(Vector3f a, float b) {
return new Vector3f(a.x / b, a.y / b, a.z / b);
}
public static Vector3f operator +(Vector3f a, Vector3f b) {
return new Vector3f(a.x + b.x, a.y + b.y, a.z + b.z);
}
public Vector3f ReflectIn(Vector3f normal) {
Vector3f negVector = -this;
Vector3f reflectedDir = normal * (2.0f * negVector.Dot(normal)) - negVector;
return reflectedDir;
}
public static Vector3f CrossProduct(Vector3f v1, Vector3f v2)
{
Vector3f v = new Vector3f();
v.x = v1.y * v2.z - v1.z * v2.y;
v.y = v1.z * v2.x - v1.x * v2.z;
v.z = v1.x * v2.y - v1.y * v2.x;
return v;
}
}
public class Ray {
public const float WORLD_MAX = 1000.0f;
public Vector3f origin;
public Vector3f direction;
public RTObject closestHitObject;
public float closestHitDistance;
public Vector3f hitPoint;
public Ray(Vector3f o, Vector3f d) {
origin = o;
direction = d;
closestHitDistance = WORLD_MAX;
closestHitObject = null;
}
}
public abstract class RTObject {
public Color color; // Surface colour
public bool isEmitter; // If true, this object's an emitter
// return distance at which this object is intersected by a ray, or -1 if no intersection
public abstract float Intersect(Ray ray);
// return the surface normal (perpendicular vector to the surface) for a given point on the surface on the object
public abstract Vector3f GetSurfaceNormalAtPoint(Vector3f p);
}
class Plane : RTObject {
// a plane can be specified with just it's surface normal and an offset from the origin in the
// direction of the normal
public Vector3f normal;
public float distance;
public Plane(Vector3f n, float d, Color c) {
normal = n;
distance = d;
color = c;
isEmitter = false;
}
public override float Intersect(Ray ray) {
float normalDotRayDir = normal.Dot(ray.direction);
if (normalDotRayDir == 0) // Ray is parallel to plane (this early-out won't help very often!)
return -1;
// Any none-parallel ray will hit the plane at some point - the question now is just
// if it in the positive or negative ray direction.
float hitDistance = -(normal.Dot(ray.origin) - distance) / normalDotRayDir;
if (hitDistance < 0) // Ray dir is negative, ie we're behind the ray's origin
return -1;
else
return hitDistance;
}
public override Vector3f GetSurfaceNormalAtPoint(Vector3f p) {
return normal; // This is of course the same across the entire plane
}
}
class Sphere : RTObject {
// to specify a sphere we need it's position and radius
public Vector3f position;
public float radius;
public Sphere(Vector3f p, float r, Color c) {
position = p;
radius = r;
color = c;
isEmitter = false;
}
public override float Intersect(Ray ray) {
Vector3f lightFromOrigin = position - ray.origin; // dir from origin to us
float v = lightFromOrigin.Dot(ray.direction); // cos of angle between dirs from origin to us and from origin to where the ray's pointing
float hitDistance = radius * radius + v * v - lightFromOrigin.x * lightFromOrigin.x - lightFromOrigin.y * lightFromOrigin.y - lightFromOrigin.z * lightFromOrigin.z;
if (hitDistance < 0) // no hit (do this check now before bothering to do the sqrt below)
return -1;
hitDistance = v - (float)Math.Sqrt(hitDistance); // get actual hit distance
if (hitDistance < 0)
return -1;
else
return (float)hitDistance;
}
public override Vector3f GetSurfaceNormalAtPoint(Vector3f p) {
Vector3f normal = p - position;
normal.Normalise();
return normal;
}
}
class Renderer {
const int CANVAS_WIDTH = 320; // output image dimensions
const int CANVAS_HEIGHT = 240;
const float TINY = 0.0001f; // a very short distance in world space coords
const int MAX_DEPTH = 4; // max recursion for reflections
const int RAYS_PER_PIXEL = 512; // how many rays to shoot per pixel?
static Vector3f eyePos = new Vector3f(0, 2.0f, -5.0f); // eye pos in world space coords
static Vector3f screenTopLeftPos = new Vector3f(-4.0f, 5.5f, 0); // top-left corner of screen in world coords - note aspect ratio should match image
static Vector3f screenBottomRightPos = new Vector3f(4.0f, -0.5f, 0); // bottom-right corner of screen in world coords
static float pixelWidth, pixelHeight; // dimensions of screen pixel **in world coords**
static List<RTObject> objects; // all RTObjects in the scene
static Random random; // global random for repeatability
static void Main(string[] args) {
// init structures
objects = new List<RTObject>();
random = new Random(45734);
Bitmap canvas = new Bitmap(CANVAS_WIDTH, CANVAS_HEIGHT);
// add some objects
Sphere s = new Sphere(new Vector3f(-2.0f, 2.0f, 0), 1.0f, Color.FromArgb(255, 127, 0, 0));
objects.Add(s);
s = new Sphere(new Vector3f(0, 2.0f, 0), 1.0f, Color.OldLace);
s.isEmitter = true; // this one's a light source
objects.Add(s);
s = new Sphere(new Vector3f(2.0f, 2.0f, 0), 1.0f, Color.FromArgb(255, 0, 127, 0));
objects.Add(s);
// ceiling and floor
// pathtracing needs things for photons to bounce off! otherwise
// most photons exit the scene early before doing their max
// number of bounces
Plane floor = new Plane(new Vector3f(0, 1.0f, 0), 1.0f, Color.FromArgb(255, 200, 200, 200));
objects.Add(floor);
Plane ceiling = new Plane(new Vector3f(0, -1.0f, 0), -5.0f, Color.FromArgb(255, 200, 200, 200));
objects.Add(ceiling);
Plane leftWall = new Plane(new Vector3f(1.0f, 0, 0), -3.0f, Color.FromArgb(255, 75, 75, 200));
objects.Add(leftWall);
Plane rightWall = new Plane(new Vector3f(-1.0f, 0, 0), -3.0f, Color.FromArgb(255, 200, 75, 75));
objects.Add(rightWall);
Plane backWall = new Plane(new Vector3f(0, 0, -1), -3.0f, Color.FromArgb(255, 200, 200, 200));
objects.Add(backWall);
// calculate width and height of a pixel in world space coords
pixelWidth = (screenBottomRightPos.x - screenTopLeftPos.x) / CANVAS_WIDTH;
pixelHeight = (screenTopLeftPos.y - screenBottomRightPos.y) / CANVAS_HEIGHT;
// render it
int dotPeriod = CANVAS_HEIGHT / 20;
System.Console.WriteLine("Rendering...\n");
System.Console.WriteLine("|0%-----------100%|");
RenderRow(canvas, dotPeriod, 0);
// save the pretties
canvas.Save("output.png");
}
static void RenderRow (System.Drawing.Bitmap canvas, int dotPeriod, int y) {
if (y >= CANVAS_HEIGHT)
return;
if ((y % dotPeriod) == 0)
System.Console.Write("*");
for (int x = 0; x < CANVAS_WIDTH; x++) {
Color c = RenderPixel(x, y);
canvas.SetPixel(x, y, c);
}
SetTimeout(0, () =>
RenderRow(canvas, dotPeriod, y + 1)
);
}
[JSReplacement("setTimeout($action, $timeoutMs)")]
static void SetTimeout (int timeoutMs, Action action) {
action();
}
// Given a ray with origin and direction set, fill in the intersection info
static void CheckIntersection(ref Ray ray) {
foreach (RTObject obj in objects) { // loop through objects, test for intersection
float hitDistance = obj.Intersect(ray); // check for intersection with this object and find distance
if (hitDistance < ray.closestHitDistance && hitDistance > 0) {
ray.closestHitObject = obj; // object hit and closest yet found - store it
ray.closestHitDistance = hitDistance;
}
}
ray.hitPoint = ray.origin + (ray.direction * ray.closestHitDistance); // also store the point of intersection
}
// render a pixel (ie, set pixel color to result of a trace of a ray starting from eye position and
// passing through the world coords of the pixel)
static Color RenderPixel(int x, int y) {
// First, calculate direction of the current pixel from eye position
float sx = screenTopLeftPos.x + (x * pixelWidth);
float sy = screenTopLeftPos.y - (y * pixelHeight);
Vector3f eyeToPixelDir = new Vector3f(sx, sy, 0) - eyePos;
eyeToPixelDir.Normalise();
// Set up primary (eye) ray
Ray ray = new Ray(eyePos, eyeToPixelDir);
// And send a bunch of reverse photons that way!
// Since each photon we send into Trace with a depth of 0 will
// bounce around randomly, we need to send many photons into
// every pixel to get good convergence
float r = 0, g = 0, b = 0;
for (int i = 0; i < RAYS_PER_PIXEL; i++) {
Color c = Trace(ray, 1);
r += c.R;
g += c.G;
b += c.B;
}
r /= RAYS_PER_PIXEL;
g /= RAYS_PER_PIXEL;
b /= RAYS_PER_PIXEL;
return (Color.FromArgb(255, (int)r, (int)g, (int)b));
}
// given a ray, trace it into the scene and return the colour of the surface it hits
// (handles bounces recursively)
static Color Trace(Ray ray, int traceDepth) {
// See if the ray intersected an object (only if it hasn't already got one - we don't need to
// recalculate the first intersection for each sample on the same pixel!)
if (ray.closestHitObject == null)
CheckIntersection(ref ray);
if (ray.closestHitDistance >= Ray.WORLD_MAX || ray.closestHitObject == null) // No intersection
return Color.Black;
// Got a hit - was it an emitter? If so just return the emitter's colour
if (ray.closestHitObject.isEmitter)
return ray.closestHitObject.color;
if (traceDepth >= MAX_DEPTH)
return Color.Black;
// Get surface normal at intersection
Vector3f surfaceNormal = ray.closestHitObject.GetSurfaceNormalAtPoint(ray.hitPoint);
// Pick a point on a hemisphere placed on the intersection point (of which
// the surface normal is the north pole)
if (surfaceNormal.Dot(ray.direction) >= 0)
surfaceNormal = surfaceNormal * -1.0f;
float r1 = (float)(random.NextDouble() * Math.PI * 2.0f);
float r2 = (float)random.NextDouble();
float r2s = (float)Math.Sqrt(r2);
Vector3f u = new Vector3f(1.0f, 0, 0);
if (Math.Abs(surfaceNormal.x) > 0.1f) {
u.x = 0;
u.y = 1.0f;
}
u = Vector3f.CrossProduct(u, surfaceNormal);
u.Normalise();
Vector3f v = Vector3f.CrossProduct(u, surfaceNormal);
// Now set up a direction from the hitpoint to that chosen point
Vector3f reflectionDirection = (u * (float)Math.Cos(r1) * r2s + v * (float)Math.Sin(r1) * r2s + surfaceNormal * (float)Math.Sqrt(1 - r2));
reflectionDirection.Normalise();
// And follow that path (note that we're not spawning a new ray -- just following the one we were
// originally passed for MAX_DEPTH jumps)
Ray reflectionRay = new Ray(ray.hitPoint, reflectionDirection);
Color reflectionCol = Trace(reflectionRay, traceDepth + 1);
// Now factor the colour we got from the reflection
// into this object's own colour; ie, illuminate
// the current object with the results of that reflection
float r = ray.closestHitObject.color.R * reflectionCol.R;
float g = ray.closestHitObject.color.G * reflectionCol.G;
float b = ray.closestHitObject.color.B * reflectionCol.B;
r /= 255.0f;
g /= 255.0f;
b /= 255.0f;
return (Color.FromArgb(255, (int)r, (int)g, (int)b));
}
}
}
|
d5a29db9c23e7d4f6f7e77b6403a6cbdf71ed9ec
|
C#
|
sh1eldbearer/uatanks
|
/NScott_UATanks/Assets/_Scripts/Tank Scripts/TankHealthManager.cs
| 2.984375
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[DisallowMultipleComponent]
/*
* This script monitors the health of a tank object, and adjusts values as needed.
*
* This script should be attached to a tank object, and will automatically be attached if
* a TankData component is added to the tank first.
*/
public class TankHealthManager : MonoBehaviour
{
/* Public Variables */
/* Private Variables */
private TankData tankData; // Used to access the tank's current and maximum health values
void Awake()
{
// Component reference assembly
tankData = this.gameObject.GetComponent<TankData>();
}
void Update()
{
// If this tank's health has reached or exceeded zero
if (tankData.currentHP <= 0)
{
// Destroys this tank
Die();
}
// Makes sure the tank's maximum health cnanot exceed the game-defined maximum
if (this.tag == "Player")
{
tankData.maxHP = Mathf.Clamp(tankData.maxHP, GameManager.gm.playerStartingHP, GameManager.gm.playerHPCap);
}
else
{
tankData.maxHP = Mathf.Clamp(tankData.maxHP, GameManager.gm.enemyStartingHP, GameManager.gm.enemyHPCap);
}
// Makes sure the tank's current health cannot exceed its maximum health
tankData.currentHP = Mathf.Clamp(tankData.currentHP, -1, tankData.maxHP);
}
/// <summary>
/// Adjusts the current hit point value of the tank object.
/// </summary>
/// <param name="changeValue">The amount to adjust the current hit points by.
/// Enter a negative number to increase the current health value,
/// and a positive number to reduce the current health value.</param>
/// <returns>Returns a positive value if the tank was destroyed by the shot
/// (Used for adjusting scores).</returns>
public int Damage(int changeValue)
{
// If the tank is allowed to take damage
if (tankData.takesDamage)
{
tankData.currentHP -= changeValue;
// If this tank's health has reached or exceeded zero
if (tankData.currentHP <= 0)
{
// Informs the calling function that the tank was destroyed
return tankData.maxHP;
}
else
{
// Informs the calling function that the tank was not destroyed
return -1;
}
}
else
{
return -1;
}
}
/// <summary>
/// Adjusts the current hit point value of the tank object.
/// </summary>
/// <param name="changeValue">The amount to adjust the current hit points by.
/// Enter a positive number to increase the current health value,
/// and a negative number to reduce the current health value.</param>
public void Heal(int changeValue)
{
tankData.currentHP += changeValue;
}
/// <summary>
/// Destroys this tank, and removes it from the appropriate TankData list
/// in the GameManager
/// </summary>
public void Die()
{
GameManager.soundMgr.StopBulletHitSound();
GameManager.soundMgr.PlayTankDeathSound();
// Looks at the tag of this tank, and removes this tank from the appropriate TankData list
if (tankData.tankTf.tag == "Player")
{
// Tank is a player
// Decreases this tank's lives count
tankData.currentLives--;
// Checks to see if this player has remaining lives
if (tankData.currentLives > 0)
{
// If it does, respawns the player (moves the player tank to a new spawn point and resets its health)
GameManager.gm.RespawnPlayer(tankData);
}
else
{
// Removes this player from the player list, and destroys the tank
GameManager.gm.players.Remove(tankData);
// Destroy the tank
GameManager.gm.DestroyPlayer(tankData);
}
}
else if (tankData.tankTf.tag == "Enemy")
{
// Tank is an enemy
GameManager.gm.enemies[GameManager.gm.enemies.IndexOf(tankData)] = null;
// Destroy this tank!
Destroy(this.gameObject);
}
}
}
|
bdaa34fa7c626998a3f79ecd4cefec5e44c9752c
|
C#
|
renzobanegass/Cotizador
|
/Cotizador/Model/Vendedor.cs
| 3.015625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cotizador.Model
{
class Vendedor
{
public int codvendedor { get; set; }
public string nombre { get; set; }
public string apellido { get; set; }
private List<Cotizacion> cotizaciones { get; set; }
public Vendedor(int Codigo, string Nombre, string Apellido)
{
codvendedor = Codigo;
nombre = Nombre;
apellido = Apellido;
cotizaciones = new List<Cotizacion>();
}
public decimal Cotizar(IPrenda _prenda, string _nombrePrenda, decimal _precio , bool _isPremium , int cantidad)
{
Cotizacion oCotizacion = new Cotizacion();
oCotizacion.num_id = cotizaciones.Count + 1;
oCotizacion.cod_vendedor = this.codvendedor;
oCotizacion.fecha = DateTime.Now;
oCotizacion.prenda = _prenda;
oCotizacion.nombrePrenda = _nombrePrenda;
oCotizacion.cantidad = cantidad;
oCotizacion.total = _prenda.Cotizar(cantidad, _precio, _isPremium);
cotizaciones.Add(oCotizacion);
return oCotizacion.total;
}
public void Historial()
{
Console.WriteLine("------------------");
Console.WriteLine("Historial de Cotizaciones");
foreach (var item in cotizaciones)
{
Console.WriteLine("------------------");
Console.WriteLine($"Numero de Identificacion: {item.num_id}");
Console.WriteLine($"Codigo del Vendedor: {item.cod_vendedor}");
Console.WriteLine($"Fecha y Hora: {item.fecha}");
Console.WriteLine($"Prenda cotizada: {item.nombrePrenda} {(item.prenda.IsPremium ? "Premium" : "Standard")}");
Console.WriteLine($"Cantidad de unidades cotizadas: {item.cantidad}");
Console.WriteLine($"Total: {item.total}");
Console.WriteLine("------------------");
}
}
}
}
|
85fbe20623fae0cfd11f1fbd92a675c363c201a3
|
C#
|
AlexVcht/unity-warbot
|
/Assets/Scripts/Intelligence/Genetique.cs
| 2.6875
| 3
|
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
[System.Serializable]
public class Genetique
{
private int tailleADN;
private float indiceMutation;
private int taillePopulation;
private Squad[] population;
private int[] bestIndices;
private int cursor;
private int gen;
public Genetique(int p_taillePopulation, int p_tailleADN, float p_indiceMutation)
{
gen = 0;
cursor = 0;
indiceMutation = p_indiceMutation;
bestIndices = new int[p_taillePopulation / 2];
population = new Squad[p_taillePopulation];
for (int p = 0; p < population.Length; p++)
{
population[p] = new Squad(p_tailleADN);
}
}
public void makeNextGeneration()
{
gen++;
// Select N/2 meilleurs
for (int i = 0; i < bestIndices.Length; i++)
bestIndices[i] = -1;
int bestIndice;
for (int bi = 0; bi < bestIndices.Length; bi++)
{
bestIndice = 0;
for (int p = 0; p < population.Length; p++)
{
if (!Array.Exists(bestIndices, e => e == p) && population[p].score >= population[bestIndice].score)
bestIndice = p;
}
bestIndices[bi] = bestIndice;
}
// Write the bests in a file to see how it evolves
writeBests(bestIndices);
// Make them reproduce (mutate & crossover => new one)
for (int p = 0; p < population.Length; p++)
{
if (!Array.Exists(bestIndices, e => e == p))
{
Squad male = population[bestIndices[UnityEngine.Random.Range(0, bestIndices.Length)]];
Squad female = population[bestIndices[UnityEngine.Random.Range(0, bestIndices.Length)]];
population[p] = Squad.crossover(male, female);
population[p].mutate(indiceMutation);
}
}
cursor = 0;
}
public Squad nextSquad()
{
if (cursor >= population.Length)
{
return null;
}
return population[cursor++];
}
public bool hasNext()
{
return cursor < population.Length;
}
public void writeBests(int[] bests)
{
using (StreamWriter sw = new StreamWriter(File.Open("bests.txt", FileMode.Append)))
{
sw.WriteLine("Generation : " + gen);
foreach (int b in bests)
{
sw.Write("pop " + b + " ; " + population[b]);
}
}
}
public void SaveState(string fileName)
{
UnityEngine.Debug.Log("saving SaveState : Generation " + this.gen + " at Squad " + (this.cursor+1) + "/" + this.population.Length);
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create (Application.persistentDataPath + "/"+ fileName +".gd");
bf.Serialize(file, this);
file.Close();
UnityEngine.Debug.Log("Saved SaveState : "+ Application.persistentDataPath + "/" + fileName + ".gd");
}
public void LoadState(string fileName)
{
UnityEngine.Debug.Log("Loading SaveState : " + Application.persistentDataPath + "/" + fileName + ".gd");
if (File.Exists(Application.persistentDataPath + "/" + fileName + ".gd")) {
Genetique objectOut = new Genetique(20, 100, 0.1f);
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/" + fileName + ".gd", FileMode.Open);
objectOut = (Genetique)bf.Deserialize(file);
file.Close();
//replacement
this.tailleADN = objectOut.tailleADN;
this.indiceMutation = objectOut.indiceMutation;
this.taillePopulation = objectOut.taillePopulation;
this.population = objectOut.population;
this.bestIndices = objectOut.bestIndices;
this.cursor = objectOut.cursor;
this.gen = objectOut.gen;
UnityEngine.Debug.Log("Loaded SaveState : Generation " + this.gen + " at Squad " + (this.cursor+1) +"/"+ this.population.Length);
} else
{
UnityEngine.Debug.Log("SaveState not found.");
}
}
}
|
ef792d11e6806cac715825b8c58e1d0efcf638f1
|
C#
|
xxramm16916/csharp
|
/FigureMath/FigureMath/EuclideanGeometry/EuclideanTriangle.cs
| 3.640625
| 4
|
using System;
using System.Collections.Generic;
using System.Text;
namespace FigureMath.EuclideanGeometry
{
public class EuclideanTriangle : EuclideanFigure
{
public EuclideanTriangle(string geometryType, string figureType) : base(geometryType, figureType)
{
}
public double GetSquare(double sideA, double sideB, double sideC)
{
Validate(sideA, sideB, sideC);
var perimeter = (sideA + sideB + sideC) / 2;
var square = Math.Round(Math.Sqrt(perimeter * (perimeter - sideA) * (perimeter - sideB) * (perimeter - sideC)), 1, MidpointRounding.AwayFromZero);
return square;
}
private void Validate(double sideA, double sideB, double sideC)
{
if (sideA < 0 || sideB < 0 || sideC < 0)
throw new Exception("Одна из сторон меньше нуля");
else if (sideA > (sideB + sideC) || sideB > (sideA + sideC) || sideC > (sideA + sideB))
throw new Exception("Сторона больше суммы двух других");
}
public bool IsStraightTriangle(double sideA, double sideB, double sideC)
{
Validate(sideA, sideB, sideC);
return sideA == Math.Sqrt(Math.Pow(sideB, 2) + Math.Pow(sideC, 2))
|| sideB == Math.Sqrt(Math.Pow(sideA, 2) + Math.Pow(sideC, 2))
|| sideC == Math.Sqrt(Math.Pow(sideA, 2) + Math.Pow(sideB, 2));
}
}
}
|
09a65ffe5224eef114e336c121f3c176e0c59c3f
|
C#
|
tempusdigital/treinamento-02
|
/Treinamento02/EntityFramework/Services/ProdutoService.cs
| 2.6875
| 3
|
using EntityFramework.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FluentValidation;
using Tempus.Utils;
namespace EntityFramework.Services
{
public class ProdutoService : IProdutoService
{
readonly LojaContext _lojaContext;
readonly ValidarProduto _validarProduto;
public ProdutoService(LojaContext lojaContext, ValidarProduto validarProduto)
{
_lojaContext = lojaContext;
_validarProduto = validarProduto;
}
public async Task<int> InserirEditar(ProdutoInserirEditarDto produtoDto)
{
await _validarProduto.ValidateAndThrowAsync(produtoDto);
Produto produto = null;
if (produtoDto.Id == null)
{
produto = new Produto();
_lojaContext.Add(produto);
}
else
{
produto = await _lojaContext
.Set<Produto>()
.Where(p => p.Id == produtoDto.Id)
.FirstOrDefaultAsync();
ChecarSe.Encontrou(produto);
}
produto.Descricao = produtoDto.Descricao;
produto.Valor = produtoDto.Valor;
await _lojaContext.SaveChangesAsync();
return produto.Id;
}
public async Task<ProdutoPesquisaResultadoDto[]> Listar(ProdutoPesquisaDto pesquisa)
{
var query = _lojaContext
.Set<Produto>()
.AsNoTracking()
.AsQueryable();
if (string.IsNullOrEmpty(pesquisa.Descricao) == false)
query = query.Where(p => p.Descricao.StartsWith(pesquisa.Descricao));
return await query
.Select(p => new ProdutoPesquisaResultadoDto
{
Id = p.Id,
Descricao = p.Descricao
})
.OrderBy(p => p.Descricao)
.ToArrayAsync();
}
public async Task Excluir(int id)
{
var produto = await _lojaContext
.Set<Produto>()
.Where(p => p.Id == id)
.FirstOrDefaultAsync();
ChecarSe.Encontrou(produto);
_lojaContext.Remove(produto);
await _lojaContext.SaveChangesAsync();
}
}
}
|
451793041150ad4b6ccf87cf6d16c079b93594f0
|
C#
|
seynurmammadov/cargo-project
|
/Back End/Business/Concrete/TariffManager.cs
| 2.734375
| 3
|
using Business.Abstract;
using DataAccess.Abstract;
using Entity.Models;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
namespace Business.Concrete
{
public class TariffManager:ITariffService
{
private readonly ITariffDAL _context;
public TariffManager(ITariffDAL context)
{
_context = context;
}
public void Add(Tariff data)
{
_context.Add(data);
}
public void Detele(int id)
{
_context.Delete(new Tariff { Id = id });
}
public List<Tariff> GetAll(Expression<Func<Tariff, bool>> filter )
{
return _context.GetAllNInclude(filter);
}
public Tariff GetWithId(int id)
{
return _context.Get(c => c.Id == id );
}
public void Update(Tariff data)
{
_context.Update(data);
}
}
}
|
e8ded281c63c1dbbb7de2be68d7d1aaf22bf5869
|
C#
|
karno/Phronesis
|
/Phronesis/Util/DependencyObjectExtension.cs
| 2.703125
| 3
|
using System;
using JetBrains.Annotations;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media;
namespace Phronesis.Util
{
public static class DependencyObjectExtension
{
public static T FindVisualChild<T>([NotNull] this DependencyObject obj) where T : DependencyObject
{
if (obj == null) throw new ArgumentNullException(nameof(obj));
var cnum = VisualTreeHelper.GetChildrenCount(obj);
for (var i = 0; i < cnum; i++)
{
var child = VisualTreeHelper.GetChild(obj, i);
var cTyped = child as T;
if (cTyped != null)
{
return cTyped;
}
var descendant = FindVisualChild<T>(child);
if (descendant != null)
{
return descendant;
}
}
return null;
}
}
}
|
40bcb6708fbe0243cabfe54874a2a04fc048b618
|
C#
|
Hutzpa/Bezuhliy_Ilia_Homework
|
/Homework_30.04/Homework_30.04/Content/MovieContentFile.cs
| 2.828125
| 3
|
using System;
namespace Homework_30._04.Content
{
public class MovieContentFile : ContentFile, IResolution
{
public int Height { get; set; }
public int Width { get; set; }
public TimeSpan Duration { get; set; }
public override string ToString()
{
return $" \t {FileName}.{FileExtension} \n \t\t Extension: {FileExtension} \n \t\t Size: {Weight}{WeightMark} \n \t\t Resolution: {Width}x{Height} \n \t \t Length: {Duration.Hours}h{Duration.Minutes}m";
}
}
}
|
0476a4c9751b26dec0d75fea104f210790e32808
|
C#
|
AleksVitvor/HelthCare
|
/Vitvor.HelthCare/Authentication/UserViewModel.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace Vitvor.HelthCare
{
class UserViewModel : INotifyPropertyChanged
{
private MainWindow _mainWindow;
public MainWindow MainWindow
{
get { return _mainWindow; }
set
{
_mainWindow = value;
}
}
private User _user;
public User User
{
get { return _user; }
set
{
_user = value;
OnPropertyChanged("User");
}
}
private RelayCommand enter;
public RelayCommand Enter
{
get
{
return enter ??
(enter = new RelayCommand(obj =>
{
User user = obj as User;
if (user != null)
{
SqlCommand sqlCommand = new SqlCommand();
user.Password = MainWindow.PassBox.Password;
if (Regex.IsMatch(user.UserName, @"^[0-9]"))
{
sqlCommand.CommandText = $"select * from PATIENTS where PATIENTS.id='{user.UserName}' and PATIENTS.Password='{user.Password}'";
sqlCommand.Connection = SingletonForSqlConnection.SqlConnection;
using (SqlDataReader reader = sqlCommand.ExecuteReader())
{
if (reader.HasRows)
{
reader.Close();
PatientWindow patientWindow = new PatientWindow(MainWindow, Convert.ToInt32(user.UserName));
patientWindow.Show();
}
else
{
MessageBox.Show("Проверьте введённые данные", "Предупреждение");
}
}
}
else if(Regex.IsMatch(user.UserName,@"Admin(\w*)"))
{
sqlCommand.CommandText = $"select ADMINS.AdminStatus, ADMINS.id from ADMINS where ADMINS.AdminUserName='{user.UserName}' and ADMINS.AdminPassword='{user.Password}'";
sqlCommand.Connection = SingletonForSqlConnection.SqlConnection;
using (SqlDataReader reader = sqlCommand.ExecuteReader())
{
if (reader.HasRows)
{
reader.Read();
int id = reader.GetInt32(1);
if (reader != null && Convert.ToString(reader.GetValue(0)).Equals("main") && reader.NextResult() == false)
{
reader.Close();
MainAdminWindow mainAdminWindow = new MainAdminWindow(MainWindow);
mainAdminWindow.Show();
}
else if (reader != null && Convert.ToString(reader.GetValue(0)).Equals("MI") && reader.NextResult() == false)
{
reader.Close();
AdminWindow adminWindow = new AdminWindow(MainWindow, id);
adminWindow.Show();
}
}
else
{
MessageBox.Show("Проверьте введённые данные", "Предупреждение"); ;
}
}
}
else
{
sqlCommand.CommandText = $"SELECT [Name]," +
$"[Patronymic]," +
$"[Direction], [MedicalInstitutionid], [id] from DOCTORS where Username='{user.UserName}' and Password='{user.Password}'";
sqlCommand.Connection = SingletonForSqlConnection.SqlConnection;
using (SqlDataReader reader=sqlCommand.ExecuteReader())
{
if (reader.HasRows)
{
reader.Read();
int doctorid = reader.GetInt32(4);
int idOfMI = reader.GetInt32(3);
if (reader.GetString(2).Equals("Медсестра"))
{
MessageBox.Show("Вход как медсестра");
}
else if (reader.GetString(2).Equals("Узкое направление"))
{
reader.Close();
NarrowDoctorWindow narrowDoctorWindow = new NarrowDoctorWindow(_mainWindow, doctorid, idOfMI);
narrowDoctorWindow.Show();
}
else if (reader.GetString(2).Equals("Общее направление"))
{
reader.Close();
GeneralDoctorWindow generalDoctor = new GeneralDoctorWindow(_mainWindow, idOfMI, doctorid);
generalDoctor.Show();
}
}
else
{
MessageBox.Show("Проверьте введённые данные", "Предупреждение");
}
}
}
MainWindow.PassBox.Clear();
MainWindow.UserNameBox.Clear();
}
}));
}
}
private RelayCommand _registrate;
public RelayCommand Registrate
{
get
{
return _registrate ??
(
_registrate=new RelayCommand(obj=>
{
RegistrationWindow registrationWindow = new RegistrationWindow(_mainWindow);
registrationWindow.Show();
_mainWindow.Hide();
}));
}
}
public UserViewModel(MainWindow mainWindow)
{
User = new User();
MainWindow = mainWindow;
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName]string prop = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
}
}
}
|
13ee3f105e3252f1e764635793e1426b0cdc3306
|
C#
|
TonyDeLuca/ScheduledTasks
|
/ScheduledTasks/DateTimeExtensions.cs
| 3.71875
| 4
|
using System;
/// <summary>
/// DateTimeExtensions provide additional functionality to DateTime objects useful for this class library.
/// </summary>
public static class DateTimeExtensions
{
/// <summary>
/// Describes the instance of a day to find in a given month.
/// </summary>
public enum CalculatedDayType
{
First = 1,
Second,
Third,
Fourth,
Last
}
/// <summary>
/// Describes the day type to find in a given month.
/// </summary>
public enum CalculcatedDayOption
{
Monday = 0,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday,
Day,
Weekday,
WeekendDay
}
/// <summary>
/// Calculates specific date rules for the given month.
/// </summary>
/// <param name="dt">The month and year to use.</param>
/// <param name="dayOption">The option we are calculating.</param>
/// <param name="instance">The instance of the option being calculated.</param>
/// <returns>The date of the instance of this option.</returns>
public static DateTime FindInstanceOfDay(this DateTime dt, CalculcatedDayOption dayOption, CalculatedDayType instance)
{
//The instance number corresponds to
int instanceNumber = (int)instance;
DateTime searchDay = new DateTime(dt.Year, dt.Month, 1);
int daysInMonth = DateTime.DaysInMonth(dt.Year, dt.Month);
if (dayOption == CalculcatedDayOption.Monday || dayOption == CalculcatedDayOption.Tuesday ||
dayOption == CalculcatedDayOption.Wednesday || dayOption == CalculcatedDayOption.Thursday ||
dayOption == CalculcatedDayOption.Friday || dayOption == CalculcatedDayOption.Saturday ||
dayOption == CalculcatedDayOption.Sunday)
{
//Converting to DayOfWeek used by DateTime.
DayOfWeek dayOfWeek = DayOfWeek.Monday;
switch (dayOption)
{
case CalculcatedDayOption.Monday:
dayOfWeek = DayOfWeek.Monday;
break;
case CalculcatedDayOption.Tuesday:
dayOfWeek = DayOfWeek.Tuesday;
break;
case CalculcatedDayOption.Wednesday:
dayOfWeek = DayOfWeek.Wednesday;
break;
case CalculcatedDayOption.Thursday:
dayOfWeek = DayOfWeek.Thursday;
break;
case CalculcatedDayOption.Friday:
dayOfWeek = DayOfWeek.Friday;
break;
case CalculcatedDayOption.Saturday:
dayOfWeek = DayOfWeek.Saturday;
break;
case CalculcatedDayOption.Sunday:
dayOfWeek = DayOfWeek.Monday;
break;
}
for (int i = 1; i <= 7; i++)
{
if (searchDay.DayOfWeek == dayOfWeek)
{
//Found the first instance.
//If there are not at least 28 days after the first instance
//then max instance is 4 otherwise it is 5.
if (instanceNumber >= 5)
{
int instanceDay = searchDay.Day;
if (daysInMonth - instanceDay < 28)
{
instanceNumber = 4;
}
else
{
instanceNumber = 5;
}
}
return searchDay.AddDays(7 * (instanceNumber - 1));
}
//Move to the next day.
searchDay = searchDay.AddDays(1);
}
}
else if (dayOption == CalculcatedDayOption.Day)
{
if (instanceNumber < 5)
{
return searchDay.AddDays(instanceNumber - 1);
}
else
{
//last day of the month
return searchDay.AddMonths(1).AddDays(-1);
}
}
else if (dayOption == CalculcatedDayOption.Weekday)
{
if (instanceNumber < 5)
{
int instanceCount = 0;
for (int i = 1; i <= daysInMonth; i++)
{
//Counting each instance of a weekday.
if (searchDay.DayOfWeek == DayOfWeek.Monday || searchDay.DayOfWeek == DayOfWeek.Tuesday
|| searchDay.DayOfWeek == DayOfWeek.Wednesday || searchDay.DayOfWeek == DayOfWeek.Thursday
|| searchDay.DayOfWeek == DayOfWeek.Friday)
{
instanceCount++;
}
if (instanceCount == instanceNumber)
{
//we found the nth instance of this weekend day.
return searchDay;
}
searchDay = searchDay.AddDays(1);
}
}
else
{
//last weekend day of the month
DateTime lastInstance = new DateTime();
for (int i = 1; i <= daysInMonth; i++)
{
//Counting each instance of a weekeday.
if (searchDay.DayOfWeek == DayOfWeek.Monday || searchDay.DayOfWeek == DayOfWeek.Tuesday
|| searchDay.DayOfWeek == DayOfWeek.Wednesday || searchDay.DayOfWeek == DayOfWeek.Thursday
|| searchDay.DayOfWeek == DayOfWeek.Friday)
{
lastInstance = searchDay;
}
searchDay = searchDay.AddDays(1);
}
return lastInstance;
}
}
else if (dayOption == CalculcatedDayOption.WeekendDay)
{
if (instanceNumber < 5)
{
int instanceCount = 0;
for (int i = 1; i < daysInMonth; i++)
{
//Counting each instance of saturday or sunday.
if (searchDay.DayOfWeek == DayOfWeek.Saturday || searchDay.DayOfWeek == DayOfWeek.Sunday)
{
instanceCount++;
}
if (instanceCount == instanceNumber)
{
//we found the nth instance of this weekend day.
return searchDay;
}
searchDay = searchDay.AddDays(1);
}
}
else
{
//last weekend day of the month
DateTime lastInstance = new DateTime();
for (int i = 1; i < daysInMonth; i++)
{
//Counting each instance of saturday or sunday.
if (searchDay.DayOfWeek == DayOfWeek.Saturday || searchDay.DayOfWeek == DayOfWeek.Sunday)
{
lastInstance = searchDay;
}
searchDay = searchDay.AddDays(1);
}
return lastInstance;
}
}
return new DateTime();
}
/// <summary>
/// Sets the time of a DateTime object to a specified time.
/// </summary>
/// <param name="dt"></param>
/// <param name="hours"></param>
/// <param name="minutes"></param>
/// <param name="seconds"></param>
/// <param name="milliseconds"></param>
/// <returns></returns>
public static DateTime SetTime(this DateTime dt, int hours, int minutes, int seconds, int milliseconds)
{
DateTime retVal = dt.Date;
retVal = retVal.AddHours(hours);
retVal = retVal.AddMinutes(minutes);
retVal = retVal.AddSeconds(seconds);
retVal = retVal.AddMilliseconds(milliseconds);
return retVal;
}
/// <summary>
/// Returns the date and time without any ticks after the millisecond.
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static DateTime StartOfMillisecond(this DateTime dt)
{
return dt.AddTicks(-(dt.Ticks % 10000000));
}
/// <summary>
/// Returns the first day of the month.
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static DateTime StartOfMonth(this DateTime dt)
{
int diff = dt.Day - 1;
return dt.AddDays(-diff).Date;
}
/// <summary>
/// Returns the first day of the week specified..
/// </summary>
/// <param name="dt"></param>
/// <param name="startOfWeek">The day of the week considered the first day of the week.</param>
/// <returns></returns>
public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
{
int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;
return dt.AddDays(-1 * diff).Date;
}
/// <summary>
/// The total months between two dates.
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
public static int TotalMonths(this DateTime start, DateTime end)
{
return (start.Year * 12 + start.Month) - (end.Year * 12 + end.Month);
}
}
|
b7b96ead4e42a689527562fcaab412d68101298f
|
C#
|
fragment2501/dotnet5-ef6-console
|
/Model.cs
| 2.953125
| 3
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace bsr_dotnet_ef6
{
public interface IBloggingContext {
DbSet<Blog> Blogs { get; set; }
DbSet<Post> Posts { get; set; }
int SaveChanges();
}
public class BloggingContext : DbContext, IBloggingContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public string ConnectionString { get; private set; }
public BloggingContext(string connectionString)
{
ConnectionString = connectionString;
}
// The following configures EF to create a Sqlite database file in the
// special "local" folder for your platform.
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlite(ConnectionString);
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; } = new List<Post>();
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
}
|
86c8de48b655545c70f4f65b7999c1e6c8cfccd3
|
C#
|
querino/Frapes
|
/Additional/LoadIndex.cs
| 2.59375
| 3
|
using System;
namespace Frapes.Additional
{
/// <summary>
/// Class used to define a Load Index used by some strategies.
/// </summary>
public class LoadIndex
{
private string _id;
//// <value>
/// The identification of the Load Index.
/// </value>
public string Id
{
get
{
return this._id;
}
set
{
this._id = value;
}
}
public LoadIndex()
{
}
/// <summary>
/// Calculates the load index.
/// </summary>
/// <returns>
/// A <see cref="System.Int32"/>
/// </returns>
public int Calculate ()
{
return 0;
}
}
}
|
7eb54fdb7e014af07e43c8d9c3e680ef112c4f45
|
C#
|
stefanatanasov7/Courier
|
/Courier_/Courier/Program.cs
| 3.125
| 3
|
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
// Create parcels and attach employees
ParcelForPlovdiv parcelForPlovdiv = new ParcelForPlovdiv("Пратка за Пловдив", 4.00);
parcelForPlovdiv.Attach(new Employee("Служител #1"));
parcelForPlovdiv.Attach(new Employee("Служител #2"));
parcelForPlovdiv.Attach(new Employee("Служител #3"));
ParcelForBulgaria parcelForBulgaria = new ParcelForBulgaria("Пратка за Страната", 4.50);
parcelForBulgaria.Attach(new Employee("Служител #1"));
parcelForBulgaria.Attach(new Employee("Служител #2"));
parcelForBulgaria.Attach(new Employee("Служител #3"));
ParcelForAbroad parcelForAbroad = new ParcelForAbroad("Пратка за Чъжбина", 10.20);
parcelForAbroad.Attach(new Employee("Служител #1"));
parcelForAbroad.Attach(new Employee("Служител #2"));
parcelForAbroad.Attach(new Employee("Служител #3"));
parcelForPlovdiv.Price = 4.50;
parcelForPlovdiv.Price = 5.20;
parcelForPlovdiv.Price = 5.20;
parcelForBulgaria.Price = 6.10;
parcelForBulgaria.Price = 7.50;
parcelForBulgaria.Price = 8.80;
parcelForAbroad.Price = 12.20;
parcelForAbroad.Price = 15.50;
parcelForAbroad.Price = 20.10;
// Wait for user
Console.ReadKey();
}
}
abstract class Parcel
{
private string _parcelType;
private double _price;
private List<IEmployee> _employees = new List<IEmployee>();
// Constructor
public Parcel(string parcelType, double price)
{
this._parcelType = parcelType;
this._price = price;
}
public void Attach(IEmployee employee)
{
_employees.Add(employee);
}
public void Detach(IEmployee employee)
{
_employees.Remove(employee);
}
public void Notify()
{
foreach (IEmployee employee in _employees)
{
employee.Update(this);
}
Console.WriteLine("");
}
public double Price
{
get { return _price; }
set
{
if (_price != value)
{
_price = value;
Notify();
}
}
}
public string ParcelName
{
get { return _parcelType; }
}
}
class ParcelForAbroad : Parcel
{
public ParcelForAbroad(string parcelType, double price)
: base(parcelType, price)
{
}
}
class ParcelForBulgaria : Parcel
{
public ParcelForBulgaria(string parcelType, double price)
: base(parcelType, price)
{
}
}
class ParcelForPlovdiv : Parcel
{
public ParcelForPlovdiv(string parcelType, double price)
: base(parcelType, price)
{
}
}
interface IEmployee
{
void Update(Parcel parcel);
}
class Employee : IEmployee
{
private string _name;
private Parcel _parcel;
// Constructor
public Employee(string name)
{
this._name = name;
}
public void Update(Parcel parcel)
{
Console.WriteLine(" {0} уведомява, че е постъпила {1} " +
"с цена {2:C} и преминава в състояние на подготовка", _name, parcel.ParcelName, parcel.Price);
}
// Gets or sets the parcel
public Parcel parcel
{
get { return _parcel; }
set { _parcel = value; }
}
}
|
10f88a8b6dcf3dd3a68a58ce5cccf6b045a4a6a6
|
C#
|
alighaffari14/consume_api_in_csharp
|
/listdata/listdata/ListDataDelivery/Program.cs
| 3.015625
| 3
|
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace listdata
{
class Program
{
static void Main(string[] args)
{
working w = new working();
w.ListarFilmes();
w.Print();
}
public class working
{
//myworking here
List<jsonData> ResultFilm = new List<jsonData>();
public List<jsonData> ListarFilmes()
{
try
{
using (WebClient webClient = new System.Net.WebClient())
{
var url = @"https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH,EOS,NEO&tsyms=USD,EUR";
var json = webClient.DownloadString(url);
dynamic array = JsonConvert.DeserializeObject(json);
JObject parsed = JObject.Parse(json);
foreach (var pair in parsed)
{
Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
}
Console.WriteLine("cryptocompare " + array.RAW.FROMSYMBOL + " " + array.RAW.PRICE + " " + array.RAW.LASTUPDATE);
}
}
catch(Exception e)
{
}
return ResultFilm;
}
public void Print()
{
for (int i = 0; i < ResultFilm.Count; i++)
{
Console.WriteLine(ResultFilm[i]);
}
}
}
}
}
|
dec61656daa7420725aeffff195de29f7e73d876
|
C#
|
bharat-mon/GlitchGarden
|
/Assets/Scripts/UI/PlayerPrefsManager.cs
| 2.796875
| 3
|
using UnityEngine;
using System.Collections;
public class PlayerPrefsManager : MonoBehaviour {
const string MASTER_VOLUME_KEY = "master_volume";
const string DIFFICULTY_KEY = "difficulty";
const string LEVEL_UNLOCKED_KEY = "level_unlocked_";
public static void SetMasterVolume (float volume) {
if (volume >= 0f && volume <= 1f) {
PlayerPrefs.SetFloat(MASTER_VOLUME_KEY, volume);
} else {
Debug.LogError("Master volume not in range");
}
}
public static float GetMasterVolume () {
return PlayerPrefs.GetFloat(MASTER_VOLUME_KEY);
}
public static void UnlockLevel (int level) {
if (level <= Application.levelCount - 1) {
PlayerPrefs.SetInt(LEVEL_UNLOCKED_KEY + level.ToString(), 1); // Using 1 for true
} else {
Debug.LogError("Trying to unlock level not in build order");
}
}
public static bool IsLevelUnlocked (int level) {
int levelValue = PlayerPrefs.GetInt(LEVEL_UNLOCKED_KEY + level.ToString());
bool levelUnlocked = (levelValue == 1);
if (level <= Application.levelCount - 1) {
return levelUnlocked;
} else {
Debug.LogError("Checking unlocked level not in build order");
return false;
}
}
public static void SetDifficulty (float difficulty) {
if (difficulty > 0f && difficulty <= 3f) {
PlayerPrefs.SetFloat(DIFFICULTY_KEY, difficulty);
} else {
Debug.LogError("Difficulty value not in range");
}
}
public static float GetDifficulty () {
return PlayerPrefs.GetFloat(DIFFICULTY_KEY);
}
}
|
debc2c864df918c1908800cc1e0e75de1e4382b7
|
C#
|
aringeorge/MapPuzzle
|
/MapPuzzle/MapDisplay.cs
| 2.96875
| 3
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MapPuzzle
{
class MapDisplay
{
Pen m_sGridPen;
Pen m_sEndLocationPen;
Font m_sMoveBonusFont;
Brush m_sFontBrush;
public MapDisplay()
{
m_sGridPen = new Pen(Color.Green);
m_sMoveBonusFont = new Font("Courier New", 12);
m_sFontBrush = new SolidBrush(Color.Blue);
m_sEndLocationPen = new Pen(Color.Gold);
}
public void DrawGrid(Graphics sGraphics, int lSize)
{
for (int i=0; i<Map.Map_Size; i++)
{
for (int j=0; j<Map.Map_Size; j++)
{
sGraphics.DrawRectangle(m_sGridPen, i * lSize, j * lSize, lSize, lSize);
}
}
}
public void DrawBonuses(Graphics sGraphics, int lSize, Map sMap)
{
for (int i=0; i<Map.Map_Size; i++)
{
for (int j=0; j<Map.Map_Size; j++)
{
int lTileMoveBonus = sMap.GetTileMovementBonus(i, j);
if (lTileMoveBonus != 0)
{
sGraphics.DrawString(lTileMoveBonus.ToString(), m_sMoveBonusFont, m_sFontBrush, i * lSize, j * lSize);
}
}
}
}
public void DrawEndLocation(Graphics sGraphics, int lSize, Map sMap)
{
for (int i = 0; i < Map.Map_Size; i++)
{
for (int j = 0; j < Map.Map_Size; j++)
{
if (sMap.IsTileEndTile(i, j) == true)
{
sGraphics.DrawEllipse(m_sEndLocationPen, i * lSize, j * lSize, lSize, lSize);
}
}
}
}
}
}
|
9212e64add36437b34436fa88180aceeee83bc20
|
C#
|
hegyiemilpeter/AdventOfCode2019
|
/AdventOfCode2019.Core/Day1.cs
| 3.59375
| 4
|
using AdventOfCode2019.InputReader;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace AdventOfCode2019.Core
{
// https://adventofcode.com/2019/day/1
public class Day1
{
public int CalculateFullAmount(string path)
{
List<int> inputs = ReadInput(path);
return inputs.Sum(x => CalculateRequiredFuel(x));
}
public int CalculateAdvancedFullAmount(string path)
{
List<int> inputs = ReadInput(path);
return inputs.Sum(x => CalculateAdvancedRequiredFuel(x));
}
public int CalculateAdvancedRequiredFuel(int mass)
{
int actualRequirement = CalculateRequiredFuel(mass);
int fullRequirement = 0;
while (actualRequirement > 0)
{
fullRequirement += actualRequirement;
actualRequirement = CalculateRequiredFuel(actualRequirement);
}
return fullRequirement;
}
public int CalculateRequiredFuel(int mass)
{
return (int)(mass / 3) - 2;
}
private static List<int> ReadInput(string path)
{
Day1InputReader inputReader = new Day1InputReader();
return inputReader.ReadArray(path, ' ').ToList();
}
}
}
|
ae62e964e8a8f97b991896f1552b76777ca9bc0e
|
C#
|
Varbanov/TelerikAcademy
|
/Data structures and algorithms/09. Combinatorics/SubarraysSums/SubarraysCombinator.cs
| 3.0625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SubarraysSums
{
public class SubarraysCombinator : CombinatorWithoutRepetition<int>
{
public int SumOfAllSubarrays { get; set; }
public SubarraysCombinator(int k, int[] inputArray)
: base(k, inputArray)
{
}
public override void Action(int[] arr)
{
foreach (var item in arr)
{
this.SumOfAllSubarrays += item;
}
}
}
}
|
9a4685502e8d8dcc083521d0afbe08fdbf32df6d
|
C#
|
kishoref22/SoftUni-Homework-Projects
|
/Databases Fundamentals/Databases Advanced/05.1 Inheritance/BankSystem/BankSystem.Models/BankAccount.cs
| 3
| 3
|
namespace BankSystem.Models
{
public abstract class BankAccount
{
public int Id { get; set; }
public string AccountNumber { get; set; }
public decimal Balance { get; set; }
public void DepositMoney(decimal amount)
{
this.Balance += amount;
}
public void WithdrawMoney(decimal amount)
{
this.Balance -= amount;
}
}
}
|
11a3e776494bccd8a0f579e30d31f9b213d9ef43
|
C#
|
huacm6171/leetcode
|
/leetcodeTests/Solutions/MyAtoiTests.cs
| 2.5625
| 3
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using leetcode.Solutions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace leetcode.Solutions.Tests
{
[TestClass()]
public class MyAtoiTests
{
[TestMethod()]
public void Solution1Test()
{
MyAtoi ai = new MyAtoi();
string s1 = " -0012a42";
string s2 = "4193 with words";
string s3 = "words and 987";
string s4 = "-91283472332";
string s5 = " -43";
Assert.AreEqual(-12, ai.Solution1(s1));
}
}
}
|
f572cadb81b4a85973da5f5c2437ae05a377e230
|
C#
|
sweekly146/ImgLib
|
/ImgLib/Superimpose/BitmapPoint.cs
| 3.5625
| 4
|
using System.Drawing;
namespace ImgLib.Superimpose
{
/// <summary>
/// Used to superimpose bitmaps onto another in parallel.
/// </summary>
public class BitmapPoint
{
public Bitmap Bitmap { get; }
public Point Point { get; }
/// <param name="bmp">Bitmap to be drawn onto an image.</param>
/// <param name="point">Point to drawn the bitmap onto the image. This will be the first pixel at the top left of the destination image that will be drawn on.</param>
public BitmapPoint(Bitmap bmp, Point point)
{
Bitmap = bmp;
Point = point;
}
}
}
|
2f4565c1614f75a27e5c9dd78509bbe0009d70b9
|
C#
|
antseitz19/CIS375
|
/resource.cs
| 2.703125
| 3
|
/* This file contains the resources which, I believe, makes it easier for the
* programmer to add or delete resources. The advantage of using this technique is
* that the resources that are available can be seen on Intellisense. Examples of
* how the resources are used can be found throughout the AC Framework by doing
* a search -- JC */
// ACFramework 1.3 changes: I made a better sound engine than the one that existed in 1.2.
// The previous sound engine would just play one sound at a time It was challenging, but there is a new
// sound engine in this version which mixes sounds so they can be played at the same time.
// The sound engine still needs work, but it is not a high priority now. One of these days, I'll
// get around to it.
using System;
using System.Threading;
using OpenTK.Audio;
using OpenTK.Input;
using System.Windows.Forms;
namespace ACFramework
{
class BitmapRes
{
// place bitmap identifiers here in numerical order,
// then place the bitmap name in the Bitmap array
private static readonly int SolidColor = 0;
public static readonly int Door = 1;
public static readonly int Wall2 = 2;
public static readonly int Wall3 = 3;
public static readonly int Graphics1 = 4;
public static readonly int Graphics3 = 5;
public static readonly int Sky = 6;
public static readonly int Wood2 = 7;
public static readonly int Concrete = 8;
private static readonly string[] Bitmap = new string[] {
"dummy", // nonexistent, used as placeholder -- JC
"door.bmp",
"wall2.bmp",
"wall3.bmp",
"graphics1.bmp",
"graphics3.bmp",
"sky.bmp",
"wood2.bmp",
"concrete1.bmp"
};
public BitmapRes()
{
for (int i = 0; i < Bitmap.Length; i++)
Bitmap[i] = "bitmaps\\" + Bitmap[i];
}
public static string getResource(int resourceID)
{
return Bitmap[resourceID];
}
public static int Solid
{
get
{
return SolidColor;
}
}
}
class Sound
{
private AudioContext context;
private AutoResetEvent swh = new AutoResetEvent(true);
private bool somethingToPlay;
private int [] request = new int [2]; // doubled when necessary
private int nrequests = 0;
private object locker = new object();
private bool nosound = false;
public static readonly int Pop = 0;
public static readonly int Clap = 1;
public static readonly int Crunch = 2;
public static readonly int Goopy = 3;
public static readonly int LaserFire = 4;
public static readonly int Hallelujah = 5;
private static readonly string[] sound = new string[] {
"pop.wav",
"clap.wav",
"crunch.wav",
"goopy.wav",
"laserfire3.wav",
"hallelujah.wav"
};
public Sound()
{
try
{
context = new AudioContext();
for (int i = 0; i < sound.Length; i++)
{
sound[i] = "sounds\\" + sound[i];
}
somethingToPlay = false;
new Thread(soundEngine).Start();
}
catch (OpenTK.Audio.AudioDeviceException)
{
MessageBox.Show("Your computer either has its speakers disabled, you have no sound device, or you have an incompatible sound device. You may continue to use the AC Framework without sound.");
nosound = true;
}
}
public void soundEngine()
{
AudioReader ar;
int buff;
int state;
// start off at a capacity of 2, will double when necessary
int [] currentSounds = new int[2];
int[] soundBluePrint = new int[2]; // to build a list of sounds which will be copied
// into currentSounds -- this is so I don't have to modify currentSounds while it
// is being used, which could cause problems since it is a reference object
int nSounds; // current number of sounds
while (true)
{
swh.WaitOne();
lock (locker)
{
if (!somethingToPlay) // a Set may have been called while requests were processed
// below
continue;
}
int k;
lock (locker)
{
somethingToPlay = false;
nSounds = 0;
if (currentSounds.Length < request.Length)
Array.Resize(ref currentSounds, request.Length);
for (k = 0; k < nrequests; k++)
{
buff = AL.GenBuffer();
currentSounds[nSounds] = AL.GenSource();
ar = new AudioReader(sound[request[k]]);
AL.BufferData(buff, ar.ReadToEnd());
AL.Source(currentSounds[nSounds], ALSourcei.Buffer, buff);
nSounds++;
}
// request array is used up, so clear it
if (request.Length > 2)
Array.Resize(ref request, 2);
nrequests = 0;
}
AL.SourcePlay(nSounds, currentSounds);
do
{
Thread.Sleep(100); // seems like I kind set it less than 100 without sound distortion
int nCurrentSounds = nSounds;
nSounds = 0;
// check if something new to play
// if new sounds are played, we cannot mess with the currentSounds array, which is being used --
// we have to build up a soundBluePrint array
lock (locker)
{
if (somethingToPlay)
{
somethingToPlay = false;
if (nCurrentSounds + request.Length > soundBluePrint.Length)
Array.Resize(ref soundBluePrint, nCurrentSounds + request.Length);
for (k = 0; k < nrequests; k++)
{
buff = AL.GenBuffer();
soundBluePrint[nSounds] = AL.GenSource();
ar = new AudioReader(sound[request[k]]);
AL.BufferData(buff, ar.ReadToEnd());
AL.Source(soundBluePrint[nSounds], ALSourcei.Buffer, buff);
nSounds++;
}
if (request.Length > 2)
Array.Resize(ref request, 2);
nrequests = 0;
}
}
// Query the sources to find out if any stop playing
int temp = nCurrentSounds;
for (int j = 0; j < temp; j++)
{
AL.GetSource(currentSounds[j], ALGetSourcei.SourceState, out state);
if ((ALSourceState)state == ALSourceState.Playing)
{
// I want to pause them here, so I can include them with the new
// sounds later -- if played again without being paused, they
// will start from the beginning. I want them to be played
// simulatenously with the new sounds, but to pick up where
// they left off
AL.SourcePause(currentSounds[j]);
soundBluePrint[nSounds] = currentSounds[j];
nSounds++;
}
else
// free these resources for later sounds
AL.DeleteSource(currentSounds[j]);
}
if (nSounds > 0)
{
if (currentSounds.Length < nSounds)
Array.Resize(ref currentSounds, nSounds);
for (k = 0; k < nSounds; k++)
currentSounds[k] = soundBluePrint[k];
AL.SourcePlay(nSounds, currentSounds);
}
} while (nSounds > 0);
}
}
public void play(int i)
{
if (!nosound)
{
lock (locker)
{
somethingToPlay = true;
if (request.Length == nrequests + 1)
Array.Resize(ref request, 2 * request.Length);
request[nrequests] = i;
nrequests++;
}
swh.Set();
}
}
}
class vk
{
// add more keys here that you need in numerical order
// then add to the array below in the same order
public static readonly int ControlLeft = 0;
public static readonly int ControlRight = 1;
public static readonly int ShiftLeft = 2;
public static readonly int ShiftRight = 3;
public static readonly int Left = 4;
public static readonly int Right = 5;
public static readonly int Up = 6;
public static readonly int Down = 7;
public static readonly int PageUp = 8;
public static readonly int PageDown = 9;
public static readonly int Home = 10;
public static readonly int End = 11;
public static readonly int Space = 12;
public static readonly int Insert = 13;
public static readonly int Delete = 14;
public static readonly int U = 15;
public static readonly int I = 16;
public static readonly int D = 17;
public static Key[] key;
public vk()
{
key = new Key[] { Key.ControlLeft,
Key.ControlRight,
Key.ShiftLeft,
Key.ShiftRight,
Key.Left,
Key.Right,
Key.Up,
Key.Down,
Key.PageUp,
Key.PageDown,
Key.Home,
Key.End,
Key.Space,
Key.Insert,
Key.Delete,
Key.U,
Key.I,
Key.D
};
}
public static Key[] KeyList
{
get { return key; }
set { key = value; }
}
}
struct ModelsMD2Info
{
public string ModelFolder;
public string ModelPcx;
public float offset;
public bool randomSelection;
/// <summary>
///
/// </summary>
/// <param name="folder">The folder name for your model.</param>
/// <param name="filename">The pcx file name of your model.</param>
/// <param name="offs">Adjusts positiion relative to floor. Try 0.0f.
/// Adjust to positive value if feet are under the floor, adjust to negative value if floating.</param>
/// <param name="ranselect">true for random selection of the critter,
/// otherwise false. At least one must be set true.</param>
public ModelsMD2Info(string folder, string filename, float offs,
bool ranselect)
{
ModelFolder = folder;
ModelPcx = filename;
offset = offs;
randomSelection = ranselect;
}
}
class ModelsMD2
{
// add more models here that you need in numerical order
// then add to the array below in the same order
public static readonly int Garfield = 0;
public static readonly int Duckman = 1;
public static readonly int Starfox = 2;
// at least one must be set true
private static readonly ModelsMD2Info[] minfo = {
new ModelsMD2Info( "Garfield", "mad.pcx", 0.2f, true ),
new ModelsMD2Info( "Duckman", "duck.pcx", 0.3f, true ),
new ModelsMD2Info( "Starfox", "starfox.pcx", 0.2f, false ),
};
private static int[] randomCritters;
public ModelsMD2()
{
for (int i = 0; i < minfo.Length; i++)
minfo[i].ModelPcx = "models\\" + minfo[i].ModelFolder + "\\" +
minfo[i].ModelPcx;
int count = 0;
for (int i = 0; i < minfo.Length; i++ )
if ( minfo[i].randomSelection == true )
count++;
randomCritters = new int[count];
count = 0;
for (int i = 0; i < minfo.Length; i++ )
if ( minfo[i].randomSelection == true )
{
randomCritters[count] = i;
count++;
}
}
public string getModelFileName(int modelIndex)
{
return "models\\" + minfo[modelIndex].ModelFolder + "\\tris.MD2";
}
public string getSkinFileName(int modelIndex)
{
return minfo[modelIndex].ModelPcx;
}
public cVector3 getCorrectionPercents(int modelIndex)
{
cVector3 cp = new cVector3();
cp.Z = minfo[modelIndex].offset;
return cp;
}
public int selectRandomCritter()
{
int selection = (int)Framework.randomOb.random((uint)randomCritters.Length);
return randomCritters[selection];
}
}
}
|
18f2be44a29361f8eef67460c4c10c52bfbd489a
|
C#
|
buergi1986/C-
|
/Einsendeaufgabe_csph11c/SMARegisTry/SMARegisTry Backup/SmartRegistry.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Diagnostics;
using System.IO;
using System.Security.Principal;
namespace SMARegisTry_Backup
{
public partial class smartRegistryMain : Form
{
// Global variables
string listPath = "", keyPath = "", actionTakenString = "", successMessages = "", prefix = "", catchErrText = "", argErrText="";
int promptIfExists = 1, argumentsMode = 0, errArgs = 0;
public int showWarnings = 1;
public string logFile = AppDomain.CurrentDomain.BaseDirectory + "\\log.txt";
public smartRegistryMain()
{
InitializeComponent();
}
private void ProcessArguments()
{
// Create the log file if it doesn't exist for when arguments are passed to the program
if (!File.Exists(logFile))
{
File.Create(logFile);
}
else
{
// If the log file is over 20MB, rename it to the name + date
FileInfo fSize = new FileInfo(logFile);
long s1 = fSize.Length;
if (s1 >= 20971520)
{
string dForFName = DateTime.Now.ToShortDateString();
dForFName = dForFName.Replace(@"/", @"_");
string newFileName = Directory.GetCurrentDirectory() + "\\log_" + dForFName + ".txt";
File.Move(logFile, newFileName);
}
}
// Get arguments for backup of a list or importing dir with registry files
string[] args = Environment.GetCommandLineArgs();
if (args.Length != 0)
{
int foundSaveFlag = -1;
int foundRestoreFlag = -1;
int k = 0;
foreach (string a in args)
{
if (a == "-s")
{
foundSaveFlag = k;
}
if (a == "-r")
{
foundRestoreFlag = k;
}
k++;
}
// Add 1 to each position for length
if (args.Length >= ((foundSaveFlag + 1) + 2) && foundSaveFlag != -1)
{
if (args[foundSaveFlag].ToString() == "-s")
{
if (!args[foundSaveFlag + 1].ToString().Equals("") && !args[foundSaveFlag + 2].ToString().Equals(""))
{
string regListFileToBackupNow = args[foundSaveFlag + 1].ToString();
string regDirectoryToBackupNow = args[foundSaveFlag + 2].ToString();
if (File.Exists(regListFileToBackupNow))
{
int dirCanBeUsed = 1;
if (!Directory.Exists(regDirectoryToBackupNow))
{
// The directory doesn't exist, so attempt to create it.
Directory.CreateDirectory(regDirectoryToBackupNow);
// If it still doesn't exist, there was a problem creating this directory.
if (!Directory.Exists(regDirectoryToBackupNow))
{
dirCanBeUsed = 0;
}
}
if (dirCanBeUsed == 1)
{
// List of keys
List<String> regListOfKeys = new List<String>();
// Set arguments mode so we can be silent and close the program without any messages after backup is successful or fails
argumentsMode = 1;
// Read list line by line
string line;
System.IO.StreamReader file = new System.IO.StreamReader(regListFileToBackupNow);
while ((line = file.ReadLine()) != null)
{
if (line != "")
{
if (!regListOfKeys.Contains(line))
{
regListOfKeys.Add(line);
}
}
}
file.Close();
// Set keypath
keyPath = regDirectoryToBackupNow;
// Perform key operations
keyOperations(regListOfKeys);
if (successMessages != "")
{
// Add to log file...
if (File.Exists(logFile))
{
using (StreamWriter w = File.AppendText(logFile))
{
w.WriteLine("-------------------------------------------------------------------------------");
w.WriteLine("The following operations ran at: " + DateTime.Now);
w.WriteLine("-------------------------------------------------------------------------------");
w.Write(successMessages);
w.Write("\n\n");
}
}
successMessages = "";
}
}
else
{
errArgs++;
argErrText += "Registry backup directory " + regDirectoryToBackupNow + " is invalid!\n";
}
}
else
{
errArgs++;
argErrText += "Registry list file " + regListFileToBackupNow + " does not exist!\n";
}
// Expecting an input file
// Run validation (make sure file exists, line starts with an HKEY of some sort)
// Call keyOperations to backup list of keys to dir specified
// Output errors in commandline arguments to log file
if (argErrText != "")
{
// Add to log file...
if (File.Exists(logFile))
{
using (StreamWriter w = File.AppendText(logFile))
{
w.WriteLine("-------------------------------------------------------------------------------");
w.WriteLine("Errors were detected in the arguments passed to SMARegisTry Backup at: " + DateTime.Now);
w.WriteLine("-------------------------------------------------------------------------------");
w.Write(argErrText);
w.Write("\n\n");
}
}
argErrText = "";
errArgs = 0;
}
}
}
}
// Add one to position for length
else if (args.Length >= ((foundRestoreFlag + 1) + 1) && foundRestoreFlag != -1)
{
if (args[foundRestoreFlag].ToString() == "-r")
{
// Restore all registry files from directory specified
string regFilesToRestoreDir = args[foundRestoreFlag + 1].ToString();
if (regFilesToRestoreDir != "" && Directory.Exists(regFilesToRestoreDir))
{
// Set arguments mode
argumentsMode = 1;
// Send the directory with registry files to the scanner method which then also restores each key that was found:
getRegFilesInDir(regFilesToRestoreDir);
// Add to log file...
if (File.Exists(logFile))
{
using (StreamWriter w = File.AppendText(logFile))
{
w.WriteLine("-------------------------------------------------------------------------------");
w.WriteLine("The following operations ran at: " + DateTime.Now);
w.WriteLine("-------------------------------------------------------------------------------");
w.Write(successMessages);
w.Write("\n\n");
}
}
successMessages = "";
}
else
{
errArgs++;
argErrText += "Registry restore directory of " + regFilesToRestoreDir + " does not exist or is invalid!\n";
}
// Output errors in commandline arguments to log file
if (argErrText != "")
{
// Add to log file...
if (File.Exists(logFile))
{
using (StreamWriter w = File.AppendText(logFile))
{
w.WriteLine("-------------------------------------------------------------------------------");
w.WriteLine("Errors were detected in the arguments passed to SMARegisTry Backup at: " + DateTime.Now);
w.WriteLine("-------------------------------------------------------------------------------");
w.Write(argErrText);
w.Write("\n\n");
}
}
argErrText = "";
errArgs = 0;
}
}
}
}
}
private void smartRegistryMain_Load(object sender, EventArgs e)
{
ProcessArguments();
if (argumentsMode == 0)
{
getSavedSettings();
ReadRegistry();
}
else
{
// Close the program after ops have been processed in command arguments mode.
this.Close();
}
}
private void ReadRegistry()
{
//HKEY_CLASSES_ROOT
TreeNode rootNode = new TreeNode(Registry.ClassesRoot.Name, 0, 1);
string[] rootSubKeys = Registry.ClassesRoot.GetSubKeyNames();
foreach (string key in rootSubKeys)
{
try
{
TreeNode node = new TreeNode(key, 0, 1);
string[] subKeys = Registry.ClassesRoot.OpenSubKey(key).GetSubKeyNames();
foreach (string subKeysKey in subKeys)
{
node.Nodes.Add(subKeysKey, subKeysKey, 0, 1);
}
rootNode.Nodes.Add(node);
}
catch
{
catchErrText += "Unable to open the HKEY_CLASSES_ROOT key of: " + key + "\n";
}
}
registryTreeView.Nodes.Add(rootNode);
//HKEY_CURRENT_CONFIG
TreeNode configNode = new TreeNode(Registry.CurrentConfig.Name, 0, 1);
string[] configSubKeys = Registry.CurrentConfig.GetSubKeyNames();
foreach (string key in configSubKeys)
{
try
{
TreeNode node = new TreeNode(key, 0, 1);
string[] subKeys =
Registry.CurrentConfig.OpenSubKey(key).GetSubKeyNames();
foreach (string subKeysKey in subKeys)
node.Nodes.Add(subKeysKey, subKeysKey, 0, 1);
configNode.Nodes.Add(node);
}
catch
{
catchErrText += "Unable to open the HKEY_CURRENT_CONFIG key of: " + key + "\n";
}
}
registryTreeView.Nodes.Add(configNode);
//HKEY_CURRENT_USER
TreeNode currentUserNode = new TreeNode(Registry.CurrentUser.Name, 0, 1);
string[] currentUserSubKeys = Registry.CurrentUser.GetSubKeyNames();
foreach (string key in currentUserSubKeys)
{
try
{
TreeNode node = new TreeNode(key, 0, 1);
string[] subKeys = Registry.CurrentUser.OpenSubKey(key).GetSubKeyNames();
foreach (string subKeysKey in subKeys)
node.Nodes.Add(subKeysKey, subKeysKey, 0, 1);
currentUserNode.Nodes.Add(node);
}
catch
{
catchErrText += "Unable to open the HKEY_CURRENT_USER key of: " + key + "\n";
}
}
registryTreeView.Nodes.Add(currentUserNode);
listBox1.Items.Add(currentUserNode);
//HKEY_LOCAL_MACHINE
TreeNode localMachineNode = new TreeNode(Registry.LocalMachine.Name);
string[] localMachineSubKeys = Registry.LocalMachine.GetSubKeyNames();
foreach (string key in localMachineSubKeys)
{
TreeNode node = new TreeNode(key, 0, 1);
TreeNode nodeTwo = new TreeNode();
try
{
string[] subKeys =
Registry.LocalMachine.OpenSubKey(key, false).GetSubKeyNames();
foreach (string subKeysKey in subKeys)
{
if (subKeysKey == "Wow6432Node")
{
nodeTwo = new TreeNode(subKeysKey, 0, 1);
//MessageBox.Show(subKeysKey);
// MessageBox.Show(key + "\\" + subKeysKey);
string[] subKeys64 = Registry.LocalMachine.OpenSubKey(key + "\\" + subKeysKey, false).GetSubKeyNames();
foreach (string subKeysKeyKey in subKeys64)
{
//MessageBox.Show(subKeysKeyKey);
nodeTwo.Nodes.Add(subKeysKeyKey, subKeysKeyKey, 0, 1);
}
node.Nodes.Add(nodeTwo);
}
else
{
node.Nodes.Add(subKeysKey, subKeysKey, 0, 1);
}
}
}
catch (Exception)
{
//an exception is thrown if the user has no access to this subkey
//if this is the case, change the icon to show a dimmed folder
node.ImageIndex = 4;
node.SelectedImageIndex = 5;
// The security key is always locked down
if (key != "SECURITY")
{
catchErrText += "Unable to open the HKEY_LOCAL_MACHINE key of: " + key + "\n";
}
}
localMachineNode.Nodes.Add(node);
}
registryTreeView.Nodes.Add(localMachineNode);
//HKEY_USERS
TreeNode usersNode = new TreeNode(Registry.Users.Name);
string[] usersSubKeys = Registry.Users.GetSubKeyNames();
foreach (string key in usersSubKeys)
{
TreeNode node = new TreeNode(key, 0, 1);
try
{
string[] subKeys = Registry.Users.OpenSubKey(key).GetSubKeyNames();
foreach (string subKeysKey in subKeys)
node.Nodes.Add(subKeysKey, subKeysKey, 0, 1);
}
catch (Exception)
{
//an exception is thrown if the user has no access to this subkey
//if this is the case, change the icon to show a dimmed folder
node.ImageIndex = 4;
node.SelectedImageIndex = 5;
catchErrText += "Unable to open the HKEY_USERS key of: " + key + "\n";
}
usersNode.Nodes.Add(node);
}
registryTreeView.Nodes.Add(usersNode);
if (catchErrText != "")
{
if (showWarnings == 1)
{
MessageBox.Show(catchErrText + "\nDoes your local security policy allow access to these registry keys?\nTo ensure access to as many keys as possible, run SMARegisTry Backup as an administrator!\nClick on \"OK\" to proceed.", "Unable to Read The Following Registry Keys", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
// Add to log file...
if (File.Exists(logFile))
{
using (StreamWriter w = File.AppendText(logFile))
{
w.WriteLine("-------------------------------------------------------------------------------");
w.WriteLine("The following Registry keys could NOT be accessed during the registry scan at: " + DateTime.Now);
w.WriteLine("-------------------------------------------------------------------------------");
w.Write(catchErrText);
w.Write("\n\n");
}
}
}
}
private static void GetValuesAndData(RegistryKey registryKey, TreeNode node)
{
string[] values = registryKey.GetValueNames();
foreach (string value in values)
{
object data = registryKey.GetValue(value);
if (data != null)
{
string stringData = data.ToString();
//if the data is too long, display the begining only
if (stringData.Length > 50)
stringData = stringData.Substring(0, 46) + " ...";
//Display the data of the value. The conditional operatore is
//needed because the default value has no name
node.Nodes.Add(value, (value == "" ? "Default" : value) +
": " + stringData, 2, 2);
}
else
{
//Display <empty> if the value is empty
node.Nodes.Add(value, (value == "" ? "Default" : value) +
": <empty>", 2, 2);
}
}
}
private void AddKeyToList_Click(object sender, EventArgs e)
{
if (registryTreeView.SelectedNode != null)
{
string keyToSave = registryTreeView.SelectedNode.FullPath;
if (keyToSave != "" & keyToSave != null)
{
//MessageBox.Show(keyToSave);
if (keysToBackup.Items.IndexOf(keyToSave) == -1)
{
keysToBackup.Items.Add(keyToSave);
}
else
{
MessageBox.Show("The key " + keyToSave + " has already been added to the list of keys to backup!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
else
{
MessageBox.Show("No registry key has been selected for addition to the list.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
registryTreeView.Focus();
}
private void removeFromList_Click(object sender, EventArgs e)
{
int index = keysToBackup.SelectedIndex;
if (index != -1)
{
keysToBackup.Items.RemoveAt(index);
}
}
public void ExportKey(string RegKey, string SavePath)
{
string path = "\"" + SavePath + "\"";
string key = "\"" + RegKey + "\"";
var proc = new Process();
try
{
proc.StartInfo.FileName = "regedit.exe";
proc.StartInfo.UseShellExecute = false;
//MessageBox.Show(path);
//MessageBox.Show(key);
proc = Process.Start("regedit.exe", "/e " + path + " " + key + "");
if (proc != null) proc.WaitForExit();
successMessages += "Successfully exported " + key + " to " + path + "\n";
}
finally
{
if (proc != null) proc.Dispose();
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void writeToRegistry(string key)
{
// Bug Fix for Not Importing Keys Successfully
// Needs quote incase directory has spaces or other special chars in it. Stupid Windows.
string parametersForRun = "/s " + "\"" + key + "\"";
// Old way of doing it... which doesn't work
// Process regeditProcess = Process.Start("regedit.exe", parametersForRun);
Process regeditProcess = new Process();
regeditProcess.StartInfo.FileName = "regedit.exe";
regeditProcess.StartInfo.Arguments = parametersForRun;
regeditProcess.StartInfo.UseShellExecute = true;
// Debugging
/*
regeditProcess.StartInfo.UseShellExecute = false;
regeditProcess.StartInfo.RedirectStandardError = true;
regeditProcess.StartInfo.RedirectStandardOutput = true;
*/
regeditProcess.Start();
// Debugging
// string stdout = regeditProcess.StandardOutput.ReadToEnd();
// string stderr = regeditProcess.StandardError.ReadToEnd();
regeditProcess.WaitForExit();
// Debug code
// MessageBox.Show(regeditProcess.ExitCode.ToString());
successMessages += "Successfully imported " + key + " into the registry!" + "\n";
}
private void SaveListButton_Click(object sender, EventArgs e)
{
saveList();
}
private void saveList()
{
if (keysToBackup.Items.Count != 0)
{
//string dateNow = DateTime.Now.ToString("M-d-yyyy");
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Text File|*.txt";
saveFileDialog1.Title = "List";
if (listPath == "")
{
saveFileDialog1.InitialDirectory = Directory.GetCurrentDirectory();
}
else
{
saveFileDialog1.InitialDirectory = listPath;
}
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if (saveFileDialog1.FileName != "")
{
using (StreamWriter sw = File.CreateText(Path.GetFullPath(saveFileDialog1.FileName)))
{
foreach (string item in keysToBackup.Items)
{
sw.WriteLine(item);
}
}
Success savedSuccess = new Success("Your list was successfully saved to " + saveFileDialog1.FileName);
savedSuccess.Show();
}
}
}
else
{
MessageBox.Show("There are no items in the list to be saved!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void saveListToolStripMenuItem_Click(object sender, EventArgs e)
{
saveList();
}
private void LoadListButton_Click(object sender, EventArgs e)
{
LoadList();
}
private void LoadList()
{
int proceed = 1;
if (keysToBackup.Items.Count > 0)
{
DialogResult result = MessageBox.Show("There are already items in your list. Are you sure you want to proceed? If your current list has not been saved, you will lose all items in the list!", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.No)
{
proceed = 0;
}
}
if (proceed == 1)
{
clearRegList();
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (listPath == "")
{
openFileDialog1.InitialDirectory = Directory.GetCurrentDirectory();
}
else
{
openFileDialog1.InitialDirectory = listPath;
}
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 1;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if (openFileDialog1.FileName != "")
{
if (File.Exists(openFileDialog1.FileName))
{
using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
keysToBackup.Items.Add(line);
}
}
}
}
Success openSuccess = new Success("Your list was successfully opened from " + openFileDialog1.FileName);
openSuccess.Show();
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
}
private void clearRegList()
{
keysToBackup.Items.Clear();
}
private void getSavedSettings()
{
string configString = "";
// Reading Saved Options:
if (File.Exists(Directory.GetCurrentDirectory().ToString() + @"\\config.txt"))
{
using (StreamReader sr = new StreamReader(Directory.GetCurrentDirectory().ToString() + @"\\config.txt"))
{
configString = sr.ReadToEnd().ToString();
sr.Close();
}
if (configString != "" & configString.IndexOf(',') != -1)
{
string[] settings;
settings = configString.Split(',');
if (settings.Length == 3)
{
if (settings[0] != "")
{
listPath = settings[0];
}
else
{
listPath = "";
}
if (settings[1] != "")
{
keyPath = settings[1];
}
else
{
keyPath = "";
}
if (settings[2] != "")
{
if (settings[2] == "1")
{
// Don't show access warnings
showWarnings = 0;
}
else
{
// Do show access warnings
showWarnings = 1;
}
}
}
}
}
}
private void BackupButton_Click(object sender, EventArgs e)
{
List<String> keysFromList = new List<String>();
if (keysToBackup.Items.Count != 0)
{
// Build list to send to keyOperations method
foreach (string itemFromList in keysToBackup.Items)
{
keysFromList.Add(itemFromList);
}
if (keyPath != "")
{
keyOperations(keysFromList);
}
else
{
MessageBox.Show("Please select the directory where you'd like to save your registry key files.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
if (folderBrowserDialog1.SelectedPath != "")
{
keyPath = folderBrowserDialog1.SelectedPath;
}
keyOperations(keysFromList);
}
}
// Show results
if (successMessages != "")
{
Success backedUp = new Success(successMessages);
backedUp.Show();
successMessages = "";
}
}
else
{
MessageBox.Show("There are no registry keys selected for backup!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void restoreKeysButton_Click(object sender, EventArgs e)
{
MessageBox.Show("Please select a directory containing registry keys to import into the registry.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
if (keyPath == "")
{
openFileDialog1.InitialDirectory = Directory.GetCurrentDirectory();
}
else
{
openFileDialog1.InitialDirectory = keyPath;
}
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
if (folderBrowserDialog1.SelectedPath != "")
{
getRegFilesInDir(folderBrowserDialog1.SelectedPath);
}
}
if (successMessages != "")
{
Success backedUp = new Success(successMessages);
backedUp.Show();
successMessages = "";
}
}
private void getRegFilesInDir(string dirToScan)
{
string[] filePaths = Directory.GetFiles(dirToScan, "*.reg");
foreach (string regFile in filePaths)
{
writeToRegistry(regFile);
}
}
private void ViewContentsButton_Click(object sender, EventArgs e)
{
try
{
if (registryTreeView.SelectedNode != null)
{
string keyToView = registryTreeView.SelectedNode.FullPath;
if (keyToView.IndexOf("\\") != -1)
{
string toSwitch = keyToView.Substring(0, keyToView.IndexOf("\\"));
string subkey = keyToView.Substring(keyToView.IndexOf("\\") + 1);
//MessageBox.Show("I got the following " + toSwitch);
// MessageBox.Show(subkey);
Microsoft.Win32.RegistryKey key;
switch (toSwitch)
{
case "HKEY_LOCAL_MACHINE":
key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(subkey, false);
break;
case "HKEY_CLASSES_ROOT":
key = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(subkey, false);
break;
case "HKEY_CURRENT_USER":
key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(subkey, false);
break;
case "HKEY_USERS":
key = Microsoft.Win32.Registry.Users.OpenSubKey(subkey, false);
break;
case "HKEY_CURRENT_CONFIG":
key = Microsoft.Win32.Registry.CurrentConfig.OpenSubKey(subkey, false);
break;
default:
key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software", false);
break;
}
if (key.SubKeyCount == 0)
{
MessageBox.Show("There are no additional subkeys or values within the selected key!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
ShowValues showIt = new ShowValues(key, this);
showIt.Show();
}
}
else
{
MessageBox.Show("Please select a subkey first for " + keyToView + " before trying to view more information!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("No registry key has been selected.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch
{
MessageBox.Show("Unable to pull information from this registry key, as permission is denied.\nThis happens with some registry keys.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void preferencesToolStripMenuItem_Click(object sender, EventArgs e)
{
Options setOptions = new Options();
setOptions.ShowDialog();
getSavedSettings();
}
private void openListToolStripMenuItem_Click(object sender, EventArgs e)
{
LoadList();
}
private void restoreIndividualButton_Click(object sender, EventArgs e)
{
MessageBox.Show("Please select a registry key to import.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
if (keyPath == "")
{
openFileDialog1.InitialDirectory = Directory.GetCurrentDirectory();
}
else
{
openFileDialog1.InitialDirectory = keyPath;
}
openFileDialog1.Filter = "reg files (*.reg)|*.reg|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 1;
openFileDialog1.RestoreDirectory = true;
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
if (openFileDialog1.FileName != "")
{
if (openFileDialog1.FileName.IndexOf(".") != -1)
{
if (openFileDialog1.FileName.Substring(openFileDialog1.FileName.LastIndexOf(".")) == ".reg")
{
writeToRegistry(openFileDialog1.FileName);
if (successMessages != "")
{
Success backedUp = new Success(successMessages);
backedUp.Show();
successMessages = "";
}
}
}
}
}
}
private void manual_MouseClick(object sender, MouseEventArgs e)
{
if (manual.Text == @"Example: HKEY_CURRENT_USER\SOFTWARE")
{
manual.Text = "";
}
}
private void button1_Click(object sender, EventArgs e)
{
int formatOK = 0;
string valueT = manual.Text;
if (valueT != @"Example: HKEY_CURRENT_USER\SOFTWARE" & valueT != "")
{
if (valueT.IndexOf(@"\\") != -1)
{
valueT = valueT.Substring(2);
}
//MessageBox.Show(valueT[valueT.Length - 1].ToString());
if (valueT[valueT.Length - 1] == '\\')
{
valueT = valueT.Substring(0, valueT.LastIndexOf(@"\"));
}
string check = "";
if (valueT.IndexOf(@"\") != -1)
{
check = valueT.Substring(0, valueT.IndexOf(@"\"));
}
else
{
check = valueT;
}
Microsoft.Win32.RegistryKey key;
switch (check)
{
case "HKEY_LOCAL_MACHINE":
if (valueT.IndexOf(@"\") != -1)
{
string sCheck = valueT.Substring(valueT.IndexOf(@"\") + 1);
//MessageBox.Show(sCheck);
key = Registry.LocalMachine.OpenSubKey(sCheck, false);
if (key != null)
{
formatOK = 1;
}
else
{
MessageBox.Show("The key you entered does not exist and is not valid!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
manual.Text = "";
}
}
else
{
formatOK = 1;
}
break;
case "HKEY_CLASSES_ROOT":
if (valueT.IndexOf(@"\") != -1)
{
string sCheck = valueT.Substring(valueT.IndexOf(@"\") + 1);
key = Registry.ClassesRoot.OpenSubKey(sCheck, false);
if (key != null)
{
formatOK = 1;
}
else
{
MessageBox.Show("The key you entered does not exist and is not valid!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
manual.Text = "";
}
}
else
{
formatOK = 1;
}
break;
case "HKEY_CURRENT_USER":
if (valueT.IndexOf(@"\") != -1)
{
string sCheck = valueT.Substring(valueT.IndexOf(@"\") + 1);
key = Registry.CurrentUser.OpenSubKey(sCheck, false);
if (key != null)
{
formatOK = 1;
}
else
{
MessageBox.Show("The key you entered does not exist and is not valid!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
manual.Text = "";
}
}
else
{
formatOK = 1;
}
break;
case "HKEY_USERS":
if (valueT.IndexOf(@"\") != -1)
{
string sCheck = valueT.Substring(valueT.IndexOf(@"\") + 1);
key = Registry.Users.OpenSubKey(sCheck, false);
if (key != null)
{
formatOK = 1;
}
else
{
MessageBox.Show("The key you entered does not exist and is not valid!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
manual.Text = "";
}
}
else
{
formatOK = 1;
}
break;
case "HKEY_CURRENT_CONFIG":
if (valueT.IndexOf(@"\") != -1)
{
string sCheck = valueT.Substring(valueT.IndexOf(@"\") + 1);
key = Registry.CurrentConfig.OpenSubKey(sCheck, false);
if (key != null)
{
formatOK = 1;
}
else
{
MessageBox.Show("The key you entered does not exist and is not valid!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
manual.Text = "";
}
}
else
{
formatOK = 1;
}
break;
}
if (formatOK == 1)
{
if (!keysToBackup.Items.Contains(valueT))
{
keysToBackup.Items.Add(valueT);
}
else
{
MessageBox.Show("The registry key of " + valueT + " already exists within your list!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("Your custom registry key is invalid!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
manual.Text = "";
}
}
else
{
MessageBox.Show("Your custom registry key is invalid!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
manual.Text = "";
}
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
About showAbout = new About();
showAbout.Show();
}
private void keyOperations(List<String> items)
{
foreach (string key in items)
{
if (!key.Equals(""))
{
int proceedWithKey = 0;
if (key.IndexOf("\\") != -1)
{
// Validate key first
string mainHive = key.Substring(0, key.IndexOf("\\"));
proceedWithKey = validateKey(mainHive);
if (proceedWithKey == 1)
{
// First six characters should return part of the HKEY
// USE THIS ONE AFTER TESTING PREFIX
// USE the BELOW string to prevent keys with the same name from conflicting and to better identify where the keys come from
string[] separators = key.Split('_');
string realPath = keyPath + "\\" + key.Substring(0, 2).ToUpper() + key.Substring(key.IndexOf("_") + 1, 1) + separators[2].Substring(0, 1) + "_" + key.Substring(key.LastIndexOf('\\') + 1) + ".reg";
// MessageBox.Show(key + "\n" + keyPath + "\\" + "\n" + key.Substring(0, 2).ToUpper() + key.Substring(key.IndexOf("_") + 1, 1) + separators[2].Substring(0,1) + "\n" + key.Substring(key.LastIndexOf('\\') + 1) + ".reg", "Info");
// OLD
// string realPath = keyPath + key.Substring(key.LastIndexOf('\\')) + ".reg";
// MessageBox.Show(realPath);
backupOps(realPath, key);
}
}
else
{
// Validate key first
proceedWithKey = validateKey(key);
if (proceedWithKey == 1)
{
string realPath = keyPath + "\\" + key + ".reg";
// MessageBox.Show(realPath);
backupOps(realPath, key);
}
}
}
}
// Reset vars if used
prefix = "";
promptIfExists = 1;
}
private int validateKey(string mainHive)
{
string[] validHives = { "HKEY_CLASSES_ROOT", "HKEY_CURRENT_CONFIG", "HKEY_CURRENT_USER", "HKEY_LOCAL_MACHINE", "HKEY_USERS" };
int valid = 0;
foreach (string hiveName in validHives)
{
if (hiveName == mainHive)
{
valid = 1;
}
}
return valid;
}
private void backupOps(string realPath, string key)
{
// MessageBox.Show(realPath);
if (File.Exists(realPath))
{
if (promptIfExists == 1 && argumentsMode == 0)
{
FileExists prompt = new FileExists(realPath, key);
prompt.ShowDialog();
actionTakenString = prompt.returnAction();
if (actionTakenString != "")
{
switch (actionTakenString)
{
// Prefix single and one time renames uses the default method which is just to accept the changed name.
case "overwrite_all":
promptIfExists = 0;
actionTakenString = "";
ExportKey(key, realPath);
break;
case "overwrite_one":
actionTakenString = "";
ExportKey(key, realPath);
break;
case "prefixAll":
actionTakenString = "";
prefix = prompt.returnPrefix();
// MessageBox.Show(prefix);
promptIfExists = 0;
// MessageBox.Show(realPath);
if (prefix != "")
{
string tempFileName = realPath.Substring(0, realPath.LastIndexOf("\\") + 1);
string actualRegFName = realPath.Substring(realPath.LastIndexOf("\\") + 1);
realPath = tempFileName + prefix + actualRegFName;
// MessageBox.Show(realPath);
ExportKey(key, realPath);
}
break;
default:
realPath = actionTakenString;
actionTakenString = "";
ExportKey(key, realPath);
break;
}
}
}
else
{
if (prefix != "")
{
string tempFileName = realPath.Substring(0, realPath.LastIndexOf("\\") + 1);
string actualRegFName = realPath.Substring(realPath.LastIndexOf("\\") + 1);
realPath = tempFileName + prefix + actualRegFName;
if (File.Exists(realPath))
{
File.Delete(realPath);
}
ExportKey(key, realPath);
}
else
{
File.Delete(realPath);
ExportKey(key, realPath);
}
}
}
else
{
ExportKey(key, realPath);
}
// MessageBox.Show(realPath);
}
private void removeAllButton_Click(object sender, EventArgs e)
{
if (keysToBackup.Items.Count > 0)
{
DialogResult r = MessageBox.Show("Are you sure you want to delete all added keys from your backup list?", "Caution", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (r == DialogResult.Yes)
{
keysToBackup.Items.Clear();
}
}
}
}
}
|
041a2773425427e4505c388e56461106127db3c9
|
C#
|
missorganize/picture
|
/huaquanshengqi/Form1.cs
| 2.828125
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace huaquanshengqi
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
string number = textBox2.Text;
string imageurl = textBox1.Text;
Image img = Image.FromFile(imageurl);
Brush brush = Brushes.Coral;
int ImageWidth, ImageHeight;
pictureBox1.Image = img;
ImageWidth = img.Width;
ImageHeight = img.Height;
Graphics g = Graphics.FromImage(img);
SolidBrush brush1 = new SolidBrush(Color.Wheat);
SolidBrush brush2 = new SolidBrush(Color.Red);
//Graphics g = this.pictureBox1.CreateGraphics();
//Pen p = new Pen(Color.Red);
Font font = new Font("Arial",30);
g.FillEllipse(brush2, ImageWidth - 50, 0, 50, 50);
if (number==String.Empty)
{
g.DrawString("1",font,brush1,ImageWidth-45,3);
}
else
{
string RegStr = @"^\d$";
System.Text.RegularExpressions.Regex rg = new System.Text.RegularExpressions.Regex(RegStr);
if (rg.IsMatch(number))
{
g.DrawString(number, font, brush1, ImageWidth - 45, 3);
}
else
{
//Font font1 = new Font("Arial", 30);
textBox2.Text = "请输入一位数字";
}
}
}
catch (Exception)
{
textBox1.Text = "请输入正确的路径";
}
}
private void button2_Click(object sender, EventArgs e)
{
SaveFileDialog save=new SaveFileDialog();
save.Filter = "(*.jpg)|*.jpg";
save.FilterIndex = 2;
save.RestoreDirectory = true;
if (save.ShowDialog()==DialogResult.OK)
{
this.pictureBox1.Image.Save(save.FileName,System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
|
03e85e8d307e5f3b5a759ab7883bf44dc9431f34
|
C#
|
beckirobards/national-parks-reservations
|
/Capstone/ParkDetailsCLI.cs
| 2.796875
| 3
|
using Capstone.DAL;
using Capstone.Models;
using ProjectOrganizer;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace Capstone
{
public class ParkDetailsCLI : CLIHelper
{
private ICampgroundsDAO campgroundDAO;
private IParksDAO parkDAO;
private ISitesDAO siteDAO;
private IReservationsDAO reservationDAO;
public ParkDetailsCLI(ICampgroundsDAO campgroundsDAO, IParksDAO parkDAO, ISitesDAO siteDAO, IReservationsDAO reservationDAO)
{
this.campgroundDAO = campgroundsDAO;
this.parkDAO = parkDAO;
this.siteDAO = siteDAO;
this.reservationDAO = reservationDAO;
}
//public ICampgroundsDAO IcampgroundsDAO { get; }
public void ParkDetailsMenu(int parkId)
{
IList<Campground> campgrounds = campgroundDAO.GetCampgrounds(parkId);
while (true)
{
Console.WriteLine();
Console.WriteLine("1) View Campgrounds");
Console.WriteLine("2) Search for Availability");
Console.WriteLine("3) Return to Previous Screen");
int userSelection = int.Parse(Console.ReadLine());
if(userSelection == 1)
{
Console.WriteLine("".PadRight(5) + "Name".PadRight(30) + "Open".PadRight(20) + "Close".PadRight(20) + "Daily Fee".PadRight(10));
foreach (Campground campground in campgrounds)
{
string openFromMonth = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(campground.OpenFrom);
string openToMonth = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(campground.OpenTo);
string finalCost = String.Format("{0:C}", campground.DailyFee);
Console.WriteLine(campground.CampgroundId.ToString().PadRight(5) + campground.Name.ToString().PadRight(30) + openFromMonth.ToString().PadRight(20) + openToMonth.ToString().PadRight(20) + finalCost);
}
}
if (userSelection == 2)
{
try
{
//TODO if user enters a date with no campsites available, return to asking them to enter a new date
Console.WriteLine("Please enter your preferred campground's number: ");
int selectedCampground = int.Parse(Console.ReadLine());
Console.WriteLine("What is your arrival date? (Enter as YYYY-MM-DD) ");
DateTime selectedFromDate = DateTime.Parse(Console.ReadLine());
Console.WriteLine("What is your departure date? (Enter as YYYY-MM-DD) ");
DateTime selectedToDate = DateTime.Parse(Console.ReadLine());
TimeSpan ts = selectedToDate - selectedFromDate;
decimal totalCost = ts.Days * campgrounds[selectedCampground - 1].DailyFee;
string convertedCost = String.Format("{0:C}", totalCost);
IList<Site> sites = siteDAO.GetAvailableSites(selectedCampground, selectedFromDate, selectedToDate);
if(sites.Count == 0)
{
Console.WriteLine("There are no available sites, please enter another date range");
}
Console.WriteLine("Site ID".PadRight(10) + "Max Occup.".PadRight(15) + "Accessible?".PadRight(15) + "Max RV Length".PadRight(15) + "Utility".PadRight(10) + "Cost".PadRight(10));
foreach (Site site in sites)
{
Console.WriteLine(site.SiteId.ToString().PadRight(10) + site.MaxOccupancy.ToString().PadRight(15) + site.IsAccessible.ToString().PadRight(15) + site.MaxRvLength.ToString().PadRight(15) + site.HasUtilities.ToString().PadRight(10) + convertedCost.PadRight(10));
}
Console.WriteLine();
Console.WriteLine("1) Make a Reservation");
Console.WriteLine("2) Return to Previous Screen");
int reservationSelection = int.Parse(Console.ReadLine());
if (reservationSelection == 1)
{
Console.WriteLine("Which site should be reserved (enter 0 to cancel)");
int siteSelection = int.Parse(Console.ReadLine());
Console.WriteLine("What name should the reservation be made under?");
string reservationName = Console.ReadLine();
Reservation newReservation = new Reservation()
{
SiteId = siteSelection,
Name = reservationName,
FromDate = selectedFromDate,
ToDate = selectedToDate,
//CreateDate = DateTime.Now
};
int reservationNumber = reservationDAO.CreateNewReservation(newReservation);
Console.WriteLine($"The reservation has been made and the confirmation id is {reservationNumber}");
}
if (reservationSelection == 2)
{
break;
}
}
catch (FormatException ex)
{
Console.WriteLine("Invalid input. Please try again.");
Console.WriteLine(ex.Message);
}
}
if (userSelection == 3)
{
break;
}
}
}
}
}
|
c10e8dafdb3963e0d4697b05e83e78e95dbc3096
|
C#
|
nielsdejong/unity-city-generation
|
/Assets/Editor/RoadMapGenerator/GrowthRules/GrowthRule.cs
| 3.078125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public abstract class GrowthRule {
/// <summary>
/// Initializes a new Growth Rule with a seed for the random number generator.
/// </summary>
/// <param name="seed">The seed</param>
public GrowthRule(int seed)
{
//Random.InitState(seed);
}
/// <summary>
/// Use the growth rule to generate branch(es) from a highway to a new highway.
/// This can be either:
/// - A straight highway "branch" (e.g. the highway continuing forward, which always happens)
/// - A left highway branch (the highway taking a left turn with some degree of angle modificiation)
/// - A right highway branch (the highway taking a right turn with some degree of angle modificiation)
/// </summary>
/// <param name="branches"></param>
/// <param name="startNode"></param>
/// <param name="oldDirection"></param>
public abstract void branchHighwayToHighway(ref List<Edge> branches, Edge oldEdge);
/// <summary>
/// Use the growth rule to generate branch(es) from a street to a new street.
/// This can be only:
/// - A forward street "branch" (e.g. the street continuing forward)
/// </summary>
/// <param name="branches"></param>
/// <param name="startNode"></param>
/// <param name="oldDirection"></param>
public abstract void branchStreetToStreet(ref List<Edge> branches, Edge oldEdge);
/// <summary>
/// Use the growth rule to generate branch(es) from a (highway or street) to a new street.
/// This can be either:
/// - A left street branch (the street taking a left turn with some degree of angle modificiation)
/// - A right street branch (the street taking a right turn with some degree of angle modificiation)
/// </summary>
/// <param name="branches"></param>
/// <param name="startNode"></param>
/// <param name="oldDirection"></param>
public abstract void branchRoadToStreet(ref List<Edge> branches, Edge oldEdge);
/// <summary>
/// Branches a new Vector2 starting at Vector2 point. The new branch is based on an old direction, which is then changed by a random value
/// in between minAngle and maxAngle. The length is the length of the new edge that is created.
/// </summary>
/// <param name="point"></param>
/// <param name="directionVector"></param>
/// <param name="minAngle"></param>
/// <param name="maxAngle"></param>
/// <param name="length"></param>
/// <returns></returns>
protected virtual Vector2 branchVectorFromPoint(Vector2 point, Vector2 directionVector, float minAngle, float maxAngle, RoadTypes roadType)
{
float diff = maxAngle - minAngle;
float randomAngle = Random.value * diff;
Vector2 newDirectionVector = Vector2.zero + directionVector;
newDirectionVector.Normalize();
newDirectionVector *= (roadType == RoadTypes.HIGHWAY) ?
CityGenerator.highwayMinLength * CityGenerator.highwayLookAhead:
CityGenerator.streetMinLength * CityGenerator.streetLookAhead;
Vector2 vector = point + (Vector2)(Quaternion.Euler(0, 0, minAngle + randomAngle) * newDirectionVector);
return vector;
}
/// <summary>
/// Casts a number of random rays within a given range, using the branchVectorFromPoint method.
/// </summary>
/// <param name="point"></param>
/// <param name="oldDirection"></param>
/// <param name="minAngle"></param>
/// <param name="maxAngle"></param>
/// <param name="length"></param>
/// <param name="rayCount"></param>
/// <returns></returns>
public List<Vector2> castVectorsFromPoint(Vector2 point, Vector2 oldDirection, float minAngle, float maxAngle, RoadTypes roadType, int rayCount)
{
float totalRange = maxAngle - minAngle;
// If the total angle range is X, the angle range for every ray is (X/rayCount)
float rayRange = totalRange / (float)rayCount;
// Create a number of rays
List<Vector2> rays = new List<Vector2>();
for(int ray = 0; ray < rayCount; ray++)
{
float minAngleForRay = minAngle + rayRange * ray;
float maxAngleForRay = minAngle + rayRange * (ray + 1);
rays.Add(this.branchVectorFromPoint(point, oldDirection, minAngleForRay, maxAngleForRay, roadType));
}
return rays;
}
/// <summary>
/// Gets the ray that results in the highest population and return it together with the population value.
/// </summary>
/// <param name="rayEndPoints">List of Vector2 points representing the ends of rays.</param>
/// <returns></returns>
public virtual KeyValuePair<Vector2, float> getBestRay(Vector2 point, List<Vector2> rayEndPoints, RoadTypes roadType)
{
float maxPopulation = float.NegativeInfinity;
Vector2 bestDirection = Vector2.zero;
// Loop through all rays and find the one that results in the highest population density.
for (int i = 0; i < rayEndPoints.Count; i++)
{
float rayLength = (roadType == RoadTypes.HIGHWAY) ?
CityGenerator.highwayMinLength * CityGenerator.highwayLookAhead :
CityGenerator.streetMinLength * CityGenerator.streetLookAhead;
int raySamples = (int)Mathf.Sqrt(rayLength);
float rayStepSize = (float)rayLength / (float)raySamples;
// take samples along the ray.
Vector2 rayDirection = getRayDirection(point, rayEndPoints[i]);
float rayPopulation = 0f;
Vector2 directionPoint = Vector2.zero;
bool isDirectionSet = false;
for (int sample = 1; sample <= raySamples; sample++)
{
//save the first point over the ray that is at a suitable distance for a road/highway
Vector2 sampleEndPoint = point + rayDirection * sample * rayStepSize;
if ((roadType == RoadTypes.HIGHWAY && sample * rayStepSize >= CityGenerator.highwayMinLength ||
roadType != RoadTypes.HIGHWAY && sample * rayStepSize >= CityGenerator.streetMinLength) && !isDirectionSet)
{
directionPoint = sampleEndPoint;
isDirectionSet = true;
}
if (!CoordinateHelper.validEndPoint (sampleEndPoint)) {
raySamples = sample -1;
break;
}
float popValue = CoordinateHelper.worldToPop(sampleEndPoint.x, sampleEndPoint.y);
/*popValue = (roadType == RoadTypes.HIGHWAY) ?
((float)sample / (float)raySamples) * popValue : // more weight to further points
(1 - (float)(sample-1) / (float)raySamples) * popValue; // more weight to closer points*/
rayPopulation = (popValue > rayPopulation) ? popValue : rayPopulation;
}
if (rayPopulation > maxPopulation && isDirectionSet)
{
maxPopulation = rayPopulation;
bestDirection = directionPoint;
}
}
return new KeyValuePair<Vector2, float>(bestDirection, maxPopulation);
}
public Vector2 getRayDirection(Vector2 point, Vector2 rayFragment)
{
return (new Vector2(rayFragment.x, rayFragment.y) - new Vector2(point.x, point.y)).normalized;
}
}
|
04c530ee88052fcb55877e525d7d7e18e11e6b75
|
C#
|
jagocki/DevOpsMetrics
|
/src/DevOpsMetrics.Core/LeadTimeForChanges.cs
| 3.234375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace DevOpsMetrics.Core
{
/// <summary>
/// Lead time for changes: Time from committing a change to deployment to production
/// </summary>
public class LeadTimeForChanges
{
private readonly List<KeyValuePair<DateTime, TimeSpan>> LeadTimeForChangesList;
public LeadTimeForChanges()
{
LeadTimeForChangesList = new List<KeyValuePair<DateTime, TimeSpan>>();
}
public float ProcessLeadTimeForChanges(List<KeyValuePair<DateTime, TimeSpan>> leadTimeForChangesList, int numberOfDays)
{
if (leadTimeForChangesList != null)
{
foreach (KeyValuePair<DateTime, TimeSpan> item in leadTimeForChangesList)
{
AddLeadTimeForChanges(item.Key, item.Value);
}
}
return CalculateLeadTimeForChanges(numberOfDays);
}
private bool AddLeadTimeForChanges(DateTime eventDateTime, TimeSpan leadTimeDuration)
{
LeadTimeForChangesList.Add(new KeyValuePair<DateTime, TimeSpan>(eventDateTime, leadTimeDuration));
return true;
}
private float CalculateLeadTimeForChanges(int numberOfDays)
{
List<KeyValuePair<DateTime, TimeSpan>> items = GetLeadTimeForChanges(numberOfDays);
//Add up the total hours
double totalHours = 0;
foreach (KeyValuePair<DateTime, TimeSpan> item in items)
{
totalHours += item.Value.TotalHours;
}
//Calculate the lead time for changes per day
float leadTimeForChanges = 0;
if (items.Count > 0)
{
leadTimeForChanges = (float)totalHours / (float)items.Count;
}
leadTimeForChanges = (float)Math.Round((double)leadTimeForChanges, 4);
return leadTimeForChanges;
}
//Filter the list by date
private List<KeyValuePair<DateTime, TimeSpan>> GetLeadTimeForChanges(int numberOfDays)
{
return LeadTimeForChangesList.Where(x => x.Key > DateTime.Now.AddDays(-numberOfDays)).ToList();
}
public string GetLeadTimeForChangesRating(float leadTimeForChangesInHours)
{
float dailyDeployment = 24f;
float weeklyDeployment = 24f * 7f;
float monthlyDeployment = 24f * 30f;
string rating = "";
if (leadTimeForChangesInHours <= 0f) //no rating
{
rating = "None";
}
else if (leadTimeForChangesInHours < dailyDeployment) //less than one day
{
rating = "Elite";
}
else if (leadTimeForChangesInHours >= dailyDeployment && leadTimeForChangesInHours <= weeklyDeployment) //between one day and one week
{
rating = "High";
}
else if (leadTimeForChangesInHours > weeklyDeployment && leadTimeForChangesInHours <= monthlyDeployment) //between one week and one month
{
rating = "Medium";
}
else if (leadTimeForChangesInHours > monthlyDeployment) //more than one month
{
rating = "Low";
}
return rating;
}
}
}
|
f4f04be016bccf5f3c9634ab4b4d1c2da2676eb9
|
C#
|
jorik041/Whoosh
|
/Assets/Scripts/ProceduralToolkit/PGUtils.cs
| 2.84375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using ProceduralToolkit.Generic;
using UnityEngine;
namespace ProceduralToolkit
{
public enum Orientation
{
CounterClockwise = -1,
NonOrientable = 0,
Clockwise = 1,
}
public class PGUtils
{
/// <summary>
/// Triangulate simple polygon without holes.
/// </summary>
/// <param name="vertices">Vertices in clockwise winding order.</param>
//public static int[] Triangulate(Vector2[] vertices)
//{
// var polygon = new LinkedList<IndexedVector<Vector2>>();
// var ears = new LinkedList<IndexedVector<Vector2>>();
// var convexVertices = new List<IndexedVector<Vector2>>();
// var reflexVertices = new List<IndexedVector<Vector2>>();
// var triangles = new List<int>();
// for (var i = 0; i < vertices.Length; i++)
// {
// polygon.AddLast(new IndexedVector<Vector2>(vertices[i], i));
// }
// var currentNode = polygon.First;
// for (var i = 0; i < polygon.Count; i++)
// {
// if (IsConvex(currentNode))
// {
// convexVertices.Add(currentNode.Value);
// }
// else
// {
// reflexVertices.Add(currentNode.Value);
// }
// currentNode = currentNode.NextOrFirst();
// }
// for (var i = 0; i < convexVertices.Count; i++)
// {
// var vertex = polygon.Find(convexVertices[i]);
// if (IsEar(reflexVertices, vertex))
// {
// ears.AddLast(convexVertices[i]);
// }
// }
// var count = 1f;
// while (polygon.Count > 3 && ears.Count > 0)
// {
// foreach (var convexVertex in convexVertices)
// {
// Debug.DrawLine(convexVertex.vector, Vector3.zero, Color.green, 100);
// }
// foreach (var reflexVertex in reflexVertices)
// {
// Debug.DrawLine(reflexVertex.vector, Vector3.zero, Color.red, 100);
// }
// foreach (var vector in ears)
// {
// Debug.DrawLine(vector.vector, Vector3.zero, Color.yellow, 100);
// }
// var earNode = ears.First;
// var previousNode = polygon.Find(earNode.Value).PreviousOrLast();
// var nextNode = polygon.Find(earNode.Value).NextOrFirst();
// var ear = earNode.Value;
// var previous = previousNode.Value;
// var next = nextNode.Value;
// //Debug.DrawLine(previous.vector, ear.vector, new Color(1, count, count), 100);
// //Debug.DrawLine(ear.vector, next.vector, new Color(1, count, count), 100);
// count -= 0.1f;
// triangles.Add(previous.index);
// triangles.Add(ear.index);
// triangles.Add(next.index);
// ears.RemoveFirst();
// foreach (var indexedVector in polygon)
// {
// if (indexedVector.index == ear.index)
// {
// polygon.Remove(indexedVector);
// break;
// }
// }
// if (reflexVertices.Contains(previous))
// {
// if (IsConvex(previousNode))
// {
// reflexVertices.Remove(previous);
// convexVertices.Add(previous);
// }
// }
// if (convexVertices.Contains(previous))
// {
// var inEars = ears.Contains(previous);
// var isEar = IsEar(reflexVertices, previousNode);
// if (inEars && !isEar) ears.Remove(previous);
// else if (!inEars && isEar) ears.AddFirst(previous);
// }
// if (reflexVertices.Contains(next))
// {
// if (IsConvex(previousNode))
// {
// reflexVertices.Remove(next);
// convexVertices.Add(next);
// }
// }
// if (convexVertices.Contains(next))
// {
// var inEars = ears.Contains(next);
// var isEar = IsEar(reflexVertices, nextNode);
// if (inEars && !isEar) ears.Remove(next);
// else if (!inEars && isEar) ears.AddFirst(next);
// }
// //Debug.Log("Reflex: " + reflexVertices.Count);
// //Debug.Log("Convex: " + convexVertices.Count);
// //Debug.Log("Ear: " + ears.Count);
// }
// if (polygon.Count == 3)
// {
// triangles.Add(polygon.First.Value.index);
// triangles.Add(polygon.First.Next.Value.index);
// triangles.Add(polygon.First.Next.Next.Value.index);
// }
// return triangles.ToArray();
//}
/// <summary>
/// Triangulate simple polygon without holes.
/// </summary>
/// <param name="polygonVertices">Polygon vertices in clockwise winding order.</param>
public static int[] Triangulate(Vector2[] polygonVertices)
{
var triangles = new List<int>();
var vertices =
new CircularList<Indexed<Vector2>>(
polygonVertices.Select((t, i) => new Indexed<Vector2>(t, i)));
while (vertices.Count > 0)
{
for (var i = 0; i < vertices.Count; i++)
{
var previous = vertices[i - 1];
var middle = vertices[i];
var next = vertices[i + 1];
var isEar = true;
for (var j = 0; j < vertices.Count; j++)
{
if (IsInTriangle(previous.value, middle.value, next.value, vertices[j].value))
{
isEar = false;
break;
}
}
if (isEar)
{
triangles.Add(previous.index);
triangles.Add(middle.index);
triangles.Add(next.index);
vertices.Remove(middle);
}
}
}
return triangles.ToArray();
}
public static int[] Triangulate(List<Vector2> vertices)
{
return Triangulate(vertices.ToArray());
}
private static bool IsConvex(Vector2 previousVertex, Vector2 middleVertex, Vector2 nextVertex)
{
return Vector3.Cross(previousVertex - middleVertex, nextVertex - middleVertex).z > 0;
}
private static bool IsConvex(LinkedListNode<Indexed<Vector2>> node)
{
return IsConvex(node.PreviousOrLast().Value.value, node.Value.value, node.NextOrFirst().Value.value);
}
private static bool IsEar(List<Indexed<Vector2>> reflexVertices,
Indexed<Vector2> previousVertex,
Indexed<Vector2> middleVertex,
Indexed<Vector2> nextVertex)
{
foreach (var reflexVertex in reflexVertices)
{
if (reflexVertex == previousVertex || reflexVertex == middleVertex || reflexVertex == nextVertex)
{
continue;
}
if (IsInTriangle(previousVertex.value, middleVertex.value, nextVertex.value, reflexVertex.value))
{
return false;
}
}
return true;
}
private static bool IsEar(List<Indexed<Vector2>> reflexVertices,
LinkedListNode<Indexed<Vector2>> node)
{
return IsEar(reflexVertices, node.PreviousOrLast().Value, node.Value, node.NextOrFirst().Value);
}
public static bool IsInTriangle(Vector2 a, Vector2 b, Vector2 c, Vector2 point)
{
if (a == point || b == point || c == point)
{
return true;
}
var ab = PerpDot(b - a, point - a);
var bc = PerpDot(c - b, point - b);
var ca = PerpDot(a - c, point - c);
return (ab <= 0 && bc <= 0 && ca <= 0) || (-ab <= 0 && -bc <= 0 && -ca <= 0);
}
/// <summary>
/// Returns perp of vector
/// </summary>
/// <remarks>
/// Hill, F. S. Jr. "The Pleasures of 'Perp Dot' Products."
/// Ch. II.5 in Graphics Gems IV (Ed. P. S. Heckbert). San Diego: Academic Press, pp. 138-148, 1994
/// </remarks>
public static Vertex2 Perp(Vertex2 vector)
{
return new Vertex2(-vector.y, vector.x);
}
public static IntVertex2 Perp(IntVertex2 vector)
{
return new IntVertex2(-vector.y, vector.x);
}
/// <summary>
/// Returns perp dot product of vectors
/// </summary>
/// <remarks>
/// Hill, F. S. Jr. "The Pleasures of 'Perp Dot' Products."
/// Ch. II.5 in Graphics Gems IV (Ed. P. S. Heckbert). San Diego: Academic Press, pp. 138-148, 1994
/// </remarks>
public static float PerpDot(Vector2 a, Vector2 b)
{
return a.x*b.y - a.y*b.x;
}
public static float PerpDot(Vertex2 a, Vertex2 b)
{
return a.x * b.y - a.y * b.x;
}
public static int PerpDot(IntVertex2 a, IntVertex2 b)
{
return a.x * b.y - a.y * b.x;
}
public static bool Approximately(Vector2 a, Vector2 b, float epsilon)
{
return Mathf.Abs(a.x - b.x) < epsilon && Mathf.Abs(a.y - b.y) < epsilon;
}
public static void Swap<T>(ref T left, ref T right)
{
T temp = left;
left = right;
right = temp;
}
/// <summary>
/// More than 0 - left, less than 0 - right, equals 0 - on line
/// </summary>
public static int LocatePointOnLine(IntVertex2 line1, IntVertex2 line2, IntVertex2 point)
{
return (line2.x - line1.x)*(point.y - line1.y) - (point.x - line1.x)*(line2.y - line1.y);
}
/// <summary>
/// More than 0 - left, less than 0 - right, equals 0 - on line
/// </summary>
public static float LocatePointOnLine(Vertex2 line1, Vertex2 line2, Vertex2 point)
{
return (line2.x - line1.x)*(point.y - line1.y) - (point.x - line1.x)*(line2.y - line1.y);
}
/// <summary>
/// Ramer-Douglas-Peucker algorithm
/// </summary>
public static void RamerDouglasPeucker()
{
}
//public List<Vector2> properRDP(List<Vector2> points,float epsilon){
// Vector2 firstPoint=points[0];
// Vector2 lastPoint=points[points.Count-1];
// if (points.Count<3){
// return points;
// }
// int index=-1;
// float dist=0;
// for (var i=1;i<points.Count-1;i++){
// var cDist=findPerpendicularDistance(points[i],firstPoint,lastPoint);
// if (cDist>dist){
// dist=cDist;
// index=i;
// }
// }
// if (dist>epsilon){
// // iterate
// var l1=points.GetRange(0, index+1);
// var l2=points.GetRange(index, 1);
// var r1=properRDP(l1,epsilon);
// var r2=properRDP(l2,epsilon);
// // concat r2 to r1 minus the end/startpoint that will be the same
// var rs=r1.GetRange(0,r1.Count-1).Add(r2);
// return rs;
// }else{
// return [firstPoint,lastPoint];
// }
//}
//public float findPerpendicularDistance(Vector2 p, Vector2 p1, Vector2 p2)
//{
// // if start and end point are on the same x the distance is the difference in X.
// float result;
// if (p1[0] == p2[0])
// {
// result = Math.Abs(p[0] - p1[0]);
// }
// else
// {
// float slope = (p2[1] - p1[1])/(p2[0] - p1[0]);
// float intercept = p1[1] - (slope*p1[0]);
// result = Mathf.Abs(slope*p[0] - p[1] + intercept)/Mathf.Sqrt(Mathf.Pow(slope, 2) + 1);
// }
// return result;
//}
}
internal static class CircularLinkedList
{
public static LinkedListNode<T> NextOrFirst<T>(this LinkedListNode<T> current)
{
return current.Next ?? current.List.First;
}
public static LinkedListNode<T> PreviousOrLast<T>(this LinkedListNode<T> current)
{
return current.Previous ?? current.List.Last;
}
}
}
|
900168a74f89981d2a8f2ab846f1e359edfe1529
|
C#
|
Sonkerud/AcademyExercises
|
/PropertiesViktor/Program.cs
| 3.65625
| 4
|
using System;
using System.Collections.Generic;
namespace PropertiesViktor
{
class Program
{
static void Main(string[] args)
{
Car car = new Car();
Console.WriteLine(car.GetLicenceNumber());
car.SetLicenceNumber("abc999");
Console.WriteLine(car.GetLicenceNumber());
car.SetColor("blue");
Console.WriteLine(car.GetColor());
Console.WriteLine("\n------------TIME TO ADD SOME CARS---------------");
List<Car> Cars = new List<Car>();
bool addMoreCars = true;
while (addMoreCars)
{
Console.WriteLine("Lägga till en bil? y / n");
var ans = Console.ReadLine();
switch (ans)
{
case "y":
Console.WriteLine("Licence number?");
string licenceNumber = Console.ReadLine();
Console.WriteLine("Color?");
string color = Console.ReadLine();
Car newCar = new Car();
newCar.SetLicenceNumber(licenceNumber);
newCar.SetColor(color);
Cars.Add(newCar);
break;
case "n":
addMoreCars = false;
break;
default:
break;
}
}
foreach (var c in Cars)
{
Console.WriteLine($"{c.GetLicenceNumber()} : {c.GetColor()}");
}
}
}
}
|
b2c2ec69353896f22f77aa9cc3d69e2b3ac45a0d
|
C#
|
Martin-Andersen/CodeToKeep
|
/CodeToKeepSolution/SomethingBlue/TheSuperObject/SuperObject.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace SomethingBlue.TheSuperObject
{
[Serializable]
public class SuperObject : DynamicObject, IDataErrorInfo
{
private List<PropertyFilterManager> PropertyFilters { get; set; }
private List<MultiSelectStrategy> MultiSelectStrategies { get; set; }
private List<object> Objects { get; set; }
private List<PropertyInfo> CommonProperties { get; set; }
private Dictionary<string, string> Errors { get; set; }
public SuperObject(IEnumerable<Object> objects) : this(objects, null, null)
{
}
public SuperObject(IEnumerable<Object> objects, List<PropertyFilterManager> propertyFilters, List<MultiSelectStrategy> multiSelectStrategies)
{
PropertyFilters = propertyFilters ?? new List<PropertyFilterManager>();
MultiSelectStrategies = multiSelectStrategies ?? new List<MultiSelectStrategy>();
Errors = new Dictionary<string, string>();
Objects = new List<object>();
Objects.AddRange(objects);
SetupObjects();
}
private void SetupObjects()
{
DynamicMembers = new Dictionary<string, object>();
if (Objects.Count == 0) return;
CommonProperties = ReflectionHelpers.GetCommonProperties(Objects);
if (PropertyFilters.Count > 0)
CommonProperties = ReflectionHelpers.FilterCommonProperties(CommonProperties, PropertyFilters);
bool useMultiSelectStrategy = MultiSelectStrategies.Count > 0 && Objects.Count() > 1;
MultiSelectStrategy multiSelectStrategy = null;
foreach (var info in CommonProperties.Where(info => info.CanRead))
{
object valueToSet = null;
if (useMultiSelectStrategy)
multiSelectStrategy = MultiSelectStrategies.FirstOrDefault(x => x.PropertyName == info.Name);
if (multiSelectStrategy != null)
{
var strategy = multiSelectStrategy.Strategy;
if (strategy == StrategyType.Hide)
continue;
if (strategy == StrategyType.Show || strategy == StrategyType.ShowAndValidate)
valueToSet = multiSelectStrategy.DefaultValue;
}
valueToSet = ReflectionHelpers.GetDefaultValue(info, Objects, valueToSet);
DynamicMembers[info.Name] = valueToSet;
UpdateErrorInfoFromOrginalObject(info);
}
}
private void UpdateErrorInfoFromOrginalObject(PropertyInfo prop)
{
string error = null;
foreach (var o in Objects)
{
var info = o as IDataErrorInfo;
if (info != null)
{
error = info[prop.Name];
if (string.IsNullOrEmpty(error) == false)
{
// add error to local error collection
Errors[prop.Name] = error;
}
}
}
// remove previous error from error collection
if (string.IsNullOrEmpty(error))
Errors.Remove(prop.Name);
}
private void ValidateRuleForProperty(PropertyInfo prop, object value)
{
string error = null;
foreach (var o in Objects)
{
var orgValue = prop.GetValue(o, null);
// check if input value is of the right type
prop.SetValue(o, value, null);
// now check for errors
var info = o as IDataErrorInfo;
if (info != null)
{
error = info[prop.Name];
if (string.IsNullOrEmpty(error) == false)
{
// add error to local error collection
Errors[prop.Name] = error;
// reset value on object
//prop.SetValue(o, orgValue, null);
//var field = o as PropertyDefinition;
//if (field != null)
// field.IsChanged = false;
break;
}
}
}
// remove previous error from error collection
if (string.IsNullOrEmpty(error))
Errors.Remove(prop.Name);
}
#region DynamicObject overrides
[Browsable(false)]
public IDictionary<string, object> DynamicMembers { get; private set; }
[Browsable(false)]
public int Count
{
get { return DynamicMembers.Keys.Count; }
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (DynamicMembers.ContainsKey(binder.Name))
{
result = DynamicMembers[binder.Name];
return true;
}
return base.TryGetMember(binder, out result); //means result = null and return = false
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
if (DynamicMembers.ContainsKey(binder.Name))
{
var prop = CommonProperties.First(x => x.Name == binder.Name);
try
{
//Convert.ChangeType does not handle conversion to nullable types
//if the property type is nullable, we need to get the underlying type of the property
if (value != null)
{
Type targetType = IsNullableType(prop.PropertyType)
? Nullable.GetUnderlyingType(prop.PropertyType)
: prop.PropertyType;
value = Convert.ChangeType(value, targetType);
}
}
catch (Exception)
{
Debug.WriteLine("Falied to set value: " + value);
return false;
}
DynamicMembers[binder.Name] = value;
ValidateRuleForProperty(prop, value);
}
else
DynamicMembers.Add(binder.Name, value);
return true;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
if (DynamicMembers.ContainsKey(binder.Name) && DynamicMembers[binder.Name] is Delegate)
{
result = (DynamicMembers[binder.Name] as Delegate).DynamicInvoke(args);
return true;
}
return base.TryInvokeMember(binder, args, out result);
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return DynamicMembers.Keys;
}
#endregion DynamicObject overrides
#region IDataErrorInfo
[Browsable(false)]
public string this[string columnName]
{
get { return Errors.ContainsKey(columnName) ? Errors[columnName] : null; }
}
[Browsable(false)]
public string Error
{
get
{
var sb = new StringBuilder();
foreach (var error in Errors.Values)
sb.AppendLine(error);
return sb.ToString();
}
}
#endregion IDataErrorInfo
#region helpers
private static bool IsNullableType(Type type)
{
return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
}
#endregion helpers
}
}
|
08c46ed3a6caf4c5b10bac3b8e2525d5f2f22367
|
C#
|
tomneko0825/mapgenerator
|
/Assets/Scripts/BattleMap/Map/MapRandom/MapRandomLandRatio/RandomMapLandRatio.cs
| 3.015625
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// ランダムマップの陸地の割合の計算
/// </summary>
public class RandomMapLandRatio
{
private ILandRatioPattern landRatioPattern;
public RandomMapLandRatio(ILandRatioPattern landRatioPattern)
{
this.landRatioPattern = landRatioPattern;
}
/// <summary>
/// 割合のキューを取得
/// </summary>
/// <param name="sizeX"></param>
/// <param name="sizeX"></param>
/// <returns></returns>
public Queue<int> GetLandRatio(int sizeX, int sizeY)
{
List<Dictionary<MapTileType, int>> landRatioList = landRatioPattern.GetLandRatioList();
List<int> retList = new List<int>();
// 一つずつのサイズを計算
Queue<int> sizeQueue = DivideSize(sizeX, sizeY, landRatioList.Count);
foreach (Dictionary<MapTileType, int> landRatio in landRatioList)
{
int size = sizeQueue.Dequeue();
List<int> list = GetLandRatio(size, landRatio);
retList.AddRange(list);
}
return new Queue<int>(retList);
}
/// <summary>
/// サイズを分割
/// </summary>
/// <param name="sizeX"></param>
/// <param name="sizeY"></param>
/// <param name="divide"></param>
/// <returns></returns>
private Queue<int> DivideSize(int sizeX, int sizeY, int divide)
{
// まずは高さを分割
List<int> list = DivideSizeY(sizeY, divide);
// すべての横を削る
List<int> tmpList = new List<int>();
foreach (int y in list)
{
int size = y * sizeX - y * 2;
tmpList.Add(size);
}
// 最初と最後はx分を削る
tmpList[0] = tmpList[0] - (sizeX - 2);
tmpList[tmpList.Count - 1] = tmpList[tmpList.Count - 1] - (sizeX - 2);
return new Queue<int>(tmpList);
}
/// <summary>
/// 高さを分割
/// </summary>
/// <param name="sizeY"></param>
/// <returns></returns>
private List<int> DivideSizeY(int sizeY, int divide)
{
List<int> list = new List<int>();
int tmp = sizeY / divide;
for (int i = 0; i < divide - 1; i++)
{
list.Add(tmp);
}
// 最後は残り
int sum = list.Count * tmp;
list.Add(sizeY - sum);
return list;
}
/// <summary>
/// 割合のリストを取得
/// </summary>
/// <param name="size"></param>
/// <param name="landRatio"></param>
/// <returns></returns>
private List<int> GetLandRatio(int size, Dictionary<MapTileType, int> landRatio)
{
int ratioSum = CalculateRatioSum(landRatio);
float mag = (float)size / (float)ratioSum;
// ソートする
var ratio = landRatio.OrderBy((x) => x.Value);
// サイズ計算された陸地タイプのリストを作成
List<int> randList = new List<int>();
// 最も多いタイプ
MapTileType lastType = default(MapTileType);
foreach (KeyValuePair<MapTileType, int> kvp in ratio)
{
int count = (int)Math.Round(kvp.Value * mag);
for (int i = 0; i < count; i++)
{
randList.Add((int)kvp.Key);
}
lastType = kvp.Key;
}
// 最も多いタイプで後ろを埋める
int diff = size - randList.Count();
for (int i = 0; i < diff; i++)
{
randList.Add((int)lastType);
}
// シャッフルする
List<int> shuffleList = randList.OrderBy(i => Guid.NewGuid()).ToList();
return shuffleList;
}
/// <summary>
/// randRatioの合計を計算
/// </summary>
/// <returns></returns>
private int CalculateRatioSum(Dictionary<MapTileType, int> landRatio)
{
int sum = 0;
foreach (KeyValuePair<MapTileType, int> kvp in landRatio)
{
sum += kvp.Value;
}
return sum;
}
///// <summary>
///// サイズを計算
///// </summary>
///// <param name="sizeX"></param>
///// <param name="sizeY"></param>
///// <returns></returns>
//private int CalculateSize(int sizeX, int sizeY)
//{
// return (sizeX - 2) * (sizeY - 2);
//}
}
|