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
|
|---|---|---|---|---|---|---|
7f0bb798f16359cdb6e64d23f02a57ce7c08f507
|
C#
|
210628-UTA-NET/iram-olivares-P0
|
/SADL/CustomerRepo.cs
| 2.9375
| 3
|
using System;
using System.Collections.Generic;
using Entity = SADL.Entities;
using System.Linq;
using SAModels;
namespace SADL
{
public class CustomerRepo : ICustomerRepo
{
private Entity.ieoDemoDBContext _context;
public CustomerRepo(Entity.ieoDemoDBContext p_context)
{
_context = p_context;
}
public Customer AddCustomer(Customer p_customer)
{
var newCustomer = new Entity.Customer{
CustomerId = p_customer.Id,
CustomerName = p_customer.Name,
CustomerAddress = p_customer.Address,
CustomerEmail = p_customer.Email,
CustomerPhone = p_customer.Phone
};
_context.Customers.Add(newCustomer);
_context.SaveChanges();
return p_customer;
}
public List<Customer> GetAllCustomers()
{
return _context.Customers.Select(
customer =>
new Customer()
{
Id = customer.CustomerId,
Name = customer.CustomerName,
Address = customer.CustomerAddress,
Email = customer.CustomerEmail,
Phone = customer.CustomerPhone
}
).ToList();
}
public Customer GetOneCustomer(string p_customerEmail)
{
return _context.Customers.Select(
customer => new Customer()
{
Id = customer.CustomerId,
Name = customer.CustomerName,
Address = customer.CustomerAddress,
Email = customer.CustomerEmail,
Phone = customer.CustomerPhone
}
).Where(check => check.Email == p_customerEmail).SingleOrDefault();
}
}
}
|
32f74990089543b70e29fd2349599126c9f76850
|
C#
|
MichaelKhaykin/SolvedLeetCodeProblems
|
/135.candy.474833496.ac.cs
| 3.515625
| 4
|
public class Solution {
public int Candy(int[] ratings) {
int[] candies = new int[ratings.Length];
Array.Fill(candies, 1);
bool anyChanges;
do
{
anyChanges = false;
for(int i = 0; i < candies.Length; i++)
{
if (i != ratings.Length - 1 && ratings[i] > ratings[i + 1] && candies[i] <= candies[i + 1]) {
candies[i] = candies[i + 1] + 1;
anyChanges = true;
}
if (i > 0 && ratings[i] > ratings[i - 1] && candies[i] <= candies[i - 1]) {
candies[i] = candies[i - 1] + 1;
anyChanges = true;
}
}
}while(anyChanges);
return candies.Sum();
}
}
|
7413354d0855a4607ed2672fb86d80bd6b108b0a
|
C#
|
halitak/004_Image_Processing_2
|
/004_Image_Processing_2/Zoom.cs
| 3.1875
| 3
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _004_Image_Processing_2
{
class Zoom
{
Zoom()
{
}
public static Bitmap setZoomIn(Bitmap bmap)
{
Bitmap copy = new Bitmap(bmap.Width * 2, bmap.Height * 2);
int x = 0, y = 0;
for (int i = 0; i < bmap.Width * 2; i += 2)
{
for (int j = 0; j < bmap.Height * 2; j += 2)
{
if ((i + 1) < copy.Width && (j + 1) < copy.Height)
{
copy.SetPixel(i, j, bmap.GetPixel(x, y));
copy.SetPixel(i + 1, j, bmap.GetPixel(x, y));
copy.SetPixel(i, j + 1, bmap.GetPixel(x, y));
copy.SetPixel(i + 1, j + 1, bmap.GetPixel(x, y));
}
y++;
}
x++;
y = 0;
}
return copy;
}
public static Bitmap setZoomIn2(Bitmap bmap)
{
int R, G, B;
Bitmap copy = new Bitmap((bmap.Width * 2) - 1, (bmap.Height * 2) - 1);
Color[,] dizi = new Color[bmap.Width, bmap.Height];
Color[,] dizi2 = new Color[(bmap.Width * 2) - 1, (bmap.Height * 2) - 1];
for (int i = 0; i < bmap.Width; i++)
{
for (int j = 0; j < bmap.Height; j++)
{
dizi[i, j] = bmap.GetPixel(i, j);
}
}
int x = 0, y = 0;
for (int i = 0; i < (bmap.Width * 2) - 1; i += 2)
{
for (int j = 0; j < (bmap.Height * 2) - 1; j += 2)
{
dizi2[i, j] = dizi[x, y];
if (x != bmap.Width - 1)
{
R = (dizi[x, y].R + dizi[x + 1, y].R) / 2;
G = (dizi[x, y].G + dizi[x + 1, y].G) / 2;
B = (dizi[x, y].B + dizi[x + 1, y].B) / 2;
dizi2[i + 1, j] = Color.FromArgb(R, G, B);
}
if (y != bmap.Height - 1)
{
R = (dizi[x, y].R + dizi[x, y + 1].R) / 2;
G = (dizi[x, y].G + dizi[x, y + 1].G) / 2;
B = (dizi[x, y].B + dizi[x, y + 1].B) / 2;
dizi2[i, j + 1] = Color.FromArgb(R, G, B);
}
if ((y != bmap.Height - 1) && (x != bmap.Width - 1))
{
R = (dizi[x, y].R + dizi[x, y + 1].R + dizi[x + 1, y].R + dizi[x + 1, y + 1].R) / 4;
G = (dizi[x, y].G + dizi[x, y + 1].G + dizi[x + 1, y].G + dizi[x + 1, y + 1].G) / 4;
B = (dizi[x, y].B + dizi[x, y + 1].B + dizi[x + 1, y].B + dizi[x + 1, y + 1].B) / 4;
dizi2[i + 1, j + 1] = Color.FromArgb(R, G, B);
}
y++;
}
y = 0;
x++;
}
for (int i = 0; i < copy.Width; i++)
{
for (int j = 0; j < copy.Height; j++)
{
copy.SetPixel(i, j, dizi2[i, j]);
}
}
return copy;
}
public static Bitmap setZoomOut(Bitmap bmap)
{
int newWith, newHeight;
newWith = bmap.Width / 2;
newHeight = bmap.Height / 2;
/* if (bmap.Width % 2 != 0)
newWith++;
if (bmap.Height % 2 != 0)
newHeight++;*/
Bitmap copy = new Bitmap(newWith, newHeight);
int i = 0, j = 0;
int R, G, B;
for (int x = 0; x < newWith; x++)
{
for (int y = 0; y < newHeight; y++)
{
R = (bmap.GetPixel(i, j).R + bmap.GetPixel(i + 1, j).R + bmap.GetPixel(i, j + 1).R + bmap.GetPixel(i + 1, j + 1).R) / 4;
G = (bmap.GetPixel(i, j).G + bmap.GetPixel(i + 1, j).G + bmap.GetPixel(i, j + 1).G + bmap.GetPixel(i + 1, j + 1).G) / 4;
B = (bmap.GetPixel(i, j).B + bmap.GetPixel(i + 1, j).B + bmap.GetPixel(i, j + 1).B + bmap.GetPixel(i + 1, j + 1).B) / 4;
copy.SetPixel(x, y, Color.FromArgb(R, G, B));
j += 2;
}
j = 0;
i += 2;
}
return copy;
}
}
}
|
00914bb5f80ad632771c508f2b5e991bcf48978c
|
C#
|
troqta/KursovaPS
|
/Kursova/Kursova/MainWindow.xaml.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Kursova
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
///
public partial class MainWindow : Window
{
DispatcherTimer dt = new DispatcherTimer();
private static readonly Random random = new Random();
int time = 0;
int pointsint = 0;
List<Button> buttons = new List<Button>();
public SolidColorBrush getRandomColor()
{
if (Difficulty.SelectedItem.Equals("Easy"))
{
return getRandomColorEasy();
}
else if (Difficulty.SelectedItem.Equals("Medium"))
{
return getRandomColorMeidum();
}
else
{
return getRandomColorHard();
}
}
public SolidColorBrush getRandomColorEasy()
{
int randomNumber = random.Next(0, 1000);
if (randomNumber < 250)
{
return new SolidColorBrush(Colors.Green);
}
else if(randomNumber>250 && randomNumber < 500)
{
return new SolidColorBrush(Colors.Blue);
}
else if (randomNumber > 500 && randomNumber < 750)
{
return new SolidColorBrush(Colors.Red);
}
else
{
return new SolidColorBrush(Colors.Yellow);
}
}
public SolidColorBrush getRandomColorMeidum()
{
int randomNumber = random.Next(0, 1250);
if (randomNumber < 250)
{
return new SolidColorBrush(Colors.Green);
}
else if (randomNumber > 250 && randomNumber < 500)
{
return new SolidColorBrush(Colors.Blue);
}
else if (randomNumber > 500 && randomNumber < 750)
{
return new SolidColorBrush(Colors.Red);
}
else if (randomNumber > 750 && randomNumber < 1000)
{
return new SolidColorBrush(Colors.Purple);
}
else
{
return new SolidColorBrush(Colors.Yellow);
}
}
public SolidColorBrush getRandomColorHard()
{
int randomNumber = random.Next(0, 1500);
if (randomNumber < 250)
{
return new SolidColorBrush(Colors.Green);
}
else if (randomNumber > 250 && randomNumber < 500)
{
return new SolidColorBrush(Colors.Blue);
}
else if (randomNumber > 500 && randomNumber < 750)
{
return new SolidColorBrush(Colors.Red);
}
else if (randomNumber > 750 && randomNumber < 1000)
{
return new SolidColorBrush(Colors.Purple);
}
else if (randomNumber > 1000 && randomNumber < 1250)
{
return new SolidColorBrush(Colors.Orange);
}
else
{
return new SolidColorBrush(Colors.Yellow);
}
}
public MainWindow()
{
InitializeComponent();
List<string> difficulties = new List<string>();
difficulties.Add("Easy");
difficulties.Add("Medium");
difficulties.Add("Hard");
Difficulty.ItemsSource = difficulties;
Difficulty.SelectedIndex = 0;
for (int i = 0; i < 15; ++i)
{
for (int j = 0; j < 15; j++)
{
Button button = new Button();
button.Height = 30;
button.Width = 30;
button.SetValue(Grid.RowProperty, i);
button.SetValue(Grid.ColumnProperty, j);
button.Click += boxClick;
button.IsEnabled = false;
gameGrid.Children.Add(button);
}
}
dt.Interval = TimeSpan.FromSeconds(1);
dt.Tick += Dt_Tick;
}
private void Dt_Tick(object sender, EventArgs e)
{
time++;
gameTime.Content = time.ToString();
if (time == 60)
{
dt.Stop();
GameOver();
time = 0;
gameTime.Content = 0;
}
}
private void StartGame_Click(object sender, RoutedEventArgs e)
{
Difficulty.IsEnabled = false;
StartGame.IsEnabled = false;
dt.Start();
points.Content = 0;
pointsint = 0;
foreach (Control ctrl in gameGrid.Children)
{
if (ctrl is Button)
{
ctrl.Background = getRandomColor();
ctrl.IsEnabled = true; ;
}
}
}
private void GameOver()
{
foreach (Control ctrl in gameGrid.Children)
{
if (ctrl is Button)
{
ctrl.Background = getRandomColor();
ctrl.IsEnabled = false;
}
}
MessageBox.Show("Game over!... Points: "+ pointsint);
Difficulty.IsEnabled = true;
StartGame.IsEnabled = true;
}
public void boxClick(object sender, RoutedEventArgs e)
{
HashSet<Button> used = new HashSet<Button>();
buttons.Add(((Button)sender));
used.Add(((Button)sender));
fillListByColor(((Button)sender), used);
if (buttons.Count >= 3) {
foreach (Button button in buttons)
{
button.Background = getRandomColor();
}
pointsint += buttons.Count * 10;
points.Content = pointsint;
}
buttons.Clear();
}
public void fillListByColor(Button button , HashSet<Button> used)
{
int col = (int)button.GetValue(Grid.ColumnProperty);
int row = (int)button.GetValue(Grid.RowProperty);
if (col+1 >= 0 && col+1<15)
{
if(getButtonByCoordinates(row, col + 1).Background.ToString().Equals(button.Background.ToString()) && !used.Contains(getButtonByCoordinates(row, col + 1)))
{
buttons.Add(getButtonByCoordinates(row, col + 1));
used.Add(getButtonByCoordinates(row, col + 1));
fillListByColor(getButtonByCoordinates(row, col + 1), used);
}
}
if (col - 1 >= 0 && col - 1 < 15)
{
if (getButtonByCoordinates(row, col - 1).Background.ToString().Equals(button.Background.ToString()) && !used.Contains(getButtonByCoordinates(row, col - 1)))
{
buttons.Add(getButtonByCoordinates(row, col - 1));
used.Add(getButtonByCoordinates(row, col - 1));
fillListByColor(getButtonByCoordinates(row, col - 1), used);
}
}
if (row + 1 >= 0 && row + 1 < 15)
{
if (getButtonByCoordinates(row +1, col).Background.ToString().Equals(button.Background.ToString()) && !used.Contains(getButtonByCoordinates(row + 1, col)))
{
buttons.Add(getButtonByCoordinates(row +1, col));
used.Add(getButtonByCoordinates(row + 1, col));
fillListByColor( getButtonByCoordinates(row +1, col), used);
}
}
if (row - 1 >= 0 && row - 1 < 15)
{
if (getButtonByCoordinates(row -1, col).Background.ToString().Equals(button.Background.ToString()) && !used.Contains(getButtonByCoordinates(row - 1, col)))
{
buttons.Add(getButtonByCoordinates(row -1, col));
used.Add(getButtonByCoordinates(row - 1, col));
fillListByColor( getButtonByCoordinates(row -1, col), used);
}
}
}
public Button getButtonByCoordinates(int row, int col)
{
foreach(Control ctrl in gameGrid.Children)
{
if(ctrl is Button)
{
if((int)ctrl.GetValue(Grid.RowProperty)==row && (int)ctrl.GetValue(Grid.ColumnProperty) == col)
{
return(Button)ctrl;
}
}
}
return null;
}
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
if (MessageBox.Show("Are you sure you wish to quit ?", "Question", MessageBoxButton.YesNo) == MessageBoxResult.No)
{
base.OnClosing(e);
e.Cancel = true;
}
else
{
base.OnClosing(e);
e.Cancel = false;
}
}
}
}
|
bc527c22d290681d2af245882be2ed0a2d00f2da
|
C#
|
DuongXuanBinh/Baitap
|
/C#/Session 2/Snippet 12/Program.cs
| 3.5
| 4
|
using System;
namespace Snippet_12
{
class Program
{
static void Main(string[] args)
{
int number, result;
number = 5;
result = 100 * number;
Console.WriteLine("Result is {0} is multiplied by {1}", result, number);
result = 150 / number;
Console.WriteLine("Result if {0} when 150 is devided by {1}", result, number);
}
}
}
|
d47e875eaea1701fa26a4325d7bc14861cbc5d3c
|
C#
|
AuroraDysis/UstbBox.old
|
/UstbBox.Models/Images/ImageObject.cs
| 3.234375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UstbBox.Models.Images
{
public class ImageObject
{
public ImageObject()
{
}
public ImageObject(string name, string uri)
{
this.Name = name;
this.Uri = uri;
}
public string Name { get; set; }
public string Uri { get; set; }
public static bool operator ==(ImageObject a, ImageObject b)
{
// If both are null, or both are same instance, return true.
if (ReferenceEquals(a, b))
{
return true;
}
// If one is null, but not both, return false.
if (((object)a == null) || ((object)b == null))
{
return false;
}
// Return true if the fields match:
return a.Name == b.Name && a.Uri == b.Uri;
}
public static bool operator !=(ImageObject a, ImageObject b)
{
return !(a == b);
}
public override bool Equals(object obj)
{
// If parameter cannot be cast to ThreeDPoint return false:
ImageObject p = obj as ImageObject;
if ((object)p == null)
{
return false;
}
// Return true if the fields match:
return this.Name == p.Name && this.Uri == p.Uri;
}
public bool Equals(ImageObject p)
{
// Return true if the fields match:
return this.Name == p.Name && this.Uri == p.Uri;
}
public override int GetHashCode()
{
return (this.Name + this.Uri).GetHashCode();
}
}
}
|
b5e8d528c34c669e009c74c6b03f789e3fb0989e
|
C#
|
GeorgDangl/XmlTools
|
/src/XmlTools/GroupFlattener/Flattener.cs
| 2.984375
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
namespace XmlTools.GroupFlattener
{
public class Flattener
{
public Flattener(Stream xsdSchemaStream)
{
_xsdSchemaStream = xsdSchemaStream ?? throw new ArgumentNullException(nameof(xsdSchemaStream));
}
private readonly Stream _xsdSchemaStream;
private readonly XNamespace _xmlSchemaNamespace = "http://www.w3.org/2001/XMLSchema";
private XDocument _sourceDocument;
public Stream FlattenGroups(List<string> specificGroupTypes = null) // If given, only specific group types will be flattened
{
_sourceDocument = XDocument.Load(_xsdSchemaStream);
if (_sourceDocument.Root?.Name != _xmlSchemaNamespace + "schema")
{
throw new ArgumentException("This is not a valid Xml schema, the root element is expected to be called \"schema\"");
}
FlattenGroupElements("group", specificGroupTypes);
FlattenGroupElements("attributeGroup", specificGroupTypes);
var keyElements = _sourceDocument.Root.Descendants()
.Where(e => e.Name == _xmlSchemaNamespace + "key" && e.Attributes().Any(a => a.Name.LocalName == "name"))
.ToList();
var keyIdentifier = 1;
foreach (var keyElement in keyElements)
{
keyElement.Attribute("name").Value += keyIdentifier++;
}
var memStream = new MemoryStream();
_sourceDocument.Save(memStream);
memStream.Position = 0;
return memStream;
}
private void FlattenGroupElements(string elementName, List<string> specificGroupTypes)
{
if (specificGroupTypes == null)
{
_sourceDocument.Root.Descendants().FlattenGroupElements(elementName);
}
else
{
foreach (var groupType in specificGroupTypes)
{
_sourceDocument.Root.Descendants().FlattenGroupElements(elementName, groupType);
}
}
}
}
}
|
e77dd52c185814a34511108e0c22a4db2066b48a
|
C#
|
GlynLeine/ProceduralArt
|
/ProceduralBuildingsSV/Assets/Scripts/ExampleGrammars/Stack/StackEditor.cs
| 2.6875
| 3
|
using UnityEngine;
using System.Collections;
using UnityEditor;
namespace Demo {
/// <summary>
/// This editor script adds two buttons to the inspector of the Stack component,
/// which can be used to call generate and destroy methods.
/// </summary>
[CustomEditor(typeof(Stack))]
public class StackEditor : Editor {
public override void OnInspectorGUI() {
Stack targetStack = (Stack)target;
GUILayout.Label("Generated objects: "+targetStack.NumberOfGeneratedObjects);
if (GUILayout.Button("Generate")) {
targetStack.Generate(0.1f);
}
if (GUILayout.Button("Destroy")) {
targetStack.DeleteGenerated();
}
DrawDefaultInspector();
}
}
}
|
cd512f97deae82dd27bc7ee8201730526d3c3283
|
C#
|
alvarogar777/ProyectoFinalBackendC-
|
/ProyectoFinalBackend/Model/DetalleCompraModel.cs
| 2.578125
| 3
|
using MahApps.Metro.Controls.Dialogs;
using ProyectoFinalBackend.Entity;
using ProyectoFinalBackend.View;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProyectoFinalBackend.Model
{
public class DetalleCompraModel
{
private ControlAlmacenDataContext db = new ControlAlmacenDataContext();
private ObservableCollection<DetalleCompra> _DetalleCompra;
public ObservableCollection<DetalleCompra> ShowList
{
get
{
if (this._DetalleCompra == null)
{
this._DetalleCompra = new ObservableCollection<DetalleCompra>();
foreach (DetalleCompra elemento in db.DetalleCompras.ToList())
{
this._DetalleCompra.Add(elemento);
}
}
return this._DetalleCompra;
}
set { this._DetalleCompra = value; }
}
public async Task<bool> Add(GenerarCompraView mensaje)
{
var resultado = await mensaje.ShowMessageAsync("Agregando", "Desea Agregar un nuevo detalle compra",
MessageDialogStyle.AffirmativeAndNegative, new MetroDialogSettings
{
AffirmativeButtonText = "Si",
NegativeButtonText = "No",
AnimateShow = true,
AnimateHide = false
});
if (resultado == MessageDialogResult.Affirmative)
{
return true;
}
else
{
return false;
}
}
public DetalleCompra Save(int idCompra,int codigoProducto,int cantidad, decimal precio,decimal subtotal)
{
DetalleCompra nuevo = new DetalleCompra();
nuevo.IdCompra = idCompra;
nuevo.CodigoProducto = codigoProducto;
nuevo.Cantidad = cantidad;
nuevo.Precio = precio;
nuevo.SubTotal = subtotal;
db.DetalleCompras.Add(nuevo);
db.SaveChanges();
return nuevo;
}
public void Delete(DetalleCompra selectDetalleCompra)
{
db.DetalleCompras.Remove(selectDetalleCompra);
db.SaveChanges();
}
public dynamic update(int idDetalle, int idCompra, int codigoProducto, int cantidad, decimal precio)
{
var updatDetalleCompra = this.db.DetalleCompras.Find(idDetalle);
updatDetalleCompra.IdCompra= idCompra;
updatDetalleCompra.CodigoProducto = codigoProducto;
updatDetalleCompra.Cantidad = cantidad;
updatDetalleCompra.Precio = precio;
this.db.Entry(updatDetalleCompra).State = EntityState.Modified;
this.db.SaveChanges();
return updatDetalleCompra;
}
public List<DetalleCompra> FindList(int idCompra)
{
//List<DetalleFactura> query = (from p in db.DetalleFacturas.ToList()
// where p.NumeroFactura == numeroFactura
// orderby p.CodigoDetalle
// select new DetalleFactura
// {
// }
// ).ToList();
List<DetalleCompra> resultado = this.db.DetalleCompras.Where(p => p.IdCompra == idCompra).ToList();
return resultado;
}
}
}
|
c28cc5d2454dd44882462bc2c21046c1542c5304
|
C#
|
Grumpstrel/Class2
|
/CarRentalApp1/CarRentalApp/Program.cs
| 3.03125
| 3
|
using System;
namespace CarRentalApp
{
class Program
{
private static string option;
static void Main(string[] args)
{
while (true)
{
PrintMainBanner();
PrintMainMenu();
var option = Console.ReadLine();
switch (option)
{
case "1":
PrintAccountCreationMenu();
Console.WriteLine("Enter first name:");
var firstName = Console.ReadLine();
Console.WriteLine("Enter Last Name:");
var lastName = Console.ReadLine();
var fullName = firstName + " " + lastName;
Console.WriteLine("Enter Address:");
var customerAddress = Console.ReadLine();
Console.WriteLine("Enter Phone Number:");
var customerPhoneNumber = Console.ReadLine();
Console.WriteLine("Enter Email Address: ");
var customerEmailAddress = Console.ReadLine();
Console.WriteLine("Enter your drivers License number:");
var customerDriversLicenseNumber = Console.ReadLine();
Console.WriteLine("Enter your rental credit card:");
var customerCreditCardNumber = Console.ReadLine();
//CreateAccount(string customerName, string customerAddress, string customerPhoneNumber, string customerEmailAddress, string driverLicenseNumber, int customerCreditCardNumber
var account = CustomerAccounts.CreateAccount(fullName, customerAddress, customerPhoneNumber, customerEmailAddress, customerEmailAddress, customerCreditCardNumber);
break;
case "2":
PrintAccountMenuHeader();
PrintAccountMenu();
Console.ReadLine();
break;
case "3":
PrintAllAccountsMenu();
PrintAllAccounts();
Console.ReadLine();
break;
case "4":
return;
}
}
}
private static void PrintMainBanner()
{
Console.Clear();
PrintBannerBar();
Console.WriteLine("1980's Enterprise Car Rental");
PrintBannerBar();
}
private static void PrintAccountMenu()
{
Console.WriteLine("1: Basic Info");
//CustomerAccounts.EditAccount
//Remember to include the insurance part
Console.WriteLine("2: Reserve a Car");
//RentalAgreement.Reservation
Console.WriteLine("3: Picking up");
//RentalAgreement.CheckOutVehical
//Need to have a check to make sure that this is completed
//InsuranceInformation.PolicyInformation
Console.WriteLine("4: Dropping off");
//RentalAgreement.CheckInVehicle
Console.WriteLine("5: Return to MainMenu");
}
private static void PrintAccountMenuHeader()
{
Console.Clear();
PrintBannerBar();
Console.WriteLine($"Welcome back this is your account menu"); //Want to add the {CustomerAccounts.GetAllAccounts.CustomerName) to the string
PrintBannerBar();
}
private static void PrintMainMenu()
{
Console.WriteLine("1: Create new account");
Console.WriteLine("2: Log into current account");
Console.WriteLine("3: Print all accounts");
Console.WriteLine("4: Exit");
Console.WriteLine("Select an option.");
PrintBannerBar();
}
private static void PrintAccountCreationMenu()
{
Console.Clear();
PrintBannerBar();
Console.WriteLine("Account Creation Menu");
PrintBannerBar();
}
private static void PrintAllAccountsMenu()
{
Console.Clear();
PrintBannerBar();
Console.WriteLine("Printing all accounts...");
PrintBannerBar();
}
private static void PrintBannerBar()
{
Console.WriteLine();
Console.WriteLine("*************************");
Console.WriteLine();
}
public static void PrintAllAccounts()
{
var accounts = CustomerAccounts.GetAllAccounts();
foreach (var getaccount in accounts)
{
Console.WriteLine($"Account Number: {getaccount.CustomerAccountNumber},");
Console.WriteLine($"Name: {getaccount.CustomerName},");
Console.WriteLine($"Address: {getaccount.CustomerAddress},");
Console.WriteLine($"Phone Number: {getaccount.CustomerPhoneNumber},");
Console.WriteLine($"Email: {getaccount.CustomerEmailAddress},");
Console.WriteLine($"Credit Card: {getaccount.CustomerCreditCardNumber}");
Console.WriteLine();
}
}
}
}
|
32c1052bf0bb053d1096cd3fd49a2a567664b165
|
C#
|
dknipper/ExcelDocumentProcessor
|
/ExcelDocumentProcessor.Web/ApplicationLogic/Security/SecurityModel.cs
| 2.5625
| 3
|
using System;
using ExcelDocumentProcessor.Web.ApplicationLogic.AppConfig;
using ExcelDocumentProcessor.Web.ApplicationLogic.Proxies.DataService;
namespace ExcelDocumentProcessor.Web.ApplicationLogic.Security
{
public class SecurityModel
{
#region Security Functions
/// <summary>
/// Check that the user has access
/// </summary>
/// <param name="userId"></param>
/// <param name="functionId"></param>
/// <returns></returns>
public bool UserHasFunction(int userId, int functionId)
{
try
{
bool rtrn;
using (var serviceClient = new NeonISGDataServiceClient(Configuration.ActiveNeonDataServiceEndpoint))
{
rtrn = serviceClient.UserHasFunction(userId, functionId);
}
return rtrn;
}
catch (Exception ex)
{
throw new Exception(string.Format("Error in SecurityVM.UserHasFunction() userId:{0} functionId:{1}", userId, functionId), ex);
}
}
/// <summary>
/// Attempt to login the user by matching their AD account to a registered user in the system
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public int? Login(string userName)
{
try
{
int? rtrn;
using (var serviceClient = new NeonISGDataServiceClient(Configuration.ActiveNeonDataServiceEndpoint))
{
rtrn = serviceClient.Login(userName);
}
return rtrn;
}
catch (Exception ex)
{
throw new Exception(string.Format("Error in SecurityVM.Login() userName:{0}", userName), ex);
}
}
#endregion
}
}
|
9a48a41aa78ecfa6d9768087040423dc190dc0fa
|
C#
|
Kros-sk/Kros.Libs
|
/Kros.Utils/src/Kros.Utils.MsAccess/Data/MsAccessIdGeneratorFactory.cs
| 2.703125
| 3
|
using Kros.Utils;
using System.Data.OleDb;
namespace Kros.Data.MsAccess
{
/// <summary>
/// Creates an instances of <see cref="MsAccessIdGenerator"/> for specified database.
/// </summary>
/// <seealso cref="MsAccessIdGenerator"/>
/// <seealso cref="IdGeneratorFactories"/>
/// <example>
/// <code language="cs" source="..\..\..\..\Documentation\Examples\Kros.Utils\IdGeneratorExamples.cs" region="IdGeneratorFactory"/>
/// </example>
public class MsAccessIdGeneratorFactory
: IIdGeneratorFactory
{
private readonly string _connectionString;
private readonly OleDbConnection _connection;
/// <summary>
/// Initializes a new instance of the <see cref="MsAccessIdGeneratorFactory"/> class.
/// </summary>
/// <param name="connection">Connection, ktorá sa použije pre získavanie unikátnych identifikátorov.</param>
public MsAccessIdGeneratorFactory(OleDbConnection connection)
{
_connection = Check.NotNull(connection, nameof(connection));
}
/// <summary>
/// Initializes a new instance of the <see cref="MsAccessIdGeneratorFactory"/> class.
/// </summary>
/// <param name="connectionString">
/// Connection string, ktorý sa použije na vytvorenie conenction pre získavanie unikátnych identifikátorov.
/// </param>
public MsAccessIdGeneratorFactory(string connectionString)
{
_connectionString = Check.NotNullOrWhiteSpace(connectionString, nameof(connectionString));
}
/// <inheritdoc/>
public IIdGenerator GetGenerator(string tableName) => GetGenerator(tableName, 1);
/// <inheritdoc/>
public IIdGenerator GetGenerator(string tableName, int batchSize) =>
_connection != null ?
new MsAccessIdGenerator(_connection, tableName, batchSize) :
new MsAccessIdGenerator(_connectionString, tableName, batchSize);
/// <summary>
/// Registers factory methods for creating an instance of factory into <see cref="IdGeneratorFactories"/>.
/// </summary>
public static void Register() =>
IdGeneratorFactories.Register<OleDbConnection>(MsAccessDataHelper.ClientId,
(conn) => new MsAccessIdGeneratorFactory(conn as OleDbConnection),
(connString) => new MsAccessIdGeneratorFactory(connString));
}
}
|
8b058a7ea0d7298bf95985d1839ce186878c580c
|
C#
|
longnvit9x/FoodyDelivery
|
/Foody/Models/GioHang.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Foody.Models
{
public class GioHang
{
FoodDeliveryEntities db = new FoodDeliveryEntities();
public string StoreID { get; set; }
public string FoodID { get; set; }
public string FoodName { get; set; }
public string FoodImage { get; set; }
public double PriceFood { get; set; }
public string FoodSize { get; set; }
public double PriceSize { get; set; }
public string FoodType { get; set; }
public double PriceType { get; set; }
public int SoLuong { get; set; }
public double ThanhTien
{
get {return SoLuong * (PriceFood + PriceSize + PriceType); }
}
public GioHang(string FoodID, int FoodSizeID, int FoodTypeID, int sl = 1)
{
FoodSize size = db.FoodSizes.Where(n => n.FoodSizeID == FoodSizeID).SingleOrDefault();
if(size == null)
{
FoodSize = "";
PriceSize = 0;
}
else
{
FoodSize = size.SizeName;
PriceSize = double.Parse(size.PriceSize.ToString());
}
FoodType type = db.FoodTypes.Where(n => n.FoodTypeID == FoodTypeID).SingleOrDefault();
if (type == null)
{
FoodType = "";
PriceType = 0;
}
else
{
FoodType = size.SizeName;
PriceType = double.Parse(type.PriceType.ToString());
}
var fdID = Guid.Parse(FoodID);
this.FoodID = FoodID;
Food food = db.Foods.SingleOrDefault(n => n.FoodID == fdID);
StoreID = food.StoreID.ToString();
FoodName = food.FoodName;
FoodImage = food.FoodImage;
PriceFood = double.Parse(food.Price.ToString());
SoLuong = sl;
}
}
}
|
5851ef0bfff591043de64a46d6eeab74ca7278ef
|
C#
|
JanCGu/nexus
|
/Core/Interfaces/IChipCardSetter.cs
| 2.65625
| 3
|
using Domain;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Core.Interfaces {
public interface IChipCardSetter {
/// <summary>
/// Inserts (Creates or Updates) the HashSet of chipcards.
/// </summary>
/// <param name="toUpdate"></param>
/// <returns>List of inserted Objects</returns>
Task<HashSet<IChipCard>> Insert(HashSet<IChipCard> toUpdate);
/// <summary>
/// Deletes the chipcards within the Hashset.
/// </summary>
/// <param name="toDelete"></param>
/// <returns></returns>
Task<HashSet<IChipCard>> Delete(HashSet<IChipCard> toDelete);
}
}
|
0e1b60e35f49f450893bf1dfe7e8ec04af5d0cf6
|
C#
|
JimmehG/PerfectHair
|
/Assets/Scripts/DynamicSoundtrack.cs
| 2.53125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DynamicSoundtrack : MonoBehaviour
{
[Header("Soundtrack Stages")]
[SerializeField]
AudioSource[] audioSources;
[Header("Current State")]
[ReadOnlyAttribute]
[SerializeField]
int currentStage;
void Start()
{
currentStage = 0;
if (audioSources.Length > 1)
{
for (int i = 1; i < audioSources.Length; i++)
{
audioSources [i].volume = 0.0f;
}
}
}
public void IncreaseSoundtrackStage()
{
if ((currentStage + 1) < audioSources.Length)
{
StartCoroutine (TransitionToNextStage());
}
}
private IEnumerator TransitionToNextStage()
{
int nextStage = currentStage + 1;
while (audioSources[nextStage].volume < 1.0f)
{
audioSources[nextStage].volume = audioSources[nextStage].volume + 0.1f;
audioSources[currentStage].volume = audioSources[currentStage].volume - 0.1f;
yield return new WaitForSeconds(0.1f);
}
currentStage = nextStage;
}
}
|
23d7725aa28dff368f1b944f77fe9da72faa18d4
|
C#
|
Gunner92/amazon
|
/AWSSDK/ThirdParty/Mono/ConfigurationManager.cs
| 2.546875
| 3
|
#region File Description
//-----------------------------------------------------------------------------
// GameScreen.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
using System.Collections.Specialized;
using System.IO;
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using System.Xml.Linq;
#endregion
namespace System.Configuration
{
/// <summary>
/// Supplies access to configuration data.
/// </summary>
public static class ConfigurationManager
{
#region Public Static Methods
static NameValueCollection appSettings;
public static NameValueCollection AppSettings {
get {
if(appSettings != null)
return appSettings;
LoadConfiguration();
return appSettings;
}
}
/// <summary>
/// Load configuration from an XML document.
/// </summary>
/// <param name="doc">The XML document containing configuration.</param>
static void LoadConfiguration()
{
appSettings = new NameValueCollection();
if(!File.Exists("App.config"))
return;
var doc = XDocument.Load(File.OpenRead("App.config"));
foreach (XElement element in doc.Element("configuration").Elements("appSettings").Elements("add"))
{
if(element.Name.LocalName == "add")
{
var key = element.Attribute("key").Value;
var value = element.Attribute("value").Value;
appSettings.Set(key,value);
}
}
}
#endregion
}
}
|
08258c478246a970b396197d52ab22a9e37d4c27
|
C#
|
nickworonekin/puyotools
|
/src/PuyoTools.Core/Core/BinaryReaderExtensions.cs
| 3.140625
| 3
|
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace PuyoTools.Core
{
public static class BinaryReaderExtensions
{
/// <summary>
/// Invokes <paramref name="func"/> with the position of the stream set to the given value.
/// </summary>
/// <param name="reader"></param>
/// <param name="position"></param>
/// <param name="func"></param>
/// <remarks>The position of the stream is set to the previous position after <paramref name="func"/> is invoked.</remarks>
public static void At(this BinaryReader reader, long position, Action<BinaryReader> func)
{
var origPosition = reader.BaseStream.Position;
if (origPosition != position)
{
reader.BaseStream.Position = position;
}
try
{
func(reader);
}
finally
{
reader.BaseStream.Position = origPosition;
}
}
/// <summary>
/// Invokes <paramref name="func"/> with the position of the stream set to the given value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="reader"></param>
/// <param name="position"></param>
/// <param name="func"></param>
/// <returns>The value returned by <paramref name="func"/>.</returns>
/// <remarks>The position of the stream is set to the previous position after <paramref name="func"/> is invoked.</remarks>
public static T At<T>(this BinaryReader reader, long position, Func<BinaryReader, T> func)
{
var origPosition = reader.BaseStream.Position;
if (origPosition != position)
{
reader.BaseStream.Position = position;
}
T value;
try
{
value = func(reader);
}
finally
{
reader.BaseStream.Position = origPosition;
}
return value;
}
/// <summary>
/// Reads a 2-byte signed integer from the current stream in big-endian format and advances the current position of the stream by two bytes.
/// </summary>
/// <param name="reader"></param>
/// <returns>A 2-byte signed integer read from the current stream.</returns>
public static short ReadInt16BigEndian(this BinaryReader reader) => BinaryPrimitives.ReverseEndianness(reader.ReadInt16());
/// <summary>
/// Reads a 4-byte signed integer from the current stream in big-endian format and advances the current position of the stream by four bytes.
/// </summary>
/// <param name="reader"></param>
/// <returns>A 4-byte signed integer read from the current stream.</returns>
public static int ReadInt32BigEndian(this BinaryReader reader) => BinaryPrimitives.ReverseEndianness(reader.ReadInt32());
/// <summary>
/// Reads an 8-byte signed integer from the current stream in big-endian format and advances the current position of the stream by eight bytes.
/// </summary>
/// <param name="reader"></param>
/// <returns>An 8-byte signed integer read from the current stream.</returns>
public static long ReadInt64BigEndian(this BinaryReader reader) => BinaryPrimitives.ReverseEndianness(reader.ReadInt64());
/// <summary>
/// Reads a 2-byte unsigned integer from the current stream in big-endian format and advances the position of the stream by two bytes.
/// </summary>
/// <param name="reader"></param>
/// <returns>A 2-byte unsigned integer read from this stream.</returns>
public static ushort ReadUInt16BigEndian(this BinaryReader reader) => BinaryPrimitives.ReverseEndianness(reader.ReadUInt16());
/// <summary>
/// Reads a 4-byte unsigned integer from the current stream in big-endian format and advances the position of the stream by four bytes.
/// </summary>
/// <param name="reader"></param>
/// <returns>A 4-byte unsigned integer read from this stream.</returns>
public static uint ReadUInt32BigEndian(this BinaryReader reader) => BinaryPrimitives.ReverseEndianness(reader.ReadUInt32());
/// <summary>
/// Reads an 8-byte unsigned integer from the current stream in big-endian format and advances the position of the stream by eight bytes.
/// </summary>
/// <param name="reader"></param>
/// <returns>An 8-byte unsigned integer read from this stream.</returns>
public static ulong ReadUInt64BigEndian(this BinaryReader reader) => BinaryPrimitives.ReverseEndianness(reader.ReadUInt64());
/// <summary>
/// Reads a 2-byte signed integer from the current stream in the specified endianness and advances the current position of the stream by two bytes.
/// </summary>
/// <param name="reader"></param>
/// <param name="endianness">The endianess of the value to read.</param>
/// <returns>A 2-byte signed integer read from the current stream.</returns>
public static short ReadInt16(this BinaryReader reader, Endianness endianness) => endianness switch
{
Endianness.Little => reader.ReadInt16(),
Endianness.Big => reader.ReadInt16BigEndian(),
_ => throw new ArgumentOutOfRangeException(nameof(endianness)),
};
/// <summary>
/// Reads a 4-byte signed integer from the current stream in the specified endianness and advances the current position of the stream by four bytes.
/// </summary>
/// <param name="reader"></param>
/// <param name="endianness">The endianess of the value to read.</param>
/// <returns>A 4-byte signed integer read from the current stream.</returns>
public static int ReadInt32(this BinaryReader reader, Endianness endianness) => endianness switch
{
Endianness.Little => reader.ReadInt32(),
Endianness.Big => reader.ReadInt32BigEndian(),
_ => throw new ArgumentOutOfRangeException(nameof(endianness)),
};
/// <summary>
/// Reads an 8-byte signed integer from the current stream in the specified endianness and advances the current position of the stream by eight bytes.
/// </summary>
/// <param name="reader"></param>
/// <param name="endianness">The endianess of the value to read.</param>
/// <returns>An 8-byte signed integer read from the current stream.</returns>
public static long ReadInt64(this BinaryReader reader, Endianness endianness) => endianness switch
{
Endianness.Little => reader.ReadInt64(),
Endianness.Big => reader.ReadInt64BigEndian(),
_ => throw new ArgumentOutOfRangeException(nameof(endianness)),
};
/// <summary>
/// Reads a 2-byte unsigned integer from the current stream in the specified endianness and advances the position of the stream by two bytes.
/// </summary>
/// <param name="reader"></param>
/// <param name="endianness">The endianess of the value to read.</param>
/// <returns>A 2-byte unsigned integer read from this stream.</returns>
public static ushort ReadUInt16(this BinaryReader reader, Endianness endianness) => endianness switch
{
Endianness.Little => reader.ReadUInt16(),
Endianness.Big => reader.ReadUInt16BigEndian(),
_ => throw new ArgumentOutOfRangeException(nameof(endianness)),
};
/// <summary>
/// Reads a 4-byte unsigned integer from the current stream in the specified endianness and advances the position of the stream by four bytes.
/// </summary>
/// <param name="reader"></param>
/// <param name="endianness">The endianess of the value to read.</param>
/// <returns>A 4-byte unsigned integer read from this stream.</returns>
public static uint ReadUInt32(this BinaryReader reader, Endianness endianness) => endianness switch
{
Endianness.Little => reader.ReadUInt32(),
Endianness.Big => reader.ReadUInt32BigEndian(),
_ => throw new ArgumentOutOfRangeException(nameof(endianness)),
};
/// <summary>
/// Reads an 8-byte unsigned integer from the current stream the specified endianness and advances the position of the stream by eight bytes.
/// </summary>
/// <param name="reader"></param>
/// <param name="endianness">The endianess of the value to read.</param>
/// <returns>An 8-byte unsigned integer read from this stream.</returns>
public static ulong ReadUInt64(this BinaryReader reader, Endianness endianness) => endianness switch
{
Endianness.Little => reader.ReadUInt64(),
Endianness.Big => reader.ReadUInt64BigEndian(),
_ => throw new ArgumentOutOfRangeException(nameof(endianness)),
};
/// <summary>
/// Reads a string from the current stream.
/// </summary>
/// <param name="reader"></param>
/// <param name="count">The number of bytes to read.</param>
/// <returns></returns>
public static string ReadString(this BinaryReader reader, int count) => ReadString(reader, count, Encoding.UTF8);
/// <summary>
/// Reads a string from the current stream with the specified encoding.
/// </summary>
/// <param name="reader"></param>
/// <param name="count">The number of bytes to read.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <returns></returns>
public static string ReadString(this BinaryReader reader, int count, Encoding encoding)
{
var s = encoding.GetString(reader.ReadBytes(count));
var indexOfNull = s.IndexOf('\0');
if (indexOfNull != -1)
{
s = s.Remove(indexOfNull);
}
return s;
}
/// <summary>
/// Reads a null-terminated string from the current stream.
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
public static string ReadNullTerminatedString(this BinaryReader reader) => ReadNullTerminatedString(reader, Encoding.UTF8);
/// <summary>
/// Reads a null-terminated string from the current stream with the specified encoding.
/// </summary>
/// <param name="reader"></param>
/// <param name="encoding">The character encoding to use.</param>
/// <returns></returns>
public static string ReadNullTerminatedString(this BinaryReader reader, Encoding encoding)
{
var bytes = new List<byte>();
byte c;
while ((c = reader.ReadByte()) != 0)
{
bytes.Add(c);
}
return encoding.GetString(bytes.ToArray());
}
}
}
|
33ac39981e8bdfc111395836c849ecc132dac8ae
|
C#
|
tddold/Telerik-Academy
|
/Programming with C#/5. Data-Structures-and-Algorithms/06. Data-Structure-Efficiency/DataStructuresEffic/01.Student Record/Solve.cs
| 3.625
| 4
|
namespace DataStructuresEfficiency
{
/*
A text file students.txt holds information about students and their courses
in the following format:
Using SortedDictionary<K,T> print the courses in alphabetical order and for
each of them prints the students ordered by family and then by name:
Kiril | Ivanov | C#
Stefka | Nikolova | SQL
Stela | Mineva | Java
Milena | Petrova | C#
Ivan | Grigorov | C#
Ivan | Kolev | SQL
C#: Ivan Grigorov, Kiril Ivanov, Milena Petrova
Java: Stela Mineva
SQL: Ivan Kolev, Stefka Nikolova
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Wintellect.PowerCollections;
public static class Solve
{
private static readonly SortedDictionary<Course, OrderedBag<Student>> StudentCourses =
new SortedDictionary<Course, OrderedBag<Student>>();
public static void Main()
{
ParseInput();
PrintStudentCources();
}
private static void ParseInput()
{
using (var reader = new StreamReader("../../students.txt"))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var studentInfo = line.Split(new char[] { ' ', '|' }, StringSplitOptions.RemoveEmptyEntries).ToArray();
StudentCourses.AddOrCreate(studentInfo[2], studentInfo[0], studentInfo[1]);
}
}
}
private static void AddOrCreate(this SortedDictionary<Course, OrderedBag<Student>> dictionary, string courseName, params string[] studentNames)
{
var course = new Course(courseName);
var student = new Student(studentNames[0], studentNames[1]);
if (!dictionary.ContainsKey(course))
{
dictionary[course] = new OrderedBag<Student>();
}
dictionary[course].Add(student);
}
private static void PrintStudentCources()
{
foreach (var course in StudentCourses)
{
Console.WriteLine("{0,-5}: {1}", course.Key.Name, string.Join(", ", course.Value));
}
Console.WriteLine();
}
}
}
|
ecbbd8572c99f8aee6c0cba9808eab9d725db8d9
|
C#
|
clemgaut/ProjetPoo
|
/SourceProject/Files.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
public class Files {
private const string PATH = @"Saves";
public static List<String> getSaves() {
if(!Directory.Exists(PATH))
return new List<String>();
List<String> files = new List<String>(Directory.GetFiles(PATH));
files.RemoveAll(f => Path.GetExtension(f) != ".small");
List<String> cleanList = new List<string>();
files.ForEach(f => cleanList.Add(Path.GetFileNameWithoutExtension(f)));
return cleanList;
}
// load or save the file
public static void saveHandle(string fileName, bool load) {
// If save directory does not exist.
if(!Directory.Exists(PATH))
Directory.CreateDirectory(PATH);
BinaryFormatter formatter = new BinaryFormatter();
FileAccess fa = (load) ? FileAccess.Read : FileAccess.Write;
string fullPath = PATH + Path.DirectorySeparatorChar + fileName + ".small";
Stream fs = new FileStream(fullPath, FileMode.OpenOrCreate, fa);
try {
if(load)
Game.instance = ((Game)formatter.Deserialize(fs));
else
formatter.Serialize(fs, Game.instance);
} catch(SerializationException e) {
Console.WriteLine("Serialization failed. Reason: " + e.Message);
} finally {
fs.Close();
}
}
}
|
034ac892618153de9a21db1752889dc16f51140c
|
C#
|
elshiekh5/SakeenaTravel
|
/CMS-FullWebFormsVersion/Version 4.0/DCCMSNameSpace/App_Code/App_Code/Modules/ItemsOrders/ItemsOrdersDetailsFactor.cs
| 2.625
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
namespace DCCMSNameSpace
{
/// <summary>
/// The factory class of ItemsOrdersDetailsModel.
/// </summary>
public class ItemsOrdersDetailsFactor
{
#region --------------Create--------------
//------------------------------------------------------------------------------------------------------
/// <summary>
/// Creates model object by calling News data provider create method.
/// </summary>
/// <param name="ItemsOrdersDetailsObj">The model object.</param>
/// <returns>The result of create operation.</returns>
//--------------------------------------------------------------------
public static bool Create(ItemsOrdersDetailsModel ItemsOrdersDetailsObj)
{
return ItemsOrdersDetailsSqlDataPrvider.Instance.Create(ItemsOrdersDetailsObj);
}
//------------------------------------------------------------------------------------------------------
#endregion
#region --------------Updat--------------
//------------------------------------------------------------------------------------------------------
/// <summary>
/// Updates model object by calling sql data provider update method.
/// </summary>
/// <param name="ItemsOrdersDetailsObj">The model object.</param>
/// <returns>The result of update operation.</returns>
//--------------------------------------------------------------------
public static bool Updat(ItemsOrdersDetailsModel ItemsOrdersDetailsObj)
{
return ItemsOrdersDetailsSqlDataPrvider.Instance.Updat(ItemsOrdersDetailsObj);
}
//------------------------------------------------------------------------------------------------------
#endregion
#region --------------Delete--------------
//------------------------------------------------------------------------------------------------------
/// <summary>
/// Deletes single model object .
/// </summary>
/// <param name="ItemID">The model id.</param>
/// <returns>The result of delete operation.</returns>
//--------------------------------------------------------------------
public static bool Delete(int ItemID)
{
return ItemsOrdersDetailsSqlDataPrvider.Instance.Delete(ItemID);
}
//------------------------------------------------------------------------------------------------------
#endregion
#region --------------GetPageByPage--------------
//------------------------------------------------------------------------------------------------------
/// <summary>
/// Gets the spesific records.
/// </summary>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="totalRecords"></param>
/// <returns></returns>
//--------------------------------------------------------------------
public static List<ItemsOrdersDetailsModel> GetPageByPage(int OrderID,int pageIndex, int pageSize, out int totalRecords)
{
return ItemsOrdersDetailsSqlDataPrvider.Instance.GetPageByPage(OrderID,pageIndex, pageSize, out totalRecords);
}
//------------------------------------------------------------------------------------------------------
#endregion
#region --------------Get--------------
//------------------------------------------------------------------------------------------------------
/// <summary>
/// Gets the spesific records.
/// </summary>
/// <param name="ItemID">The model id.</param>
/// <returns>Model object.</returns>
//--------------------------------------------------------------------
public static List<ItemsOrdersDetailsModel> Get(int orderID)
{
return ItemsOrdersDetailsSqlDataPrvider.Instance.Get(orderID);
}
//------------------------------------------------------------------------------------------------------
#endregion
}
}
|
4680d7e7adc19a929599365211da2a3f4bb9ef1b
|
C#
|
kasik1/PlaywrightSharp
|
/CustomerHelperUtility/FindElementByXpath.cs
| 2.921875
| 3
|
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
namespace CustomerHelperUtility
{
public class FindElementByXpath : IFindElement
{
private IWebDriver _WebDriver;
public void IntiateDriver(IWebDriver driver)
{
_WebDriver = driver;
}
public IWebElement GetElement(string locator)
{
try
{
WebDriverWait wait = new WebDriverWait(_WebDriver, TimeSpan.FromSeconds(60));
IWebElement element = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.XPath(locator)));
return element;
}
catch (Exception)
{
return null;
}
}
public IList<IWebElement> GetElements(string locator)
{
try
{
WebDriverWait wait = new WebDriverWait(_WebDriver, TimeSpan.FromSeconds(60));
var element = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.XPath(locator)));
return element;
}
catch (Exception)
{
IList<IWebElement> emptyList = Array.Empty<IWebElement>();
return emptyList;
}
}
}
}
|
c87e3210b079773bf63bdda8e555085c989673e9
|
C#
|
patel-nikhil/UnofficialCrusaderPatch
|
/UnofficialCrusaderPatch/Extensions.cs
| 3.15625
| 3
|
using System;
using System.Text;
using System.Windows;
namespace UCP
{
static class Extensions
{
public static double MeasureHeight(this FrameworkElement element)
{
element.Arrange(new Rect());
return element.ActualHeight;
}
public static int FindIndex(this byte[] self, params byte[] search)
{
int last = search.Length - 1;
for (int i = 0; i < self.Length; i++)
{
for (int j = 0; j < search.Length; j++)
{
if (self[i + j] == search[j])
{
if (j == last)
return i;
}
else
{
break;
}
}
}
return -1;
}
public static int FindIndex(this byte[] self, int value)
{
return self.FindIndex(BitConverter.GetBytes(value));
}
public static string ToHexString(this byte[] self)
{
StringBuilder sb = new StringBuilder(12 + 3 * self.Length);
sb.Append("byte[");
sb.Append(self.Length);
sb.Append("] { ");
for (int i = 0; i < self.Length; i++)
{
sb.Append(self[i].ToString("X2"));
sb.Append(' ');
}
sb.Append('}');
return sb.ToString();
}
}
}
|
fc79ad4d0104e14f7fdf4b4707f04666b271f8f4
|
C#
|
ayonchev/Software-University
|
/Open-Courses/Data-Structures/Exercises-and-Labs/Basic-Trees/Solutions/Trees/Trees/BinaryTree.cs
| 3.71875
| 4
|
using System;
public class BinaryTree<T>
{
public BinaryTree(T value, BinaryTree<T> leftChild = null, BinaryTree<T> rightChild = null)
{
this.Value = value;
this.LeftChild = leftChild;
this.RightChild = rightChild;
}
public T Value { get; private set; }
public BinaryTree<T> LeftChild { get; private set; }
public BinaryTree<T> RightChild { get; private set; }
public void PrintIndentedPreOrder(int indent = 0)
{
Console.WriteLine(new string(' ', indent) + this.Value);
LeftChild?.PrintIndentedPreOrder(indent + 2);
RightChild?.PrintIndentedPreOrder(indent + 2);
}
public void EachInOrder(Action<T> action)
{
LeftChild?.EachInOrder(action);
action.Invoke(this.Value);
RightChild?.EachInOrder(action);
}
public void EachPostOrder(Action<T> action)
{
LeftChild?.EachPostOrder(action);
RightChild?.EachPostOrder(action);
action.Invoke(this.Value);
}
}
|
593127e211bafa49f29e625765865dba00859d17
|
C#
|
saxx/Saxx.Storyblok
|
/src/Saxx.Storyblok/StoryblokMappings.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using Saxx.Storyblok.Attributes;
namespace Saxx.Storyblok
{
public static class StoryblokMappings
{
private static IDictionary<string, Mapping>? _mappingsCache; // make static, because it should be "valid" for as long as the app is running
public static IDictionary<string, Mapping> Mappings
{
get
{
if (_mappingsCache == null)
{
var components = from a in AppDomain.CurrentDomain.GetAssemblies()
from t in a.GetTypes()
let attributes = t.GetCustomAttributes(typeof(StoryblokComponentAttribute), true)
where attributes != null && attributes.Length > 0
select new {Type = t, Attribute = attributes.Cast<StoryblokComponentAttribute>().First()};
_mappingsCache = new Dictionary<string, Mapping>();
foreach (var c in components)
{
if (_mappingsCache.ContainsKey(c.Attribute.Name))
{
continue;
}
_mappingsCache[c.Attribute.Name] = new Mapping
{
Type = c.Type,
ComponentName = c.Attribute.Name,
View = c.Attribute.View
};
}
}
return _mappingsCache;
}
}
public class Mapping
{
// ReSharper disable once UnusedAutoPropertyAccessor.Global
public string ComponentName { get; set; } = "";
public Type Type { get; set; } = typeof(object);
public string? View { get; set; }
}
}
}
|
29ed63450a7f5b001e7a4cf68b8c669ec3d7edf6
|
C#
|
FelixFan1122/LeetCode
|
/KthAncestorOfATreeNode/KthAncestorOfATreeNode.cs
| 3.484375
| 3
|
namespace LeetCode.KthAncestorOfATreeNode
{
public class TreeAncestor
{
private readonly int[] parent;
public TreeAncestor(int n, int[] parent)
{
this.parent = parent;
}
public int GetKthAncestor(int node, int k)
{
while (k > 0 && node != 0)
{
node = parent[node];
k--;
}
return k == 0 ? node : -1;
}
}
}
|
d4a5b0e3743102bac28e3b734620b5be2fc727b6
|
C#
|
thinkaboutcsharp/FriendlySample
|
/FriendlyMySample/FriendlyMySample/InputForm.cs
| 2.546875
| 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 FriendlyMySample
{
public partial class InputForm : Form
{
internal (string id, string name) Info { get; private set; }
public InputForm()
{
InitializeComponent();
}
private void SetReturnInfo()
{
this.Info = (txt_Id.Text, txt_Name.Text);
}
private void InputForm_Load(object sender, EventArgs e)
{
this.Info = (null, null);
}
private void btn_Ok_Click(object sender, EventArgs e)
{
this.SetReturnInfo();
}
private void InputForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.F12)
{
this.SetReturnInfo();
this.DialogResult = DialogResult.OK;
}
else if (e.KeyCode == Keys.Escape)
{
this.DialogResult = DialogResult.Cancel;
}
}
}
}
|
9252534950323ae8a74bcf21488423c887c33b0a
|
C#
|
tylerwh/OlympicGames
|
/Models/OlympicSession.cs
| 2.8125
| 3
|
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OlympicGames.Models
{
public class OlympicSession
{
private const string TeamsKey = "myteams";
private const string CountKey = "teamcount";
private const string CategoryKey = "category";
private const string GameKey = "game";
private ISession session { get; set; }
public OlympicSession(ISession session)
{
this.session = session;
}
public void SetUserName(string userName) => session.SetString("UserName", userName);
public string GetUserName() => session.GetString("UserName");
public void SetMyTeams(List<Team> teams)
{
session.SetObject(TeamsKey, teams); // extension from SessionExtensions.cs
session.SetInt32(CountKey, teams.Count);
}
public List<Team> GetMyTeams() =>
session.GetObject<List<Team>>(TeamsKey) ?? new List<Team>();
public int? GetMyTeamsCount() => session.GetInt32(CountKey);
public void SetActiveCategory(string cat) =>
session.SetString(CategoryKey, cat);
public string GetActiveCategory() => session.GetString(CategoryKey);
public void SetActiveGame(string game) =>
session.SetString(GameKey, game);
public string GetActiveGame() => session.GetString(GameKey);
public void RemoveMyTeams()
{
session.Remove(TeamsKey);
session.Remove(CountKey);
}
}
}
|
e97bf7def482a669a942acab0c85c03619f2631e
|
C#
|
PawelHaracz/MsGraphExample
|
/GraphExample/Program.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.Graph;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Polly;
using Microsoft.Identity.Client;
namespace GraphExample
{
class Program
{
public static async Task Main(string[] args)
{
var scope = new[] {
"User.Read",
"Mail.Send",
"Files.ReadWrite"
};
var graphServiceClient = GraphClientFactory.GetGraphServiceClient("", "https://login.microsoftonline.com/common", scope);
if(graphServiceClient == null)
{
throw new ArgumentException(nameof(graphServiceClient));
}
var user = await graphServiceClient.Me.Request().GetAsync();
string userId = user.Id;
string mailAddress = user.UserPrincipalName;
string displayName = user.DisplayName;
Console.WriteLine("Hello, " + displayName + ". Would you like to send an email to yourself or someone else?");
Console.WriteLine("Enter the address to which you'd like to send a message. If you enter nothing, the message will go to your address.");
}
}
}
|
589299e40de2300067092fe43eb91cbf2985d4d0
|
C#
|
moneer-alasmar/dojo_csharp
|
/puzzles/Program.cs
| 4.0625
| 4
|
using System;
namespace ConsoleApplication
{
public class Program
{
// Create a function called RandomArray() that returns an integer array
// Place 10 random integer values between 5-25 into the array
// Print the min and max values of the array
// Print the sum of all the values
public static int[] Random_Array()
{
Random rand = new Random();
int[] newarr = new int [10];
int min = 27;
int max = newarr[0];
int sum = 0;
for (int i = 0; i < newarr.Length; i++)
{
newarr[i] = rand.Next(5,26);
sum += newarr[i];
if (newarr[i] < min)
{
min = newarr[i];
}
if (newarr[i] > max)
{
max = newarr[i];
}
}
System.Console.WriteLine("Sum: " + sum);
System.Console.WriteLine("Min: " + min);
System.Console.WriteLine("Max: " + max);
return newarr;
}
// Create a function called TossCoin() that returns a string
//Have the function print "Tossing a Coin!"
//Randomize a coin toss with a result signaling either side of the coin
//Have the function print either "Heads" or "Tails"
//return the result
public static string TossCoin()
{
System.Console.WriteLine("Tossing a Coin!");
Random head_or_tail = new Random();
string result;
if (head_or_tail.Next(0,2) == 0)
{
result = "Heads!";
System.Console.WriteLine(result);
}
else
{
result = "Tails!";
System.Console.WriteLine(result);
}
return result;
}
// Create another function called TossMultipleCoins(int num) that returns a Double
// Have the function call the tossCoin function multiple times based on num value
// Have the function return a Double that reflects the ratio of head toss to total toss
public static Double TossMultipleCoins(int num)
{
double head_counter = 0;
double tail_counter = 0;
double ratio = 0;
while (num >= 0)
{
string result = TossCoin();
if (result == "Heads!")
{
head_counter++;
}
else
{
tail_counter++;
}
num--;
}
ratio = head_counter/(head_counter + tail_counter);
return ratio;
}
// Build a function Names that returns an array of strings
// Create an array with the values: Todd, Tiffany, Charlie, Geneva, Sydney
// Shuffle the array and print the values in the new order
// Return an array that only includes names longer than 5 characters
public static string[] Names()
{
string[] names = {"Todd", "Tiffany", "Charlie", "Geneva", "Sydney"};
string[] newarr = new string[4];
int index = 0;
for (int i = 0; i < names.Length; i++)
{
string temp = names[i];
if (temp.Length > 5)
{
newarr[index] = temp;
// System.Console.WriteLine("index " + index + " is "+ temp);
index++;
}
}
return newarr;
}
public static void Main(string[] args)
{
// Random_Array();
// TossCoin();
// double tester = TossMultipleCoins(5);
// System.Console.WriteLine(tester);
Names();
}
}
}
|
e1cb42386cc35f3b8c267ac2e0123fc339671583
|
C#
|
hdgardner/ECF
|
/BusinessLayer/CommerceLib/Engine/Caching/CacheHelper.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Caching;
using System.Collections;
using System.Text.RegularExpressions;
using System.Web;
using System.Threading;
namespace Mediachase.Commerce.Engine.Caching
{
public class CacheHelper
{
private static readonly Cache _cache;
/// <summary>
/// Initializes the <see cref="CacheHelper"/> class.
/// </summary>
static CacheHelper()
{
HttpContext context = HttpContext.Current;
if (context != null)
{
_cache = context.Cache;
}
else
{
_cache = HttpRuntime.Cache;
}
}
/// <summary>
/// Creates the cache key.
/// </summary>
/// <param name="prefix">The prefix.</param>
/// <param name="keys">The keys.</param>
/// <returns></returns>
public static string CreateCacheKey(string prefix, params string[] keys)
{
StringBuilder returnKey = new StringBuilder(prefix);
foreach (string key in keys)
{
returnKey.Append("-");
returnKey.Append(key);
}
return returnKey.ToString();
}
/// <summary>
/// Removes all items from the Cache
/// </summary>
/// <param name="prefix">The prefix.</param>
public static void Clear(string prefix)
{
RemoveByPattern(prefix);
}
/// <summary>
/// Removes the cache by pattern.
/// </summary>
/// <param name="pattern">The pattern.</param>
public static void RemoveByPattern(string pattern)
{
IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled);
while (CacheEnum.MoveNext())
{
if (regex.IsMatch(CacheEnum.Key.ToString()))
_cache.Remove(CacheEnum.Key.ToString());
}
}
/// <summary>
/// Removes the specified key from the cache
/// </summary>
/// <param name="key">The key.</param>
public static void Remove(string key)
{
_cache.Remove(key);
}
/// <summary>
/// Inserts the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="obj">The obj.</param>
/// <param name="timespan">The timespan.</param>
public static void Insert(string key, object obj, TimeSpan timespan)
{
Insert(key, obj, null, timespan);
}
/// <summary>
/// Inserts the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="obj">The obj.</param>
/// <param name="timespan">The timespan.</param>
/// <param name="priority">The priority.</param>
public static void Insert(string key, object obj, TimeSpan timespan, CacheItemPriority priority)
{
Insert(key, obj, null, timespan, priority);
}
/// <summary>
/// Inserts the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="obj">The obj.</param>
/// <param name="dep">The dep.</param>
/// <param name="timespan">The timespan.</param>
public static void Insert(string key, object obj, CacheDependency dep, TimeSpan timespan)
{
Insert(key, obj, dep, timespan, CacheItemPriority.Normal);
}
/// <summary>
/// Inserts the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="obj">The obj.</param>
/// <param name="dep">The dep.</param>
/// <param name="timeframe">The timeframe.</param>
/// <param name="priority">The priority.</param>
public static void Insert(string key, object obj, CacheDependency dep, TimeSpan timeframe, CacheItemPriority priority)
{
CacheItemRemovedCallback callback = null;
// only need call back if item is in the locking states
if(CacheEntries.ContainsKey(key))
callback = new CacheItemRemovedCallback(CacheHelper.ItemRemovedCallback);
Insert(key, obj, dep, timeframe, priority, callback);
}
/// <summary>
/// Inserts the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="obj">The obj.</param>
/// <param name="dep">The dep.</param>
/// <param name="timeframe">The timeframe.</param>
/// <param name="priority">The priority.</param>
/// <param name="callback">The callback.</param>
public static void Insert(string key, object obj, CacheDependency dep, TimeSpan timeframe, CacheItemPriority priority, CacheItemRemovedCallback callback)
{
if (obj != null)
{
_cache.Insert(key, obj, dep, DateTime.Now.Add(timeframe), Cache.NoSlidingExpiration, priority, callback);
}
}
/// <summary>
/// Gets the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
public static object Get(string key)
{
return _cache[key];
}
/// <summary>
/// Gets the lock.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
public static object GetLock(string key)
{
return CacheEntries.GetLock(key);
}
/// <summary>
/// Items the removed callback.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="reason">The reason.</param>
internal static void ItemRemovedCallback(string key, object value, CacheItemRemovedReason reason)
{
if (reason == CacheItemRemovedReason.Expired)
{
CacheEntry cacheEntry = CacheEntries.Get(key);
if (cacheEntry != null)
{
lock (cacheEntry.Lock)
{
CacheEntries.Remove(key);
}
}
}
}
}
}
|
5081d4ca8eb228241df9ffb06363bf812a1de44d
|
C#
|
CostyVoronianu/Obligatiune
|
/src/BondAnalytics/BondAnalytics/Calculations/ZeroRate.cs
| 3.25
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BondAnalytics.Calculations
{
class ZeroRate
{
/// <summary>
/// Implementing linear interpolation with 2 given points with the respective coordinates
/// and the abscissa of a third point
/// </summary>
/// <param name="X1"></param>
/// <param name="X2"></param>
/// <param name="X3"></param>
/// <param name="Y1"></param>
/// <param name="Y3"></param>
/// <returns></returns>
public double LinearInterpolation(DateTime AsOfDate, DateTime X2, List<Tuple<String, Int32, double>> _interestList)
{
Double y2 = 0;
for (int i = 0; i < _interestList.Count - 1; i++)
{
var BeforeDate = AsOfDate.AddDays(_interestList[i].Item2);
var AfterDate = AsOfDate.AddDays(_interestList[i+1].Item2);
if (X2 > BeforeDate && X2 < AfterDate)
{
y2 = (((X2 - BeforeDate).Days) * (_interestList[i+1].Item3 - _interestList[i].Item3)) / ((AfterDate - BeforeDate).Days) + _interestList[i].Item3;
return y2;
}
}
return y2;
}
}
}
|
314290c7d4f338d6f46d04e53960360802c86d3f
|
C#
|
alexcpendleton/Pendletron.Tfs.FolderDiffGet
|
/Pendletron.Tfs.FolderDiffGet.Core/FolderDiffCmdParsing/OutputParser.cs
| 2.984375
| 3
|
using System;
using System.Collections.Generic;
namespace Pendletron.Tfs.FolderDiffGet.Core.FolderDiffCmdParsing
{
public class OutputParser
{
public OutputParser(string src, string target)
{
SourcePath = src;
TargetPath = target;
HeaderOutlineText = "=====";
ExistOnlyInText = "Items That Exist Only in {0}";
DifferentText = "Show Items That Have Different Contents";
IdenticalText = "Show Items That Have Identical Contents";
SummaryText = "Summary: ";
}
public string SourcePath { get; set; }
public string TargetPath { get; set; }
public string HeaderOutlineText { get; set; }
public string ExistOnlyInText { get; set; }
public string SummaryText { get; set; }
public string IdenticalText { get; set; }
public string DifferentText { get; set; }
public ParseResults Parse(string text)
{
List<string> lines = new List<string>();
lines.AddRange(text.Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries));
var results = new ParseResults();
string onlyInSourceFormatted = String.Format(ExistOnlyInText, SourcePath);
string onlyInTargetFormatted = String.Format(ExistOnlyInText, TargetPath);
results.OnlyInSource = FindSection(lines, onlyInSourceFormatted, true);
results.OnlyInTarget = FindSection(lines, onlyInTargetFormatted, true);
results.DifferentContents = FindContentsSection(lines, DifferentText);
results.IdenticalContents = FindContentsSection(lines, IdenticalText);
results.Summary = FindSummary(lines);
return results;
}
public HashSet<string> FindContentsSection(List<string> lines, string text)
{
var section = FindSection(lines, text, false);
var results = new HashSet<string>();
foreach (var s in section)
{
string tab = "\t";
if(s.StartsWith(tab))
{
results.Add(s.Trim());
}
}
return results;
}
private string FindSummary(List<string> lines)
{
int index = lines.FindLastIndex(s => s.Contains(SummaryText));
string results = "";
if(index > -1)
{
results = lines[index];
}
return results;
}
public HashSet<string> FindSection(List<string> lines, string text, bool partial)
{
Predicate<string> finder = s => s.Equals(text);
if(partial)
{
finder = s => s.Contains(text);
}
return FindSection(lines, finder);
}
public HashSet<string> FindSection(List<string> lines, Predicate<string> headerFinder)
{
int headerIndex = lines.FindIndex(headerFinder);
var results = new HashSet<string>();
if(headerIndex > -1)
{
int startAtIndex = headerIndex + 2;
// Find the next header section so we can get everything in between
int endOfSectionIndex = lines.FindIndex(startAtIndex, s=>s.Contains(HeaderOutlineText));
int lineCount = endOfSectionIndex - startAtIndex;
foreach (var x in lines.GetRange(startAtIndex, lineCount))
{
results.Add(x);
}
}
return results;
}
}
}
|
a736b3b40af5c27974962947512b51b6053dee5c
|
C#
|
sidby/Sklad1
|
/SidBy.Sklad.DataAccess/Mappings/UsersMap.cs
| 2.5625
| 3
|
using SidBy.Sklad.Domain;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
namespace SidBy.Sklad.DataAccess.Mappings
{
public class UsersMap : EntityTypeConfiguration<UserProfile>
{
public UsersMap()
{
// Primary key
this.HasKey(t => t.UserId);
// Properties
this.Property(t => t.UserId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(t => t.UserName)
.HasMaxLength(56).IsRequired();
this.Property(t => t.UserEmail)
.HasMaxLength(320);
this.Property(t => t.DisplayName)
.HasMaxLength(100);
this.Property(t => t.Surname)
.HasMaxLength(100);
this.Property(t => t.Name)
.HasMaxLength(100);
this.Property(t => t.MiddleName)
.HasMaxLength(100);
this.Property(t => t.Phone1)
.HasMaxLength(150);
this.Property(t => t.Phone2)
.HasMaxLength(150);
this.Property(t => t.Skype)
.HasMaxLength(150);
this.Ignore(x => x.NewPassword);
// Table & Column Mappings
this.ToTable("UserProfile");
// Relationships
this.HasOptional(t => t.Job)
.WithMany(t => t.Employees)
.HasForeignKey(d => d.LegalEntityId);
this.HasOptional(t => t.Type)
.WithMany(t => t.Profiles)
.HasForeignKey(d => d.ContactTypeId);
}
}
}
|
07724cebc9a5086643e0473e4d949173f1abca74
|
C#
|
LadaOndris/FIT_VUT
|
/IVS/proj2/src/GUICalculator/ViewModel/Expressions/Power.cs
| 2.640625
| 3
|
using GUICalculator.ViewModel.Expressions.Base;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
namespace GUICalculator.ViewModel.Expressions
{
/// <summary>
/// Power expression is a SingleExpression which means it consists of
/// a single list of expressions.
/// As of all expressions, the look is represented by the specific template.
/// </summary>
internal class Power : SingleExpression
{
public Power()
: base("PowerExpressionTemplate")
{
}
public override string ConvertToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("^(");
foreach (Expression expression in Items)
sb.Append(expression.ConvertToString());
sb.Append(")");
return sb.ToString();
}
}
}
|
bd2ca209b954c4cb2cc0506ca312ce9d37575980
|
C#
|
Ujinjinjin/dingo
|
/Src/Cliff/Extensions/ServiceProviderExtensions.cs
| 2.8125
| 3
|
using Microsoft.Extensions.DependencyInjection;
using System;
namespace Cliff.Extensions
{
/// <summary> Collection of extensions for <see cref="IServiceProvider"/></summary>
public static class ServiceProviderExtensions
{
/// <summary> Invoke <see cref="CliController.Register"/> method for every controller in service collection </summary>
/// <param name="serviceProvider">Service provider of your application</param>
/// <returns>Self</returns>
public static IServiceProvider RegisterControllers(this IServiceProvider serviceProvider)
{
var controllers = serviceProvider.GetServices<IController>();
foreach (var controller in controllers)
{
controller.Register();
}
return serviceProvider;
}
}
}
|
61da6a1eb551ab9b2622cd7a49e37cf8f5521cda
|
C#
|
Discaulit/4INFO_SmallWorld
|
/CS_SmallWorld/UnitTestSmallWorld/UnitTest1.cs
| 2.71875
| 3
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using CS_SmallWorld;
using wrapperLibSmallWorld;
using System.Collections.Generic;
namespace UnitTestSmallWorld
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethodPlateau()
{
int taille = 5;
WrapperLibsSmallWorld wrapper = new WrapperLibsSmallWorld(taille);
PlateauConcret plateau = new PlateauConcret(taille, wrapper);
bool plateauOk = false;
bool[] types = {false, false, false, false, false};
for (int i = 0; i < taille; i++)
{
for (int j = 0; j < taille; j++)
{
if (plateau.getCaseAt(new Position(i, j)) is CaseMontagneConcret)
types[0] = true;
if (plateau.getCaseAt(new Position(i, j)) is CasePlaineConcret)
types[1] = true;
if (plateau.getCaseAt(new Position(i, j)) is CaseDesertConcret)
types[2] = true;
if (plateau.getCaseAt(new Position(i, j)) is CaseEauConcret)
types[3] = true;
if (plateau.getCaseAt(new Position(i, j)) is CaseForetConcret)
types[4] = true;
}
}
plateauOk = types[0] && types[1] && types[2] && types[3] && types[4];
Assert.IsTrue(plateauOk);
}
[TestMethod]
public void TestMethodCombat()
{
int taille = 5;
WrapperLibsSmallWorld wrapper = new WrapperLibsSmallWorld(taille);
Combat combat = PartieConcret._singletonCombat;
bool[] resDuCombat = { false, false, false };
bool resFinal = false;
int uniteAttaque, uniteDef;
int cpt = 0;
//Test plusieurs fois pour savoir si on peut avoir atq gagne, def gagne et match nul
while (!resFinal)
{
uniteAttaque = 5;
uniteDef = 5;
/* Ceci est un copier-coller quasi identique du code de CombatConcret.lancerCombat(Unite atq, Case caseDef).
* Le but est de tester l'algo de combat, sans devoir passer par la création d'une Unite et donc d'un Peuple,
* d'une Case et donc d'un Plateau etc.
*/
List<int> resCombat = wrapper.combatResult(uniteAttaque, uniteDef, 3, 3, 5);
uniteAttaque = resCombat[0];
uniteDef = resCombat[1];
if (uniteAttaque > 0)
{
if (uniteDef > 0)
resDuCombat[1] = true; //Atq vivant, Def vivant = match null
else
resDuCombat[0] = true; // Atq vivant, Def mort = victoire attaquant
}
else
resDuCombat[2] = true; // Atq mort = victoire def
cpt++;
resFinal = resDuCombat[0] && resDuCombat[1];
}//while
bool b = cpt < 500;
Assert.IsTrue(b); // On verifie que le defenseur a au moins une chance de faire match nul
}
[TestMethod]
public void TestMethodPartie()
{
System.Collections.Generic.Dictionary<String,int> players = new System.Collections.Generic.Dictionary<String,int>();
// /!\ Pb de conception = Joueur demande un Peuple pour etre creer et Peuple demande un joueur ...
players.Add("Tom",1);
players.Add("Fab",2);
Partie partie = new PartieConcret(5, players);
Assert.AreEqual(partie.Joueurs[0].Name, "Tom");
}
}
}
|
77ae95fb76e41a6dd3d76058b6f5f396de66f88e
|
C#
|
kdeng00/DotnetAndCPP
|
/Program.cs
| 2.90625
| 3
|
using System;
using System.Runtime.InteropServices;
namespace DotnetAndCPP
{
class Program
{
static void Main(string[] args)
{
var a = 54;
var b = 23;
var result = add(a, b);
Console.WriteLine($"a: {a} + b: {b} = {result}");
}
[DllImport("libTestExample.so")]
public static extern int add(int a, int b);
}
}
|
96822bcd94b31d86369900a87d61fb70a604c1e6
|
C#
|
sweep3r/Myra
|
/src/Myra/Graphics2D/Text/TextLine.cs
| 2.734375
| 3
|
using Myra.Utility;
using System;
#if !XENKO
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
#else
using Xenko.Core.Mathematics;
using Xenko.Graphics;
#endif
namespace Myra.Graphics2D.Text
{
public class TextLine
{
protected string _text;
protected readonly SpriteFont _spriteFont;
protected Point _size;
public int Count
{
get { return _text.Length(); }
}
public string Text
{
get { return _text; }
}
public Point Size
{
get
{
return _size;
}
}
public int? UnderscoreIndex { get; set; }
public int LineIndex
{
get; internal set;
}
public int Top
{
get; internal set;
}
public int LineStart
{
get; internal set;
}
public TextLine(SpriteFont font, string text, Point size)
{
if (font == null)
{
throw new ArgumentNullException("font");
}
_spriteFont = font;
_text = text;
_size = size;
}
public virtual void Draw(SpriteBatch batch, Point pos, Color color, float opacity = 1.0f)
{
batch.DrawString(_spriteFont, _text, new Vector2(pos.X, pos.Y), color * opacity);
}
}
}
|
6b43ad46313c111be9d5085c73e88b93c76e63b7
|
C#
|
rcody720/JohnForteLibraryBackEnd
|
/JohnForteLibrary.Domain/ValueObjects/PhoneNumber.cs
| 3.390625
| 3
|
using CSharpFunctionalExtensions;
using System;
using System.Collections.Generic;
using System.Text;
namespace JohnForteLibrary.Domain.ValueObjects
{
public class PhoneNumber : SimpleValueObject<string>
{
private PhoneNumber(string value) : base(value) { }
public static Result<PhoneNumber> Create(string number)
{
if (string.IsNullOrEmpty(number))
{
return Result.Success(new PhoneNumber(number));
}
var numberOfDashesAndParenthesese = 0;
foreach (char c in number)
if (c == '-' || c == '(' || c == ')') numberOfDashesAndParenthesese++;
var numberOfDigits = number.Length - numberOfDashesAndParenthesese;
if (numberOfDigits != 10)
return Result.Failure<PhoneNumber>("Phone number should be 10 digits in length.");
string newNumber = number.Replace("-", "").Replace("(", "").Replace(")", "");
long longNumber = 0;
bool result = long.TryParse(newNumber, out longNumber);
if (!result)
return Result.Failure<PhoneNumber>("Phone Number must be in a valid format: only use numbers with dashes and parenthesese");
return Result.Success(new PhoneNumber(number));
}
}
}
|
2660b387f1f7e363b90c95be5f3f396c6cbad068
|
C#
|
ischool-desktop/ischedulePreprocess
|
/dylan/分割設定/frmAssignSplitSpec.cs
| 2.546875
| 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;
using FISCA.Presentation.Controls;
namespace Sunset.NewCourse
{
public partial class frmAssignSplitSpec : FISCA.Presentation.Controls.BaseForm
{
int _period { get; set; }
public frmAssignSplitSpec(int period)
{
InitializeComponent();
_period = period;
lbHelp1.Text = "所選課程節數為:" + _period.ToString();
}
public bool IsCreateCourseSection { get { return chkCreateCourseSection.Checked; } }
public string SplitSpec { get { return txtSplitSpec.Text; } }
private void txtSplitSpec_TextChanged(object sender, EventArgs e)
{
errSplitSpec.Clear();
if (!string.IsNullOrEmpty(txtSplitSpec.Text))
{
int a;
int TotalLen = 0;
string[] Specs = txtSplitSpec.Text.Split(new char[] { ',' });
for (int i = 0; i < Specs.Length; i++)
{
//每一個值都必須是數字型態
if (!int.TryParse(Specs[i], out a))
errSplitSpec.SetError(txtSplitSpec, "必須為以逗號分隔的數字組合\n例如:4節之課程,可分割為[2,2]或[2,1,1]");
else
TotalLen += a;
}
if (TotalLen != _period)
{
errSplitSpec.SetError(txtSplitSpec, "分割設定與節次不符!");
}
}
else
{
//如果是空值,則提示輸入內容
errSplitSpec.SetError(txtSplitSpec, "請輸入分割設定!");
}
}
private void btnOK_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(errSplitSpec.GetError(txtSplitSpec)))
MsgBox.Show("分割設定有誤\n請修正後再儲存!");
else
this.DialogResult = System.Windows.Forms.DialogResult.OK;
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.No;
}
}
}
|
a4fc453a824c549e42f4f5e7ab352ce50b7ebe30
|
C#
|
bubdm/StructLinq
|
/src/StructLinq.Benchmark/ToArrayOnArraySelect.cs
| 2.8125
| 3
|
using System.Linq;
using BenchmarkDotNet.Attributes;
namespace StructLinq.Benchmark
{
[DisassemblyDiagnoser(4), MemoryDiagnoser]
public class ToArrayOnArraySelect
{
private const int Count = 10000;
private readonly int[] array;
public ToArrayOnArraySelect()
{
array = Enumerable.Range(0, Count).ToArray();
}
[Benchmark(Baseline = true)]
public int[] Linq() => array
.Select(x => x * 2)
.ToArray();
[Benchmark]
public int[] StructLinq() => array
.ToStructEnumerable()
.Select(x => x * 2)
.ToArray();
[Benchmark]
public int[] StructLinqZeroAlloc() => array
.ToStructEnumerable()
.Select(x => x * 2)
.ToArray(x=>x);
[Benchmark]
public int[] StructLinqWithFunction()
{
var select = new SelectFunction();
return array
.ToStructEnumerable()
.Select(ref @select, x=>x, x=>x)
.ToArray(x=>x);
}
}
}
|
285d07c830318a8ff53269b3dee07f1b04a20de1
|
C#
|
teodory/SoftUni-Homeworks
|
/[HomeworK] OOP CS/HomeworkEncapsulationAndPolymorphism/_03_GameEngine/Items/Injection.cs
| 2.9375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _03_GameEngine.Items
{
class Injection : Bonus
{
//Injection – Bonus item with HealthEffect of 200 for 3 turns.
//If a character's health points fall under 1 after the
//bonus times out (and is removed), his/her health points become 1.
public Injection(string id)
:base(id, 200, 0, 0, 3)
{
}
}
}
|
dcd4eb112ec40dc9a06a66e2244f42a10daade16
|
C#
|
isaac109/mainframe-tbs-engine
|
/CSharp/FeldmansGame/FeldmansGame/Core/GridSpace.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mainframe.Core.Units;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Mainframe.Constants;
using Mainframe.Animations;
using Mainframe.Core.Combat;
using Mainframe.Animations.Environment;
namespace Mainframe.Core
{
/// <summary>
/// A single space on which cover/characters can reside.
/// </summary>
public class GridSpace
{
protected Actor currentActor;
protected Sprite spaceSprite, minimapSprite;
protected bool isOccupied, availableFlag; //isOccupied stores whether currentActor currently points to a value. availableFlag indicates whether this space is marked by the grid to be highlighted.
protected int moveCost, elevation, spaceType;
protected Vector2 gridPos;
protected Grid parent;
protected List<SpaceProjectile> projectilesInSpace;
protected Wall[] walls;
/// <summary>
/// Enumerator used for tracking different sprite columns for animation purposes.
/// </summary>
private enum AnimationColumns
{
normal = 0,
puzzleActive,
}
/// <summary>
/// Default constructor for an un-positioned gridspace
/// </summary>
/// <param name="parentGrid">Grid of which to be a technical, but undrawn and inaccessible, member.</param>
public GridSpace(Grid parentGrid)
{
currentActor = null;
isOccupied = false;
moveCost = 1;
parent = parentGrid;
walls = new Wall[3];
}
/// <summary>
/// Creates a grid space that considers itself at position (posX, posY) in the parent grid.
/// </summary>
/// <param name="spaceTypeSelector">Chooses the texture for this space. Does not affect the properties of it otherwise.</param>
/// <param name="posX">Horizontal position in the grid</param>
/// <param name="posY">Vertical position in the grid</param>
/// <param name="elevation"></param>
/// <param name="Parent"></param>
public GridSpace(int spaceTypeSelector, int posX, int posY, int elevation, Grid Parent)
{
EnvironmentTextureHolder holder = EnvironmentTextureHolder.Holder;
currentActor = null;
isOccupied = false;
moveCost = 1;
parent = Parent;
projectilesInSpace = new List<SpaceProjectile>();
gridPos = new Vector2(posX, posY);
spaceSprite = holder.MainHexagonSprites[spaceTypeSelector].copySprite();
minimapSprite = holder.MinimapHexagonSprites[spaceTypeSelector].copySprite();
spaceType = spaceTypeSelector;
walls = new Wall[3];
for (int i = 0; i < 3; ++i)
{
walls[i] = new Wall();
}
this.elevation = elevation;
}
#region Updating
/// <summary>
/// Runs frame to frame management operations.
/// </summary>
public void Update()
{
foreach (SpaceProjectile proj in projectilesInSpace)
{
proj.Update();
if (proj.DeleteFlag)
{
projectilesInSpace.Remove(proj);
}
}
}
#endregion
#region Interaction
/// <summary>
/// Look for an actor in this space.
/// </summary>
/// <returns>The actor in this space, or null.</returns>
public Actor tryGetActor()
{
if (isOccupied)
return currentActor;
return null;
}
/// <summary>
/// Attempts to put an actor in this space.
/// </summary>
/// <param name="newOccupant">Actor to be placed</param>
/// <returns>True if the space was empty and now has the new occupant, false if it was already occupied.</returns>
public bool tryPutActor(Actor newOccupant)
{
if (!isOccupied)
{
currentActor = newOccupant;
currentActor.setParent(parent);
currentActor.setPosition(gridPos);
}
else
return false;
isOccupied = true;
return true;
}
/// <summary>
/// Get rid of the actor in this space.
/// </summary>
/// <returns>The removed actor</returns>
public Actor removeActor()
{
Actor toReturn = currentActor;
isOccupied = false;
currentActor = null;
return toReturn;
}
/// <summary>
/// Puts a projectile into this space to be drawn.
/// </summary>
/// <param name="newProj">The new Projectile to be inserted.</param>
public void AddProjectile(SpaceProjectile newProj)
{
projectilesInSpace.Add(newProj);
}
#endregion
#region Drawing
/// <summary>
/// Draws all of the space's sprites, then if it's occupied, its occupant's sprites.
/// </summary>
/// <param name="batch">Main game spritebatch.</param>
/// <param name="drawPos">Top left corner from which to draw</param>
public void draw(SpriteBatch batch, Vector2 drawPos)
{
spaceSprite.Draw(batch, new Rectangle((int)drawPos.X, (int)drawPos.Y,
(int)ConstantHolder.HexagonGrid_HexSizeX, spaceSprite.SpriteSizeY), availableFlag ? Color.YellowGreen : Color.White);
for (int i = 0; i < 3; ++i)
{
walls[i].Draw(batch, drawPos);
}
if (isOccupied)
{
CurrentActor.Draw(batch);
}
foreach(SpaceProjectile proj in projectilesInSpace)
{
proj.Draw(batch, drawPos);
}
}
public void drawMinimap(SpriteBatch batch, Vector2 drawPos, Vector2 dimensions)
{
minimapSprite.Draw(batch, new Rectangle((int) drawPos.X, (int) drawPos.Y, (int) dimensions.X, (int) dimensions.Y));
if (isOccupied)
{
currentActor.DrawMinimap(batch, drawPos, dimensions);
}
}
#endregion
#region Accessors/Mutators
public Actor CurrentActor
{
get { return currentActor; }
}
public int SpaceType
{
get { return spaceType; }
}
public bool IsOccupied
{
get { return isOccupied; }
}
public Vector2 GridPosition
{
get { return gridPos; }
}
public int Elevation
{
get { return elevation; }
}
public bool AvailableFlag
{
get { return availableFlag; }
set { availableFlag = value; }
}
public Wall[] Walls
{
get { return walls; }
}
#endregion
}
}
|
8af50b90040aa24e8510346479819e41b213079c
|
C#
|
mxprshn/NumMethods
|
/NumericMethods/NumAn/Objects/Matrix.cs
| 3.34375
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace NumAn
{
/// <summary>
/// 2D matrix with real elements
/// </summary>
public class Matrix
{
private double[,] elements;
/// <summary>
/// Number of rows in the matrix
/// </summary>
public int Height => elements.GetLength(0);
/// <summary>
/// Number of columns in matrix
/// </summary>
public int Width => elements.GetLength(1);
public double this[int row, int column] => elements[row, column];
private double? determinant = null;
/// <summary>
/// Calculates if needed and returns the determinant of the matrix. Determinant is calculated with LU-decomposition
/// </summary>
public double Determinant
{
get
{
if (determinant.HasValue)
{
return determinant.Value;
}
try
{
var (l, u) = MatrixUtils.LuDecomposition(this);
var product = 1.0;
for (var i = 0; i < l.Height; ++i)
{
product *= l[i, i];
}
determinant = product;
}
catch (MatrixUtils.LuZeroDiagonalElementException)
{
determinant = 0.0;
}
return determinant.Value;
}
}
private double? frobeniusNorm = null;
/// <summary>
/// Calculates if needed and returns the Frobenius norm of the matrix
/// </summary>
public double FrobeniusNorm
{
get
{
if (frobeniusNorm.HasValue)
{
return frobeniusNorm.Value;
}
var sum = 0.0;
for (var i = 0; i < Height; ++i)
{
for (var j = 0; j < Width; ++j)
{
sum += Math.Pow(Math.Abs(elements[i, j]), 2.0);
}
}
frobeniusNorm = Math.Sqrt(sum);
return frobeniusNorm.Value;
}
}
public Matrix(double[,] elements)
{
this.elements = new double[elements.GetLength(0), elements.GetLength(1)];
for (var i = 0; i < elements.GetLength(0); ++i)
{
for (var j = 0; j < elements.GetLength(1); ++j)
{
this.elements[i, j] = elements[i, j];
}
}
}
private Matrix inverse = null;
/// <summary>
/// Calculates if needed and returns inverse for the matrix. Inverse is calculated with Jordan decomposition
/// </summary>
/// <exception cref="SingularMatrixException">Matrix is singular and has no invrese</exception>
/// <returns>Inverse for the matrix</returns>
public Matrix Inverse()
{
if (Height != Width)
{
throw new ArgumentException("System matrix must be square");
}
if (Determinant == 0.0)
{
throw new SingularMatrixException();
}
if (inverse != null)
{
return inverse;
}
var identity = Identity(Height);
inverse = SystemSolving.SystemSolver.Jordan(this, identity);
return inverse;
}
private double? conditionNumber = null;
/// <summary>
/// Calculates if needed and returns condition number of the matrix
/// </summary>
/// <returns>Condition number of the matrix</returns>
public double ConditionNumber()
{
if (conditionNumber.HasValue)
{
return conditionNumber.Value;
}
conditionNumber = FrobeniusNorm * Inverse().FrobeniusNorm;
return conditionNumber.Value;
}
/// <summary>
/// Multiplies elements of the matrix by scalar real value
/// </summary>
/// <param name="scalar">Scalar to multiply matrix to</param>
/// <returns>Result matrix</returns>
public Matrix MultiplyByScalar(double scalar)
{
var result = new double[Height, Width];
for (var i = 0; i < Height; ++i)
{
for (var j = 0; j < Width; ++j)
{
result[i, j] = scalar * this[i, j];
}
}
return new Matrix(result);
}
/// <summary>
/// Adds a matrix to this matrix
/// </summary>
/// <param name="other">Matrix to add</param>
/// <returns>Sum of matrices</returns>
public Matrix Add(Matrix other)
{
if (other.Width != Width || other.Height != Height)
{
throw new ArgumentException("Incompatible matrix dimensions.");
}
var result = new double[Height, Width];
for (var i = 0; i < Height; ++i)
{
for (var j = 0; j < Width; ++j)
{
result[i, j] = other[i, j] + this[i, j];
}
}
return new Matrix(result);
}
/// <summary>
/// Right multiply this matrix by another
/// </summary>
/// <param name="other">Matrix to multiply this matrix to</param>
/// <returns>Matrix product</returns>
public Matrix RightMultiply(Matrix other)
{
if (other.Height != Width)
{
throw new ArgumentException("Incompatible matrix dimensions.");
}
var result = new double[Height, other.Width];
for (var i = 0; i < Height; ++i)
{
for (var j = 0; j < other.Width; ++j)
{
var sum = 0.0;
for (var k = 0; k < Width; ++k)
{
sum += this[i, k] * other[k, j];
}
result[i, j] = sum;
}
}
return new Matrix(result);
}
public override string ToString() => elements.Format();
public static Matrix operator *(double scalar, Matrix matrix)
{
return matrix.MultiplyByScalar(scalar);
}
public static Matrix operator *(Matrix matrix, double scalar)
{
return matrix.MultiplyByScalar(scalar);
}
public static Matrix operator *(Matrix one, Matrix another)
{
return one.RightMultiply(another);
}
public static Matrix operator +(Matrix one, Matrix another)
{
return one.Add(another);
}
public static Matrix operator -(Matrix one, Matrix another)
{
return one.Add(-1 * another);
}
/// <summary>
/// Creates identity matrix of given size
/// </summary>
/// <param name="size">Size of the matrix to create</param>
/// <returns>Identity matrix</returns>
public static Matrix Identity(int size)
{
var elements = new double[size, size];
for (var i = 0; i < size; ++i)
{
elements[i, i] = 1.0;
}
return new Matrix(elements);
}
[Serializable]
public class SingularMatrixException : Exception
{
public SingularMatrixException() { }
public SingularMatrixException(string message) : base(message) { }
public SingularMatrixException(string message, Exception inner) : base(message, inner) { }
protected SingularMatrixException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
}
}
|
8d560ed4c086e8f31a6ee6b1a8bcba594bd2de67
|
C#
|
CrazyPandaLimited/assets-system
|
/Runtime/Manifests/AssetBundles/GameAssetType.cs
| 2.75
| 3
|
namespace CrazyPanda.UnityCore.AssetsSystem
{
/// <summary>
/// Game asset type discryptor
/// </summary>
public class GameAssetType
{
/// <summary>
/// Gets or sets the tag.
/// </summary>
/// <value>
/// The tag.
/// </value>
public string Tag { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="GameAssetType"/> class.
/// </summary>
/// <param name="tag">The tag.</param>
public GameAssetType( string tag )
{
Tag = tag;
}
/// <summary>
/// Initializes a new instance of the <see cref="GameAssetType"/> class.
/// </summary>
public GameAssetType() : this( string.Empty )
{
}
}
}
|
717002b2387f3adf3213dfba742f9935026e9061
|
C#
|
Kintaro/Art
|
/Art.Core/Interfaces/ISampler.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Art.Core.Geometry;
namespace Art.Core.Interfaces
{
/// <summary>
///
/// </summary>
public abstract class ISampler
{
/// <summary>
///
/// </summary>
public readonly int xPixelStart;
/// <summary>
///
/// </summary>
public readonly int xPixelEnd;
/// <summary>
///
/// </summary>
public readonly int yPixelStart;
/// <summary>
///
/// </summary>
public readonly int yPixelEnd;
/// <summary>
///
/// </summary>
public readonly int SamplesPerPixel;
/// <summary>
///
/// </summary>
public readonly double ShutterOpen;
/// <summary>
///
/// </summary>
public readonly double ShutterClose;
/// <summary>
///
/// </summary>
/// <param name="sample"></param>
/// <returns></returns>
public abstract int GetMoreSamples (Sample[] sample);
/// <summary>
///
/// </summary>
/// <param name="sample"></param>
/// <returns></returns>
public abstract Task<int> GetMoreSamplesAsync (Sample[] sample);
/// <summary>
///
/// </summary>
/// <param name="num"></param>
/// <param name="count"></param>
/// <returns></returns>
public abstract ISampler GetSubSampler (int num, int count);
/// <summary>
///
/// </summary>
/// <param name="size"></param>
/// <returns></returns>
public abstract int RoundSize (int size);
/// <summary>
///
/// </summary>
public abstract int MaximumSampleCount { get; }
/// <summary>
///
/// </summary>
/// <param name="num"></param>
/// <param name="count"></param>
/// <param name="xstart"></param>
/// <param name="xend"></param>
/// <param name="ystart"></param>
/// <param name="yend"></param>
protected void ComputeSubWindow (int num, int count, ref int xstart, ref int xend, ref int ystart, ref int yend)
{
var dx = xPixelEnd - xPixelStart;
var dy = yPixelEnd - yPixelStart;
var nx = count;
var ny = 1;
while ((nx & 0x1) == 0 && 2 * dx * ny < dy * nx)
{
nx >>= 1;
ny <<= 1;
}
Debug.Assert (nx * ny == count);
var xo = num % nx;
var yo = num / nx;
var tx0 = (double) xo / (double)nx;
var tx1 = (double)(xo + 1) / (double)nx;
var ty0 = (double) yo / (double)ny;
var ty1 = (double)(yo + 1) / (double)ny;
xstart = Util.Floor2Int (Util.Lerp (tx0, xPixelStart, xPixelEnd));
xend = Util.Floor2Int (Util.Lerp (tx1, xPixelStart, xPixelEnd));
ystart = Util.Floor2Int (Util.Lerp (ty0, yPixelStart, yPixelEnd));
yend = Util.Floor2Int (Util.Lerp (ty1, yPixelStart, yPixelEnd));
}
}
}
|
5dd1a2671d2d9ac2fdabcae64e95220b5e25c21d
|
C#
|
SparkDevNetwork/Rock
|
/Rock/Financial/FinancialGivingAnalyticsFrequencyLabel.cs
| 2.578125
| 3
|
// <copyright>
// Copyright by the Spark Development Network
//
// Licensed under the Rock Community License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.rockrms.com/license
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//
using System.ComponentModel;
namespace Rock.Financial
{
/// <summary>
/// Frequency Labels:
/// <list>
/// <item>
/// Weekly = Avg days between 4.5 - 8.5; Std Dev < 7;
/// </item>
/// <item>
/// Bi-Weekly = Avg days between 9 - 17; Std Dev < 10;
/// </item>
/// <item>
/// Monthly = Avg days between 25 - 35; Std Dev < 10;
/// </item>
/// <item>
/// Quarterly = Avg days between 80 - 110; Std Dev < 15;
/// </item>
/// <item>
/// Erratic = Freq Avg / 2 < Std Dev
/// </item>
/// <item>
/// Undetermined = Everything else
/// </item>
/// </list>
/// </summary>
public enum FinancialGivingAnalyticsFrequencyLabel
{
/// <summary>
/// Weekly Avg days between 4.5 - 8.5; Std Dev < 7;
/// </summary>
[Description( "Weekly" )]
Weekly = 1,
/// <summary>
/// Bi-Weekly: Avg days between 9 - 17; Std Dev < 10;
/// </summary>
[Description( "Bi-Weekly" )]
BiWeekly = 2,
/// <summary>
/// Monthly: Avg days between 25 - 35; Std Dev < 10;
/// </summary>
[Description( "Monthly" )]
Monthly = 3,
/// <summary>
/// Quarterly - Avg days between 80 - 110; Std Dev < 15;
/// </summary>
[Description( "Quarterly" )]
Quarterly = 4,
/// <summary>
/// Erratic: Freq Avg / 2 < Std Dev
/// </summary>
[Description( "Erratic" )]
Erratic = 5,
/// <summary>
/// Undetermined: Everything else
/// </summary>
[Description( "Undetermined" )]
Undetermined = 6
}
}
|
10e391571ea265ccda4e630ae84a21e9b68c59f3
|
C#
|
iwhitmor/tic-tac-toe
|
/Lab04_TicTacToe/Lab04_TicTacToe/Program.cs
| 3.875
| 4
|
using System;
using Lab04_TicTacToe.Classes;
namespace Lab04_TicTacToe
{
class Program
{
static void Main(string[] args)
{
Board board = new Board();
StartGame();
}
static void StartGame()
{
// TODO: Setup your game. Create a new method that creates your players and instantiates the game class. Call that method in your Main method.
// You are requesting a Winner to be returned, Determine who the winner is output the celebratory message to the correct player. If it's a draw, tell them that there is no winner.
Console.WriteLine("What is your name player one?");
string inputName1 = Console.ReadLine();
Console.WriteLine("What is your name player two?");
string inputName2 = Console.ReadLine();
Player p1 = new Player();
p1.Marker = "X";
p1.Name = inputName1;
p1.IsTurn = true;
Player p2 = new Player();
p2.Marker = "O";
p2.Name = inputName2;
Game game = new Game(p1, p2);
game.Board.DisplayBoard();
Player winner = game.Play();
if (winner == null)
{
Console.WriteLine("Tie game, play again");
}
else
Console.WriteLine($"Congrats {winner.Name}");
}
}
}
|
79037b0d3b497b11e69212b14c6622cac85a382a
|
C#
|
killingerr/Rosella
|
/4.12.cs
| 3.625
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment
{
class Invoice
{
static void Main(string[] args)
{
int quantity = 0;
double price = 0;
// Invoice class object with required parameters
InvoiceClass myInvoice = new InvoiceClass("item number","item description",quantity,price);
Console.WriteLine("Enter quantity:");
quantity = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter price:");
price = Convert.ToDouble(Console.ReadLine());
myInvoice.GetInvoice(quantity, price); // Class method used for calculating item price
}
}
}
|
0588f241a340a60fbf12bb10adae9724885bad4f
|
C#
|
lostm1nd/TelerikAcademy
|
/10DataStructuresAndAlgorithms/HOMEWORK/10DynamicProgramming/Tribonnaci/Program.cs
| 3.796875
| 4
|
namespace Tribonnaci
{
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
string[] input = Console.ReadLine().Split(' ');
int count = int.Parse(input[3]);
LinkedList<decimal> tribonnaci = new LinkedList<decimal>();
for (int i = 0; i < input.Length - 1; i++)
{
tribonnaci.AddLast(decimal.Parse(input[i]));
}
if (count <= tribonnaci.Count)
{
var node = tribonnaci.First;
for (int i = 1; i < count; i++)
{
node = node.Next;
}
Console.WriteLine(node.Value);
}
else
{
for (int i = tribonnaci.Count; i < count; i++)
{
decimal next = tribonnaci.First.Value + tribonnaci.First.Next.Value + tribonnaci.First.Next.Next.Value;
tribonnaci.RemoveFirst();
tribonnaci.AddLast(next);
}
Console.WriteLine(tribonnaci.Last.Value);
}
}
}
}
|
e9494a75c1e91fa2febd6e13799a627fd1d67347
|
C#
|
kaiclemente/ShopTest
|
/ShopBackEnd.Repository/Base/Repository.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace ShopBackEnd.Repository
{
public abstract class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
private readonly IDbContext _context;
private readonly IDbSet<TEntity> _dbSet;
protected IDbContext Context { get { return _context; } }
protected IDbSet<TEntity> DbSet { get { return _dbSet; } }
protected Repository(IDbContext context)
{
_context = context;
_dbSet = context.Set<TEntity>();
}
public virtual TEntity FindById(object id)
{
return _dbSet.Find(id);
}
public virtual IEnumerable<TEntity> GetAll()
{
return _dbSet.ToList();
}
public virtual void Update(TEntity entity)
{
_dbSet.Attach(entity);
}
public virtual void Delete(object id)
{
var entity = _dbSet.Find(id);
var objectState = entity as IObjectState;
if (objectState != null)
objectState.State = ObjectState.Deleted;
Delete(entity);
}
public virtual void Delete(TEntity entity)
{
_dbSet.Attach(entity);
_dbSet.Remove(entity);
}
public virtual void Insert(TEntity entity)
{
_dbSet.Attach(entity);
}
public virtual RepositoryQuery<TEntity> Query()
{
var repositoryGetFluentHelper =
new RepositoryQuery<TEntity>(this);
return repositoryGetFluentHelper;
}
internal IQueryable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>,
IOrderedQueryable<TEntity>> orderBy = null,
List<Expression<Func<TEntity, object>>>
includeProperties = null,
int? page = null,
int? pageSize = null)
{
IQueryable<TEntity> query = _dbSet;
if (includeProperties != null)
includeProperties.ForEach(i => { query = query.Include(i); });
if (filter != null)
query = query.Where(filter);
if (orderBy != null)
query = orderBy(query);
if (page != null && pageSize != null)
query = query
.Skip((page.Value - 1) * pageSize.Value)
.Take(pageSize.Value);
return query;
}
}
}
|
f3af6cbc0de379d1f557e2ed022773b2c307701d
|
C#
|
anasem007/QA-Automation-Lab-iTechArt
|
/ArraysAndCollections/ArraysAndCollections/Sorting/MergeSort.cs
| 3.734375
| 4
|
using System.Collections.Generic;
using System.Linq;
namespace ArraysAndCollections.Sorting
{
public static class MergeSort
{
public static int[] MSort(int[] array)
{
if (array.Length == 1)
return array;
var middleIndex = array.Length / 2;
return Merge(MSort(array.Take(middleIndex).ToArray()), MSort(array.Skip(middleIndex).ToArray()));
}
private static int[] Merge(IReadOnlyList<int> firstArray, IReadOnlyList<int> secondArray)
{
var firstArrayIndex = 0;
var secondArrayIndex = 0;
var mergedArray = new int[firstArray.Count + secondArray.Count];
for (var i = 0; i < firstArray.Count + secondArray.Count; i++)
{
switch (secondArrayIndex < secondArray.Count)
{
case true when firstArrayIndex < firstArray.Count:
{
if (firstArray[firstArrayIndex] > secondArray[secondArrayIndex])
mergedArray[i] = secondArray[secondArrayIndex++];
else
mergedArray[i] = firstArray[firstArrayIndex++];
break;
}
case true:
mergedArray[i] = secondArray[secondArrayIndex++];
break;
default:
mergedArray[i] = firstArray[firstArrayIndex++];
break;
}
}
return mergedArray;
}
}
}
|
f0834c42f311bde683b6c7375975d39727092ee8
|
C#
|
V-Uzunov/Soft-Uni-Education
|
/05.DatabasesAdvancedEntityFramework/05.EFRelation/02.Photographer/Data/DBSeed.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _02.Photographer.Data
{
class DBSeed
{
class DbInitializerPhotographerContext : DropCreateDatabaseAlways<PhotographerContext>
{
protected override void Seed(PhotographerContext context)
{
Console.WriteLine($"Seeding...");
Photographer photographer01 = new Photographer("Ivan", "ivanEp1ChO7Klass4!%@", "ivan@softuni.bg");
Photographer photographer02 = new Photographer("Maria", "B1nag1C4gl4sn4$@#", "mimi69@gola.sam");
Photographer photographer03 = new Photographer("Pesho", "Sn1m4mS1Br4t**", "pepi@abv.gg");
Photographer photographer04 = new Photographer("FourStar", "asfuij8h7**", "four@five.bg");
Album album1 = new Album("Summer 2017", "Blue", true);
Album album2 = new Album("Winter 2017", "White", true);
Album album3 = new Album("Dubai 2017", "Sandy", false);
Album album4 = new Album("Private", "Black and red", false);
Picture picture1 = new Picture("Pic001", "PrivatePic001", $"/root/Pictures/Pic001");
Picture picture2 = new Picture("Pic002", "PrivatePic002", $"/root/Pictures/Pic002");
Picture picture3 = new Picture("Pic003", "PrivatePic003", $"/root/Pictures/Pic003");
Picture picture4 = new Picture("Pic004", "PrivatePic004", $"/root/Pictures/Pic004");
Picture picture5 = new Picture("Pic005", "PrivatePic005", $"/root/Pictures/Pic005");
Picture picture6 = new Picture("Pic006", "PrivatePic006", $"/root/Pictures/Pic006");
Picture picture7 = new Picture("Pic007", "PrivatePic007", $"/root/Pictures/Pic007");
Tag tag1 = new Tag("#CS");
Tag tag2 = new Tag("#CSharp");
Tag tag3 = new Tag("#.NET");
Tag tag4 = new Tag("#EntityFramework");
album1.Pictures.Add(picture1);
album1.Pictures.Add(picture2);
album1.Pictures.Add(picture3);
album1.Pictures.Add(picture4);
album1.Pictures.Add(picture5);
album1.Pictures.Add(picture6);
album1.Pictures.Add(picture7);
album2.Pictures.Add(picture1);
album2.Pictures.Add(picture2);
album2.Pictures.Add(picture3);
album2.Pictures.Add(picture4);
album3.Pictures.Add(picture5);
album3.Pictures.Add(picture6);
album3.Pictures.Add(picture7);
album4.Pictures.Add(picture7);
album1.Tags.Add(tag1);
album1.Tags.Add(tag2);
album2.Tags.Add(tag1);
album2.Tags.Add(tag2);
album2.Tags.Add(tag3);
album3.Tags.Add(tag1);
album3.Tags.Add(tag2);
album3.Tags.Add(tag3);
album3.Tags.Add(tag4);
album4.Tags.Add(tag1);
photographer01.Albums.Add(album1);
photographer01.Albums.Add(album2);
photographer02.Albums.Add(album3);
// The migration for uniq album owner is located here: ./Migrations/201703091822532_SingleAlbum.cs
// It is commented out for easy further DB use
//photographer03.Albums.Add(album3);
photographer04.Albums.Add(album4);
Console.WriteLine($"Seeding Photographers..");
context.Photographers.AddOrUpdate(x => x.Username, photographer01);
context.Photographers.AddOrUpdate(x => x.Username, photographer02);
context.Photographers.AddOrUpdate(x => x.Username, photographer03);
context.Photographers.AddOrUpdate(x => x.Username, photographer04);
context.SaveChanges();
Console.WriteLine($"Seeding Albums..");
context.Albums.AddOrUpdate(x => x.Name, album1);
context.Albums.AddOrUpdate(x => x.Name, album2);
context.Albums.AddOrUpdate(x => x.Name, album3);
context.Albums.AddOrUpdate(x => x.Name, album4);
context.SaveChanges();
Console.WriteLine($"Seeding Pictures..");
context.Pictures.AddOrUpdate(x => x.Title, picture1);
context.Pictures.AddOrUpdate(x => x.Title, picture2);
context.Pictures.AddOrUpdate(x => x.Title, picture3);
context.Pictures.AddOrUpdate(x => x.Title, picture4);
context.Pictures.AddOrUpdate(x => x.Title, picture5);
context.Pictures.AddOrUpdate(x => x.Title, picture6);
context.Pictures.AddOrUpdate(x => x.Title, picture7);
context.SaveChanges();
Console.WriteLine($"Seeding Tags..");
context.Tags.AddOrUpdate(x => x.TagName, tag1);
context.Tags.AddOrUpdate(x => x.TagName, tag2);
context.Tags.AddOrUpdate(x => x.TagName, tag3);
context.Tags.AddOrUpdate(x => x.TagName, tag4);
context.SaveChanges();
base.Seed(context);
}
}
}
}
|
b8e5684bffed33dae750ac8cd4f145d906616938
|
C#
|
bickeylam/ps-selenium
|
/MyTester.Test/Tests/NonBrowserBasedTest.cs
| 2.578125
| 3
|
namespace MyTester.Test.Tests
{
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
[TestClass]
public class NonBrowserBasedTest
{
public TestContext TestContext { get; set; }
[TestInitialize]
public void BeforeTest()
{
}
[TestCleanup]
public void AfterTest()
{
}
[DataTestMethod]
[DataRow(1, 2, 3)]
[TestCategory("smoke")]
public void GivenTwoNumbersWhenAddThenResultCalculated(int a, int b, int expected)
{
int actual = a + b;
Assert.AreEqual<int>(expected, actual);
TestContext.WriteLine($@"Result: {actual}");
Debug.WriteLine($@"Debug: {actual}");
Trace.WriteLine($@"Trace: {actual}");
}
}
}
|
97adee36ed7371c12dfde97301f5ef9abaeb23c5
|
C#
|
xiaoningning/dotnet-algorithm-2020
|
/FindMaxLength/Program.cs
| 3.8125
| 4
|
using System;
using System.Collections.Generic;
namespace FindMaxLength
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("0/1 array: {0}", args[0]);
int[] nums = Array.ConvertAll(args[0].Split(','), s => int.Parse(s));
Console.WriteLine("max length of equal of 0, 1: {0}", FindMaxLength(nums));
}
static int FindMaxLength(int[] nums) {
// key: sum, value: index
Dictionary<int, int> map = new Dictionary<int, int>();
int sum = 0;
int maxLen = 0;
map[0] = -1; // initial position of equal of 0/1
for(int i = 0; i < nums.Length; i++){
sum += nums[i] == 1 ? 1 : -1;
if (map.ContainsKey(sum)){
maxLen = Math.Max(maxLen, i - map[sum]);
}
else{
map[sum] = i;
}
}
return maxLen;
}
}
}
|
8db180346dab15af432100c26508bf5fbf204946
|
C#
|
jamesconsultingllc/AspectCentral.Abstractions
|
/AspectCentral.Abstractions/Configuration/AspectConfigurationEntry.cs
| 2.71875
| 3
|
// ----------------------------------------------------------------------------------------------------------------------
// <copyright file="AspectConfigurationEntry.cs" company="James Consulting LLC">
// Copyright (c) 2019 All Rights Reserved
// </copyright>
// <author>Rudy James</author>
// <summary>
//
// </summary>
// ----------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using JamesConsulting.Reflection;
namespace AspectCentral.Abstractions.Configuration
{
/// <summary>
/// The aspect configuration.
/// </summary>
public class AspectConfigurationEntry : IEqualityComparer<AspectConfigurationEntry?>
{
/// <summary>
/// Gets or sets the methods to intercept.
/// </summary>
private List<MethodInfo> methodsToIntercept;
/// <summary>
/// Initializes a new instance of the <see cref="AspectConfigurationEntry" /> class.
/// </summary>
/// <param name="aspectType">
/// The aspect factory type.
/// </param>
/// <param name="sortOrder">
/// The sort Order.
/// </param>
/// <param name="methodsToIntercept">
/// The methods To Intercept.
/// </param>
internal AspectConfigurationEntry(Type aspectType, int sortOrder, params MethodInfo[]? methodsToIntercept)
{
AspectType = aspectType ?? throw new ArgumentNullException(nameof(aspectType));
if (!aspectType.IsConcreteClass())
throw new ArgumentException("Type must be a concrete class", nameof(aspectType));
SortOrder = sortOrder;
this.methodsToIntercept = methodsToIntercept == null
? new List<MethodInfo>()
: new List<MethodInfo>(methodsToIntercept);
}
/// <summary>
/// Gets or sets the aspect type.
/// </summary>
public Type AspectType { get; }
/// <summary>
/// Gets or sets the sort order.
/// </summary>
public int SortOrder { get; }
public virtual bool Equals(AspectConfigurationEntry? x, AspectConfigurationEntry? y)
{
if (ReferenceEquals(x, y)) return true;
if (ReferenceEquals(x, null)) return false;
if (ReferenceEquals(y, null)) return false;
if (x.GetType() != y.GetType()) return false;
return x.AspectType == y.AspectType;
}
public virtual int GetHashCode(AspectConfigurationEntry? obj)
{
return obj?.AspectType != null ? obj.AspectType.GetHashCode() : 0;
}
/// <summary>
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(AspectConfigurationEntry? other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return AspectType == other.AspectType;
}
/// <summary>
/// The ==.
/// </summary>
/// <param name="left">
/// The left.
/// </param>
/// <param name="right">
/// The right.
/// </param>
/// <returns>
/// </returns>
public static bool operator ==(AspectConfigurationEntry? left, AspectConfigurationEntry? right)
{
if (ReferenceEquals(left, right)) return true;
if (ReferenceEquals(left, null)) return false;
return !ReferenceEquals(right, null) && left.Equals(right);
}
/// <summary>
/// The !=.
/// </summary>
/// <param name="left">
/// The left.
/// </param>
/// <param name="right">
/// The right.
/// </param>
/// <returns>
/// </returns>
public static bool operator !=(AspectConfigurationEntry left, AspectConfigurationEntry right)
{
return !(left == right);
}
/// <summary>
/// The add methods to intercept.
/// </summary>
/// <param name="newMethodsToIntercept">
/// The methods to intercept.
/// </param>
/// <exception cref="ArgumentNullException">
/// </exception>
/// <exception cref="ArgumentException">
/// </exception>
public void AddMethodsToIntercept(params MethodInfo[] newMethodsToIntercept)
{
if (newMethodsToIntercept == null) throw new ArgumentNullException(nameof(newMethodsToIntercept));
if (newMethodsToIntercept.Length == 0)
throw new ArgumentException("Value cannot be an empty collection.", nameof(newMethodsToIntercept));
methodsToIntercept = methodsToIntercept.Union(newMethodsToIntercept).ToList();
}
/// <summary>
/// The equals.
/// </summary>
/// <param name="obj">
/// The obj.
/// </param>
/// <returns>
/// The <see cref="bool" />.
/// </returns>
public override bool Equals(object? obj)
{
return Equals(obj as AspectConfigurationEntry);
}
/// <inheritdoc />
public override int GetHashCode()
{
return GetHashCode(this);
}
/// <summary>
/// The get methods to intercept.
/// </summary>
/// <returns>
/// The <see cref="List{MethodInfo}" />.
/// </returns>
public List<MethodInfo> GetMethodsToIntercept()
{
return methodsToIntercept.ToList();
}
/// <summary>
/// </summary>
/// <param name="methodsToBeRemoved">
/// </param>
public void RemoveMethodsToIntercept(params MethodInfo[]? methodsToBeRemoved)
{
if (methodsToBeRemoved == null || methodsToBeRemoved.Length == 0) return;
methodsToIntercept.RemoveAll(methodsToBeRemoved.Contains);
}
}
}
|
185d6b108d101c548f084cf297b0287100f69dc5
|
C#
|
chefache/OOP
|
/Polymorphism/Exercise/Vehicles/Models/Truck.cs
| 3.140625
| 3
|
namespace Vehicles.Models
{
public class Truck : Vehicle
{
private const double aditionalFuelConsumption = 1.6;
public Truck(double fuelQuantity, double fuelConsumption)
: base(fuelQuantity, fuelConsumption)
{
// this.FuelConsumption += aditionalFuelConsumption;
}
public override double Drive(double distance)
{
bool canDrive = this.FuelQuantity
- ((this.FuelConsumption + aditionalFuelConsumption) * distance) >= 0;
if (canDrive)
{
this.FuelQuantity -= ((this.FuelConsumption + aditionalFuelConsumption) * distance);
return distance;
}
return 0;
}
public override void Refuel(double aditionalFuel)
{
base.Refuel(aditionalFuel * 0.95);
}
}
}
|
b04f855cf4640a39967722c50020019aeaca7f71
|
C#
|
dlebansais/SolutionControls
|
/SolutionPresenter/Presenter/Events/DocumentSelected/DocumentSelectedEventArgs.cs
| 2.546875
| 3
|
namespace SolutionPresenter
{
using System.Collections.Generic;
using System.Windows;
using SolutionControls;
/// <summary>
/// Represents the event data for a document selected event.
/// </summary>
public class DocumentSelectedEventArgs : SolutionPresenterEventArgs<DocumentSelectedEventArgs>
{
/// <summary>
/// Initializes a new instance of the <see cref="DocumentSelectedEventArgs"/> class.
/// </summary>
/// <param name="routedEvent">The event that occured.</param>
/// <param name="eventContext">The event context.</param>
public DocumentSelectedEventArgs(RoutedEvent routedEvent, DocumentSelectedEventContext eventContext)
: base(routedEvent, eventContext)
{
}
/// <summary>
/// Notifies handlers that the operation is completed.
/// </summary>
/// <param name="documentPathList">The list of selected documents.</param>
public virtual void NotifyCompleted(IList<IDocumentPath> documentPathList)
{
IDocumentSelectedCompletionArgs CompletionArgs = new DocumentSelectedCompletionArgs(documentPathList);
NotifyEventCompleted(CompletionArgs);
}
}
}
|
576aea9c1e5881898ca3ba1d95c2e3cce618e2c7
|
C#
|
Redz111/CalculoM-diaAluno
|
/CalculoMédiaAluno/TelaEntradaDados.cs
| 2.75
| 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 CalculoMédiaAluno
{
public partial class TelaEntradaDados : Form
{
public TelaEntradaDados()
{
InitializeComponent();
}
private decimal MediaAluno (params decimal[] notas)
{
decimal soma = 0;
for (int i=0; i <= notas.GetLength(0)-1; i++)
{
soma += notas[i];
}
return soma / notas.Length;
}
private void btnMedia_Click(object sender, EventArgs e)
{
lBResul.Items.Clear();
string nome = tbNome.Text;
string nascimento = dTPNacimento.Value.ToString();
decimal nota1 = nAtiv01.Value;
decimal nota2 = nAtiv02.Value;
decimal nota3 = nAtiv03.Value;
decimal nota4 = nAtiv04.Value;
lBResul.Items.Add(
"Aluno: " + nome
);
lBResul.Items.Add(
"Data de Nascimento: " + nascimento
);
lBResul.Items.Add("Notas das Atividade: ");
lBResul.Items.Add("Atividade 01: " + nota1);
lBResul.Items.Add("Atividade 02: " + nota2);
lBResul.Items.Add("Atividade 03: " + nota3);
lBResul.Items.Add("Atividade 04: " + nota4);
lBResul.Items.Add("Média Final: " + MediaAluno(nota1, nota2, nota3, nota4));
decimal media = MediaAluno(nota1, nota2, nota3, nota4);
//nMedia.Value = media;
decimal valormedia = nMedia.Value;
if(media >= valormedia)
{
MessageBox.Show("Aluno Aprovado");
}
else
{
MessageBox.Show("Aluno Reprovado");
}
}
}
}
|
77197a59f68b24b9943d50dde17dbfda7c381c22
|
C#
|
lar3811/Echo
|
/Echo/src/InitializationStrategies/Initialize4x2D.cs
| 3.015625
| 3
|
using Echo.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
namespace Echo.InitializationStrategies
{
/// <summary>
/// Creates 4 waves (all aligned with either X or Y axis) at every provided location.
/// </summary>
/// <typeparam name="TWave">Type of waves to create.</typeparam>
public sealed class Initialize4x2D<TWave> : InitializationStrategyBase<TWave>
where TWave : IWave, new()
{
private readonly IWaveBuilder<TWave> _builder;
private readonly Vector3[] _locations;
/// <summary>
/// Creates an instance of the class.
/// </summary>
/// <param name="builder">Wave initialization logic (e.g. <see cref="Waves.Base{TWave}.Builder"/>).</param>
/// <param name="locations">Locations where waves should be created.</param>
public Initialize4x2D(IWaveBuilder<TWave> builder, params Vector3[] locations)
{
_builder = builder;
_locations = locations;
}
protected override Parameters[] GetParameters()
{
if (_locations == null) return null;
var output = new Parameters[4 * _locations.Length];
for (int i = 0; i < _locations.Length; i++)
{
output[4 * i + 0] = new Parameters(_builder, _locations[i], Vector3.UnitX);
output[4 * i + 1] = new Parameters(_builder, _locations[i], Vector3.UnitY);
output[4 * i + 2] = new Parameters(_builder, _locations[i], -Vector3.UnitX);
output[4 * i + 3] = new Parameters(_builder, _locations[i], -Vector3.UnitY);
}
return output;
}
}
}
|
e91dd6a0d4f47ec949d6bf51b6fb8301af20f1d6
|
C#
|
nowen3/Backup2
|
/Backup 2/SyncFiles.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace Backup_2
{
public delegate void OnSyncLoggerEvent(string msg);
public delegate void OnSyncListfilesEvent(string fname,string destname);
class SyncFiles
{
private List<string> excludedirs = new List<string>();
private List<string> excludeextn = new List<string>();
private List<string> excludefiles = new List<string>();
private List<Syncinfo> mysyncjobs = new List<Syncinfo>();
private BindingList<Fileinfo> newfilelist = new BindingList<Fileinfo>();
private string xmlbackupfile = string.Empty;
public SyncFiles(string BackupXMLfile)
{
var mysetting = new SyncSettings(BackupXMLfile);
xmlbackupfile = mysetting.Filename;
excludedirs = mysetting.ExcludeDirs;
excludefiles = mysetting.ExcludeFiles;
excludeextn = mysetting.ExcludeExtn;
mysyncjobs = mysetting.Syncjobs;
Equalisesync = false;
Timestamp = false;
}
public event OnSyncLoggerEvent mylogger;
public event OnSyncListfilesEvent OnListFiles;
public bool Equalisesync { get; set; }
public bool Timestamp { get; set; }
public List<Syncinfo> Syncjobs
{
get { return mysyncjobs; }
set { mysyncjobs = value; }
}
public List<string> ExcludeDirs
{
get { return excludedirs; }
set { excludedirs = value; }
}
public List<string> ExcludeExtn
{
get { return excludeextn; }
set { excludeextn = value; }
}
public List<string> ExcludeFiles
{
get { return excludefiles; }
set { excludefiles = value; }
}
public void RunSync()
{
foreach (Syncinfo item in mysyncjobs)
{
PrepairSync(item.source, item.destination, item.Recursive);
}
Syncdir();
}
public void GetSyncFileList()
{
foreach (Syncinfo item in mysyncjobs)
{
PrepairSync(item.source, item.destination, item.Recursive);
}
//load listview with backup files through delegate
for (int i = 0; i <= newfilelist.Count - 1; i++)
{
if (OnListFiles != null) { OnListFiles(newfilelist[i].Filename, newfilelist[i].DestFilename); }
}
}
public void RunSyncBackwards()
{
string sdir = "";
string temp = "";
BindingList<Fileinfo> tempfilelist = new BindingList<Fileinfo>();
newfilelist.Clear();
foreach (Syncinfo item in mysyncjobs)
{
if (sdir != item.destination)
{
int dirindex = item.source.LastIndexOf('\\') + 1;
temp = item.source.Substring(dirindex);
string SourceDir = item.destination + "\\" + temp;
string DestDir = item.source;
PrepairSync(SourceDir, DestDir, item.Recursive, true);
foreach (Fileinfo myitem in newfilelist)
{
tempfilelist.Add(myitem);
}
newfilelist.Clear();
}
sdir = item.destination + "\\" + temp;
}
newfilelist = tempfilelist;
Syncdir();
}
private void PrepairSync(string source, string dest, bool rec, bool backwards = false)
{
var dir_info = new DirectoryInfo(source);
try
{
//get list of files in source dir
if (rec)
{
Fileutils.SearchDirectory(dir_info, newfilelist);
}
else
Fileutils.SearchDirectory(dir_info, newfilelist, true);
if (mylogger != null) { mylogger("Found " + newfilelist.Count.ToString() + " files in backup directory " + source); }
int count = newfilelist.Count;
//remove excluded files and dirs
Removeexclude(ref newfilelist);
if (mylogger != null) { mylogger("Removed " + (count - newfilelist.Count + " files from backup " + source)); }
count = newfilelist.Count;
if (backwards == false)
{
for (int i = 0; i <= newfilelist.Count - 1; i++)
{
int dirindex = source.LastIndexOf('\\') + 1;
string temp = newfilelist[i].Filename;
temp = dest + "\\" + temp.Substring(dirindex);
newfilelist[i].DestFilename = temp;
}
}
else
{
for (int i = 0; i <= newfilelist.Count - 1; i++)
{
int dirindex = source.Length;
string temp = newfilelist[i].Filename;
string temp1 = temp.Substring(dirindex);
temp = dest + "\\" + temp.Substring(dirindex);
newfilelist[i].DestFilename = temp;
}
}
}
catch (System.Exception ex1)
{
MessageBox.Show("exception in PrepairSync: " + ex1);
}
}
private void Removeexclude(ref BindingList<Fileinfo> oldlist)
{
var newlist = new BindingList<Fileinfo>();
bool ex = false;
// remove exclude files and dirs
for (int i = 0; i <= oldlist.Count - 1; i++)
{
try
{
foreach (string s in excludefiles)
{
if (oldlist[i].Filename == s)
{
ex = true;
break;
}
}
foreach (string sd in excludedirs)
{
if (sd.Length < oldlist[i].Filename.Length && oldlist[i].Filename.Substring(0, sd.Length) == sd)
{
ex = true;
break;
}
}
foreach (string s in excludeextn)
{
if (Path.GetExtension(oldlist[i].Filename) == "." + s)
{
ex = true;
if (mylogger != null) { mylogger("Removed File with extn " + s + "--" + oldlist[i].Filename); }
break;
}
}
}
catch (System.Exception ex1)
{
MessageBox.Show("exception in Removeexclude: " + ex1);
}
if (ex == false)
newlist.Add(oldlist[i]);
ex = false;
}
oldlist.Clear();
oldlist = newlist;
}
private void Syncdir(bool tstamp = false)
{
for (int i = 0; i <= newfilelist.Count - 1; i++)
{
if (!Directory.Exists(Path.GetDirectoryName(newfilelist[i].DestFilename)))
{
Directory.CreateDirectory(Path.GetDirectoryName(newfilelist[i].DestFilename));
}
if (File.Exists(newfilelist[i].DestFilename) && (Fileutils.Comparemoddate(newfilelist[i].Filename, newfilelist[i].DestFilename) > 0))
{
if (tstamp == true)
{ Fileutils.CopyFileExactly(newfilelist[i].Filename, newfilelist[i].DestFilename); }
else { File.Copy(newfilelist[i].Filename, newfilelist[i].DestFilename, true); }
if (mylogger != null) { mylogger("Updated file " + (newfilelist[i].Filename + " To " + newfilelist[i].DestFilename)); }
if (OnListFiles != null) { OnListFiles(newfilelist[i].Filename, newfilelist[i].DestFilename); }
}
if (File.Exists(newfilelist[i].Filename) && (Fileutils.Comparemoddate(newfilelist[i].Filename, newfilelist[i].DestFilename) < 0) && Equalisesync == true)
{
if (tstamp == true)
{ Fileutils.CopyFileExactly(newfilelist[i].DestFilename, newfilelist[i].Filename); }
else { File.Copy(newfilelist[i].DestFilename, newfilelist[i].Filename, true); }
if (mylogger != null) { mylogger("Updated file " + (newfilelist[i].Filename + " To " + newfilelist[i].DestFilename)); }
if (OnListFiles != null) { OnListFiles(newfilelist[i].Filename, newfilelist[i].DestFilename); }
}
if (!File.Exists(newfilelist[i].DestFilename))
{
if (tstamp == true)
{ Fileutils.CopyFileExactly(newfilelist[i].Filename, newfilelist[i].DestFilename); }
else { File.Copy(newfilelist[i].Filename, newfilelist[i].DestFilename); }
if (mylogger != null) { mylogger("Copied file " + (newfilelist[i].Filename + " To " + newfilelist[i].DestFilename)); }
if (OnListFiles != null) { OnListFiles(newfilelist[i].Filename, newfilelist[i].DestFilename); }
}
}
}
}
}
|
42e89edca0493ea729a4f3f1fd5736b58bd4b1c0
|
C#
|
ebuna/Dice.API
|
/Controllers/DiceRollController.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Net;
namespace Dice.API.Controllers
{
[ApiController]
[Route("[controller]")]
public class DiceRollController : ControllerBase
{
private readonly ILogger<DiceRollController> _logger;
public DiceRollController(ILogger<DiceRollController> logger)
{
_logger = logger;
}
[HttpPost]
public DiceRollResult Post(DiceRoll rolls)
{
DiceRollResult result = new DiceRollResult();
result.sumOfRolls = 0;
result.actualRolls = new List<int>();
var rng = new Random();
int rollValue = 0;
_logger.LogInformation("Request received from IP: {0}", GetIp());
for (int i = 0; i < rolls.numberOfRolls; i++)
{
rollValue = rng.Next(1, 7);
result.actualRolls.Add(rollValue);
result.sumOfRolls += rollValue;
}
return result;
}
[HttpGet]
public int Get()
{
var roll = new Random();
return roll.Next(1, 7);
}
public string GetIp()
{
string ip = HttpContext.Connection.RemoteIpAddress?.ToString();
return ip;
}
}
}
|
6b115b00509b5f92b6a475267305748a21ffdc99
|
C#
|
mikevh/Units
|
/Units.Data/UnitOfWork.cs
| 2.796875
| 3
|
using System;
using System.Data.Entity;
using Units.Data.Models;
namespace Units.Data
{
public interface IUnitOfWork : IDisposable
{
IStudentRepository Students { get; }
ICourseRepository Courses { get; }
IGradeRepository Grades { get; }
ITododRepository Todos { get; }
int Save();
}
public class UnitOfWork : IUnitOfWork, IDisposable
{
private readonly DbContext _db;
private readonly ICacher _cacher;
private IStudentRepository students;
private ICourseRepository courses;
private ITododRepository todos;
private IGradeRepository grades;
public UnitOfWork(DbContext db, ICacher cache)
{
_cacher = cache;
_db = db;
}
public IStudentRepository Students => students = students ?? new StudentRepo(_db);
public ICourseRepository Courses => courses = courses ?? new CourseRepo(_db);
public ITododRepository Todos => todos = todos ?? new TodoRepo(_db);
public IGradeRepository Grades => grades = grades ?? new GradeRepo(_db);
public int Save()
{
var rv = _db.SaveChanges();
return rv;
}
private bool disposed;
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
_db.Dispose();
}
}
disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
|
bb45a6fecb2993844ada3779c1508fb5153bb04a
|
C#
|
punio/PurchaseSample
|
/PurchaseSample/MainPage.xaml.cs
| 2.671875
| 3
|
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Store;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace PurchaseSample
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.DataContext = this;
}
public ObservableCollection<string> Log { get; } = new ObservableCollection<string>();
private async void Button_Click(object sender, RoutedEventArgs e)
{
Log.Add("ジャブジャブ課金");
#if DEBUG
// デバッグ時は CurrentAppSimulator にxmlを突っ込んで課金をシミュレート
var proxyFile = await Package.Current.InstalledLocation.GetFileAsync("test.xml");
await CurrentAppSimulator.ReloadSimulatorAsync(proxyFile);
var listing = await CurrentAppSimulator.LoadListingInformationAsync();
#else
var listing = await CurrentApp.LoadListingInformationAsync();
#endif
var paidStage1 = listing.ProductListings["jab1"];
// 本来はメッセージボックス等で確認を取った方がいいよね
Log.Add($"{paidStage1.FormattedPrice} 円の課金を開始しますよ");
await BuyAndFulFill("jab1");
}
private async Task BuyAndFulFill(string productId)
{
try
{
#if DEBUG
var result = await CurrentAppSimulator.RequestProductPurchaseAsync(productId);
#else
var result = await CurrentApp.RequestProductPurchaseAsync(productId);
#endif
Log.Add($"BuyAndFulFill {result.Status}");
switch (result.Status)
{
case ProductPurchaseStatus.Succeeded: // 買った
case ProductPurchaseStatus.NotFulfilled: // まだサーバー(?)とのやり取りが終わってないけどとりあえず買った?
課金処理(result.TransactionId);
FulfillProduct(productId, result.TransactionId);
break;
case ProductPurchaseStatus.NotPurchased: // 買ってない
break;
}
}
catch (Exception exp)
{
Log.Add(exp.Message);
}
}
private void 課金処理(Guid transactionId)
{
// transactionIdが被ってなかったら課金後の処理(アイテム増加とか)を実行
}
private async void FulfillProduct(string productId, Guid transactionId)
{
var result = await CurrentAppSimulator.ReportConsumableFulfillmentAsync(productId, transactionId);
Log.Add($"FulfillProduct {result}");
switch (result)
{
case FulfillmentResult.Succeeded:
Log.Add("課金してくれてありがとう");
break;
case FulfillmentResult.NothingToFulfill:
break;
case FulfillmentResult.PurchasePending:
break;
case FulfillmentResult.PurchaseReverted: // 購入したんだけどキャンセル?
Log.Add("課金情報をキャンセルしとく");
break;
case FulfillmentResult.ServerError:
break;
}
}
/// <summary>
/// 決済処理が終わっていないやつをまとめて決済・・・?
/// </summary>
public async void GetUnfulfilledConsumables()
{
#if DEBUG
var products = await CurrentAppSimulator.GetUnfulfilledConsumablesAsync();
#else
var products = await CurrentApp.GetUnfulfilledConsumablesAsync();
#endif
foreach (var product in products.Where(product => product.ProductId == "jab1"))
{
this.課金処理(product.TransactionId);
this.FulfillProduct(product.ProductId, product.TransactionId);
}
}
}
}
|
fbfa7ae2d32db42954cf26d562cc7255b3182718
|
C#
|
skinnydoo/RaceTrackSimulator
|
/Racetrack Simulator/Bet.cs
| 3.421875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Racetrack_Simulator {
public class Bet {
public int Amount; // the amount of cash that was bet
public int Dog; // the number of the dog the bet is on
public Guy Bettor; // the guy who place the bet
/// <summary>
/// Return a string that says who placed the bet, how much cash
/// was bet, and which dog he bet on ( joe bets 8 on dog #4).
/// If the amount is zero, no bet was placed ( joe hasn't placed a bet)
/// </summary>
/// <returns></returns>
public string GetDescription () {
if ( Amount == 0 ) {
return Bettor.Name + " hasn't placed a bet";
}
else {
return Bettor.Name + " bets " + Amount + " on dog #" + Dog;
}
}
/// <summary>
/// The parameter is the winner of the race. If the dog won,
/// return the amount bet. Otherwise, return the negative of the amount bet
/// </summary>
/// <param name="winner"></param>
/// <returns> amount bet, otherwise, the negative of the amoun bet </returns>
public int PayOut ( int winner ) {
if ( Dog == winner )
return Amount;
else
return -Amount;
}
}
}
|
d7779258e807b62eb005e36c4ba4cd2daa318886
|
C#
|
correianet/dantas-framework
|
/Dantas.Support/MailUtil.cs
| 2.96875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
namespace Dantas.Support
{
/// <summary>
/// Help send email using system.net configuration
/// </summary>
public static class MailUtil
{
/// <summary>
/// Send mail async with task library.
/// </summary>
/// <param name="to">To mail expression.</param>
/// <param name="subject">Subject text.</param>
/// <param name="body">Body text with or not html markup.</param>
/// <param name="html">Send body with html support.</param>
/// <returns></returns>
public static Task SendEmail(string to, string subject, string body, bool html = true)
{
return Task.Factory.StartNew(() =>
{
using (var mail = new MailMessage { Subject = subject, Body = body, IsBodyHtml = html })
using (var smtp = new SmtpClient())
{
mail.To.Add(to);
smtp.Send(mail);
}
});
}
}
}
|
334bdc4af1dfa5518a1faeba840bb70871c98018
|
C#
|
rutkowskii/learn-xamarin
|
/learn-xamarin/learn_xamarin/Utils/AsyncOp.cs
| 3.03125
| 3
|
using System;
using System.Threading.Tasks;
namespace learn_xamarin.Utils
{
public static class AsyncOp
{
public static AsyncOp<T> Get<T>(Func<Task<T>> asyncOp, Action<T> onSuccess, Action<Exception> onFailure, Action onCancel)
{
return new AsyncOp<T>(asyncOp, onSuccess, onFailure, onCancel);
}
public static AsyncOp<T> Get<T>(Func<Task<T>> asyncOp)
{
return new AsyncOp<T>(asyncOp, x => { }, e => { }, () => { });
}
}
public class AsyncOp<T>
{
private readonly Func<Task<T>> _taskPrep;
private readonly Action<T> _onSuccess;
private readonly Action<Exception> _onFailure;
private readonly Action _onCancel;
public AsyncOp(Func<Task<T>> taskPrep, Action<T> onSuccess, Action<Exception> onFailure, Action onCancel)
{
_taskPrep = taskPrep;
_onSuccess = onSuccess;
_onFailure = onFailure;
_onCancel = onCancel;
}
public async void Run()
{
var asyncOpResult = await RunCore();
if (asyncOpResult.ResultFlag == OperationResult.Completed)
{
_onSuccess?.Invoke(asyncOpResult.Result);
}
}
private async Task<AsyncOpResult<T>> RunCore()
{
try
{
var task = _taskPrep();
var resultCore = await task;
return new AsyncOpResult<T>
{
ResultFlag = OperationResult.Completed,
Result = resultCore
};
}
catch (OperationCanceledException)
{
_onCancel.Invoke();
return new AsyncOpResult<T>{ResultFlag = OperationResult.Cancelled};
}
catch (Exception e)
{
_onFailure?.Invoke(e);
return new AsyncOpResult<T>{ResultFlag = OperationResult.Failed};
}
}
enum OperationResult{ Cancelled, Completed, Failed}
class AsyncOpResult<T>
{
public OperationResult ResultFlag { get; set; }
public T Result { get; set; }
}
}
}
|
c886d707e31db9bacd4cafb55525f1a74551c78b
|
C#
|
jgreywolf/mark
|
/websitegen/Utils/HtmlGenerator.cs
| 2.84375
| 3
|
using Markdig;
using Markdig.Renderers;
using Markdig.Syntax;
using Markdig.Syntax.Inlines;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace websitegen.Utils
{
class HtmlGenerator
{
private static readonly Regex urlRegex = new Regex(@"^(http://|https://|ftp://|file:///)", RegexOptions.IgnoreCase);
private static MarkdownPipeline pipeline = null;
public static string MarkdownToHtml(string src, string srcUrl, bool transformUrl = true, bool forWebsite = false)
{
if (pipeline == null)
pipeline = new MarkdownPipelineBuilder().UseAdvancedExtensions().Build();
var builder = new StringBuilder();
var textwriter = new StringWriter(builder);
var renderer = new HtmlRenderer(textwriter);
pipeline.Setup(renderer);
MarkdownDocument doc = Markdown.Parse(src, pipeline);
if (transformUrl)
TransformUrl(doc, srcUrl, forWebsite);
renderer.Render(doc);
string result = builder.ToString();
return result;
}
private static void TransformUrl(MarkdownObject markdownObject, string srcUrl, bool forWebsite)
{
if (!forWebsite)
{
foreach (MarkdownObject child in markdownObject.Descendants())
{
// LinkInline can be both an image or a <a href="...">
LinkInline link = child as LinkInline;
if (link != null)
{
string url = link.Url;
if (!urlRegex.IsMatch(url))
{
link.Url = srcUrl + "/" + url;
}
}
TransformUrl(child, srcUrl, forWebsite);
}
} else
{
foreach (MarkdownObject child in markdownObject.Descendants())
{
// LinkInline can be both an image or a <a href="...">
LinkInline link = child as LinkInline;
if (link != null)
{
string url = link.Url;
if (!urlRegex.IsMatch(url) && url.StartsWith("."))
{
if (url.EndsWith(".md") || url.EndsWith(".markdown"))
{
url = url.Substring(0, url.LastIndexOf(".")) + ".html";
}
link.Url = srcUrl + "/" + url;
}
}
TransformUrl(child, srcUrl, forWebsite);
}
}
}
}
}
|
0965dd15b5f70b1e05bc4b92e3cf8922ec252a98
|
C#
|
MySqlBackupNET/MySqlBackup.Net
|
/source code/MySqlBackup(MySql.Data)/Methods/CryptoExpress.cs
| 2.953125
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;
namespace System.Security.Cryptography
{
public class CryptoExpress
{
public static string ConvertByteArrayToHexString(byte[] ba)
{
if (ba == null || ba.Length == 0)
return "";
// Method 1 (slower)
//return "0x"+ BitConverter.ToString(bytes).Replace("-", string.Empty);
// Method 2 (faster)
char[] c = new char[ba.Length * 2 + 2];
byte b;
c[0] = '0'; c[1] = 'x';
for (int y = 0, x = 2; y < ba.Length; ++y, ++x)
{
b = ((byte)(ba[y] >> 4));
c[x] = (char)(b > 9 ? b + 0x37 : b + 0x30);
b = ((byte)(ba[y] & 0xF));
c[++x] = (char)(b > 9 ? b + 0x37 : b + 0x30);
}
return new string(c);
}
//public static string RandomString(int size)
//{
// byte[] randBuffer = new byte[size + (10)];
// RandomNumberGenerator.Create().GetBytes(randBuffer);
// return System.Convert.ToBase64String(randBuffer).Replace("/", string.Empty).Replace("+", string.Empty).Replace("=", string.Empty).Remove(size);
//}
//public static string Sha128Hash(string input)
//{
// SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();
// byte[] ba = Encoding.UTF8.GetBytes(input);
// byte[] ba2 = sha.ComputeHash(ba);
// sha = null;
// return BitConverter.ToString(ba2).Replace("-", string.Empty).ToLower();
//}
//public static string Sha256Hash(string input)
//{
// byte[] ba = Encoding.UTF8.GetBytes(input);
// return Sha256Hash(ba);
//}
//public static string Sha256Hash(byte[] ba)
//{
// SHA256Managed sha2 = new SHA256Managed();
// byte[] ba2 = sha2.ComputeHash(ba);
// sha2 = null;
// return BitConverter.ToString(ba2).Replace("-", string.Empty).ToLower();
//}
//public static string Sha512Hash(string input)
//{
// byte[] ba = Encoding.UTF8.GetBytes(input);
// SHA512Managed sha5 = new SHA512Managed();
// byte[] ba2 = sha5.ComputeHash(ba);
// sha5 = null;
// return BitConverter.ToString(ba2).Replace("-", string.Empty).ToLower();
//}
//public static string AES_Encrypt(string input, string password)
//{
// byte[] clearBytes = System.Text.Encoding.UTF8.GetBytes(input);
// byte[] encryptedData = AES_Encrypt(clearBytes, password);
// return Convert.ToBase64String(encryptedData);
//}
//public static byte[] AES_Encrypt(byte[] input, string password)
//{
// PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
// return AES_Encrypt(input, pdb.GetBytes(32), pdb.GetBytes(16));
//}
//public static string AES_Decrypt(string input, string password)
//{
// byte[] cipherBytes = Convert.FromBase64String(input);
// byte[] decryptedData = AES_Decrypt(cipherBytes, password);
// return System.Text.Encoding.UTF8.GetString(decryptedData);
//}
//public static byte[] AES_Decrypt(byte[] input, string password)
//{
// PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
// return AES_Decrypt(input, pdb.GetBytes(32), pdb.GetBytes(16));
//}
//static byte[] AES_Encrypt(byte[] clearData, byte[] Key, byte[] IV)
//{
// byte[] encryptedData = null;
// using (MemoryStream ms = new MemoryStream())
// {
// using (Rijndael alg = Rijndael.Create())
// {
// alg.Key = Key;
// alg.IV = IV;
// using (CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write))
// {
// cs.Write(clearData, 0, clearData.Length);
// cs.Close();
// }
// encryptedData = ms.ToArray();
// }
// }
// return encryptedData;
//}
//static byte[] AES_Decrypt(byte[] cipherData, byte[] Key, byte[] IV)
//{
// try
// {
// byte[] decryptedData = null;
// using (MemoryStream ms = new MemoryStream())
// {
// using (Rijndael alg = Rijndael.Create())
// {
// alg.Key = Key;
// alg.IV = IV;
// using (CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write))
// {
// cs.Write(cipherData, 0, cipherData.Length);
// cs.Close();
// }
// decryptedData = ms.ToArray();
// }
// }
// return decryptedData;
// }
// catch
// {
// throw new Exception("Incorrect password or corrupted context.");
// }
//}
}
}
|
6e98c9f44243f4fe40c8068c37b27ac388833e36
|
C#
|
frostblooded/TelerikHomework
|
/C# Part 2/Arrays/PrimeNumbersToTenMillion/Program.cs
| 3.28125
| 3
|
using System;
class Program
{
static void Main()
{
bool[] numbers = new bool[10000000];
for (int i = 2; i < numbers.Length; i++)
{
if (!numbers[i])
{
Console.WriteLine(i);
numbers[i] = true;
int j = 2;
while (i * j < numbers.Length)
{
numbers[i * j] = true;
j++;
}
}
}
}
}
|
262474dedf22be21366da3dab0970b880a7dcc88
|
C#
|
tomicabo/work-order-and-invoicing-system
|
/ViewModels/NarocilniceViewModel.cs
| 2.6875
| 3
|
using MySql.Data.MySqlClient;
using POSSavkovic.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace POSSavkovic.ViewModels
{
class NarocilniceViewModel
{
public ObservableCollection<NarocilniceModel> narocilnice = new ObservableCollection<NarocilniceModel>();
public ObservableCollection<NarocilniceModel> Narocilnice
{
get;
set;
}
public NarocilniceViewModel()
{
DobiNarocilnice();
Narocilnice = narocilnice;
}
public ObservableCollection<NarocilniceModel> DobiNarocilnice()
{
var connectionString = ConfigurationManager.ConnectionStrings["myDatabaseConnection"].ConnectionString;
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
var query = "select n.id, n.ustvarjeno, n.st_narocilnice, n.skupaj_cena, d.podjetje " +
"from narocilnice n " +
"join dobavitelji d on n.dobavitelj = d.id; ";
connection.Open();
using (MySqlCommand command = new MySqlCommand(query, connection))
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
NarocilniceModel n_temp = new NarocilniceModel();
if (reader["id"] != DBNull.Value)
n_temp.Id = Convert.ToInt32(reader["id"]);
if (reader["ustvarjeno"] != DBNull.Value)
{
DateTime temp = Convert.ToDateTime(reader["ustvarjeno"]);
n_temp.Ustvarjeno = temp.ToString("dd.MM.yyyy");
}
if (reader["st_narocilnice"] != DBNull.Value)
n_temp.StNarocilnice = Convert.ToString(reader["st_narocilnice"]);
if (reader["podjetje"] != DBNull.Value)
n_temp.Dobavitelj = Convert.ToString(reader["podjetje"]);
if (reader["skupaj_cena"] != DBNull.Value)
n_temp.SkupajCena = Convert.ToString(reader["skupaj_cena"]);
else n_temp.SkupajCena = "posamična cena";
narocilnice.Add(n_temp);
}
}
connection.Close();
return narocilnice;
}
}
}
}
|
ac76eabf1167df7bcf0c67f8c1a55652b894c2f8
|
C#
|
Lch3181/PickupSticks
|
/PickupSticks/Form1.cs
| 3.109375
| 3
|
using System;
using System.Windows.Forms;
namespace PickupSticks
{
public partial class Main : Form
{
//Game parameters
int TotalNumberOfPlayers;
int MaxNumberOfSticks;
int PlayerPickupRange;
//Game status
bool GameHasStarted;
int CurrentPlayerTurn;
int CurrentNumberOfSticks;
public Main()
{
InitializeComponent();
}
private void StartButton_Click(object sender, EventArgs e)
{
if(!GameHasStarted)
{
StartGame();
}
else
{
RestartGame();
}
}
private void PickUpButton_Click(object sender, EventArgs e)
{
//game progress
MakeMove();
//check win status
CheckWinStatus();
}
private void StartGame()
{
//init stat
ExtractGameParameters();
CurrentPlayerTurn = 1;
CurrentNumberOfSticks = MaxNumberOfSticks;
UpdateGameUI();
//disable settings
SetGameSettingsVisibility(false);
//enable game
SetGameControlsVisibility(true);
GameHasStarted = true;
}
private void RestartGame()
{
//enable settings
SetGameSettingsVisibility(true);
//disable game
SetGameControlsVisibility(false);
GameHasStarted = false;
}
private void MakeMove()
{
if (CurrentNumberOfSticks > 0)
{
int pickUpAmount = Convert.ToInt16(PickUpAmountTextbox.Text);
if (pickUpAmount <= PlayerPickupRange && pickUpAmount > 0)
{
//pick up sticks
CurrentNumberOfSticks -= pickUpAmount;
//next player
if (CurrentPlayerTurn < TotalNumberOfPlayers)
{
CurrentPlayerTurn++;
}
else
{
CurrentPlayerTurn = 1;
}
UpdateGameUI();
}
}
}
private void CheckWinStatus()
{
if (CurrentNumberOfSticks <= 0)
{
//disable game
SetGameControlsVisibility(false);
DisplayWinner();
}
}
private void SetGameSettingsVisibility(bool status)
{
TotalPlayersTextbox.Enabled = status;
TotalSticksTextbox.Enabled = status;
PickUpRangeTextbox.Enabled = status;
}
private void SetGameControlsVisibility(bool status)
{
PickUpAmountTextbox.Enabled = status;
PickUpButton.Enabled = status;
StartButton.Text = (status) ? "Restart" : "Start";
}
private void ExtractGameParameters()
{
TotalNumberOfPlayers = Convert.ToInt16(TotalPlayersTextbox.Text);
MaxNumberOfSticks = Convert.ToInt16(TotalSticksTextbox.Text);
PlayerPickupRange = Convert.ToInt16(PickUpRangeTextbox.Text);
}
private void UpdateGameUI()
{
CurrentPlayerLabel.Text = "Player " + Convert.ToString(CurrentPlayerTurn);
CurrentSticksLabel.Text = Convert.ToString(CurrentNumberOfSticks);
}
private void DisplayWinner()
{
CurrentSticksLabel.Text = "0";
MessageBox.Show(CurrentPlayerLabel.Text + " Wins!");
}
}
}
|
ef61dd282fc4e4baebd341308e40c4f1b9131fa1
|
C#
|
Vasil-Kostov/Technology-Fundamentals---September-2018
|
/Arrays - Lab/08. Condense Array to Number/Program.cs
| 3.796875
| 4
|
namespace _08.Condense_Array_to_Number
{
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] numbers = Console.ReadLine().Split().Select(int.Parse).ToArray();
while (numbers.Length > 1)
{
int[] conensed = new int[numbers.Length - 1];
for (int i = 0; i < conensed.Length; i++)
{
conensed[i] = numbers[i] + numbers[i + 1];
}
numbers = conensed;
}
Console.WriteLine(numbers[0]);
}
}
}
|
ce646fc0fb8f80eaab608307709776ffe9c3cc6c
|
C#
|
superowner/Yzmeir.NamedPipes
|
/src/NamedPipesClient/Program.cs
| 3
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using Yzmeir.InterProcessComm;
using Yzmeir.NamedPipes;
namespace NamedPipesClient
{
class Program
{
static void Main(string[] args)
{
string key = "";
while ((key = Console.ReadLine()) != "exit")
{
if (key != "")
{
DateTime dt = DateTime.Now;
// This cycle is used only when you want to run numerous name pipes requests
// and measure the performance. In the general case it is not needed.
for (int i = 0; i < 1; i++)
{
IInterProcessConnection clientConnection = null;
try
{
clientConnection = new ClientPipeConnection("MyPipe", ".");
clientConnection.Connect();
clientConnection.Write(key);
Console.WriteLine(clientConnection.Read());
clientConnection.Close();
}
catch (Exception ex)
{
clientConnection.Dispose();
throw (ex);
}
}
Console.WriteLine(DateTime.Now.Subtract(dt).Milliseconds.ToString());
}
}
}
}
}
|
6341bab4d17b45d448b04751a8dd357a5c9e78a2
|
C#
|
JoseDuDev/ManyToMany
|
/ManyToMany/Repository/UnitOfWorkRepository.cs
| 2.6875
| 3
|
using ManyToMany.Data;
using ManyToMany.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ManyToMany.Repository
{
public class UnitOfWorkRepository : IUnitOfWork
{
private readonly ManyToManyContext _context;
private IPost _iPost;
private ITag _iTag;
public UnitOfWorkRepository(ManyToManyContext context)
{
_context = context;
}
public IPost Post
{
get
{
return _iPost = _iPost ?? new PostRepository(_context);
}
}
public ITag Tag
{
get
{
return _iTag = _iTag ?? new TagRepository(_context);
}
}
public void Save()
{
_context.SaveChanges();
}
}
}
|
2d5c8c1ccf138519df63d482e3b00282021b80be
|
C#
|
seyedmoeinsaadati/TMirrorT
|
/Assets/Packages/TMirrorT/Scripts/PointMirror.cs
| 2.515625
| 3
|
using UnityEngine;
namespace SMSPackages.TMirrorT
{
public class PointMirror : Point, IMirror
{
[Header("Mirror Properties")]
public float factor = 1f;
[Tooltip("Lock axis with set 0 for locking axis. Use only 0 or 1 value for this feild.")]
public Vector3 beAxis = Vector3.one;
[Tooltip("Custom your mirror behaviour by changing mirror rotation axes")]
public Vector4 customRotaionQuaternion = Vector4.one;
public Vector3 GetMirrorPosition(Vector3 target)
{
float x = target.x - 2 * (target.x - transform.position.x) * beAxis.x;
float y = target.y - 2 * (target.y - transform.position.y) * beAxis.y;
float z = target.z - 2 * (target.z - transform.position.z) * beAxis.z;
return new Vector3(x, y, z) * factor;
}
public Quaternion GetMirrorRotation(Quaternion target)
{
return new Quaternion(target.x * customRotaionQuaternion.x,
target.y * customRotaionQuaternion.y,
target.z * customRotaionQuaternion.z, target.w * customRotaionQuaternion.w);
}
public Vector3 GetMirrorScale(Vector3 target)
{
float x = target.x * (beAxis.x > 0 ? -1 : 1);
float y = target.y * (beAxis.y > 0 ? -1 : 1);
float z = target.z * (beAxis.z > 0 ? -1 : 1);
return new Vector3(x, y, z);
}
}
}
|
4b6e59933286a4542bed81b93231118b765ac0c6
|
C#
|
nikolay-spasov/TelerikAcademy_OOP_Homeworks
|
/OOP_HW_1_DefiningClasses/1_MobilePhone/GSMCallHistoryTest.cs
| 3.203125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
public class GSMCallHistoryTest
{
private const decimal PRICE_PER_MINUTE = 0.37m;
private static GSM gsm = new GSM("k700i", "Sony-Ericsson");
public static void Test()
{
Console.WriteLine("Testing Calls");
Console.WriteLine("============================");
Console.WriteLine(gsm.ToString());
AddSomeCalls();
PrintCalls();
PrintTotalPrice();
RemoveCallWithMaxDuration();
Console.WriteLine("After removing the call with maximal duration:");
PrintTotalPrice();
Console.WriteLine("Clearing the call history.");
ClearCallsHistory();
Console.WriteLine("After clearing total calls in history: {0}", gsm.Calls.Count);
PrintCalls();
}
private static void AddSomeCalls()
{
gsm.AddCall(new Call("025 6584 555 1", 300));
gsm.AddCall(new Call("025 456 555 1", 330));
gsm.AddCall(new Call("025 614568 85 1", 600));
gsm.AddCall(new Call("025 4562 555 1", 60));
gsm.AddCall(new Call("025 123 555 1", 148));
gsm.AddCall(new Call("025 4568 535 1", 15));
gsm.AddCall(new Call("025 6114 135 1", 67));
gsm.AddCall(new Call("025 4 555 1", 123));
gsm.AddCall(new Call("025 58 15 1", 432));
}
private static void PrintCalls()
{
foreach (Call call in gsm.Calls)
{
Console.WriteLine("Date: {0}, Time: {1}, Phone number: {2}, Duration: {3}",
call.Date, call.Time, call.DialedPhoneNumber, call.Duration);
}
}
private static void PrintTotalPrice()
{
decimal totalPrice = gsm.CalculateTotalPriceOfCalls(PRICE_PER_MINUTE);
Console.WriteLine("Total price: {0:c}", totalPrice);
}
private static void RemoveCallWithMaxDuration()
{
uint maxDuration = gsm.Calls.Max(x => x.Duration);
Call maxDurationCall = gsm.Calls.Find(x => x.Duration == maxDuration);
gsm.RemoveCall(maxDurationCall);
}
private static void ClearCallsHistory()
{
gsm.ClearCallHistory();
}
}
|
a95a53105f3b60e701bcc0437ca18c50979f732b
|
C#
|
jmslagle/twxp
|
/Source/TWX30/Library-old/Database/XmlBase.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
namespace TWXP.Database
{
public class XmlBase
{
protected string xsd = "";
public static string AssemblyDirectory
{
get
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
}
//public void Serialize(object sender, string filename)
public void Serialize(string filename)
{
if (!Directory.Exists($"{AssemblyDirectory}\\Data"))
{
Directory.CreateDirectory($"{AssemblyDirectory}\\Data");
}
//string configFile = @"c:\ProgramData\MailLink\config.xml";
using (FileStream fs = new FileStream($"{AssemblyDirectory}\\Data\\{filename}", FileMode.Create))
{
XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces();
xmlns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
//xmlns.Add("noNamespaceSchemaLocation", xsd);
//XmlSerializer xml = new XmlSerializer(this.GetType(),);
XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings()
{
// If set to true XmlWriter would close MemoryStream automatically and using would then do double dispose
// Code analysis does not understand that. That's why there is a suppress message.
CloseOutput = false,
Encoding = Encoding.UTF8,
OmitXmlDeclaration = false,
Indent = true
};
using (System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(fs, xmlWriterSettings))
{
XmlSerializer s = new XmlSerializer(this.GetType());
s.Serialize(xw, this, xmlns);
}
//xml.Serialize(fs, this, xmlns);
fs.Close();
}
}
public static void Deserialize()
{
string configFile = @"c:\ProgramData\MailLink\config.xml";
if (!File.Exists(configFile))
{
//Config c = new Config();
//c.Create();
//c.Serialize();
//return c;
}
else
{
using (FileStream fs = new FileStream(configFile, FileMode.Open))
{
//XmlSerializer xml = new XmlSerializer(typeof(this));
// Config config = (Config)xml.Deserialize(fs);
fs.Close();
//return config;
}
}
}
}
}
|
20f167cfcbfa4c9e45d98d5d74e624580423b870
|
C#
|
michaela03/AverageGrade
|
/Form1.cs
| 2.8125
| 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.IO;
namespace SREDEN_USPEH
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
double BEL, Math, Foreign, Phys, Informatics, Bio;
private void button1_Click(object sender, EventArgs e)
{
Form1.ActiveForm.Hide();
Form form2 = new Form();
form2.Show();
}
List<Student> students = new List<Student>();
private void buttonAverage_Click(object sender, EventArgs e)
{
textBoxAverage.Text = ((double.Parse(textBoxBEL.Text) + double.Parse(textBoxMath.Text) + double.Parse(textBoxInformatics.Text) + double.Parse(textBoxPhys.Text) + double.Parse(textBoxBio.Text) + double.Parse(textBoxForeign.Text)) / 6).ToString();
}
private void buttonClean_Click(object sender, EventArgs e)
{
textBoxCLas.Clear();
textBoxID.Clear();
textBoxName.Clear();
textBoxBEL.Clear();
textBoxForeign.Clear();
textBoxMath.Clear();
textBoxInformatics.Clear();
textBoxPhys.Clear();
textBoxBio.Clear();
textBoxAverage.Clear();
}
private void buttonSave_Click(object sender, EventArgs e)
{
Student student = new Student(textBoxName.Text, int.Parse(textBoxID.Text),
textBoxCLas.Text, double.Parse(textBoxBEL.Text),
double.Parse(textBoxMath.Text),
double.Parse(textBoxForeign.Text), double.Parse(textBoxPhys.Text),
double.Parse(textBoxInformatics.Text), double.Parse(textBoxBio.Text), double.Parse(textBoxAverage.Text));
students.Add(student);
StreamWriter A = new StreamWriter(Application.StartupPath + "\\form\\." + "custdetails.txt");
A.WriteLine(label1.Text + " " + textBoxCLas.Text);
A.WriteLine(label2.Text + " " + textBoxID.Text);
A.WriteLine (label3.Text + " " + textBoxName.Text);
A.WriteLine(label4.Text + " " + textBoxBEL.Text);
A.WriteLine(label5.Text + " " + textBoxForeign.Text);
A.WriteLine(label6.Text + " " + textBoxMath.Text);
A.WriteLine(label7.Text + " " + textBoxInformatics.Text);
A.WriteLine(label8.Text + " " + textBoxPhys.Text);
A.WriteLine(label9.Text + " " + textBoxBio.Text);
A.WriteLine(labelAverage.Text + " " + textBoxAverage.Text);
A.Close();
}
private void buttonFind_Click(object sender, EventArgs e)
{
foreach (Student student in students)
{
if (student.Id == int.Parse(textBoxID.Text) && student.Clas == textBoxCLas.Text)
{
textBoxName.Text = student.Name;
textBoxBEL.Text = student.BEL.ToString();
textBoxMath.Text = student.Mathematik.ToString();
textBoxPhys.Text = student.Phys.ToString();
textBoxInformatics.Text = student.Informatics.ToString();
textBoxForeign.Text = student.Foreign.ToString();
textBoxBio.Text = student.Bio.ToString();
textBoxAverage.Text = student.Avg.ToString();
}
}
}
}
}
|
cdfd7b0879bcc2e5d2966f55290fce443264f87f
|
C#
|
kate512/kurs_pt
|
/KindergardenV2/Classes/Reward.cs
| 3.0625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KindergardenV2.Classes
{
enum who
{
Educator,
Child
}
class Reward
{
public string Name;// { get; }
public DateTime Data { get; }
public who Who;//{ get; }
//вывод информации на экран
public void Get_Info()
{
Console.WriteLine(" "+Name + ", выдана:" + Data + " (" + Who + ")");
}
//конструтор
public Reward(string Name1, DateTime Data1, who Who1)
{
Name = Name1;
Data = Data1;
Who = Who1;
}
}
}
|
4b8d4337fe0d566cfb92a61d3da35f38200ae704
|
C#
|
namanmittal1/SmartShare
|
/SmartShare/Behaviours/LoadUnloadBehaviour.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace SmartShare
{
public static class LoadUnloadBehaviour
{
public static readonly DependencyProperty LoadUnloadProperty =
DependencyProperty.RegisterAttached("LoadUnload", typeof(Boolean),
typeof(LoadUnloadBehaviour),
new FrameworkPropertyMetadata(false,
new PropertyChangedCallback(OnLoadUnloadChanged)));
public static void SetLoadUnload(FrameworkElement element, Boolean value)
{
element.SetValue(LoadUnloadProperty, value);
}
public static Boolean GetLoadUnload(FrameworkElement element)
{
return (Boolean)element.GetValue(LoadUnloadProperty);
}
public static void OnLoadUnloadChanged(DependencyObject obj,
DependencyPropertyChangedEventArgs args)
{
FrameworkElement element = obj as FrameworkElement;
if (element == null)
throw new InvalidOperationException();
element.DataContextChanged += (sender, e) =>
{
if (!element.IsLoaded)
return;
if (e.OldValue is BaseViewModel)
{
BaseViewModel viewModel = ((BaseViewModel)e.OldValue);
if (viewModel.Initialized)
{
viewModel.Unload(element);
viewModel.Initialized = false;
}
}
if (e.NewValue is BaseViewModel)
{
BaseViewModel viewModel = ((BaseViewModel)e.NewValue);
if (!viewModel.Initialized)
{
viewModel.Initialized = true;
viewModel.Load(element);
}
}
};
element.Loaded += (sender, e) =>
{
BaseViewModel viewModel =
element.GetValue(FrameworkElement.DataContextProperty) as BaseViewModel;
if (viewModel != null && !viewModel.Initialized)
{
viewModel.Initialized = true;
viewModel.Load(element);
}
};
element.Unloaded += (sender, e) =>
{
BaseViewModel viewModel =
element.GetValue(FrameworkElement.DataContextProperty) as BaseViewModel;
if (viewModel != null && viewModel.Initialized)
{
viewModel.Unload(element);
viewModel.Initialized = false;
}
};
}
}
}
|
75ea88e5c374c099d9e90bb3320267c5315d2c99
|
C#
|
akmsprhns-edu/BakD-GomokuTrainer
|
/GomokuLib/GameState.cs
| 3.390625
| 3
|
using GomokuLib.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
namespace GomokuLib
{
public class GameState : IEquatable<GameState>
{
private BoardState Board;
public static int BoardSize { get => Consts.BOARD_SIZE; }
public PlayerColor PlayerTurn { get => Board.PlayerTurn; }
private GameState()
{
Board = new BoardState();
}
private GameState(BoardState board)
{
Board = board;
}
public void MakeMoveInPlace(PlayerMove move)
{
MakeMoveInPlace(move.Row, move.Column);
}
public void MakeMoveInPlace(int row, int col)
{
if (!IsValidMove(row, col))
{
throw new GameStateException($"Impossible move, [{row},{col}] aledy occupied");
}
Board.MakeMoveInPlace(row, col);
}
public GameState MakeMove(PlayerMove move)
{
return MakeMove(move.Row, move.Column);
}
public GameState MakeMove(int row, int col)
{
if(!IsValidMove(row, col))
{
throw new GameStateException($"Impossible move, [{row},{col}] aledy occupied:\n" + DrawBoard());
}
var newBoardState = Board.MakeMove(row, col);
return new GameState(newBoardState);
}
public GameState Copy()
{
return new GameState(Board.Copy());
}
public bool IsValidMove(int row, int col)
{
return Board.OccupiedBy(row, col) == StoneColor.None;
}
public bool IsValidPriorityMove(int row, int col)
{
return (IsInCentre(row, col) || Board.IsAnyAdjacent(row, col)) && IsValidMove(row, col);
}
public bool IsPriorityMove(int row, int col)
{
return IsInCentre(row, col) || Board.IsAnyAdjacent(row, col);
}
private const int centerIndex = (Consts.BOARD_SIZE + 1) / 2 - 1;
public bool IsInCentre(int row, int col)
{
return row >= centerIndex - 1 && row <= centerIndex + 1 && col >= centerIndex - 1 && col <= centerIndex + 1;
}
public StoneColor OccupiedBy(int row, int col)
{
return Board.OccupiedBy(row, col);
}
public byte[] GetBoardByteArray()
{
return Board.GetBoardStateArray().Select(x => Convert.ToByte(x)).ToArray();
}
public float[] GetBoardFloatArray()
{
var result = new List<float>();
var boardArr = Board.GetBoardStateArray();
for (int i = 0; i < boardArr.Length; i += 2)
{
if(boardArr[i] == false && boardArr[i+1] == false)
{
result.Add(0);
}
else if (boardArr[i] == true && boardArr[i + 1] == false)
{
result.Add(1);
}
else if (boardArr[i] == false && boardArr[i + 1] == true)
{
result.Add(-1);
}
else
{
throw new Exception("Board array malformed");
}
}
return result.ToArray();
}
public IEnumerable<(int row, int colmun)> GetUnoccupiedPositions()
{
return Board.GetUnoccupiedPositions();
}
public GameResult? IsGameOver()
{
return Board.IsGameOver();
}
public static GameState NewGame()
{
return new GameState();
}
public static GameState GenerateRandomGameState(int? Seed = null)
{
Random rnd = Seed == null ? new Random() : new Random(Seed ?? 0);
var gameState = new GameState();
for (var i = 0; i < BoardSize * BoardSize; i++)
{
var row = rnd.Next(BoardSize);
var col = rnd.Next(BoardSize);
if(gameState.IsValidMove(row, col))
{
gameState = gameState.MakeMove(row, col);
}
}
return gameState;
}
public GameState MakeRandomMove(int? Seed = null)
{
Random rnd = Seed == null ? new Random() : new Random(Seed ?? 0);
while(true)
{
var row = rnd.Next(BoardSize);
var col = rnd.Next(BoardSize);
if (IsValidMove(row, col))
{
return MakeMove(row, col);
}
}
}
public string DrawBoard()
{
return Board.DrawBoard();
}
public StoneColor[,] Get2DArrary()
{
return Board.Get2DArrary();
}
public override bool Equals(object obj)
{
return Equals(obj as GameState);
}
public bool Equals(GameState other)
{
return other != null &&
Board.Equals(other.Board);
}
public override int GetHashCode()
{
return HashCode.Combine(Board);
}
}
}
|
ea9e5b3a7cc1f143d59ec21855c21653df111a64
|
C#
|
jscstc007/MoTa
|
/Assets/Scripts/Test.cs
| 2.65625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public struct SkillTreeData
{
public string Name;
public SkillTreeData(string name)
{
Name = name;
}
public override string ToString()
{
return string.Format("SkillTreeData:{0}", Name);
}
}
public class Test : MonoBehaviour {
// Use this for initialization
void Start () {
//测试一个树状图
CheckTree();
}
private void CheckTree ()
{
TreeData<SkillTreeData> t1 = new TreeData<SkillTreeData>(new SkillTreeData("1"));
TreeData<SkillTreeData> t1_1 = new TreeData<SkillTreeData>(new SkillTreeData("1-1"));
TreeData<SkillTreeData> t1_1_1 = new TreeData<SkillTreeData>(new SkillTreeData("1-1-1"));
TreeData<SkillTreeData> t1_1_2 = new TreeData<SkillTreeData>(new SkillTreeData("1-1-2"));
TreeData<SkillTreeData> t1_1_2_1 = new TreeData<SkillTreeData>(new SkillTreeData("1-1-2-1"));
TreeData<SkillTreeData> t1_2 = new TreeData<SkillTreeData>(new SkillTreeData("1-2"));
t1.AddChildNode(t1_1);
t1_1.AddChildNode(t1_1_1);
t1_1.AddChildNode(t1_1_2);
t1_1_2.AddChildNode(t1_1_2_1);
t1.AddChildNode(t1_2);
t1.DebugNodes();
foreach(TreeData<SkillTreeData> node in t1.ChildDataList)
{
node.DebugNodes();
}
}
}
|
833d7744b44c03bb72c38afd2a6073b3aaa2b201
|
C#
|
almasry2011/DrinkStore
|
/DrinkStore/Data/Repositories/OrderRepo.cs
| 2.765625
| 3
|
using DrinkStore.Data.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http;
namespace DrinkStore.Data.Repositories
{
public class OrderRepo : IOrderRepo
{
private readonly DrinksDbContext db;
private readonly IShoppinCartRepo shoppinCartRepo;
private readonly IHttpContextAccessor context;
public OrderRepo(DrinksDbContext db,IShoppinCartRepo shoppinCartRepo,IHttpContextAccessor Context)
{
this.db = db;
this.shoppinCartRepo = shoppinCartRepo;
context = Context;
}
public void CreateOrder(Order order)
{
order.OrderPlaced = DateTime.Now;
db.orders.Add(order);
foreach (var item in shoppinCartRepo.ViewShoppingCart())
{
DrinkOrder drinkOrder = new DrinkOrder
{
DrinkId = item.Drink.DrinkId,
OrderId = order.OrderId,
Amount=item.amount,
Price=item.Drink.Price * item.amount
};
db.drinkOrders.Add(drinkOrder);
}
if (db.SaveChanges()<0)
{
foreach (var item in shoppinCartRepo.ViewShoppingCart())
{
item.Drink.Stock += item.amount;
}
db.SaveChanges();
}
}
public Order ViewOrder(string SessionId)
{
if (context.HttpContext.Session.Id== SessionId)
{
var order = db.orders.Last();
return order;
}
else { return null; }
}
}
}
|
e70ef45da09d4afcc371ed78f22e8c112de45c00
|
C#
|
DianaKoba/FacebookApp
|
/FacebookApp/PlaceRecommendations.cs
| 2.515625
| 3
|
using System;
using System.Text;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Facebook;
using FacebookWrapper;
using FacebookWrapper.ObjectModel;
namespace A18_Ex03_Vladi_308921915_Diana_323643932
{
public class PlaceRecommendations
{
public IOrderFriendList FriendListOrderer { get; set; }
public List<User> FriendListBeenThere { get; private set; }
private readonly object sr_AddToListLock = new object();
public bool FoundFriend { get; private set; }
public PlaceRecommendations()
{
FriendListBeenThere = new List<User>();
FriendListOrderer = new OrderFriendListAlphabeticly();
}
public void AddFriendListOrderer(IOrderFriendList i_Orderer)
{
FriendListOrderer = i_Orderer;
}
public void AskFriendForRecommendation(User i_User, List<User> i_FriendsToAsk, string i_PlaceName)
{
try
{
if (i_User != null)
{
string askFriendPost = string.Format("Hey! I'm interested about {0}, how was there? I would love a recommendation please :)", i_PlaceName);
foreach (User friend in i_FriendsToAsk)
{
i_User.PostStatus(askFriendPost, null, null, friend.Id);
}
MessageBox.Show("Your question was posted");
}
else
{
throw new Exception("You must be logged in, in order to proceed.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
public void CheckPlace(string i_PlaceName, User i_User, ListBox i_GivenListBox, System.Windows.Forms.BindingSource i_BindingSource)
{
FriendListBeenThere.Clear();
i_GivenListBox.Invoke(new Action(() =>
{
i_GivenListBox.DataSource = null;
i_GivenListBox.Items.Clear();
}));
FoundFriend = false;
ProperFriendFinder properFriendFinder = new ProperFriendFinder { FacebookUser = i_User, PlaceName = i_PlaceName };
try
{
if (i_User != null)
{
if (i_User.Friends.Count > 0)
{
IEnumerator<User> currentFriend = properFriendFinder.GetEnumerator();
User properFriend = currentFriend.Current;
lock (sr_AddToListLock)
{
while (currentFriend.MoveNext())
{
FoundFriend = true;
properFriend = currentFriend.Current;
FriendListBeenThere.Add(currentFriend.Current);
}
}
if (FoundFriend)
{
FriendListOrderer.OrderFriendList(FriendListBeenThere);
i_BindingSource.DataSource = FriendListBeenThere;
i_GivenListBox.Invoke(new Action(() => i_GivenListBox.DataSource = i_BindingSource));
}
else
{
string message = string.Format("None of your friends were in {0}", i_PlaceName);
MessageBox.Show(message);
}
}
else
{
string message = string.Format("You have no friends to ask from.");
MessageBox.Show(message);
}
}
else
{
throw new Exception("You must be logged in, in order to proceed.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
public void AddFriendsToAskToList(User i_User, ListBox i_FriendsThatBeenThere, ListBox i_FriendsToAsk)
{
try
{
if (i_User != null)
{
if (i_FriendsThatBeenThere.SelectedItem as User != null)
{
if (i_FriendsToAsk.Items.Contains(i_FriendsThatBeenThere.SelectedItem))
{
MessageBox.Show("This friend has already been added to the list.");
}
else
{
i_FriendsToAsk.Items.Add(i_FriendsThatBeenThere.SelectedItem as User);
}
}
else
{
MessageBox.Show("There are no friends to add.");
}
}
else
{
throw new Exception("You must be logged in, in order to proceed.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
public void DeleteFriendsToAskFromList(User i_User, ListBox i_FriendsToAsk)
{
try
{
if (i_User != null)
{
if (i_FriendsToAsk.SelectedItem != null)
{
i_FriendsToAsk.Items.Remove(i_FriendsToAsk.SelectedItem);
}
else
{
MessageBox.Show("There are no friends to delete.");
}
}
else
{
throw new Exception("You must be logged in, in order to proceed.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
}
|
24c961d6a31fdf6cd6022398fb143f14453189a9
|
C#
|
jesfisher/gitstudy
|
/SW插件-ZQ/ZQCODE/frmMaterialClass.cs
| 2.515625
| 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 ZQCode
{
public partial class frmMaterialClass : Form
{
private MaterialService objMaterialService = new MaterialService();
private DataTable dtMaterialClass = new DataTable();
public frmMaterialClass()
{
InitializeComponent();
AddMaterialTree();
}
#region 添加物料编码分类树结构(dtMaterialClass)
//添加物料编码分类树
private void AddMaterialTree()
{
//【仅显示集团和本事业部的物料分类】获取树节点需要的数据
dtMaterialClass = objMaterialService.GetFactoryMaterialClass();
DataView dv = new DataView(dtMaterialClass);
//创建一个根节点:默认根节点的值=0
this.tvMaterialClass.Nodes.Clear();
TreeNode rootNode = new TreeNode();
rootNode.Text = "物料分类";
rootNode.Tag = "0_0";
rootNode.Name = "0";
this.tvMaterialClass.Nodes.Add(rootNode);//添加根节点
CreateChildNode(rootNode, dtMaterialClass, "0");//递归方法调用
this.tvMaterialClass.Nodes[0].Expand(); //将递归树的一级目录展开
}
//递归
private void CreateChildNode(TreeNode parentNode, DataTable dt, string parentId)
{
//找到所有以该节点为父节点的子项
DataRow[] rowList = dt.Select(string.Format("ParentId='{0}'", parentId));
//循环创建该节点的所有子节点
foreach (DataRow dr in rowList)
{
//创建新的节点并设置属性
TreeNode childNode = new TreeNode();
childNode.Text = string.Format("【{0}】{1}", dr["MaterialClassId"].ToString(), dr["MaterialClassName"].ToString());
childNode.Tag = dr["MaterialClassId"].ToString() + "_" + dr["ParentId"].ToString();
childNode.Name = dr["MaterialClassId"].ToString();
parentNode.Nodes.Add(childNode); //父节点加入该子节点
childNode.ImageIndex = childNode.Level;//设置节点图片(来自ImageList)
//递归调用,以此子节点为父节点创建该子节点的其他节点
CreateChildNode(childNode, dt, dr["MaterialClassId"].ToString());
}
}
#endregion
//选择正确的子节点,并给全局变量赋值
private void tsbConfirm_Click(object sender, EventArgs e)
{
//未选中任何节点,提示
if (tvMaterialClass.SelectedNode == null)
{
Msg.ShowError("未选中任何节点,无法操作!");
return;
}
//选中节点的ID【MaterialClassId】
string selectedNodeId = tvMaterialClass.SelectedNode.Tag.ToString().Split('_')[0];
//选中最后一层,不允许添加节点
if (selectedNodeId.Length < 4)//最后一层,位数为4位,如:1001
{
Msg.ShowError("请选择最后一级节点!");
return;
}
//从数据库获取选中节点的完整信息
DataRow dr = objMaterialService.GetMaterialClassById(selectedNodeId);
MaterialModel objMaterial = new MaterialModel()
{
MaterialClassId = selectedNodeId,
IsPublic = ConvertEx.ToBoolean(dr["IsPublic"]),
FactoryCode = ConvertEx.ToString(dr["FactoryCode"])
};
//Globals.CurrentMaterial.MaterialClassId = ConvertEx.ToInt(selectedNodeId);
//Globals.CurrentMaterial.IsPublic = ConvertEx.ToBoolean(dr["IsPublic"]);
//Globals.CurrentMaterial.FactoryCode = ConvertEx.ToString(dr["FactoryCode"]);
if (selectedNodeId.Length == 4)
{
Globals.CurrentMaterial = objMaterial;
this.DialogResult = DialogResult.Yes;
}
else
{
this.DialogResult = DialogResult.No;
}
//Msg.ShowInformation(objMaterial.MaterialClassId.ToString());
}
}
}
|
633a153c7a47422479317e6bf99ff6fec5ffaf19
|
C#
|
Manasa987/contact-page
|
/BankApplication/BankApplication/BankApplication/Lowest.cs
| 3.109375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankApplication
{
class Lowest:IAction
{
public void DoAction()
{
Console.Clear();
Console.WriteLine("List of users having lower balances");
Console.WriteLine("-----------------------------------");
var sortedDict = (from item in Manager.ListofAccounts
orderby item.Value
ascending
select item).Take(3);
foreach (var item in sortedDict)
Console.WriteLine(item.Key + "\t\t" + item.Value);
Console.Read();
}
}
}
|
95fc89dbe1f6cecef9e89996ab8fb3694e47408b
|
C#
|
sillyatom/ProjectMaze
|
/ProjectRogue/Assets/Scripts/Utility/MessageManager.cs
| 2.53125
| 3
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class MessageVO
{
public float displayTime;
public string message;
public float scale;
public bool showBlocker;
public MessageVO(string message, float displayTime, float scale, bool showBlocker)
{
this.displayTime = displayTime;
this.message = message;
this.scale = scale;
this.showBlocker = showBlocker;
}
}
public class MessageManager
{
private static MessageManager instance;
private Message _activeMessage;
private List<MessageVO> _messages;
public static MessageManager GetInstance()
{
if (instance == null)
{
instance = new MessageManager();
}
return instance;
}
public MessageManager()
{
_messages = new List<MessageVO>();
_activeMessage = null;
}
public void ShowMessage(string msg, float displayTime = 1.5f, float scale = 1.0f, bool showBlocker = false)
{
if (_activeMessage != null && string.Compare(msg, _activeMessage.GetMessage(), true) != 0)
{
_messages.Add(new MessageVO(msg, displayTime, scale, showBlocker));
}
if (_activeMessage == null)
{
_messages.Add(new MessageVO(msg, displayTime, scale, showBlocker));
ShowNext();
}
}
private void ShowNext()
{
if (_activeMessage == null && _messages.Count > 0)
{
string message = _messages[0].message;
float displayTime = _messages[0].displayTime;
float scale = _messages[0].scale;
bool showBlocker = _messages[0].showBlocker;
_messages.RemoveAt(0);
DisplayMessage(message, displayTime, scale, showBlocker);
}
else if (ObjectCache.instance.messagepanel.childCount > 0)
{
GameObject.Destroy(ObjectCache.instance.messagepanel.GetChild(0));
}
}
private void DisplayMessage(string msg, float seconds, float scale, bool showBlocker)
{
GameObject go = AssetReference.instance.GetGameObjectInstance("Message");
go.transform.SetParent(ObjectCache.instance.messagepanel);
ObjectCache.instance.messagepanel.GetComponent<Image>().enabled = showBlocker;
go.GetComponent<RectTransform>().anchoredPosition = Vector3.zero;
go.transform.localScale = Vector3.one * scale;
_activeMessage = go.GetComponent<Message>();
_activeMessage.SetText(msg, seconds, DestroyOnSeconds);
}
private void DestroyOnSeconds()
{
ObjectCache.instance.messagepanel.GetComponent<Image>().enabled = false;
_activeMessage = null;
ShowNext();
}
}
|
5e8b7ed6000557e5e99c94b566bc32bfc36528d0
|
C#
|
JSystemsTech/DBFacade.Net
|
/DbFacadeShared/DataLayer/Models/Validators/Rules/ValidationRuleResult.cs
| 2.890625
| 3
|
using System.Threading.Tasks;
namespace DbFacade.DataLayer.Models.Validators.Rules
{
/// <summary>
///
/// </summary>
public enum ValidationStatus
{
/// <summary>
/// The pass
/// </summary>
PASS,
/// <summary>
/// The fail
/// </summary>
FAIL
}
/// <summary>
///
/// </summary>
public interface IValidationRuleResult
{
/// <summary>
/// Gets the status.
/// </summary>
/// <value>
/// The status.
/// </value>
ValidationStatus Status { get; }
/// <summary>
/// Gets the error message.
/// </summary>
/// <value>
/// The error message.
/// </value>
string ErrorMessage { get; }
/// <summary>
/// Gets the model.
/// </summary>
/// <value>
/// The model.
/// </value>
object Model { get; }
}
/// <summary>
///
/// </summary>
internal sealed class ValidationRuleResult : IValidationRuleResult
{
/// <summary>
/// Initializes a new instance of the <see cref="ValidationRuleResult" /> class.
/// </summary>
/// <param name="model">The model.</param>
/// <param name="errorMessage">The error message.</param>
/// <param name="status">The status.</param>
public ValidationRuleResult(object model, string errorMessage, ValidationStatus status)
{
Model = model;
ErrorMessage = errorMessage;
Status = status;
}
/// <summary>
/// Initializes a new instance of the <see cref="ValidationRuleResult"/> class.
/// </summary>
public ValidationRuleResult() { }
/// <summary>
/// Creates the asynchronous.
/// </summary>
/// <param name="model">The model.</param>
/// <param name="errorMessage">The error message.</param>
/// <param name="status">The status.</param>
/// <returns></returns>
public static async Task<ValidationRuleResult> CreateAsync(object model, string errorMessage, ValidationStatus status)
{
ValidationRuleResult result = new ValidationRuleResult();
await result.InitializeAsync(model, errorMessage, status);
return result;
}
/// <summary>
/// Initializes the asynchronous.
/// </summary>
/// <param name="model">The model.</param>
/// <param name="errorMessage">The error message.</param>
/// <param name="status">The status.</param>
private async Task InitializeAsync(object model, string errorMessage, ValidationStatus status)
{
Model = model;
ErrorMessage = errorMessage;
Status = status;
await Task.CompletedTask;
}
/// <summary>
/// Gets the status.
/// </summary>
/// <value>
/// The status.
/// </value>
public ValidationStatus Status { get; private set; }
/// <summary>
/// Gets the error message.
/// </summary>
/// <value>
/// The error message.
/// </value>
public string ErrorMessage { get; private set; }
/// <summary>
/// Gets the model.
/// </summary>
/// <value>
/// The model.
/// </value>
public object Model { get; private set; }
}
}
|
aeb116dbb2778e34424d2781fef89dee3175a623
|
C#
|
DeveloperIlnaz/VirtualFitnessTrainer
|
/VirtualFitnessTrainer.MVC/Controllers/SerializableDataManager.cs
| 3.1875
| 3
|
using System.IO;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
namespace VirtualFitnessTrainer.MVC.Controllers
{
/// <summary>
/// Serializable менеджер данных.
/// </summary>
public class SerializableDataManager : IDataManager
{
#region Methods
/// <summary>
/// Выгружает (десериализует) данные.
/// </summary>
/// <typeparam name="T">Тип элментов.</typeparam>
/// <returns></returns>
public List<T> Load<T>() where T : class
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
string filePath = typeof(T).Name + ".dat";
using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate))
{
if (fileStream.Length < 1)
{
return new List<T>();
}
List<T> items = binaryFormatter.Deserialize(fileStream) as List<T>;
return items;
}
}
/// <summary>
/// Сохраняет (сериализует) данные.
/// </summary>
/// <typeparam name="T">Тип элементов.</typeparam>
/// <param name="items">Элементы.</param>
public void Save<T>(List<T> items) where T : class
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
string filePath = typeof(T).Name + ".dat";
using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate))
{
binaryFormatter.Serialize(fileStream, items);
}
}
#endregion
}
}
|
13fc8436fff5e53c2b530d36389d2421c35ac60f
|
C#
|
nixelt/E-Shop
|
/E-Shop/E-Shop.Service/ProductFilters/ProductDeletedFilter.cs
| 2.5625
| 3
|
namespace E_Shop.Service.ProductFilters
{
using System.Collections.Generic;
using System.Linq;
using Model;
public class ProductDeletedFilter : IProductFilter
{
private readonly bool _deleted;
public ProductDeletedFilter(bool deleted)
{
_deleted = deleted;
}
public IEnumerable<Product> GetEntities(IEnumerable<Product> products)
{
products = products.Where(x => x.IsDeleted == _deleted);
return products;
}
}
}
|
c3dca94b010db056e4f179e22fb706d83a7a9282
|
C#
|
sean-m/mre
|
/Model/Condition/ConditionNotMatch.cs
| 2.640625
| 3
|
namespace Granfeldt
{
using Microsoft.MetadirectoryServices;
using System.Text.RegularExpressions;
public class ConditionNotMatch : ConditionBase
{
public string MVAttribute;
public string Pattern;
public override bool Met(MVEntry mventry, CSEntry csentry)
{
if (mventry[this.MVAttribute].IsPresent)
{
if (Regex.IsMatch(mventry[this.MVAttribute].Value, this.Pattern, RegexOptions.IgnoreCase))
{
Tracer.TraceInformation("Condition failed (Reason: RegEx match) {0}", this.Description);
return false;
}
}
return true; // value not present effectively means not-match
}
}
}
|
c41289b1350b14647e60c194f080894a650fd683
|
C#
|
Bodzounet/XYZ
|
/Assets/Scripts/AI/EnemyHealthManager.cs
| 2.578125
| 3
|
using UnityEngine;
using System.Collections;
using System;
public class EnemyHealthManager : HealthManager
{
public delegate void Die();
public event Die OnDie;
public override void TakeDamages(int damages)
{
Life -= damages;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.T))
{
TakeDamages(10);
}
}
protected override void _Die()
{
if (OnDie != null)
OnDie();
}
}
|
647de3918399a6b8498eabae8295bb4a11f2ce0e
|
C#
|
anemeu/ble
|
/DemoXamarinBLE/DemoXamarinBLE/VistaModelo/VistaModeloBLE.cs
| 2.59375
| 3
|
using DemoXamarinBLE.Modelo;
using Plugin.BLE;
using Plugin.BLE.Abstractions.Contracts;
using Plugin.BLE.Abstractions.EventArgs;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using Xamarin.Forms;
namespace DemoXamarinBLE.VistaModelo
{
public class VistaModeloBLE : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
// modelo
private ModeloBLE _modelo;
public ModeloBLE modelo
{
get
{
return _modelo;
}
set
{
_modelo = value;
OnPropertyChanged("modelo");
}
}
// gestor de BLE
private IAdapter bleAdapter;
private IBluetoothLE bleHandler;
public VistaModeloBLE()
{
// este constructor hace todo
// crea el modelo
modelo = new ModeloBLE
{
EstatusBLE = "",
ListaCaracteristicas = new System.Collections.ObjectModel.ObservableCollection<Plugin.BLE.Abstractions.Contracts.ICharacteristic>(),
ListaDispositivos = new System.Collections.ObjectModel.ObservableCollection<Plugin.BLE.Abstractions.Contracts.IDevice>(),
ListaServicios = new System.Collections.ObjectModel.ObservableCollection<Plugin.BLE.Abstractions.Contracts.IService>(),
DatosLeidos = ""
};
// obteniendo las instancias del hardware ble
bleHandler = CrossBluetoothLE.Current;
bleAdapter = CrossBluetoothLE.Current.Adapter;
// configurando evento inicial del proceso de escaneo de dispositivos
// y cambios de estado
bleHandler.StateChanged += (sender, args) =>
{
modelo.EstatusBLE = $"Estado del bluetooth: {args.NewState}";
};
bleAdapter.ScanMode = ScanMode.LowPower; // se establece que el escaneo de advertising se optimiza para bajo consumo
bleAdapter.ScanTimeout = 10000; // tiempo de busqueda de dispositivos en advertising
bleAdapter.ScanTimeoutElapsed += (sender, args) =>
{
System.Diagnostics.Debug.WriteLine("El escaneo se ha terminado");
modelo.EstatusBLE = $"Estado del bluetooth: {bleHandler.State}";
};
// se ejecuta cuando BLE encuentra un dispositivo que esta en advertising
bleAdapter.DeviceDiscovered += (sender, args) =>
{
System.Diagnostics.Debug.WriteLine("Se ha descubierto un dispositivo");
IDevice dispositivoDescubierto = args.Device;
// buscando en la lista de dispositivos en memoria si ya existe
//List<IDevice> lstDispositivoRepetido = (from disps in modelo.ListaDispositivos
// where disps.Name == dispositivoDescubierto.Name
// select disps).ToList();
//// no hay repetidos
//if (!lstDispositivoRepetido.Any())
//{
modelo.ListaDispositivos.Add(dispositivoDescubierto);
//}
};
bleAdapter.DeviceDisconnected += OnDeviceDisconnected;
bleAdapter.DeviceConnectionLost += OnDeviceConnectionLost;
modelo.EstatusBLE = "Listo...";
}
private void OnDeviceConnectionLost(object sender, DeviceErrorEventArgs e)
{
/*Devices.FirstOrDefault(d => d.Id == e.Device.Id)?.Update();
_userDialogs.HideLoading();
_userDialogs.ErrorToast("Error", $"Connection LOST {e.Device.Name}", TimeSpan.FromMilliseconds(6000));*/
System.Diagnostics.Debug.WriteLine("CONNECTION LOST !!!!");
}
private void OnDeviceDisconnected(object sender, DeviceEventArgs e)
{
/*Devices.FirstOrDefault(d => d.Id == e.Device.Id)?.Update();
_userDialogs.HideLoading();
_userDialogs.Toast($"Disconnected {e.Device.Name}");
Console.WriteLine($"Disconnected {e.Device.Name}");*/
System.Diagnostics.Debug.WriteLine("DEVICE DISCONNECTED !!!!");
}
// conecta a dispositivo conocido
private Command _CmdConectaDispositivoConocido;
public Command CmdConectaDispositivoConocido
{
get
{
if (_CmdConectaDispositivoConocido == null)
{
_CmdConectaDispositivoConocido = new Command(async () =>
{
System.Diagnostics.Debug.WriteLine("conectar a dispositivo conocido");
//System.Guid address = new System.Guid("D5-07-0E-4F-46-B7");
//IDevice disp = await bleAdapter.ConnectToKnownDeviceAsync(System.Guid.Parse("00000000-0000-0000-0000-d5070e4f46b7"));
IDevice disp = await bleAdapter.ConnectToKnownDeviceAsync(System.Guid.Parse("00000000-0000-0000-0000-000d6f289f87"));
modelo.ListaServicios.Clear();
foreach (IService servicio in await disp.GetServicesAsync())
{
if (servicio.Id.Equals(System.Guid.Parse("85601a0a-82b5-4c25-a107-565ff8402d97")))
{
System.Diagnostics.Debug.WriteLine("ES EL MISMO ID!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
//servicio.Name.Concat("IKKONEKT");
}
modelo.ListaServicios.Add(servicio);
}
// pasar a la siguiente pagina
modelo.EstatusBLE = $"Estado del bluetooth: {bleHandler.State}";
await ((NavigationPage)App.Current.MainPage).PushAsync(new Vista.VistaServicios(App.vmBle));
});
}
return _CmdConectaDispositivoConocido;
}
}
private Command _CmdIniciaEscaneo;
public Command CmdIniciaEscaneo
{
get
{
if (_CmdIniciaEscaneo == null)
{
_CmdIniciaEscaneo = new Command(async () =>
{
try
{
await ((NavigationPage)App.Current.MainPage).PushAsync(new Vista.VistaDispositivos(App.vmBle));
if (!bleAdapter.IsScanning)
{
System.Diagnostics.Debug.WriteLine("Comienza el escaneo");
modelo.EstatusBLE = "Escanenado por dispositivos BLE";
modelo.ListaDispositivos.Clear();
await bleAdapter.StartScanningForDevicesAsync();
}
}
catch (System.Exception ex)
{
await App.Current.MainPage.DisplayAlert("Demo BLE", ex.Message, "Ok");
}
});
}
return _CmdIniciaEscaneo;
}
}
// conecta el dispositivo
private Command _CmdConectaDispositivo;
public Command CmdConectaDispositivo
{
get
{
if (_CmdConectaDispositivo == null)
{
_CmdConectaDispositivo = new Command(async () =>
{
if (bleAdapter.IsScanning)
{
await bleAdapter.StopScanningForDevicesAsync();
}
modelo.EstatusBLE = "Conectando con el periférico...";
//await bleAdapter.ConnectToDeviceAsync(modelo.DispositivoConectado, new Plugin.BLE.Abstractions.ConnectParameters(true,false));
await bleAdapter.ConnectToDeviceAsync(modelo.DispositivoConectado);
System.Diagnostics.Debug.WriteLine("SE CONECTA!!!!!!!!!!!!!!!!");
modelo.ListaServicios.Clear();
foreach (IService servicio in await modelo.DispositivoConectado.GetServicesAsync())
{
modelo.ListaServicios.Add(servicio);
}
// pasar a la siguiente pagina
modelo.EstatusBLE = $"Estado del bluetooth: {bleHandler.State}";
await ((NavigationPage)App.Current.MainPage).PushAsync(new Vista.VistaServicios(App.vmBle));
});
}
return _CmdConectaDispositivo;
}
}
private Command _CmdSeleccionaServicio;
public Command CmdSeleccionaServicio
{
get
{
if (_CmdSeleccionaServicio == null)
{
_CmdSeleccionaServicio = new Command(async () =>
{
modelo.ListaCaracteristicas.Clear();
foreach (ICharacteristic characteristic in await modelo.ServicioSeleccionado.GetCharacteristicsAsync())
{
modelo.ListaCaracteristicas.Add(characteristic);
}
// cambiar pagina
await ((NavigationPage)App.Current.MainPage).PushAsync(new Vista.VistaCaracteristicas(App.vmBle));
});
}
return _CmdSeleccionaServicio;
}
}
private Command _CmdInteractuarConCaracteristica;
public Command CmdInteractuarConCaracteristica
{
get
{
if (_CmdInteractuarConCaracteristica == null)
{
_CmdInteractuarConCaracteristica = new Command(async () =>
{
// imprimir las capacidades de la caracteristica
System.Diagnostics.Debug.WriteLine($"Capcidades de la caracteristica: Lectura {modelo.CaracteristicaSeleccionada.CanRead}, Escritura {modelo.CaracteristicaSeleccionada.CanWrite}, Actualizacion {modelo.CaracteristicaSeleccionada.CanWrite}");
// HEMENDIK NOTIFY-ENA
/*
//var descriptor = await modelo.CaracteristicaSeleccionada.GetDescriptorAsync(System.Guid.Parse("{00002902-0000-1000-8000-00805f9b34fb}"));
var descriptor = await modelo.CaracteristicaSeleccionada.GetDescriptorAsync(System.Guid.Parse("{f1e1a72c-6a1e-4558-ae90-c29d2e20245a}"));
if (descriptor != null)
{
byte[] array2 = { 02, 00};
await descriptor.WriteAsync(array2);
} else
{
System.Diagnostics.Debug.WriteLine("No descriptor");
}
modelo.CaracteristicaSeleccionada.ValueUpdated += (o, args) =>
{
var bytes = args.Characteristic.Value;
//var result = System.BitConverter.ToInt64(bytes,0);
foreach(var b in bytes)
{
System.Diagnostics.Debug.WriteLine(b);
}
System.Diagnostics.Debug.WriteLine("UPDATE!!!!!!");
};
modelo.CaracteristicaSeleccionada.ValueUpdated += (o, args) =>
{
var bytes = args.Characteristic.Value;
};
await modelo.CaracteristicaSeleccionada.StartUpdatesAsync();
*/
// HONAINO
/*
if (modelo.CaracteristicaSeleccionada.CanRead)
{
byte[] datos = await modelo.CaracteristicaSeleccionada.ReadAsync();
System.Diagnostics.Debug.WriteLine($"Datos: {Encoding.UTF8.GetString(datos)}");
}
if (modelo.CaracteristicaSeleccionada.CanWrite)
{
string newName = "Ane";
byte[] newNameBytes = Encoding.ASCII.GetBytes(newName);
await modelo.CaracteristicaSeleccionada.WriteAsync(newNameBytes);
}
if (modelo.CaracteristicaSeleccionada.CanRead)
{
byte[] datos = await modelo.CaracteristicaSeleccionada.ReadAsync();
System.Diagnostics.Debug.WriteLine($"Datos: {Encoding.UTF8.GetString(datos)}");
}
*/
await ((NavigationPage)App.Current.MainPage).PushAsync(new Vista.ReadWritePage(App.vmBle));
});
}
return _CmdInteractuarConCaracteristica;
}
}
private Command _CmdRead;
public Command CmdRead
{
get
{
if (_CmdRead == null)
{
_CmdRead = new Command(async () =>
{
// imprimir las capacidades de la caracteristica
System.Diagnostics.Debug.WriteLine($"Capcidades de la caracteristica: Lectura {modelo.CaracteristicaSeleccionada.CanRead}, Escritura {modelo.CaracteristicaSeleccionada.CanWrite}, Actualizacion {modelo.CaracteristicaSeleccionada.CanWrite}");
if (modelo.CaracteristicaSeleccionada.CanRead)
{
System.Diagnostics.Debug.WriteLine("Hona bai");
byte[] datos = await modelo.CaracteristicaSeleccionada.ReadAsync();
System.Diagnostics.Debug.WriteLine("Hone be bai");
System.Diagnostics.Debug.WriteLine($"Daots en bytes: {datos[0]}");
//System.Diagnostics.Debug.WriteLine($"Datos: {Encoding.UTF8.GetString(datos)}");
System.Diagnostics.Debug.WriteLine(modelo.DatosLeidos);
//modelo.DatosLeidos = Encoding.UTF8.GetString(datos);
modelo.DatosLeidos = datos[0].ToString();
System.Diagnostics.Debug.WriteLine(modelo.DatosLeidos);
}
/*
if (modelo.CaracteristicaSeleccionada.CanWrite)
{
string newName = "Ane";
byte[] newNameBytes = Encoding.ASCII.GetBytes(newName);
await modelo.CaracteristicaSeleccionada.WriteAsync(newNameBytes);
}*/
});
}
return _CmdRead;
}
}
private Command _CmdWrite;
public Command CmdWrite
{
get
{
if (_CmdWrite == null)
{
_CmdWrite = new Command(async () =>
{
// imprimir las capacidades de la caracteristica
System.Diagnostics.Debug.WriteLine($"Capcidades de la caracteristica: Lectura {modelo.CaracteristicaSeleccionada.CanRead}, Escritura {modelo.CaracteristicaSeleccionada.CanWrite}, Actualizacion {modelo.CaracteristicaSeleccionada.CanWrite}");
System.Diagnostics.Debug.WriteLine(modelo.TextoEnviar);
if (modelo.CaracteristicaSeleccionada.CanWrite)
{
/*string newName = "Ane2";
byte[] newNameBytes = Encoding.ASCII.GetBytes(newName);
await modelo.CaracteristicaSeleccionada.WriteAsync(newNameBytes);*/
//await modelo.CaracteristicaSeleccionada.WriteAsync(Encoding.ASCII.GetBytes(modelo.TextoEnviar));
await modelo.CaracteristicaSeleccionada.WriteAsync(System.BitConverter.GetBytes(modelo.TextoEnviar));
//System.Diagnostics.Debug.WriteLine($"Bytes: {System.BitConverter.GetBytes(modelo.TextoEnviar)}");
}
});
}
return _CmdWrite;
}
}
private Command _CmdHabilitarNot;
public Command CmdHabilitarNot
{
get
{
if (_CmdHabilitarNot == null)
{
_CmdHabilitarNot = new Command(async () =>
{
//var descriptor = await modelo.CaracteristicaSeleccionada.GetDescriptorAsync(System.Guid.Parse("{f1e1a72c-6a1e-4558-ae90-c29d2e20245a}"));
/* modelo.DescriptorSeleccionado = await modelo.CaracteristicaSeleccionada.GetDescriptorAsync(System.Guid.Parse("{f1e1a72c-6a1e-4558-ae90-c29d2e20245a}"));
if (modelo.DescriptorSeleccionado != null)
{
byte[] array2 = { 02, 00 };
await modelo.DescriptorSeleccionado.WriteAsync(array2);
modelo.DatosNotificacion += "Notificaciones habilitadas\n";
}
else
{
System.Diagnostics.Debug.WriteLine("No descriptor");
}*/
modelo.DatosNotificacion += "Notificaciones habilitadas\n";
modelo.CaracteristicaSeleccionada.ValueUpdated += (o, args) =>
{
var bytes = args.Characteristic.Value;
//var result = System.BitConverter.ToInt64(bytes,0);
// modelo.DatosNotificacion += "Temperatura: " + bytes[0] + "\n";
System.Diagnostics.Debug.WriteLine("NOTIFICACIONES");
// for (int i=0; i<1; i++)
// {
// System.Diagnostics.Debug.WriteLine("Byte 1:");
// System.Diagnostics.Debug.WriteLine(bytes.GetValue(0));
// }
System.Diagnostics.Debug.WriteLine("Temperatura: " + bytes.GetValue(0) + "\n");
modelo.DatosNotificacion += "Temperatura: " + bytes.GetValue(0) + "\n";
// foreach (var b in bytes)
// {
// System.Diagnostics.Debug.WriteLine(b);
// modelo.DatosNotificacion += "Temperatura: " + b + "\n";
// System.Diagnostics.Debug.WriteLine("Temperatura: " + b);
// }
System.Diagnostics.Debug.WriteLine("UPDATE!!!!!!");
};
/* modelo.CaracteristicaSeleccionada.ValueUpdated += (o, args) =>
{
var bytes = args.Characteristic.Value;
};*/
await modelo.CaracteristicaSeleccionada.StartUpdatesAsync();
});
}
return _CmdHabilitarNot;
}
}
private Command _CmdDeshabilitarNot;
public Command CmdDeshabilitarNot
{
get
{
if (_CmdDeshabilitarNot == null)
{
_CmdDeshabilitarNot = new Command(async () =>
{
//modelo.DescriptorSeleccionado = await modelo.CaracteristicaSeleccionada.GetDescriptorAsync(System.Guid.Parse("{f1e1a72c-6a1e-4558-ae90-c29d2e20245a}"));
await modelo.CaracteristicaSeleccionada.StopUpdatesAsync();
// modelo.DescriptorSeleccionado = await modelo.CaracteristicaSeleccionada.GetDescriptorAsync(System.Guid.Parse("{f1e1a72c-6a1e-4558-ae90-c29d2e20245a}"));
// byte[] array2 = { 00, 00 };
// await modelo.DescriptorSeleccionado.WriteAsync(array2);
modelo.DatosNotificacion += "Notificaciones deshabilitadas\n";
});
}
return _CmdDeshabilitarNot;
}
}
public void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
|
1d2b01e2cb7469dd48278629afc3a9c654272f23
|
C#
|
shendongnian/download4
|
/code2/361660-59877740-213520077-2.cs
| 3.9375
| 4
|
static void Main(string[] args)
{
GetCombination(new List<int> { 1, 2, 3 });
}
private static void GetCombination(List<int> list)
{
var bitwiseList = new List<int>(list.Count);
for (int i = 0; i < list.Count; i++)
{
// Builds a list containing [1,2,4,8,16 etc.]
bitwiseList.Add(1 << i);
}
double count = Math.Pow(2, list.Count);
for (int i = 1; i <= count - 1; i++)
{
for (int j = 0; j < list.Count; j++)
{
int b = i & bitwiseList[j];
if (b > 0)
{
Console.Write(list[j]);
}
}
Console.WriteLine();
}
}
|
92a22da3737e7694074bcc61f84201c690f1bbde
|
C#
|
DanielBMann9000/SpecFlow-Examples
|
/EulerPoker54/EulerPoker54.Tests.Unit/When_Creating_A_Poker_Card.cs
| 3.03125
| 3
|
using EulerPoker54.Core.Model;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace EulerPoker54.Tests.Unit
{
[TestClass]
public class When_Creating_A_Poker_Card
{
[TestMethod]
public void Can_Create_A_Poker_Card()
{
var card = new Card(Value.Ten, Suit.Hearts);
Assert.IsNotNull(card);
}
[TestMethod]
public void A_Card_Has_A_Suit_And_A_Value()
{
var card = new Card(Value.Ten, Suit.Hearts);
Assert.AreEqual(Value.Ten, card.Value);
Assert.AreEqual(Suit.Hearts, card.Suit);
}
}
}
|
c7b8a11ef638d381524013bffe67324b55a3d261
|
C#
|
nadya02/It-kariera
|
/02. Programming/4. Arrays and lists/Lists/SquareNumbers.cs
| 3.640625
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SquareNumbers
{
class SquareNumbers
{
static void Main(string[] args)
{
List<int> nums = Console.ReadLine().Split(' ').Select(int.Parse).ToList();
nums.Sort();
nums.Reverse();
for (int i = 0; i < nums.Count; i++)
{
int x =(int)Math.Sqrt(nums[i]);
if (x * x == nums[i]) Console.Write(nums[i]+" ");
}
Console.WriteLine();
}
}
}
|
ddee90b817ec12ea04e2c3ef436317373cf4ce38
|
C#
|
EmrullahKarakoc/cs_sakarya
|
/1.SINIF/2.Yarıyıl/Nesneye Dayalı Programlama/C# Örnekler/C#/NamespaceClass/NamespaceClass/Program.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NamespaceClass
{
class temel_sinif
{
protected void method1()
{
Console.WriteLine("ben temel sınıf methoduyum");
}
}
class tureyen_sinif:temel_sinif
{
public void method2()
{
Console.WriteLine("ben tureyen sinif methoduyum");
}
}
class Program
{
static void Main(string[] args)
{
tureyen_sinif obj = new tureyen_sinif();
obj.method2();
}
}
}
|
b216358010ad5c024337e6d804fece0e9ba4d662
|
C#
|
Yotsev/CSharpAdvanced
|
/01.StacksAndQueues/StacksAndQueuesLabExercise/12.CupsAndBottles/Program.cs
| 3.6875
| 4
|
using System;
using System.Linq;
using System.Collections.Generic;
namespace _12.CupsAndBottles
{
class Program
{
static void Main(string[] args)
{
int[] cupCapacity = Console.ReadLine()
.Split(" ", StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
int[] filledBottles = Console.ReadLine()
.Split(" ", StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
Stack<int> cups = new Stack<int>(cupCapacity.Reverse());
Stack<int> bottles = new Stack<int>(filledBottles);
int wastedLitters = 0;
bool allCupsAreFilled = false;
while (bottles.Count > 0 && cups.Count > 0)
{
if (cups.Peek() > bottles.Peek())
{
cups.Push(cups.Pop() - bottles.Pop());
}
else if (cups.Peek() <= bottles.Peek())
{
wastedLitters += bottles.Pop() - cups.Pop();
}
if (cups.Count == 0)
{
allCupsAreFilled = true;
}
}
if (allCupsAreFilled)
{
Console.WriteLine($"Bottles: {string.Join(" ",bottles)}");
}
else
{
Console.WriteLine($"Cups: {string.Join(" ",cups)}");
}
Console.WriteLine($"Wasted litters of water: {wastedLitters}");
}
}
}
|
b37004f9a8371c6778f3b13136b33d0f43b5ce85
|
C#
|
damp-xx/Damp
|
/DampGUIv2/DampGUI/Models/EventSubscriber.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Xml;
using CommunicationLibrary;
namespace DampGUI
{
internal class EventSubscriber : IEventSubscribe
{
public static Dictionary<string, ChatView> ChatIdentyfier = new Dictionary<string, ChatView>();
public void HandleNewChatMessage(string from, string message, string fromTitle)
{
Console.WriteLine("HandleNewChatMessage");
Console.WriteLine(from + message);
if (ChatIdentyfier.ContainsKey(from))
{
try
{
Console.WriteLine("from known");
var d = ChatIdentyfier[from];
d.Dispatcher.BeginInvoke(new Action(delegate() { d.SendData(fromTitle + ": " + message); }));
}
catch (InvalidCastException)
{
Console.WriteLine("blablabla" + from);
}
}
else
{
Console.WriteLine("from unknown");
MainWindow._MWDispatcher.MwDispatcher.BeginInvoke(new Action(delegate()
{
var d = new ChatView(from);
d.Owner = Application.Current.MainWindow;
d.Show();
d.SendData(fromTitle + ": " + message);
ChatIdentyfier.Add(from, d);
}));
}
}
public void HandleUserOnline(XmlElement Event)
{
MainPageViewModel.MpvmDispatcherclassDispatcher.MpvmDispatcher.BeginInvoke(new Action(delegate()
{
var userid = Event.GetElementsByTagName("Message").Item(0).InnerText;
MainPageViewModel.MpvmDispatcherclassDispatcher.MpvmDispatcher.BeginInvoke(new Action(delegate()
{
foreach (var friend in MainPageViewModel.MpvmDispatcherclassDispatcher.friends.Where(friend => friend.Id.Equals(userid)))
{
friend.Name = "(Online) " + friend.RealName;
break;
}
}));
}));
}
public void HandleUserOffline(XmlElement Event)
{
MainPageViewModel.MpvmDispatcherclassDispatcher.MpvmDispatcher.BeginInvoke(new Action(delegate()
{
var userid = Event.GetElementsByTagName("Message").Item(0).InnerText;
MainPageViewModel.MpvmDispatcherclassDispatcher.MpvmDispatcher.BeginInvoke(new Action(delegate()
{
foreach (var friend in MainPageViewModel.MpvmDispatcherclassDispatcher.friends.Where(friend => friend.Id.Equals(userid)))
{
friend.Name = friend.RealName;
break;
}
}));
}));
}
public void HandleFriendRequest(XmlElement Event)
{
MainPageViewModel.MpvmDispatcherclassDispatcher.MpvmDispatcher.BeginInvoke(new Action(delegate()
{
var userid = Event.GetElementsByTagName("From").Item(0).InnerText;
MainPageViewModel.MpvmDispatcherclassDispatcher.MpvmDispatcher.BeginInvoke(new Action(delegate()
{
Friend friend = ComFriend.GetUser(userid);
MainPageViewModel.MpvmDispatcherclassDispatcher.friends.Add(friend);
}));
}));
}
public void HandleFriendAccepted(XmlElement Event)
{
MainPageViewModel.MpvmDispatcherclassDispatcher.MpvmDispatcher.BeginInvoke(new Action(delegate()
{
var userid = Event.GetElementsByTagName("From").Item(0).InnerText;
MainPageViewModel.MpvmDispatcherclassDispatcher.MpvmDispatcher.BeginInvoke(new Action(delegate()
{
Friend friend = ComFriend.GetUser(userid);
MainPageViewModel.MpvmDispatcherclassDispatcher.friends.Add(friend);
}));
}));
}
public static void NewChat(string from, ChatView Instance)
{
if (!ChatIdentyfier.ContainsKey(from))
{
//Console.WriteLine("Hej from: {0}", from);
ChatIdentyfier.Add(from, Instance);
}
}
}
}
|