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
|
|---|---|---|---|---|---|---|
0b9a1b9ec47452ab1ccf9e60b11a7752c58fc52b
|
C#
|
LafoiMasque/WebMVCSite
|
/WebSite.RabbitMQProducer/Program.cs
| 2.859375
| 3
|
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WebSite.RabbitMQProducer
{
class Program
{
static void Main(string[] args)
{
//部署在我的服务器 http://120.78.212.68:15672/#/ 帐号密码不公开
var factory = new ConnectionFactory
{
HostName = "localhost",//RabbitMQ服务在本地运行
// Port = 5672,
UserName = "****",
Password = "****"
};
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
//channel 通信
//第二个参数为是否持久化
channel.QueueDeclare("Test", true, false, false, null);//创建一个名称为hello的消息队列
string message = "vidic.huang"; //传递的消息内容
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish("", "Test", null, body); //开始传递
Console.WriteLine("已发送: {0}", message);
Console.ReadLine();
}
}
Console.ReadKey();
}
}
}
|
61e171e55f01de72418767c043ae59973e950bce
|
C#
|
renukadeshmukh/Tutorials
|
/TreeTutorials/TreeTutorials/TreeLibrary.cs
| 3.640625
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TreeTutorials
{
public class TreeLibrary
{
//Size of a tree is the number of elements present in the tree.
public int SizeOfTree(Node<int> root)
{
if (root == null)
return 0;
else
return 1 + SizeOfTree(root.Left) + SizeOfTree(root.Right);
}
/*
Two trees are identical when they have same data and arrangement of data is also same.
To identify if two trees are identical, we need to traverse both trees simultaneously,
and while traversing we need to compare data and children of the trees.
*/
public bool AreTreesEqual(Node<int> root1, Node<int> root2)
{
if (root1 == null && root2 == null)
return true;
else if ((root1 == null && root2 != null) || (root2 == null && root1 != null))
return false;
else if (root1.Value != root2.Value)
return false;
else
return (AreTreesEqual(root1.Left, root2.Left) && AreTreesEqual(root1.Right, root2.Right));
}
/*
* Recursively calculate height of left and right subtrees of a node and assign height to the
* node as max of the heights of two children plus 1.
*/
public int MaxHeightOfTree(Node<int> root)
{
if (root == null)
return 0;
else
return 1 + Math.Max(MaxHeightOfTree(root.Left), MaxHeightOfTree(root.Right));
}
public void DeleteTree(Node<int> root)
{
root = null;
}
/*
* Mirror of a Tree: Mirror of a Binary Tree T is another Binary Tree M(T) with left and right
* children of all non-leaf nodes interchanged.
*/
public Node<int> MirrorATree(Node<int> root)
{
if (root == null)
return null;
else
{
Node<int> leftsubtree = root.Left;
root.Left = MirrorATree(root.Right);
root.Right = MirrorATree(leftsubtree);
}
return root;
}
/*
* Given a binary tree, print out all of its root-to-leaf paths one per line
*/
public void PrintRootToLeafPaths(Node<int> root, string path)
{
if (root.Left == null && root.Right == null)
{
Console.WriteLine(path.Trim() + " " + root.Value);
}
else
{
path = path + " " + root.Value;
PrintRootToLeafPaths(root.Left, path);
PrintRootToLeafPaths(root.Right, path);
}
}
/*
* A node is a leaf node if both left and right child nodes of it are NULL
*/
public int NumberOfLeafNodes(Node<int> root)
{
if (root == null)
return 0;
else if (root.Left == null && root.Right == null)
return 1;
else return (NumberOfLeafNodes(root.Left) + NumberOfLeafNodes(root.Right));
}
public bool CheckChildrenSumProperty(Node<int> root)
{
if (root == null || (root.Left == null && root.Right == null))
return true;
int leftVal = root.Left == null ? 0 : root.Left.Value;
int rightVal = root.Right == null ? 0 : root.Right.Value;
if (root.Value == leftVal + rightVal)
{
return CheckChildrenSumProperty(root.Left) && CheckChildrenSumProperty(root.Right);
}
else
return false;
}
public void BalanceChildrenSumProperty(Node<int> root)
{
if (root == null || (root.Left == null && root.Right == null))
return;
BalanceChildrenSumProperty(root.Left);
BalanceChildrenSumProperty(root.Right);
int leftVal = root.Left == null ? 0 : root.Left.Value;
int rightVal = root.Right == null ? 0 : root.Right.Value;
int diff = root.Value - (leftVal + rightVal);
if (diff == 0)
{
return;
}
else if (diff < 0)
{
root.Value = root.Value - diff;
}
else
{
if (root.Left != null)
{
root.Left.Value += diff;
BalanceChildrenSumProperty(root.Left);
}
else
{
root.Right.Value += diff;
BalanceChildrenSumProperty(root.Right);
}
}
}
/*
* The diameter of a tree (sometimes called the width) is the
* number of nodes on the longest path between two leaves in the tree.
*/
public int GetDiameterofBinaryTree(Node<int> root)
{
if (root == null)
return 0;
int left = GetDiameterofBinaryTree(root.Left);
int right = GetDiameterofBinaryTree(root.Right);
int max = Math.Max( left , right);
return max = Math.Max(max , MaxHeightOfTree(root.Left) + MaxHeightOfTree(root.Right) +1 );
}
/*
* To check if a tree is height-balanced, get the height of left
* and right subtrees. Return true if difference between heights is
* not more than 1 and left and right subtrees are balanced, otherwise
* return false.
*/
public bool CheckBalancedBinaryTree(Node<int> root)
{
if (root == null)
return true;
int leftHt = MaxHeightOfTree(root.Left);
int rightHt = MaxHeightOfTree(root.Right);
int diff = leftHt - rightHt;
if (diff > -2 && diff < 2)
{
return CheckBalancedBinaryTree(root.Left) && CheckBalancedBinaryTree(root.Right);
}
else return false;
}
private bool HasPathSum(Node<int> root, int sum, int calculatedSum)
{
if (root == null)
{
if (calculatedSum == sum)
return true;
return false;
}
calculatedSum += root.Value;
return HasPathSum(root.Left, sum, calculatedSum) || HasPathSum(root.Right, sum, calculatedSum);
}
/*
* Given a binary tree and a number, return true if the tree has
* a root-to-leaf path such that adding up all the values along
* the path equals the given number. Return false if no such path
* can be found.
*/
public bool HasPathSum(Node<int> root, int sum)
{
if (root == null && sum == 0)
return true;
else
return HasPathSum(root, sum, 0);
}
public Node<int> BuildTreeFromInAndPre(string inorder, string preorder, Node<int> root)
{
if (preorder.Length > 0)
{
char n = preorder[0];
int node = Int32.Parse(n.ToString());
root = new Node<int>(node);
preorder = preorder.Substring(1);
string inleft = string.Empty, inright = string.Empty;
bool flag = false;
Dictionary<char, int> ignoreDict = new Dictionary<char, int>();
for (int i = 0; i < inorder.Length; i++)
{
if (inorder[i] == n)
{
flag = true;
continue;
}
if (flag == false)
{
inleft = string.Concat(inleft, inorder[i]);
ignoreDict.Add(inorder[i], 0);
}
else
inright = string.Concat(inright, inorder[i]);
}
string preleft = string.Empty, preright = string.Empty;
for (int i = 0; i < preorder.Length; i++)
{
if(ignoreDict.ContainsKey(preorder[i]))
preleft = string.Concat(preleft, preorder[i]);
else
preright = string.Concat(preright, preorder[i]);
}
root.Left = BuildTreeFromInAndPre(inleft, preleft, root.Left);
root.Right = BuildTreeFromInAndPre(inright, preright, root.Right);
}
return root;
}
/*
*To create Double tree of the given tree, create a new duplicate for each node, and insert
*the duplicate as the left child of the original node
*/
public void DoubleTree(Node<int> root)
{
if (root != null)
{
Node<int> newNode = new Node<int>(root.Value);
newNode.Left = root.Left;
root.Left = newNode;
DoubleTree(root.Left.Left);
DoubleTree(root.Right);
}
}
/*
A tree can be folded if left and right subtrees of the tree are structure wise mirror image
of each other. An empty tree is considered as foldable.
*/
public bool IsFoldable(Node<int> root)
{
if (root == null)
return true;
else return IsFoldable(root.Left, root.Right);
}
private bool IsFoldable(Node<int> root1, Node<int> root2)
{
if (root1 == null && root2 == null)
return true;
else if (root1 == null && root2 != null)
return false;
else if (root1 != null && root2 == null)
return false;
else return (IsFoldable(root1.Left, root2.Right) && IsFoldable(root1.Right, root2.Left));
}
}
}
|
8c9633d993f0c2dd644a00ca296d60b8a52628eb
|
C#
|
darkspring1/anywayanyday
|
/VendingMachine/backend/VM.Dal.EF/Repository.cs
| 2.890625
| 3
|
using VM.Business.Dal;
using System.Data.Entity;
using System.Linq;
namespace VM.Dal.EF
{
public class Repository<T> : IRepository<T> where T : class
{
readonly DbSet<T> _set;
readonly DataContext _context;
public Repository(DataContext context)
{
_set = context.Set<T>();
_context = context;
}
public IQueryable<T> GetAll()
{
return _set;
}
public T GetById(object key)
{
return _set.Find(key);
}
public void Add(T entity)
{
_set.Add(entity);
}
public void SaveChanges()
{
_context.SaveChanges();
}
}
}
|
595ee76a34af5d12f744df32a28eccc758f70dd2
|
C#
|
OlivierMounicq/HopfieldNetwork-DotNetCore
|
/HopfieldNetwork/Mathematics/Vector.cs
| 3.296875
| 3
|
using System;
using System.Collections.Generic;
namespace HopfieldNetwork.Mathematics
{
public abstract class Vector
{
private readonly double[] vector;
public double this[int i]
{
get => vector[i];
set => vector[i] = value;
}
public int Length
{
get => vector.Length;
}
public Vector(Vector v)
{
this.vector = new double[v.Length];
for(var idx = 0; idx < v.Length; idx++)
{
this.vector[idx] = v[idx];
}
}
public Vector(int length)
=> this.vector = new double[length];
public Vector(double[] vector)
=> this.vector = vector;
}
}
|
37572618b326ce4f75087533ce17bdcb007cc537
|
C#
|
salesandrey/RiverRaid
|
/WindowsGame1/GerenciadorTiro.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
namespace RIVER_RAID
{
class GerenciadorTiro
{
private List<Tiro> lista;
private int numTiros = 20;
public GerenciadorTiro()
{
lista = new List<Tiro>(numTiros );
for (int i = 0; i < numTiros ; i++)
{
Tiro t = new Tiro(0, 0);
lista.Add(t);
}
}
public Tiro getTiro()
{
foreach (Tiro t in lista)
{
if (!t.vivo)
{
return t;
}
}
return null;
}
public void finalizar()
{
Tiro[] t = lista.ToArray();
int i = 0;
while (i < t.Length)
{
t[i].vivo=false;
t[i].ativo = false;
i++;
}
lista.Clear();
}
public void Add(Tiro t)
{
lista.Add(t);
}
public bool verificarColisao(Obstaculo obs)
{
Tiro[] t = lista.ToArray();
int i = 0;
while ((i < t.Length)&& (obs!=null))
{
if (t[i].vivo)
{
if (obs.ativo)
{
/*if ((obs.pos.Y >= t[i].pos.Y) && (obs.pos.Y <= t[i].pos.Y + t[i].altura) &&
(obs.pos.X >= t[i].pos.X) && (obs.pos.X <= t[i].pos.X + t[i].largura)
)*/
if ((t[i].pos.Y + (t[i].altura / 2) >= obs.pos.Y ) && (t[i].pos.Y - (t[i].altura / 2) <= obs.pos.Y + (obs.altura / 2)) &&
(t[i].pos.X+(t[i].largura / 2) >= obs.pos.X ) && (t[i].pos.X-(t[i].largura/2) <= obs.pos.X + (obs.largura / 2))
)
{
//lista.Remove(t[i]);
t[i].vivo = false;
return true;
}
}
}
i++;
}
return false;
}
public void drawTiros(Texture2D texture, SpriteBatch SB)
{
Tiro[] t = lista.ToArray();
for (int i = 0; i < t.Length;i++ )
{
if (t[i].vivo)
{
DrawTiro.draw(t[i], SB, texture);
if (t[i].pos.Y < 0)
{
t[i].vivo = false;
//lista.Remove(t[i]);
}
}
}
}
}
}
|
e042f66110575aaca80df383275e25ba43380d8f
|
C#
|
MeGaDeTH91/SoftUni
|
/C# DB/Databases Advanced - Entity Framework/10 Intro to EF Exer/Exercise/P03_EmpsFullInfo/StartUp.cs
| 3.09375
| 3
|
using System;
using P02_DatabaseFirst;
using P02_DatabaseFirst.Data;
using System.Linq;
namespace P03_EmpsFullInfo
{
class StartUp
{
static void Main(string[] args)
{
using (var context = new SoftUniContext())
{
var employees = context.Employees
.OrderBy(x => x.EmployeeId)
.Select(x => new
{
x.FirstName, x.LastName, x.MiddleName, x.JobTitle, x.Salary
})
.ToList();
foreach (var emp in employees)
{
Console.WriteLine($"{emp.FirstName} {emp.LastName} {emp.MiddleName} {emp.JobTitle} {emp.Salary:F2}");
}
}
}
}
}
|
33944ca4076440c04a867a0c52c72791cf7e22dd
|
C#
|
flapek/GraphRepo
|
/Graph2D/Data/TheCorrectnessOfData.cs
| 3.34375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Graph2D.Data
{
static class TheCorrectnessOfData
{
/// <summary>
/// check that the text entered is correct
/// </summary>
private static readonly Regex _regex = new Regex("[^0-9,]+"); //regex that matches disallowed text
public static Task<bool> IsTextAllowed(string text) => Task.FromResult(!_regex.IsMatch(text));
public static Task<bool> IsAValueInTheRange(double min, double max, string text)
{
if (!double.TryParse(text, out double result))
return Task.FromResult(false);
if (min <= result && result <= max)
return Task.FromResult(true);
else
return Task.FromResult(false);
}
public static Task<bool> IsTheCorrectNumberOfEdges(string edges, string nodes)
{
if (!int.TryParse(edges, out int edgesResult) || !int.TryParse(nodes, out int nodesResult))
{
return Task.FromResult(false);
}
return Task.FromResult(edgesResult < Calculations.CalculateTheBorderNumberOfEdges(nodesResult));
}
public static Task<bool> checkGraphCompact(int[][] graph) => Task.Run(() =>
{
int[] array = new int[graph.Length];
int sum;
for (int i = 0; i < graph.Length; i++)
{
sum = 0;
for (int j = 0; j < graph.Length; j++)
{
sum += graph[i][j];
}
array[i] = sum;
}
for (int i = 0; i < array.Length; i++)
{
if (!(array[i] > 0))
{
return false;
}
}
return true;
});
}
}
|
fd5d86c404ef5fb574e6171d30decad687b883f2
|
C#
|
BakanovMaksim/Origin
|
/WebApplicationTest/Services/UsersDbServices.cs
| 3.015625
| 3
|
using ApplicationOrigin.Data;
using ApplicationOrigin.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
namespace ApplicationOrigin.Services
{
public class UsersDbServices : IDbLogic
{
private readonly ILogger<UsersDbServices> _logger;
private readonly UsersDbContext _usersDbContext;
public UsersDbServices(UsersDbContext usersDbContext, ILogger<UsersDbServices> logger)
{
_usersDbContext = usersDbContext;
_logger = logger;
}
public User GetUserId(int id)
{
_logger.LogInformation("Получен идентификатор пользователя.", id);
return _usersDbContext.People.FirstOrDefault(p => p.Id == id);
}
public User GetUserLogin(string login)
{
_logger.LogInformation("Получен логин пользователя.", login);
return _usersDbContext.People.FirstOrDefault(p => p.Login == login);
}
public IEnumerable<User> GetUsers() => _usersDbContext.People.ToList();
public void Add(User user)
{
_logger.LogInformation("Данные пользователя получены.", nameof(user));
if (CheckNewUser(user))
{
_usersDbContext.People.Add(user);
_usersDbContext.SaveChanges();
_logger.LogInformation("Пользователь добавлен в базу данных.", nameof(user));
}
_logger.LogWarning("Пользователь не добавлен в базу данных.", nameof(user));
}
public void Edit(User user)
{
_logger.LogInformation("Данные пользователя получены.", nameof(user));
_usersDbContext.People.Update(user);
_usersDbContext.SaveChanges();
}
public void Remove(User user)
{
_logger.LogInformation("Данные пользователя получены.", nameof(user));
_usersDbContext.People.Remove(user);
_usersDbContext.SaveChanges();
}
public bool CheckNewUser(User user)
{
_logger.LogInformation("Данные пользователя получены.", nameof(user));
var count = 0;
foreach (var item in GetUsers())
if ((item.Login == user.Login) && (item.Password == user.Password)) ++count;
return count > 0 ? throw new ArgumentException("Такой пользователь уже существует.", nameof(user)) : true;
}
}
}
|
417db601553b473b0a64a93b9215b8d1c59c3a3c
|
C#
|
ynhj123/CSharpStudy
|
/ConsoleGame/Controller/AutoAttachIntervalSystem.cs
| 2.796875
| 3
|
using ConsoleGame.model;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleGame.Controller
{
class AutoAttachIntervalSystem : IExecuteSystem
{
List<Player> autoPlayer = new List<Player>();
GameSence scence;
public AutoAttachIntervalSystem(GameSence scence)
{
this.scence = scence;
}
public void AddAutoPlayer(Player player)
{
autoPlayer.Add(player);
}
public void RemoveAutoPlayer(Player player)
{
autoPlayer.Remove(player);
}
public void Execute()
{
List<Sprite> players = scence.sprites.Where(spirte => spirte is Player).ToList();
foreach (Player player in players)
{
if (autoPlayer.Contains(player) && player.AttchInterval == 5)
{
MsgAttack msgAttack = new MsgAttack();
msgAttack.playId = player.Id;
NetManagerEvent.Send(msgAttack);
player.AttchInterval = 1;
}
else
{
if (player.AttchInterval < 5)
{
player.AttchInterval += 1;
}
}
}
}
}
}
|
76063a0ae0c7a4d665336fb340f020de4c1e9d53
|
C#
|
warxx/Programming-Fundamentals
|
/06.Arrays/Homework/Exercise_Demo/Problem_5/Program.cs
| 3.578125
| 4
|
using System;
using System.Linq;
namespace Problem_5
{
class Program
{
static void Main(string[] args)
{
var arr1 = Console.ReadLine().Split(' ').Select(e => char.Parse(e)).ToArray();
var arr2 = Console.ReadLine().Split(' ').Select(e => char.Parse(e)).ToArray();
int n = 0;
if (arr1.Length < arr2.Length)
{
n = arr1.Length;
}
else
{
n = arr2.Length;
}
char[] biggerArr = null;
char[] smallerArr = null;
bool areEqual = true;
for (int i = 0; i < n; i++)
{
if (arr1[i] > arr2[i])
{
biggerArr = arr1;
smallerArr = arr2;
areEqual = false;
break;
}
if (arr1[i] < arr2[i])
{
biggerArr = arr2;
smallerArr = arr1;
areEqual = false;
break;
}
}
if (areEqual && arr1.Length != arr2.Length)
{
if (arr1.Length > arr2.Length)
{
Console.WriteLine(string.Join("", arr2));
Console.WriteLine(string.Join("", arr1));
}
else if (arr1.Length < arr2.Length)
{
Console.WriteLine(string.Join("", arr1));
Console.WriteLine(string.Join("", arr2));
}
}
else if (areEqual && arr1.Length == arr2.Length)
{
Console.WriteLine(string.Join("", arr1));
Console.WriteLine(string.Join("", arr2));
}
else
{
Console.WriteLine(string.Join("", smallerArr));
Console.WriteLine(string.Join("", biggerArr));
}
}
}
}
|
1c044559c2e10a26d361791dd68e4e1f648f1aaa
|
C#
|
exiledude22/CISServer
|
/libcis/Providers/AuthenticationProvider.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace libcis.Providers
{
/// <summary>
/// <see cref="IAuthenticationProvider"/> for details.
/// </summary>
public class AuthenticationProvider : libcis.DataAccessLogic.IAuthenticationProvider
{
public libcis.DataAccessLogic.AuthenticationResult Get(int marker_id)
{
var context = new libcis.Models.CISDatabaseEntities();
var result = from provider_hotspots in context.ProviderHotspots
where provider_hotspots.MarkerId == marker_id
select provider_hotspots;
var provider_hotspot = result.ToList();
var return_message = new libcis.DataAccessLogic.AuthenticationResult();
if(provider_hotspot.Count == 0)
{
return_message.Success = false;
//TODO: do not keep static strings here
return_message.ErrorMessage = string.Format("Invalid marker id: {0}", marker_id);
}
else
{
var hotspot = provider_hotspot.First();
libcis.Models.Order customer_order = new libcis.Models.Order();
customer_order.ProviderHotspotId = hotspot.Id;
context.Orders.Add(customer_order);
context.SaveChanges();
return_message.OrderId = customer_order.Id;
return_message.Success = true;
return_message.ProviderId = hotspot.ProviderId;
return_message.HotspotId = hotspot.Id;
}
context.Dispose();
return return_message;
}
}
}
|
bcf0d6babed84b6ff8bdc5a9bce8cba8450b8f62
|
C#
|
mayermi/Open-Games-Workshop
|
/Assets/Scripts/Creature.cs
| 2.53125
| 3
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public abstract class Creature {
public int MaxHealth { get; set;}
public int CurrentHealth { get; set;}
public float Speed { get; set; }
public int VisionRange { get; set;}
public GameObject GameObject { get; set;}
private bool dead;
public Creature(int health, float speed, int range) {
MaxHealth = health;
CurrentHealth = MaxHealth;
Speed = speed;
VisionRange = range;
}
public void MoveTo(Vector3 target)
{
if (GameObject.tag != "Dead")
{
GameObject.GetComponent<PathNavigator>().locked = false;
GameObject.GetComponent<PathNavigator>().SetTarget(target);
}
}
public void StopMoving()
{
Animation anim = GameObject.GetComponent<Animation>();
if (anim["Run"]) anim.Stop("Run");
if (anim["Walk"]) anim.Stop("Walk");
GameObject.GetComponent<PathNavigator>().StopMoving();
}
public virtual void TakeDamage(int d, object source = null)
{
CurrentHealth = CurrentHealth - d;
GameObject.GetComponent<CreatureHelper>().AdjustHealthBar();
if (CurrentHealth <= 0) Die();
}
public virtual void GetHealed(int d, object source=null)
{
CurrentHealth = CurrentHealth + d;
if (CurrentHealth > MaxHealth)
CurrentHealth = MaxHealth;
GameObject.GetComponent<CreatureHelper>().AdjustHealthBar();
}
public virtual void Die()
{
if (!dead)
{
dead = true;
GameObject.tag = "Dead";
GameObject.Find("GameController").SendMessage("RemoveReferences", this);
GameObject.Find("GameState").SendMessage("RemoveCreature", this);
StopMoving();
GameObject.GetComponent<CreatureHelper>().StartDying();
}
}
public bool IsInRange(GameObject g)
{
float d = CoordinateHelper.calcDistance(GameObject.transform.position, g.transform.position);
if (d < VisionRange)
return true;
return false;
}
}
|
4c92e48d02a267e567cb5673e892adb1942e59af
|
C#
|
shendongnian/download4
|
/first_version_download2/503633-46000815-155250690-4.cs
| 2.734375
| 3
|
public partial class _Default : Page
{
Dictionary<string, string> _dynamicControlId = new Dictionary<string, string>();
protected void Page_Init(object sender, EventArgs e)
{
CreateControls();
}
protected void SubmitButton_Click(object sender, EventArgs e)
{
ResultLabel.Text = "Result : " + RetrieveValues();
}
private void CreateControls()
{
string dynamicFieldstring = "one=1|two=2|three=3|four=4";
if (!string.IsNullOrEmpty(dynamicFieldstring))
{
string[] groupControl = dynamicFieldstring.Split('|');
for (int i = 0; i < groupControl.Length;)
{
TableRow row = new TableRow();
for (int j = 0; j < 2; j++)
{
if (i >= groupControl.Length)
break;
string[] singleControl = groupControl[i].Split('=');
Label label = new Label();
TextBox textbox = new TextBox();
string textboxId = string.Empty;
string labelId = string.Empty;
TableCell cell = new TableCell();
label.Text = singleControl[0];
labelId = "lbl" + i + j;
label.ID = labelId; // <--- value should be labelId instead of textboxId
label.Attributes.Add("runat", "server");
cell.Controls.Add(label);
TableCell cell1 = new TableCell();
textbox.Text = singleControl[1];
textboxId = "txt" + i + j;
textbox.ID = textboxId;
textbox.Attributes.Add("runat", "server");
cell1.Controls.Add(textbox);
_dynamicControlId.Add(labelId, textboxId);
row.Cells.Add(cell);
row.Cells.Add(cell1);
i = i + 1;
}
extraAttr.Rows.Add(row);
Session["controllIds"] = _dynamicControlId;
}
}
}
private string RetrieveValues()
{
string value = string.Empty;
_dynamicControlId = Session["controllIds"] as Dictionary<string, string>;
if (_dynamicControlId != null && _dynamicControlId.Count > 0)
{
foreach (var item in _dynamicControlId)
{
Label label = FindControlRecursive(extraAttr, item.Key) as Label;
value += label.Text + "="; // <--- Operator should be should be +=
var textbox = FindControlRecursive(extraAttr, item.Value) as TextBox;
value += textbox.Text + "|";
}
}
return value;
}
private Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
return root;
return root.Controls.Cast<Control>()
.Select(c => FindControlRecursive(c, id))
.FirstOrDefault(c => c != null);
}
}
|
3cefa51d6082e4bbeb0b6f037933555b94608ecb
|
C#
|
shendongnian/download4
|
/first_version_download2/380234-57687073-204301385-2.cs
| 2.90625
| 3
|
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject item = JObject.Load(reader);
switch (item["type"].Value<string>())
{
case "Armor":
var armorItem = new ArmorItem();
serializer.Populate(item.CreateReader(), armorItem);
return armorItem;
default:
var defaultItem = new Item();
serializer.Populate(item.CreateReader(), defaultItem);
return defaultItem;
}
}
|
92e8fc1b29a0f88f125e3c4c08ad420ed2280a45
|
C#
|
cuesto/ConsultaCrea-Clientes
|
/ConsultaCrea-Cliente/Model/Serializadora.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace ConsultaCrea_Cliente.Model
{
public class Serializadora
{
public string WsAdIvnd { get; set; } // web service
public string SvrIvnd { get; set; } // server DB
public string DBIvnd { get; set; } // DB name
public string UsrIvnd { get; set; } // user DB
public string PassIvnd { get; set; } // pass DB
public Serializadora()
{
WsAdIvnd = "";
SvrIvnd = "";
DBIvnd = "";
UsrIvnd = "";
PassIvnd = "";
}
public void EscribirObjeto(string NombreArchivo)
{
using(var stream = new FileStream(NombreArchivo, FileMode.Create))
{
var XML = new XmlSerializer(typeof(Serializadora));
XML.Serialize(stream, this);
}
}
public static Serializadora LeerObjeto(string NombreArchivo)
{
using (var stream = new FileStream(NombreArchivo, FileMode.Open))
{
var XML = new XmlSerializer(typeof(Serializadora));
return (Serializadora)XML.Deserialize(stream);
}
}
}
}
|
d67271dc91f4b00ef0be487f7e86641663c8a4ca
|
C#
|
Hendrik-Jacobs/MvvM-Example
|
/mvvmTest2/CustomClasses/SqliteAccess.cs
| 3.015625
| 3
|
using System;
using System.IO;
using System.Windows;
using System.Data;
using System.Data.SQLite;
namespace mvvmTest2.CustomClasses
{
static class SqliteAccess
{
private static string _filePath;
public static string Filepath
{
get => _filePath;
set => _filePath = value;
}
public static bool CreateIfNotExist(string path)
{
if (!File.Exists(path))
{
try
{
SQLiteConnection.CreateFile(path);
}
catch
{
return false;
}
}
_filePath = path;
return true;
}
public static void WriteSql(string command, string[] args = null)
{
try
{
using (SQLiteConnection con = new SQLiteConnection(string.Format("Data Source = {0};Version = 3;", _filePath)))
{
using (SQLiteCommand com = new SQLiteCommand(con))
{
con.Open();
com.CommandText = command;
if (args != null)
{
AddParameter(com, args);
}
com.ExecuteNonQuery();
con.Close();
}
}
}
catch
{
MessageBox.Show("Fail: " + command);
}
}
private static void AddParameter(SQLiteCommand com, string[] args)
{
int counter = 0;
foreach (string arg in args)
{
string name = "@param" + counter;
com.Parameters.AddWithValue(name, arg);
Console.WriteLine(name);
counter++;
}
}
public static DataTable ExecuteReadQuery(string query)
{
DataTable table = new DataTable();
using (SQLiteConnection con = new SQLiteConnection(string.Format("Data Source = {0};Version = 3;", _filePath)))
{
SQLiteCommand com = new SQLiteCommand(query, con);
try
{
con.Open();
SQLiteDataReader reader = com.ExecuteReader();
if (reader.HasRows)
{
for (int i = 0; i < reader.FieldCount; i++)
{
table.Columns.Add(new DataColumn(reader.GetName(i)));
}
}
int j = 0;
while (reader.Read())
{
DataRow row = table.NewRow();
table.Rows.Add(row);
for (int i = 0; i < reader.FieldCount; i++)
{
table.Rows[j][i] = reader.GetValue(i);
}
j++;
}
con.Close();
}
catch (SQLiteException e)
{
MessageBox.Show($"Error:\n{e}");
}
return table;
}
}
}
}
|
cb55675a10e021d1df4f82f69fe4f29c958c85e1
|
C#
|
Beier/Omnium
|
/Omnium.Compiler/Program.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using CommandLine;
using Omnium.Core.ast;
using Omnium.Core.compiler;
namespace Omnium
{
class Program
{
public class Options
{
[Option('i', "inputFiles", Required = true, HelpText = "Path to one or more input files. Imported files will automatically be included.")]
public IEnumerable<string> InputFiles { get; set; }
[Option('o', "outputFile", Required = true, HelpText = "Path to output file")]
public string OutputFile { get; set; }
}
static void Main(string[] args)
{
Parser.Default.ParseArguments<Options>(args)
.WithParsed(options =>
{
var compiler = new TypescriptToOverwatchCompiler();
try
{
var result = compiler.Compile(options.InputFiles.ToArray());
if (result == null)
{
Console.WriteLine("Build failed!");
return;
}
using (var outputStream = new StreamWriter(File.Create(options.OutputFile)))
{
outputStream.Write(result);
}
Console.WriteLine("Build succeeded");
}
catch (Exception e)
{
Console.WriteLine("Internal error occured: " + e);
}
});
}
}
}
|
dddd9591b7292ce72e5c8ef4ef93dd16ebb107c1
|
C#
|
devbryank/AsmrDarlingAlexaSkill
|
/Sonnar/Templates/SpeechTemplate.cs
| 2.890625
| 3
|
using Sonnar.Components;
namespace Sonnar.Templates
{
class SpeechTemplate
{
public const string WelcomeBack = "Welcome back. ";
public static string WelcomeNew = $"Welcome to {SkillSetting.SkillName}. ";
public const string Help = "You can either say a recording name, list, or shuffle. ";
public const string Intro = "Say the name of recording, or list to hear about available recordings, or help to find out other options. ";
public const string MoreOptions = "You can either say a recording name, list, shuffle, or help. ";
public static string NoUnderstand
{
get
{
return GetPropmpt();
}
set
{
}
}
public const string NoNext = "Next recording is not available. You can say resume to keep play, or say list to hear more options ";
public const string NoPrevious = "Previous recording is not available. You can say resume to keep play, or say list to hear more options ";
public const string GoodBye = "Good Bye. ";
public const string SeeYouSoon = "See you soon. ";
public const string SeeYouNextTime = "See you next time. ";
public static string ListItems = "Here is the list of ASMR items. What is ASMR. " +
"10 triggers to help you sleep. " +
"20 triggers to help you sleep. " +
"100 triggers to help you sleep. " +
"A to z triggers to help you sleep. " +
"Brushing the microphone. " +
"Relaxing head massage. " +
"Relaxing scalp massage. " +
"Whispered tapping and scratching. " +
"Close up personal attention for you to sleep. " +
"Which item do you want me to play? ";
public const string SystemException = "The skill is not working at the moment. Please try again later. ";
public static string GetPropmpt()
{
string reprompt = string.Empty;
switch (Core.State.UserState.NumReprompt)
{
case 0:
reprompt = "I didn't understand. Please try again. ";
break;
case 1:
reprompt = "You can say a name of recording, list, or help. ";
break;
case 2:
reprompt = "If you like to play any recording, just say shuffle. ";
break;
case 3:
reprompt = "I suggest you to say help. ";
break;
case 5:
reprompt = "Sorry. Something went wrong, please try again. ";
break;
}
Core.State.UserState.NumReprompt++;
return reprompt;
}
}
}
|
05463fe8d42a632129a1fb998a69e576ed27101a
|
C#
|
FaxMachin3/Data-Structures-and-Algorithms
|
/C#/MergeSort.cs
| 3.40625
| 3
|
using System;
namespace MergeSortDemo {
class Example {
static public void merge(int[] arr, int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;
// Console.WriteLine(left+" "+mid+" "+right);
// Console.WriteLine(n1+" "+n2);
int[] L = new int[n1];
int[] R = new int[n2];
for (i = 0; i < n1; i++) {
L[i] = arr[left + i];
}
for (j = 0; j < n2; j++) {
R[j] = arr[mid + 1 + j];
}
// Console.WriteLine(string.Join(", ",L));
// Console.WriteLine(string.Join(", ",R));
i = 0;
j = 0;
k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
static public void mergeSort(int[] arr, int left, int right) {
if (left < right) {
int mid = (left + right) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
// static void Main(string[] args) {
// int[] arr = {76, 3, 89, 23, 1, 55, 78, 99, 12, 65, 100, 3, 2};
// int n = arr.Length - 1, i;
// Console.WriteLine("Merge Sort");
// Console.Write("Initial array is: ");
// for (i = 0; i < n; i++) {
// Console.Write(arr[i] + " ");
// }
// Console.WriteLine();
// mergeSort(arr, 0, n);
// Console.Write("\nSorted Array is: ");
// for (i = 0; i < n; i++) {
// Console.Write(arr[i] + " ");
// }
// }
}
}
|
b28290b2d4fa3c4d454b32cc896c6d7801b7d8a7
|
C#
|
jonasrm/CashMachine
|
/CashMachine/CashMachine/Program.cs
| 3.265625
| 3
|
using CashMachine.Classes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CashMachine
{
class Program
{
static void Main(string[] args)
{
Operation operation = new Operation();
string userInput = string.Empty;
Console.WriteLine("--------------------------------------------------------------------------");
Console.WriteLine("Bem-vindo ao Caixa Eletrônico do banco Zenvia.");
Console.WriteLine("Cédulas disponíveis " + string.Join(", ", operation.getOptionsValues()) + ".");
Console.WriteLine("Esse caixa possuí um limite de " + operation.getMaxValuePerOperation().ToString() + " por saque.");
Console.WriteLine("--------------------------------------------------------------------------");
try
{
while (string.IsNullOrWhiteSpace(userInput))
{
Console.WriteLine("");
Console.Write("Valor do Saque (R$): ");
userInput = Console.ReadLine();
decimal value = 0;
if (decimal.TryParse(userInput, out value))
{
string result = string.Join(", ", operation.CashOut(value));
Console.WriteLine("Resultado: " + result);
}
else
{
Console.WriteLine("Valor incorreto, os valores permitidos pelo sistema são entre 1 e 3000.");
userInput = string.Empty;
}
}
Console.WriteLine("--------------------------------------------------------------------------");
Console.WriteLine("Pressione qualquer tecla para fechar");
Console.WriteLine("--------------------------------------------------------------------------");
Console.ReadKey();
}
catch (Exception)
{
throw;
}
}
}
}
|
595c8910ea2bb85725682cce5b7c0b53407b4ab4
|
C#
|
jasarsoft/examples
|
/cs/jlp4/Poglavlje 21/Primjer 06/Program.cs
| 3.578125
| 4
|
using System;
using System.IO;
namespace ReadingWritingToTextFile
{
class Program
{
static void Main()
{
//otvara datoteku
FileInfo theSourceFile = new FileInfo(@"input.txt");
//stvara citac teksta za tu datoteku
StreamReader reader = theSourceFile.OpenText();
//stvara pisac teksta za novu datoteku
StreamWriter writer = new StreamWriter(@"output.txt", false);
//stvara tekstualnu varijablu za cuvanje svakog reda
string text;
//prolazi kroz datoteku cita svaki red i upisuje ih u datoteku
do
{
text = reader.ReadLine();
writer.WriteLine(text);
Console.WriteLine(text);
} while (text != null);
//spremanje i zatvaranje
reader.Close();
writer.Close();
}
}
}
|
8dfe9fa7862f4eb2ed5fb7cf85ea7dd3473ef734
|
C#
|
Mr-Coxall/Computer-Based-Problem-Solving
|
/code_examples/3-Structured_Problem_Solving/18-Nested_Loops/CSharp/main.cs
| 3.21875
| 3
|
/* Created by: Mr. Coxall
* Created on: Sep 2020
* This program uses a nested loop
*/
using System;
/*
* The Program class
*/
class Program {
static void Main() {
// this function uses a nested loop
// process & output
for (int counter1 = 0; counter1 < 10; counter1++) {
for (int counter2 = 0; counter2 < 10; counter2++) {
Console.WriteLine("Odometer: " + counter1 + counter2);
}
}
Console.WriteLine("\nDone.");
}
}
|
f2d303cf7c53f0ba6bf3b841554d1b98062ff5ad
|
C#
|
geravishal/RabbitMQ-tutorials
|
/Topic Repo/Topic/Topic/Program.cs
| 3.0625
| 3
|
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Topic
{
class Program
{
/// <summary>
/// When we need to disseminate messages to all queues bind to that exchange filter on the basis of more than one criteria.
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
channel.ExchangeDeclare(exchange: "OnlineUsers", type: "topic");
string message1 = "Send to facebook men young users";
var body1 = Encoding.UTF8.GetBytes(message1);
channel.BasicPublish(exchange: "OnlineUsers",
routingKey: "facebook.men.young",
basicProperties: null,
body: body1);
string message2 = "Send to facebook women young users";
var body2 = Encoding.UTF8.GetBytes(message2);
channel.BasicPublish(exchange: "OnlineUsers",
routingKey: "facebook.women.young",
basicProperties: null,
body: body2);
string message3 = "Send to twitter men old users";
var body3 = Encoding.UTF8.GetBytes(message3);
channel.BasicPublish(exchange: "OnlineUsers",
routingKey: "twitter.men.old",
basicProperties: null,
body: body3);
string message4 = "Send to twitter women old users";
var body4 = Encoding.UTF8.GetBytes(message4);
channel.BasicPublish(exchange: "OnlineUsers",
routingKey: "twitter.women.old",
basicProperties: null,
body: body4);
Console.WriteLine("{0} {1} {2} {3}", message1 + "\n", message2 + "\n", message3 + "\n", message4);
}
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();
}
}
}
|
9a810883e7989cdd9fcb8337f002e46a8be9c50d
|
C#
|
elkrot/Examples-CSharp
|
/metanit/Patterns/Patterns/BehaviorPatterns/State.cs
| 3.25
| 3
|
// -----------------------------------------------------------------------
// <copyright file="State.cs" company="Co">
// Copyright Kolodiyazjny Sergey
// </copyright>
// -----------------------------------------------------------------------
/*
Состояние (State) - шаблон проектирования, который позволяет объекту изменять свое поведение в зависимости от внутреннего состояния.
Когда применяется данный паттерн?
Когда поведение объекта должно зависеть от его состояния и может изменяться динамически во время выполнения
Когда в коде методов объекта используются многочисленные условные конструкции, выбор которых зависит от текущего состояния объекта
*/
namespace Patterns
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Water
{
public IWaterState State { get; set; }
public Water(IWaterState ws)
{
State = ws;
}
public void Heat()
{
State.Heat(this);
}
public void Frost()
{
State.Frost(this);
}
}
interface IWaterState
{
void Heat(Water water);
void Frost(Water water);
}
class SolidWaterState : IWaterState
{
public void Heat(Water water)
{
Console.WriteLine("Превращаем лед в жидкость");
water.State = new LiquidWaterState();
}
public void Frost(Water water)
{
Console.WriteLine("Продолжаем заморозку льда");
}
}
class LiquidWaterState : IWaterState
{
public void Heat(Water water)
{
Console.WriteLine("Превращаем жидкость в пар");
water.State = new GasWaterState();
}
public void Frost(Water water)
{
Console.WriteLine("Превращаем жидкость в лед");
water.State = new SolidWaterState();
}
}
class GasWaterState : IWaterState
{
public void Heat(Water water)
{
Console.WriteLine("Повышаем температуру водяного пара");
}
public void Frost(Water water)
{
Console.WriteLine("Превращаем водяной пар в жидкость");
water.State = new LiquidWaterState();
}
}
}
|
09f7ccd42445a6161a98503d2f027c3a7f2cd931
|
C#
|
richardszalay/build-scout
|
/source/RichardSzalay.PocketCiTray/Infrastructure/Converters/BooleanVisibilityConverter.cs
| 2.75
| 3
|
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace RichardSzalay.PocketCiTray.Infrastructure
{
public class BooleanVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return GetBooleanVisibility(value, parameter)
? Visibility.Visible
: Visibility.Collapsed;
}
private bool GetBooleanVisibility(object value, object parameter)
{
bool rawValue = (bool)value;
return ((parameter as String) == "!")
? !rawValue
: rawValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
|
7fd5283eb47e96306ec03b2f34d3d197946e2590
|
C#
|
Jhultink/Sidescroller-Mono
|
/SideScroller/UI/InventorySlot.cs
| 2.578125
| 3
|
using Microsoft.Xna.Framework;
using SideScroller;
using SideScroller.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
namespace SideScroller.UI
{
public class InventorySlot : UIElement
{
private ContentManager content;
private Texture2D itemTexture;
private SpriteFont countFont;
public TileType? Type { get; set; }
public int Count { get; set; } = 0;
public InventorySlot(Vector2 relativePosition, int width, int height) : base(relativePosition, "inventorySlot", width, height)
{
}
public override void Load(ContentManager content)
{
base.Load(content);
this.content = content;
this.countFont = content.Load<SpriteFont>("MainFont");
}
public override void Draw(SpriteBatch spriteBatch, Camera camera)
{
base.Draw(spriteBatch, camera);
if(this.Type != null && this.Count != 0)
{
float x = this.AbsolutePosition.X + (this.Width / 4f); // 25% margin
float y = this.AbsolutePosition.Y + (this.Height / 4f); // 25% margin
spriteBatch.Draw(this.itemTexture, new Rectangle((int)x, (int)y, (int)(this.Width * .5f), (int)(this.Height * .5f)), Color.White); // 50% margin
spriteBatch.DrawString(countFont, this.Count.ToString(), this.AbsolutePosition + new Vector2(this.Width * .6f, this.Height * .6f), Color.Black);
}
}
public void AddItems(TileType type, int count)
{
if (this.Type == null)
{
this.Type = type;
this.itemTexture = this.content.Load<Texture2D>(this.Type.ToString());
}
else if (this.Type != type)
throw new ArgumentException();
this.Count += count;
}
}
}
|
723fa9f1d75144120ad17388d8e8b706645cc2f1
|
C#
|
bmacgregor/Blade-of-the-Iron-Throne
|
/Character Creator/Character Creator/Data/Asset.cs
| 3.125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Character_Creator.Data
{
class Asset
{
public enum Culture { all, decadent, degenerate, restricted }
private Culture _cultureLeve = Culture.all;
public string Name { get; set; }
public bool Good { get; set; }
public bool Poor { get; set; }
public Culture CultureLevel { get { return _cultureLeve; } set { _cultureLeve = value; } }
public string Description { get; set; }
public Asset(string name, int good, int poor, int cLevel, string desc)
{
Name = name;
Good = Convert.ToBoolean(good);
Poor = Convert.ToBoolean(poor);
CultureLevel = (Culture)cLevel;
Description = desc;
}
}
}
|
5def1f475fc10bbdde762412822f9bb9ae2eb186
|
C#
|
shendongnian/download4
|
/code8/1415636-38496926-123120356-2.cs
| 3.03125
| 3
|
public interface IXFactory
{
IX GetX(XRequest request);
}
public interface IX
{
void SomeMethod()
}
//And I'd do A as an abstract class and rename to XBase
public class A : IX
{
public void SomeMethod() {}
}
public class D
{
public D(IXFactory xFactory)
{
XFactory = xFactory;
}
public void SomeMethod()
{
var x1 = XFactory.GetX(/*some request to get B*/);
var x2 = XFactory.GetX(/*some request to get C*/);
}
public IXFactory XFactory { get; set; }
}
|
8e2abdd245dbbbf218987d8bdab4f45b330b40d4
|
C#
|
rotemtzaban/ghc17
|
/GoogleHashCode/2019_Qualification/Printer.cs
| 2.953125
| 3
|
using HashCodeCommon;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _2019_Qualification
{
public class Printer : PrinterBase<ProblemOutput>
{
public override void PrintToConsole(ProblemOutput result)
{
foreach (var slide in result.Slides)
{
if (slide.Images.Count() == 1)
{
Console.WriteLine(slide.Images[0].Index);
}
else
{
Console.WriteLine($"{slide.Images[0].Index} {slide.Images[1].Index}");
}
}
}
public override void PrintToFile(ProblemOutput result, string outputPath)
{
using (var writer = new StreamWriter(outputPath))
{
writer.WriteLine(result.Slides.Count);
foreach (var slide in result.Slides)
{
if (slide.Images.Count() == 1)
{
writer.WriteLine(slide.Images[0].Index);
}
else
{
writer.WriteLine($"{slide.Images[0].Index} {slide.Images[1].Index}");
}
}
}
}
}
}
|
661e86c0fa4a95f1331fd6878b9a4564977bdfa9
|
C#
|
arman-g/DesignPatterns
|
/Tests/DesignPatterns.xUnitTests/InterpreterTests.cs
| 2.765625
| 3
|
using DesignPatterns.Interpreter.DomainObjects;
using System.Linq;
using Xunit;
using Xunit.Abstractions;
namespace DesignPatterns.xUnitTests
{
public class InterpreterTests
{
private readonly ITestOutputHelper _output;
public InterpreterTests(ITestOutputHelper output)
{
_output = output;
}
[Fact(DisplayName = "Positive Case - Generate Bar Code")]
public void BarCode_Test()
{
var upc = new Upc(
new ManufacturerId(
new Digit(0),
new Digit(3),
new Digit(6),
new Digit(0),
new Digit(0),
new Digit(0)),
new ItemNumber(
new Digit(2),
new Digit(9),
new Digit(1),
new Digit(4),
new Digit(5)),
new CheckDigit()
);
var context = new Context();
upc.Interpret(context: context);
_output.WriteLine(context.Output);
Assert.Equal(12, context.Output.Length);
Assert.Equal('2', context.Output.Last(x => x == '2'));
}
}
}
|
be1835fa054f2fa06c58d7b49320bda949c44190
|
C#
|
CAUCSE-Steamers/Top-of-SI
|
/Assets/Scripts/Programmer/ProgrammerStatus.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace Model
{
public class ProgrammerStatus : IEventDisposable, IXmlConvertible, IXmlStateRecoverable
{
public event Action<int> OnHealthChanged = delegate { };
private int health;
private List<IBurf> burfs = new List<IBurf>();
private List<DeBurfStructure> deburf = new List<DeBurfStructure>();
public string PortraitName
{
get; set;
}
public string Name
{
get; set;
}
public Money Cost
{
get; set;
}
public ProgrammerStatus()
{
ResetStageParameters();
FullHealth = Health;
Cost = new Money(30, 300, 200);
HealRate = 0.0;
Leadership = 0;
Sociality = 0;
}
public void ResetStageParameters()
{
StartVacationDay = null;
AdditionalDamageRatio = 0.0;
AdditionalSkillCostRatio = 0.0;
RemainingVacationDay = 0;
IsMovable = true;
burfs.Clear();
}
public bool IsMovable
{
get; set;
}
public int? StartVacationDay
{
get; set;
}
public bool IsOnVacation
{
get
{
return StartVacationDay != null;
}
}
public double AdditionalDamageRatio
{
get; set;
}
public double AdditionalSkillCostRatio
{
get; set;
}
public int FullHealth
{
get; set;
}
public int Health
{
get
{
return health;
}
set
{
health = value;
OnHealthChanged(health);
}
}
public void AddLeadership(int quantity)
{
int currentLeadershipBonusLevel = Leadership / 10;
int updatedLeadershipBonusLevel = (Leadership + quantity) / 10;
int levelDifference = updatedLeadershipBonusLevel - currentLeadershipBonusLevel;
if (levelDifference > 0)
{
CommonLogger.LogFormat("ProgrammerStatus::AddLeadership => 리더쉽 증가 효과로 정신력/총 정신력이 {0}만큼 증가함.", 3 * levelDifference);
FullHealth += 3 * levelDifference;
Health += 3 * levelDifference;
}
Leadership += quantity;
}
public int Leadership
{
get; private set;
}
public void AddSociality(int quantity)
{
int currentSocialityBonusLevel = Sociality / 10;
int updatedSocialityBonusLevel = (Sociality + quantity) / 10;
int levelDifference = updatedSocialityBonusLevel - currentSocialityBonusLevel;
if (levelDifference > 0)
{
CommonLogger.LogFormat("ProgrammerStatus::AddSociality => 사교성 증가 효과로 회복량이 {0}만큼 증가함.", 0.03 * levelDifference);
HealRate += 0.03 * levelDifference;
}
Sociality += quantity;
}
public int Sociality
{
get; private set;
}
public double HealRate
{
get; set;
}
public int RemainingVacationDay
{
get; set;
}
public void AddBurf(IBurf newBurf)
{
burfs.Add(newBurf);
}
public void RemoveBurf(IBurf targetBurf)
{
burfs = burfs.Where(burf => burf.Equals(targetBurf) == false)
.ToList();
}
public IEnumerable<IBurf> Burfs
{
get
{
return burfs;
}
}
public IEnumerable<IBurf> PositiveBurfs
{
get
{
return Burfs.Where(burf => burf.IsPositiveBurf);
}
}
public IEnumerable<IBurf> NegativeBurfs
{
get
{
return Burfs.Where(burf => burf.IsPositiveBurf == false);
}
}
public TBurf GetBurf<TBurf>() where TBurf : IBurf
{
var burf = Burfs.OfType<TBurf>().FirstOrDefault();
return burf;
}
public bool HasBurf<TBurf>() where TBurf : IBurf
{
var burf = Burfs.OfType<TBurf>().FirstOrDefault();
return burf != null;
}
public IEnumerable<IBurf> DecayBurfAndFetchExpiredBurfs()
{
burfs.ForEach(burf => --burf.RemainingTurn);
var expiredBurfs = burfs.Where(burf => burf.RemainingTurn <= 0);
burfs = burfs.Where(burf => burf.RemainingTurn > 0)
.ToList();
return expiredBurfs;
}
public List<DeBurfStructure> Deburf
{
get
{
return deburf;
}
set
{
deburf.AddRange(value);
}
}
public bool OnDeburf(DeburfType status)
{
foreach (var iter in deburf)
{
if ((iter.Type & status) > 0)
{
return true;
}
}
return false;
}
public void DisposeRegisteredEvents()
{
OnHealthChanged = delegate { };
}
public XElement ToXmlElement()
{
return new XElement("Status",
new XAttribute("Portrait", PortraitName),
new XAttribute("Name", Name),
new XAttribute("FullHealth", FullHealth),
new XAttribute("Health", Health),
new XAttribute("Leadership", Leadership),
new XAttribute("Sociality", Sociality),
new XAttribute("HealRate", HealRate),
Cost.ToXmlElement());
}
public void RecoverStateFromXml(string rawXml)
{
var element = XElement.Parse(rawXml);
PortraitName = element.AttributeValue("Portrait");
Name = element.AttributeValue("Name");
FullHealth = element.AttributeValue("FullHealth", int.Parse);
Health = element.AttributeValue("Health", int.Parse);
Leadership = element.AttributeValue("Leadership", int.Parse);
Sociality = element.AttributeValue("Sociality", int.Parse);
HealRate = element.AttributeValue("HealRate", double.Parse);
Cost.RecoverStateFromXml(element.Element("Money").ToString());
}
}
}
|
c5351aa9e903841119349148fa588f6946d94e65
|
C#
|
Flexberry/NewPlatform.Flexberry.ORM
|
/ICSSoft.STORMNET.Business/IConfigResolver.cs
| 2.6875
| 3
|
namespace ICSSoft.STORMNET.Business
{
/// <summary>
/// Интерфейс, определяющий абстракцию для способа разрешения свойств классов на основе данных из файла конфигурации приложения.
/// </summary>
public interface IConfigResolver
{
/// <summary>
/// Получить строку соединения по ее имени в секции <c>connectionStrings</c>.
/// </summary>
/// <param name="connStringName">Имя строки соединения в секции <c>connectionStrings</c>.</param>
/// <returns>Строка соединения.</returns>
string ResolveConnectionString(string connStringName);
}
}
|
728ca0596e442c42265bf473522fffdc92f869fa
|
C#
|
AnttiLei/Olio-kurssi
|
/Labra4Tehtä5/Labra4Tehtä5/Bikes.cs
| 2.828125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Labra4Tehtä5
{
class Bikes : Vehicles
{
public string GearWheels { get; set; }
public string GearName { get; set; }
public Bikes(string name, string model, int year, string color, string gearWheels, string gearName) : base(name, model, year, color)
{
GearWheels = gearWheels;
GearName = gearName;
}
public override string ToString()
{
return "Name: " + Name + " Model " + Model + " Model year " + Year + " Color: " + Color + " GearWheels: " + GearWheels + " GearName " + GearName;
}
}
}
|
9a15c6ca454f5e06e169b86d53bc607027ac12ed
|
C#
|
k1nval/EqOfMathPhysics
|
/EqOfMathPhysics/SystemsEquationsSolver/DefaultSystemEquations.cs
| 2.984375
| 3
|
namespace SystemsEquationsSolver
{
using System.Collections.Generic;
using System.Linq;
public class DefaultSystemEquations : ISystemEquations
{
public DefaultSystemEquations()
{
}
public DefaultSystemEquations(double[,] matrix, IEnumerable<double> b)
{
Matrix = matrix;
B = b;
}
public double[,] Matrix { get; set; }
public IEnumerable<double> B { get; set; }
public int Count
{
get
{
return B.Count();
}
}
}
}
|
19d8646bde0d0878651b8b693d2ca188f5103586
|
C#
|
owin/museum-piece-gate
|
/src/Main/Gate/Response.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Gate.Utils;
using System.Text;
using System.IO;
using System.Threading;
namespace Gate
{
// A helper object for creating, modifying, or consuming response data in the Environment dictionary.
public struct Response
{
public Response(IDictionary<string, object> environment)
: this()
{
this.Environment = environment;
this.Encoding = Encoding.UTF8;
}
public IDictionary<string, object> Environment { get; set; }
// Retrieves the value if present, or returns the default (null) otherwise.
public T Get<T>(string key)
{
object value;
return Environment.TryGetValue(key, out value) ? (T)value : default(T);
}
// Sets the value if non-null, or removes it otherwise
public Response Set<T>(string key, T value)
{
if (object.Equals(value, default(T)))
{
Environment.Remove(key);
}
else
{
Environment[key] = value;
}
return this;
}
public IDictionary<string, string[]> Headers
{
get { return Get<IDictionary<string, string[]>>(OwinConstants.ResponseHeaders); }
set { Set<IDictionary<string, string[]>>(OwinConstants.ResponseHeaders, value); }
}
public string Status
{
get
{
var reasonPhrase = ReasonPhrase;
return string.IsNullOrEmpty(reasonPhrase)
? StatusCode.ToString(CultureInfo.InvariantCulture)
: StatusCode.ToString(CultureInfo.InvariantCulture) + " " + reasonPhrase;
}
set
{
if (value.Length < 3 || (value.Length >= 4 && value[3] != ' '))
{
throw new ArgumentException("Status must be a string with 3 digit statuscode, a space, and a reason phrase");
}
StatusCode = int.Parse(value.Substring(0, 3));
ReasonPhrase = value.Length < 4 ? null : value.Substring(4);
}
}
public int StatusCode
{
get { return Get<int>(OwinConstants.ResponseStatusCode); }
set { Set<int>(OwinConstants.ResponseStatusCode, value); }
}
public string ReasonPhrase
{
get
{
string reasonPhrase = Get<string>(OwinConstants.ResponseReasonPhrase);
return string.IsNullOrEmpty(reasonPhrase) ? ReasonPhrases.ToReasonPhrase(StatusCode) : reasonPhrase;
}
set { Set<string>(OwinConstants.ResponseReasonPhrase, value); }
}
public string GetHeader(string name)
{
var values = GetHeaders(name);
if (values == null)
{
return null;
}
switch (values.Length)
{
case 0:
return string.Empty;
case 1:
return values[0];
default:
return string.Join(",", values);
}
}
public string[] GetHeaders(string name)
{
string[] existingValues;
return Headers.TryGetValue(name, out existingValues) ? existingValues : null;
}
public Response SetHeader(string name, string value)
{
if (string.IsNullOrWhiteSpace(value))
Headers.Remove(value);
else
Headers[name] = new[] { value };
return this;
}
void OnSendingHeaders(Action<object> callback, object state)
{
var register = Get<Action<Action<object>, object>>(OwinConstants.OnSendingHeaders);
if (register == null)
{
throw new NotImplementedException("Environment does not contain server.OnSendingHeaders");
}
register(callback, state);
}
public Response SetCookie(string key, string value)
{
Headers.AddHeader("Set-Cookie", Uri.EscapeDataString(key) + "=" + Uri.EscapeDataString(value) + "; path=/");
return this;
}
public Response SetCookie(string key, Cookie cookie)
{
var domainHasValue = !string.IsNullOrEmpty(cookie.Domain);
var pathHasValue = !string.IsNullOrEmpty(cookie.Path);
var expiresHasValue = cookie.Expires.HasValue;
var setCookieValue = string.Concat(
Uri.EscapeDataString(key),
"=",
Uri.EscapeDataString(cookie.Value ?? ""),
!domainHasValue ? null : "; domain=",
!domainHasValue ? null : cookie.Domain,
!pathHasValue ? null : "; path=",
!pathHasValue ? null : cookie.Path,
!expiresHasValue ? null : "; expires=",
!expiresHasValue ? null : cookie.Expires.Value.ToString("ddd, dd-MMM-yyyy HH:mm:ss ") + "GMT",
!cookie.Secure ? null : "; secure",
!cookie.HttpOnly ? null : "; HttpOnly"
);
Headers.AddHeader("Set-Cookie", setCookieValue);
return this;
}
public Response DeleteCookie(string key)
{
Func<string, bool> predicate = value => value.StartsWith(key + "=", StringComparison.InvariantCultureIgnoreCase);
var deleteCookies = new[] { Uri.EscapeDataString(key) + "=; expires=Thu, 01-Jan-1970 00:00:00 GMT" };
var existingValues = Headers.GetHeaders("Set-Cookie");
if (existingValues == null)
{
Headers["Set-Cookie"] = deleteCookies;
return this;
}
Headers["Set-Cookie"] = existingValues.Where(value => !predicate(value)).Concat(deleteCookies).ToArray();
return this;
}
public Response DeleteCookie(string key, Cookie cookie)
{
var domainHasValue = !string.IsNullOrEmpty(cookie.Domain);
var pathHasValue = !string.IsNullOrEmpty(cookie.Path);
Func<string, bool> rejectPredicate;
if (domainHasValue)
{
rejectPredicate = value =>
value.StartsWith(key + "=", StringComparison.InvariantCultureIgnoreCase) &&
value.IndexOf("domain=" + cookie.Domain, StringComparison.InvariantCultureIgnoreCase) != -1;
}
else if (pathHasValue)
{
rejectPredicate = value =>
value.StartsWith(key + "=", StringComparison.InvariantCultureIgnoreCase) &&
value.IndexOf("path=" + cookie.Path, StringComparison.InvariantCultureIgnoreCase) != -1;
}
else
{
rejectPredicate = value => value.StartsWith(key + "=", StringComparison.InvariantCultureIgnoreCase);
}
var existingValues = Headers.GetHeaders("Set-Cookie");
if (existingValues != null)
{
Headers["Set-Cookie"] = existingValues.Where(value => !rejectPredicate(value)).ToArray();
}
return SetCookie(key, new Cookie
{
Path = cookie.Path,
Domain = cookie.Domain,
Expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc),
});
}
public /* and remains public in sources */ class Cookie
{
public Cookie()
{
Path = "/";
}
public Cookie(string value)
{
Path = "/";
Value = value;
}
public string Value { get; set; }
public string Domain { get; set; }
public string Path { get; set; }
public DateTime? Expires { get; set; }
public bool Secure { get; set; }
public bool HttpOnly { get; set; }
}
public string ContentType
{
get { return GetHeader("Content-Type"); }
set { SetHeader("Content-Type", value); }
}
public long ContentLength
{
get { return long.Parse(GetHeader("Content-Length"), CultureInfo.InvariantCulture); }
set { SetHeader("Content-Length", value.ToString(CultureInfo.InvariantCulture)); }
}
public Encoding Encoding { get; set; }
public Stream Body
{
get { return Get<Stream>(OwinConstants.ResponseBody); }
set { Set<Stream>(OwinConstants.ResponseBody, value); }
}
public Stream OutputStream
{
get { return Get<Stream>(OwinConstants.ResponseBody); }
set { Set<Stream>(OwinConstants.ResponseBody, value); }
}
public void Write(string text)
{
var data = Encoding.GetBytes(text);
Write(data);
}
public void Write(string format, params object[] args)
{
Write(string.Format(format, args));
}
public void Write(byte[] buffer)
{
OutputStream.Write(buffer, 0, buffer.Length);
}
public void Write(byte[] buffer, int offset, int count)
{
OutputStream.Write(buffer, offset, count);
}
public void Write(ArraySegment<byte> data)
{
OutputStream.Write(data.Array, data.Offset, data.Count);
}
public Task WriteAsync(string text, CancellationToken cancellationToken = default(CancellationToken))
{
var data = Encoding.GetBytes(text);
return WriteAsync(data, cancellationToken);
}
public Task WriteAsync(byte[] buffer, CancellationToken cancellationToken = default(CancellationToken))
{
return OutputStream.WriteAsync(buffer, 0, buffer.Length, cancellationToken);
}
public Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken = default(CancellationToken))
{
return OutputStream.WriteAsync(buffer, offset, count, cancellationToken);
}
public Task WriteAsync(ArraySegment<byte> data, CancellationToken cancellationToken = default(CancellationToken))
{
return OutputStream.WriteAsync(data.Array, data.Offset, data.Count, cancellationToken);
}
public Func<string, long, long?, CancellationToken, Task> SendFileAsync
{
get { return Get<Func<string, long, long?, CancellationToken, Task>>("sendfile.SendAsync"); }
set { Set("sendfile.SendAsync", value); }
}
}
}
|
f8b1e14f7b3cf239134c3e176e940f1c1507b3b0
|
C#
|
pedroalmeida-dev/Student-Projects
|
/Generic Game Engine/Components/Steering/Wander.cs
| 3.390625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
namespace GameEngine.Components.Steering
{
/// <summary>
/// Generates a new random target to move to, every interval between "minTime" and "maxTime"
/// The target will be generated in the circunference of a circle
/// When vehicle gets to the target, it will get a new one even if the interval has not passed.
/// </summary>
class Wander : ISteeringBehavior
{
//Random instance to generate random values
Random random;
//Used to generate a new target every N seconds
float timer;
//Random target generated
Vector2 target = new Vector2();
//Time for the next target to be generated, it value is between minTime and maxTime
int timeInterval;
/* CUSTOMIZABLE PROPERTIES */
//Radius of the circle where the target point will be generated
float radius = 50;
//Distance of the circle origin from the vehicle
float distance = 1;
//Minimum distance that the vehicle will get to the target before searching for new target
int minDistanceToTarget = 10;
//Time between searches (max and min)
int minTime = 1;
int maxTime = 4;
public Wander()
{
random = Game1.random;
timer = maxTime;
}
public void OnStart()
{
}
/// <summary>
/// Calculates the steering force for wander. Generates a random point in a circunference
/// And subtracts the vehicle position, resulting in a direction vector
/// </summary>
/// <param name="vehicle">Vehicle affected by the steering force</param>
/// <returns>Force Vector2 of calculated behaviour</returns>
public Vector2 Calculate(CVehicle vehicle)
{
//Gets the Elapsed game time from the last frame and adds it to the timer
timer += (float) vehicle.GameTime.ElapsedGameTime.TotalSeconds;
//Calculates the distance of the vehicle from the current target
float dist = Vector2.DistanceSquared(vehicle.Owner.position, target);
//If distance is less than minDistanceToTarget -> Set timer equal to max timer to get a new target
if ( dist <= minDistanceToTarget)
{
timer = maxTime;
}
if (timer >= timeInterval)
{
//Generates an angle from 0 to 360 degrees
double angle = random.NextDouble() * Math.PI * 2;
//Generates X and Y coordinates on the circunference
target.X = (float)Math.Cos(angle) * radius;
target.Y = (float)Math.Sin(angle) * radius;
//Converts the generated coordinates to world position and adds the distance from the vehicle
target += vehicle.Owner.position + (Vector2.Normalize(vehicle.orientation) * distance);
//Resets timer
timer = 0;
//set new interval time for the next change of target
timeInterval = random.Next(minTime, maxTime);
}
//returns the vector pointing from position to target generated
return target - vehicle.Owner.position;
}
}
}
|
f552fa6cf078bc1352d7dee3c8bc015baa83d7b7
|
C#
|
darrenudaiyan/WaterPipePollutionDemo
|
/MaxNumberFouledUnits/DataProviders/IWaterUnitsFileHandler.cs
| 2.59375
| 3
|
using System.Collections.Generic;
namespace Udaiyan.MaxNumberFouledUnits.DataProviders
{
/// <summary>
/// The IWaterUnitsFileHandler interface to the WaterUnitsFileHandler class.
/// This reads and checks the WaterUnits file and returns a list of lists.
/// </summary>
public interface IWaterUnitsFileHandler
{
/// <summary>
/// This uses the WaterUnitsFileReader object to get the WaterUnits lists.
/// It was done this way to make unit testing easier and reduce the class size.
/// </summary>
/// <returns>
/// A List of Lists
/// </returns>
List<List<string>> CheckAndGetWaterUnitsLists();
}
}
|
3668a9153199c2a2a9530a0266f9d12caf5fdff0
|
C#
|
veler/AlgorithmSimulator
|
/Sources/Libraries/Algo.Runtime/Build/Runtime/Interpreter/Expressions/ThisReference.cs
| 2.625
| 3
|
using Algo.Runtime.Build.AlgorithmDOM.DOM;
using Algo.Runtime.Build.Runtime.Debugger;
using Algo.Runtime.Build.Runtime.Debugger.Exceptions;
using Algo.Runtime.Build.Runtime.Interpreter.Interpreter;
namespace Algo.Runtime.Build.Runtime.Interpreter.Expressions
{
/// <summary>
/// Provide the interpreter for a reference to the current class
/// </summary>
internal sealed class ThisReference : InterpretExpression
{
#region Constructors
/// <summary>
/// Initialize a new instance of <see cref="ThisReference"/>
/// </summary>
/// <param name="debugMode">Defines if the debug mode is enabled</param>
/// <param name="parentInterpreter">The parent block interpreter</param>
/// <param name="expression">The algorithm expression</param>
internal ThisReference(bool debugMode, BlockInterpreter parentInterpreter, AlgorithmExpression expression)
: base(debugMode, parentInterpreter, expression)
{
}
#endregion
#region Methods
/// <summary>
/// Run the interpretation
/// </summary>
/// <returns>Returns the result of the interpretation</returns>
internal override object Execute()
{
var parentClass = ParentInterpreter.ParentClassInterpreter;
if (parentClass == null)
{
ParentInterpreter.ChangeState(this, new AlgorithmInterpreterStateEventArgs(new Error(new ClassNotFoundException("{Unknow}", "It looks like the parent class does not exists."), Expression), ParentInterpreter.GetDebugInfo()));
return null;
}
if (!parentClass.IsInstance)
{
ParentInterpreter.ChangeState(this, new AlgorithmInterpreterStateEventArgs(new Error(new NoInstanceReferenceException("Unable to get the instance of the parent class of a static method."), Expression), ParentInterpreter.GetDebugInfo()));
return null;
}
if (DebugMode)
{
ParentInterpreter.Log(this, $"Reference to the current instance : {parentClass.ClassDeclaration.Name}");
}
return parentClass;
}
#endregion
}
}
|
27eea69cad6efd0aa178c1633680229955a61e72
|
C#
|
GermanObregon/ApiRestful_Unaj
|
/Api-Restful.AccesData/Validations/MercaderiaValidator.cs
| 2.515625
| 3
|
using Api_Restful.AccesData.Queries.Repository;
using Api_Restful.Domain.DTO_s;
using FluentValidation;
namespace Api_Restful.AccesData.Validations
{
public class MercaderiaValidator : AbstractValidator<MercaderiaDto>
{
private readonly IMercaderiaQuery _query;
public MercaderiaValidator(IMercaderiaQuery query)
{
_query = query;
RuleFor(x => x.Nombre).NotEmpty().WithMessage("El nombre no puede estar vacio.");
RuleFor(x => x.Nombre).MaximumLength(50).WithMessage("El nombre debe tener menos de 50 caracteres.");
RuleFor(x => x.Ingredientes).NotEmpty().WithMessage("Los ingredientes no puede estar vacio.");
RuleFor(x => x.Ingredientes).MaximumLength(255).WithMessage("El nombre debe tener menos de 255 caracteres.");
RuleFor(x => x.Imagen).NotEmpty().WithMessage("La Imagen no puede estar vacia.");
RuleFor(x => x.Imagen).MaximumLength(255).WithMessage("La Imagne debe tener menos de 255 caracteres.");
RuleFor(x => x.Preparacion).NotEmpty().WithMessage("La Preparacion no puede estar vacia.");
RuleFor(x => x.Preparacion).MaximumLength(255).WithMessage("La Preparacion debe tener menos de 255 caracteres.}");
RuleFor(x => x.Precio).GreaterThan(0).WithMessage("El precio debe ser mayor que cero.");
RuleFor(x => x.Precio).NotNull().WithMessage("Debe Ingresar un Numero");
int cantidad = _query.GetCantidadTipos().Cantidad;
RuleFor(x => x.TipoMercaderiaId).LessThan(cantidad).WithMessage("No existe ese tipoMercaderiaId")
.GreaterThan(0).WithMessage("El TipoMercaderiaId no puede ser menor ni igual a cero.");
}
}
}
|
46defa81bfb1edcaa65bd615c48b3a1acc1b0108
|
C#
|
georgy-n/SnakeOnC-sharp
|
/GameSnake/Food.cs
| 2.84375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GameSnake
{
public class Food
{
public int CountScore { get; set; }
public int X { get; set; }
public int Y { get; set; }
public String Name { get; set; }
public Food(int x, int y, int countScore, String name)
{
Name = name;
CountScore = countScore;
X = x;
Y = y;
}
}
}
|
809bcee1d9370c43c79b94624dd1c8bf7c4c8d43
|
C#
|
ValeriFilipov87/TelerikAcademy
|
/CSharp2/04Numeral Systems/02 Binary To Decimal/BinaryToDecimal.cs
| 3.421875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Numerics;
namespace _02_Binary_To_Decimal
{
class BinaryToDecimal
{
static void Main(string[] args)
{
string digit = Console.ReadLine();
BigInteger result = 0;
for (int i = 0; i < digit.Length; i++)
{
result += (BigInteger)((digit[i] - '0') * Math.Pow(2, digit.Length - 1 - i));
}
Console.WriteLine(result);
}
}
}
|
b39d5eb4911176a3c1538be85b3c28d97e041325
|
C#
|
green-fox-academy/mirekjiranek
|
/week-05/Day-1/DataStructure_Practicing/ShoppingList2/Program.cs
| 3.3125
| 3
|
using System;
using System.Collections.Generic;
namespace ShoppingList2
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, double> Products = new Dictionary<string, double>
{
["Milk"] = 1.07,
["Rice"] = 1.59,
["Eggs"] = 3.14,
["Cheese"] = 12.60,
["Chicken Breasts"] = 9.40,
["Apples"] = 2.31,
["Tomato"] = 2.58,
["Potato"] = 1.75,
["Onion"] = 1.10,
};
Dictionary<string, int> BobsList = new Dictionary<string, int>
{
["Milk"] = 3,
["Rice"] = 2,
["Eggs"] = 2,
["Cheese"] = 1,
["Chicken Breasts"] = 4,
["Apples"] = 1,
["Tomato"] = 2,
["Potato"] = 1,
};
Dictionary<string, int> AlicesList = new Dictionary<string, int>
{
["Rice"] = 1,
["Eggs"] = 5,
["Chicken Breasts"] = 2,
["Apples"] = 1,
["Tomato"] = 10,
};
Console.WriteLine($"Bob payed {BobsShoppingList(Products,BobsList)} in total.");
Console.WriteLine($"Alice payed {AlicesShoppingList(Products, AlicesList)} in total.");
Console.WriteLine(WhoBuysMoreRice(BobsList, AlicesList));
Console.WriteLine(WhoBuysMorePotato(BobsList, AlicesList));
Console.WriteLine(DifferentProducts(BobsList, AlicesList));
Console.WriteLine(MoreProducts(BobsList, AlicesList));
}
static double BobsShoppingList(Dictionary<string, double> products, Dictionary<string, int> bobslist)
{
double sum = 0;
foreach (KeyValuePair<string, int> s in bobslist)
{
foreach (KeyValuePair<string, double> i in products)
{
if (s.Key == i.Key)
{
sum += s.Value * i.Value;
}
}
}
return sum;
}
static double AlicesShoppingList(Dictionary<string, double> products, Dictionary<string, int> alicelist)
{
double sum = 0;
foreach (KeyValuePair<string, int> s in alicelist)
{
foreach (KeyValuePair<string, double> i in products)
{
if (s.Key == i.Key)
{
sum += s.Value * i.Value;
}
}
}
return sum;
}
static string WhoBuysMoreRice(Dictionary<string, int> bobslist, Dictionary<string, int> alicelist)
{
if (bobslist["Rice"] < alicelist["Rice"])
{
return $"Alice bought more rice({alicelist["Rice"]}) than Bob ({bobslist["Rice"]})";
}
else
{
return $"Bob bought more rice({bobslist["Rice"]}) than Alice({alicelist["Rice"]}) ";
}
}
static string WhoBuysMorePotato(Dictionary<string, int> bobslist, Dictionary<string, int> alicelist)
{
if (!bobslist.ContainsKey("Potato") || !alicelist.ContainsKey("Potato"))
{
return "Alice or Bob didnt buy this product.";
}
else if (bobslist["Potato"] < alicelist["Potato"])
{
return $"Alice bought more potato({alicelist["Potato"]}) than Bob ({bobslist["Potato"]})";
}
else
{
return $"Bob bought more potato({bobslist["Potato"]}) than Alice ({alicelist["Potato"]})";
}
}
static string DifferentProducts(Dictionary<string, int> bobslist, Dictionary<string, int> alicelist)
{
if (bobslist.Count < alicelist.Count)
{
return $"Alice bought more products({alicelist.Count}) than Bob ({bobslist.Count})";
}
else
{
return $"Bob bought more products({bobslist.Count}) than Alice ({alicelist.Count})";
}
}
static string MoreProducts(Dictionary<string, int> bobslist, Dictionary<string, int> alicelist)
{
int BobSum = 0;
int AliceSum = 0;
foreach (int value in bobslist.Values)
{
BobSum += value;
}
foreach (int value in alicelist.Values)
{
AliceSum += value;
}
if (BobSum < AliceSum)
{
return $"Alice bought more pieces of products.";
}
else
{
return $"Bob bought more pieces of products.";
}
}
}
}
|
20432f00e3c8053c37f54df97261f8393c5ce124
|
C#
|
euvgub/Polygon
|
/src/Polygon.Connector.CQGContinuum/AdapterEvent.cs
| 2.609375
| 3
|
using System;
using System.Linq;
using System.Threading;
using Polygon.Diagnostics;
using ProtoBuf;
using System.Reflection;
namespace Polygon.Connector.CQGContinuum
{
/// <summary>
/// Событие получения адаптером сообщения
/// </summary>
/// <typeparam name="T">
/// Тип сообщения
/// </typeparam>
internal sealed class AdapterEvent<T>
{
private readonly string messageName;
private AdapterEventHandler<T> handler;
public AdapterEvent()
{
messageName = typeof(T).GetTypeInfo().GetCustomAttributes(typeof(ProtoContractAttribute), false)
.OfType<ProtoContractAttribute>()
.Select(_ => _.Name)
.FirstOrDefault() ?? typeof(T).Name;
}
/// <summary>
/// Добавить обработчик события
/// </summary>
public void Add(AdapterEventHandler<T> value)
{
var comparable = handler;
AdapterEventHandler<T> comparand;
do
{
comparand = comparable;
comparable = Interlocked.CompareExchange(
ref handler,
(AdapterEventHandler<T>)Delegate.Combine(comparand, value),
comparand);
} while (comparable != comparand);
}
/// <summary>
/// Удалить обработчик события
/// </summary>
public void Remove(AdapterEventHandler<T> value)
{
var comparable = handler;
AdapterEventHandler<T> comparand;
do
{
comparand = comparable;
comparable = Interlocked.CompareExchange(
ref handler,
(AdapterEventHandler<T>)Delegate.Remove(comparand, value),
comparand);
} while (comparable != comparand);
}
/// <summary>
/// Обработать сообщение
/// </summary>
public void Raise(T message) => RaiseImpl(message, hasRequestId: false);
/// <summary>
/// Обработать сообщение
/// </summary>
public void Raise(uint requestId, T message) => RaiseImpl(message, requestId);
/// <summary>
/// Обработать сообщение
/// </summary>
private void RaiseImpl(T message, uint requestId = 0, bool hasRequestId = true)
{
var h = handler;
if (h != null)
{
try
{
var args = new AdapterEventArgs<T>(message);
h(args);
if (args.Handled)
{
return;
}
}
catch (Exception e)
{
CQGCAdapter.Log.Error().Print(e, $"Failed to process a {messageName} message");
return;
}
}
if (hasRequestId)
{
CQGCAdapter.Log.Warn().Print(
$"Received a {messageName} message but there are no consumers to handle it",
LogFields.RequestId(requestId)
);
}
else
{
CQGCAdapter.Log.Warn().Print($"Received a {messageName} message but there are no consumers to handle it");
}
}
}
}
|
17140ffb56b97f67ff53d133dd7b46b0bd9f5f79
|
C#
|
NOtherDev/developwithpassion.specifications
|
/source/developwithpassion.specifications/core/reflection/PropertyInfoMemberAccessor.cs
| 2.859375
| 3
|
using System;
using System.Reflection;
namespace developwithpassion.specifications.core.reflection
{
public class PropertyInfoMemberAccessor : MemberAccessor
{
PropertyInfo member;
public PropertyInfoMemberAccessor(PropertyInfo member)
{
this.member = member;
}
public Type accessor_type
{
get { return member.PropertyType; }
}
public Type declaring_type
{
get { return member.DeclaringType; }
}
public void change_value_to(object target,object new_value)
{
if (member.CanWrite) this.member.SetValue(target, new_value, null);
}
public string name
{
get { return member.Name;}
}
public object get_value(object target)
{
return this.member.GetValue(target, null);
}
}
}
|
bb230b4e218a681e33f3972ccb8910c26b422643
|
C#
|
MED6-631/AI-Masters---Global-Domination
|
/Testing/Assets/Scripts/AI Logic/UtilityAI/OptionScorers/AttackTargetLowHealthScorer.cs
| 2.59375
| 3
|
namespace AI.Master
{
using Apex.Serialization;
using UnityEngine;
using Apex.AI;
public sealed class AttackTargetLowHealthScorer : OptionScorerBase<ICanDie>
{
[ApexSerialization, FriendlyName("Max Score", "The highest score that this scorer can output to an option")]
public float maxScore = 10f;
[ApexSerialization, FriendlyName("Factor", "A factor used to multiply the option's current health by")]
public float factor = 1f;
public override float Score(IAIContext context, ICanDie option)
{
// low health options score closer to MaxScore than options with more health
var health = option.currentHealth * this.factor;
return Mathf.Max(0f, this.maxScore - health);
}
}
}
|
12e226ece67e8badfad1fb1fdcfca2a2fc9e43ef
|
C#
|
mang0kitty/DublinBusStopApp
|
/Edge.cs
| 3.375
| 3
|
namespace DijkstraTransportGraph
{
public class Edge : IEdge
{
public Edge(Vertex v1, Vertex v2, int weight)
{
Weight = weight;
Vertex1 = v1;
Vertex2 = v2;
}
public int Weight { get; private set; }
public int Vertex1ID { get { return Vertex1.ID; } }
public int Vertex2ID { get { return Vertex2.ID; } }
public Vertex Vertex1 { get; private set; }
public Vertex Vertex2 { get; private set; }
public bool Connects(Vertex v1, Vertex v2)
{
return (this.Vertex1 == v1 && this.Vertex2 == v2)
|| (this.Vertex1 == v2 && this.Vertex2 == v1);
}
public override string ToString()
{
return $"{Vertex1.Name} -> {Vertex2.Name} [{Weight}]";
}
}
}
|
f5b3cf7a1fd23d67b3ac303932fab1b62e20ea08
|
C#
|
DomNomNom/RoyalRampage
|
/Assets/Scripts/RageAndHealth.cs
| 2.921875
| 3
|
/**************************************************\
| Stores and controls the player's rage and health |
\**************************************************/
using UnityEngine;
using System.Collections;
public class RageAndHealth : MonoBehaviour {
//VARIABLES
//gui style
public GUIStyle style = new GUIStyle();
//is true if debug mode is enabled
public bool debug = true;
///the maximum health the player can have
public readonly int MAX_HEALTH = 100;
//the maximum rage the player can have
public readonly float MAX_RAGE = 100.0f;
//the amount which the rage decreases
private readonly float RAGE_DECREASE = 3.0f;
//the values
private int health = 100;
private float rage = 15.0f;
//timing
private float startTime;
//user needs to be spammed
private bool spamalise = false;
// Use this for initialization
void Start () {
startTime = Time.timeSinceLevelLoad;
}
// Update is called once per frame
void Update () {
//decrease rage over time
float timeDiff = Time.timeSinceLevelLoad - startTime;
deceaseRage(timeDiff * RAGE_DECREASE);
startTime = Time.timeSinceLevelLoad;
}
/*void OnTriggerEnter(Collider other) {
//Debug.Log("HITTING something with tag " + other.tag);
// smashable things are now handled in the other object
Explod explod = (Explod)other.GetComponent(typeof(Explod));
if (explod != null) {
increaseRage(4.0f);
}
}*/
//show debug messages
void OnGUI () {
if (debug) {
GUI.Label(new Rect(20, 80, 80, 20), "Rage: " + rage, style);
}
if (spamalise) {
for (int i = 0; i < 30; ++i) {
for (int j = 0; j < 10; ++j) {
float xShift = Random.Range(0, 10) / 2.0f;
float yShift = Random.Range(0, 10) / 2.0f;
GUI.Label(new Rect(0 + (160 * j) + xShift,
0 + (i * 20) + yShift, 100, 20),
"WHAT ARE YOU DOING?!", style);
}
}
}
}
//decreases the rage
public void deceaseRage(float amount) {
//spam if someone passes a negative value (learning by punishment)
if (amount < 0.0f) {
spamalise = true;
}
rage -= amount;
//make sure the rage doesn't go below zero
if (rage < 0.0f) {
rage = 0.0f;
}
}
//increase the rage
public void increaseRage(float amount) {
//spam if someone passes a negative value (learning by punishment)
if (amount < 0.0f) {
spamalise = true;
}
rage += amount;
//make sure the rage doesn't go above max rage
if (rage > MAX_RAGE) {
rage = MAX_RAGE;
}
}
//decrease health
public void deceaseHealth(int amount) {
//spam if someone passes a negative value (learning by punishment)
if (amount < 0) {
spamalise = true;
}
health -= amount;
//make sure the health doesn't go below zero
if (health < 0) {
health = 0;
}
}
//increase the health
public void increaseHealth(int amount) {
//spam if someone passes a negative value (learning by punishment)
if (amount < 0) {
spamalise = true;
}
health += amount;
//make sure the health doesn't go above max health
if (health > MAX_HEALTH) {
health = MAX_HEALTH;
}
}
//return the rage
public float getRage() {
return rage;
}
//return the health
public int getHealth() {
return health;
}
}
|
72bf6d872f88e7441abf1dbe4d3c89dfdf549140
|
C#
|
ETrobocon/ETrobo2018Garageneer
|
/G000_ETロボコン・シニア部門作っちゃおうかな/実装コード/Common/CommandIF.cs
| 2.65625
| 3
|
using BricRoboRTE;
using System;
namespace BricRoboApp
{
public partial class CommandIF
{
override public string ToString()
{
return string.Format("({0}) {1} {2} {3}", cmd, param1, param2, param3);
}
public const int bufSize = 7;
public void FromBuffer( byte[] buf, int offset )
{
cmd = buf[offset+0];
param1 = BitConverter.ToInt16(buf, offset + 1);
param2 = BitConverter.ToInt16(buf, offset + 3);
param3 = BitConverter.ToInt16(buf, offset + 5);
}
public void ToBuffer(byte[] buf, int offset)
{
BitConverter.GetBytes(cmd).CopyTo(buf, offset+0);
BitConverter.GetBytes(param1).CopyTo(buf, offset + 1);
BitConverter.GetBytes(param2).CopyTo(buf, offset + 3);
BitConverter.GetBytes(param3).CopyTo(buf, offset + 5);
}
}
}
|
19a914546d55351a9d017c6eedbb24138a99f87a
|
C#
|
anadera/lessons
|
/Challenge5/Challenge5/Challenge5/Assignment.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Challenge5
{
public class Assignment
{
public string SpyName { get; set; }
public string Name { get; set; }
public DateTime EndDatePA { get; set; }
public DateTime StartDateNA { get; set; }
public DateTime ProjectedEndDateNA { get; set; }
//public int Budget;
public Assignment(string spyName, string name, DateTime endDatePA, DateTime startDateNA, DateTime projectedEndDateNA)
{
this.SpyName = spyName;
this.Name = name;
this.EndDatePA = endDatePA;
this.StartDateNA = startDateNA;
this.ProjectedEndDateNA = projectedEndDateNA;
}
public bool CheckValidDate()
{
TimeSpan t = this.StartDateNA.Subtract(this.EndDatePA);
int result = TimeSpan.Compare(t, TimeSpan.FromDays(14));
if (result >= 0)
return true;
else
return false;
}
public int CalculateBudget()
{
int result;
TimeSpan t = this.ProjectedEndDateNA.Subtract(this.StartDateNA);
result = t.Days * 500;
if (t.Days > 21)
result += 1000;
return result;
}
}
}
|
5081f4ba2e7660a0f56146aee74bebda9872c55d
|
C#
|
csinkers/ualbion
|
/src/Game/Gui/Controls/VerticalStacker.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.Numerics;
using UAlbion.Core;
namespace UAlbion.Game.Gui.Controls;
/// <summary>
/// Arranges a list of elements vertically. If Greedy is true, then all child
/// elements will be arranged with the width of the widest element (unless the
/// entire stack is otherwise constrained).
/// </summary>
public class VerticalStacker : UiElement
{
public VerticalStacker(params IUiElement[] children) : this((IList<IUiElement>)children) { }
public VerticalStacker(IList<IUiElement> children)
{
if (children == null) throw new ArgumentNullException(nameof(children));
foreach(var child in children)
AttachChild(child);
}
public bool Greedy { get; set; } = true;
public override Vector2 GetSize()
{
Vector2 size = Vector2.Zero;
foreach (var child in Children)
{
if (child is not IUiElement { IsActive: true } childElement)
continue;
var childSize = childElement.GetSize();
if (childSize.X > size.X)
size.X = childSize.X;
size.Y += childSize.Y;
}
return size;
}
protected override int DoLayout<T>(Rectangle extents, int order, T context, LayoutFunc<T> func)
{
if (func == null) throw new ArgumentNullException(nameof(func));
int offset = extents.Y;
int maxOrder = order;
foreach(var child in Children)
{
if (child is not IUiElement { IsActive: true } childElement)
continue;
bool greedy = Greedy || child is IGreedyUiElement;
var childSize = childElement.GetSize();
int height = (int)childSize.Y;
var childExtents = greedy
? new Rectangle(extents.X, offset, extents.Width, height)
: new Rectangle(extents.X + (int)(extents.Width - childSize.X) / 2, offset, (int)childSize.X, height);
maxOrder = Math.Max(maxOrder, func(childElement, childExtents, order + 1, context));
// Rendering may have altered the size of any text elements, so retrieve it
// again to ensure correct rendering on the first frame.
height = (int)childElement.GetSize().Y;
offset += height;
}
return maxOrder;
}
}
|
ecbf6e139ffa7e911d20cf107e35368d445bcc7b
|
C#
|
doriswang/Test
|
/Test.WebApi/RequestResult.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
namespace Test.WebApi
{
public class BaseResult
{
public bool InternalServerError { get; set; }
public HttpStatusCode Status { get; set; }
public string ErrorMessage { get; set; }
}
public class RequestResult<T> : BaseResult
where T : class, new()
{
public T Model { get; set; }
public RequestResult()
{
Status = HttpStatusCode.OK;
}
public RequestResult(HttpStatusCode status)
{
Status = status;
}
public RequestResult(string errorMessage)
{
InternalServerError = true;
ErrorMessage = errorMessage;
}
public RequestResult(HttpStatusCode status, string errorMessage)
{
Status = status;
ErrorMessage = errorMessage;
}
public RequestResult(T model)
{
Status = HttpStatusCode.OK;
Model = model;
}
}
}
|
b5d9c1b7c96437b30844e60f95d44468d8cadefd
|
C#
|
piyushnariani/Algorithms
|
/SelectionSort/C#/SelectionSort/Program.cs
| 3.734375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelectionSort
{
class Program
{
static void Main(string[] args)
{
int[] arr = new int[]{ 14, 33, 27, 10, 35, 19, 42, 44 };
int[] sortedArr = selectionSort(arr);
for (int i = 0; i < sortedArr.Length; i++)
{
Console.Write("{0} ", sortedArr[i]);
}
Console.ReadLine();
}
public static int[] selectionSort(int[] arr)
{
int len = arr.Length;
for (int i = 0; i < len - 1; i++)
{
int min = i;
for (int j = i + 1; j < len; j++)
{
if (arr[min] > arr[j])
{
min = j;
}
}
if (min != i)
{
int tmp = arr[i];
arr[i] = arr[min];
arr[min] = tmp;
}
}
return arr;
}
}
}
|
b6f97775757e3d591fa2cafceb8090bf31ee6ac4
|
C#
|
alvinamartya/happyfarmprg4
|
/HappyFarmProject/HappyFarmProjectAPI/Controllers/BusinessLogic/RegionLogic.cs
| 2.640625
| 3
|
using HappyFarmProjectAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
namespace HappyFarmProjectAPI.Controllers.BusinessLogic
{
public class RegionLogic
{
/// <summary>
/// Validate Data When Add Region
/// </summary>
/// <param name="regionRequest"></param>
/// <returns></returns>
public ResponseModel AddRegion(AddRegionRequest regionRequest)
{
using (HappyFarmPRG4Entities db = new HappyFarmPRG4Entities())
{
// validate name
bool nameAlreadyExists = db.Regions.Where(x => x.Name.ToLower() == regionRequest.Name.ToLower()).FirstOrDefault() != null;
if (nameAlreadyExists)
{
// name is exists
return new ResponseModel()
{
Message = "Nama region sudah tersedia",
StatusCode = HttpStatusCode.BadRequest
};
}
else
{
// check authorization
return checkAuthorization(regionRequest.CreatedBy, HttpStatusCode.Created);
}
}
}
/// <summary>
/// Validate Data when Edit Region
/// </summary>
/// <param name="regionRequest"></param>
/// /// <param name="id"></param>
/// <returns></returns>
public ResponseModel EditRegion(int id, EditRegionRequest regionRequest)
{
using (HappyFarmPRG4Entities db = new HappyFarmPRG4Entities())
{
// get employee
var region = db.Regions.Where(x => x.Id == id).FirstOrDefault();
if (region != null)
{
// validate name
bool nameAlreadyExists = db.Regions
.Where(x => x.Name.ToLower().Equals(regionRequest.Name.ToLower()) && x.Id != id)
.FirstOrDefault() != null;
if (nameAlreadyExists)
{
// name is exists
return new ResponseModel()
{
Message = "Nama sudah tersedia",
StatusCode = HttpStatusCode.BadRequest
};
}
else
{
// check authorization
return checkAuthorization(regionRequest.ModifiedBy, HttpStatusCode.OK);
}
}
else
// region is not found
return new ResponseModel()
{
Message = "Wilayah tidak tersedia",
StatusCode = HttpStatusCode.BadRequest
};
}
}
/// <summary>
/// Check Authorization
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
private ResponseModel checkAuthorization(int id, HttpStatusCode responseSuccess)
{
using (HappyFarmPRG4Entities db = new HappyFarmPRG4Entities())
{
var employee = db.Employees.Where(x => x.Id == id && x.RowStatus == "A").FirstOrDefault();
if (employee != null)
{
if (employee.UserLogin.Role.Name != "Super Admin" && employee.UserLogin.Role.Name != "Manager")
{
// unauthroized
return new ResponseModel()
{
StatusCode = HttpStatusCode.Unauthorized,
Message = "Anda tidak memiliki hak akses"
};
}
else
{
// return ok
return new ResponseModel()
{
Message = "Berhasil",
StatusCode = responseSuccess
};
}
}
else
{
// employee not found
return new ResponseModel()
{
Message = "Data karyawan tidak ditemukan",
StatusCode = HttpStatusCode.BadRequest
};
}
}
}
/// <summary>
/// Validate data for getting region by id
/// </summary>
/// <param name="id"></param>
/// <param name="role"></param>
/// <returns></returns>
public ResponseModel GetRegionById(int id, string role)
{
using(HappyFarmPRG4Entities db = new HappyFarmPRG4Entities())
{
// get region
var region = db.Regions.Where(x => x.Id == id && x.RowStatus == "A").FirstOrDefault();
if(region != null)
{
if(role != "Super Admin" && role != "Manager")
{
// unauthorized
return new ResponseModel()
{
StatusCode = HttpStatusCode.Unauthorized,
Message = "Anda tidak memiliki hak akses"
};
}
else
{
// return ok
return new ResponseModel()
{
Message = "Berhasil",
StatusCode = HttpStatusCode.OK
};
}
}
else
{
// region is not found
return new ResponseModel()
{
Message = "Wilayah tidak tersedia",
StatusCode = HttpStatusCode.BadRequest
};
}
}
}
}
}
|
06164c8caf9a712bc4698059b4ed8f2fa0ea61ce
|
C#
|
Jacopo47/ssd-project
|
/Controllers/DbTestConnectionController.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace ssdProject.Controllers
{
[ApiController]
[Route("orders")]
public class DbTestConnection : ControllerBase
{
private readonly ILogger<WeatherForecastController> _logger;
public DbTestConnection(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<String> GetAll()
{
return new Persistence().readOrdini().ToArray();
}
[HttpGet("{id}")]
public IEnumerable<String> GetByID(string id)
{
return new Persistence().readOrdiniByID(id).ToArray();
}
[HttpGet("insert")]
public ContentResult insert()
{
try {
Order order = new Order("", "cust1", "0", 0);
order.create();
return Content("Successfully created!");
} catch(Exception ex) {
return Content("Error on create: " + ex.Message);
}
}
[HttpGet("update/{id}")]
public ContentResult update(string id)
{
try {
Order order = Order.select(id);
order.update();
return Content("Successfully update!");
} catch(Exception ex) {
return Content("Error on update: " + ex.Message);
}
}
[HttpGet("delete/{id}")]
public ContentResult delete(string id)
{
try {
Order order = Order.select(id);
order.delete();
return Content("Successfully deleted!");
} catch(Exception ex) {
return Content("Error on delete: " + ex.Message);
}
}
[HttpGet("order/{id}")]
public ContentResult getOrderByID(string id)
{
try {
Order order = Order.select(id);
return Content(order.ToString());
} catch(Exception ex) {
return Content("Error on get order: " + ex.Message);
}
}
}
}
|
340fd905cf7b91ba69c5201a8548f72eec8f8454
|
C#
|
Qorpent/qorpent.sys
|
/Qorpent.IO.Tests/VcsStorageWorkingWithStreamsTests.cs
| 2.6875
| 3
|
using System;
using System.IO;
using System.Text;
using NUnit.Framework;
using Qorpent.IO.Storages;
using Qorpent.IO.VcsStorage;
namespace Qorpent.IO.Tests {
[TestFixture]
public class VcsStorageWorkingWithStreamsTests {
/// <summary>
///
/// </summary>
private string _workingDirectory;
/// <summary>
///
/// </summary>
private IVcsStoragePersister _vcsStorage;
/// <summary>
///
/// </summary>
[TestFixtureSetUp]
public void TestFixtureSetUp() {
_workingDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
}
/// <summary>
///
/// </summary>
[SetUp]
public void SetUp() {
if (Directory.Exists(_workingDirectory)) {
Directory.Delete(_workingDirectory);
}
_vcsStorage = new VcsStoragePersister(new FileStorageFs(new DirectoryInfo(_workingDirectory)));
}
/// <summary>
///
/// </summary>
[Test]
public void CanReadFromStreamWriteAndGive() {
var msFirst = new MemoryStream();
var msSecond = new MemoryStream();
msFirst.Write(Encoding.UTF8.GetBytes("test"), 0, 4);
msSecond.Write(Encoding.UTF8.GetBytes("tezt"), 0, 4);
_vcsStorage.Commit(new VcsCommit {File = new FileDescriptor {Path = "test"}}, msFirst);
var got = _vcsStorage.Commit(new VcsCommit {File = new FileDescriptor {Path = "test"}}, msSecond);
Assert.AreEqual("tezt", new StreamReader(_vcsStorage.Pick(got)).ReadToEnd());
}
}
}
|
59ee0151f54276b5f47da36d87aad68ec9f8a40a
|
C#
|
kaifudeng/learn_program
|
/Csharp高级编程第九章到第十章内容/列表/Program.cs
| 3.21875
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
namespace 列表
{
public class Racer:IComparable<Racer>,IFormattable
{
public int Id { get; private set; }
public string FirstName { get; private set; }
public string LastName { get; private set; }
public string Country { get; set; }
public int Wins { get; set; }
public Racer(int id,string firstname,string lastname,string country):this(id,firstname,lastname,country,wins:0)
{
}
public Racer (int id,string firstname,string lastname,string country ,int wins)
{
this.Id = id;
this.FirstName = firstname;
this.LastName = lastname;
this.Country = country;
this.Wins = wins;
}
public override string ToString()
{
return string.Format("{0} {1}", FirstName, LastName);
}
public string ToString(string format,IFormatProvider formatProvider)
{
if (format == null) format = "N";
switch(format.ToUpper())
{
case "N":
return ToString();
case "F":
return FirstName;
case "L":
return LastName;
case "W":
return string.Format("{0}, Wins: {1}",ToString(),Wins);
case "C":
return string.Format("{0}, Country: {1}", ToString(), Country);
case "A":
return string.Format("{0}, {1} Wins: {2}", ToString(), Country, Wins);
default: throw new FormatException(String.Format(formatProvider, "Format {0} is not supported", format));
}
}
public string ToString(string format)
{
return ToString(format, null);
}
public int CompareTo(Racer other)
{
if (other == null) return -1;
int compare = string.Compare(this.LastName, other.LastName);
if(compare==0)
return string.Compare(this.FirstName, other.FirstName);
return compare;
}
}
public class FindCountry
{
public FindCountry(string country)
{
this.country = country;
}
private string country;
public bool findcountryPredicate(Racer racer)
{
Contract.Requires<ArgumentNullException>(racer != null);
return racer.Country==country;
}
}
public class RacerComparer : IComparer<Racer>
{
public enum ComparerType
{
FirstName,
LastName,
Country,
Wins
}
private ComparerType comparerType;
public RacerComparer(ComparerType comparerType)
{
this.comparerType = comparerType;
}
public int Compare(Racer x,Racer y)
{
if (x == null && y == null) return 0;
if (x == null) return 1;
if (y == null) return 1;
int result;
switch (comparerType)
{
case ComparerType.FirstName:
return string.Compare(x.FirstName, y.FirstName);
case ComparerType.LastName:
return string.Compare(x.LastName, y.LastName);
case ComparerType.Country:
result = string.Compare(x.Country, y.Country);
if (result == 0)
{
return string.Compare(x.LastName, y.LastName);
}
else return result;
case ComparerType.Wins:
return x.Wins.CompareTo(y.Wins);
default:throw new ArgumentException("Invaild Compare Type");
}
}
}
public class Person
{
private string name;
public Person(string name)
{
this.name = name;
}
public override string ToString()
{
return name;
}
}
class Program
{
static void Main(string[] args)
{
var grham = new Racer(7, "Grham", "Hill","UK",14);
var emerson = new Racer(13, "Emerson", "Fittipaldi", "Brazil", 14);
var mario = new Racer(16, "Mario", "Andretti", "USA", 12);
var racers = new List<Racer>(20) { grham, emerson, mario };
racers.Add(new Racer(24, "Michael", "Schumacher", "Germany", 91));
racers.Add(new Racer(27, "mika", "Hakkinen", "Finland", 20));
racers.AddRange(new Racer[]
{
new Racer(14,"niki","lauda","austria",25),
new Racer(21,"alain","prost","france",51)
});
racers.Insert(3, new Racer(6, "Phil", "Hill", "USA", 3));
Racer r1 = racers[3];
for (int i = 0; i < racers.Count; i++)
{
Console.WriteLine(racers[i]);
}
foreach(Racer r in racers)
{
Console.WriteLine(r);
}
//删除
if(!racers.Remove(grham))
{
Console.WriteLine("object not found in collection");
}
racers.RemoveRange(1,2);
//搜索
int index1 = racers.IndexOf(mario);
int index2 = racers.FindIndex(new FindCountry("Finland").findcountryPredicate);
int index3 = racers.FindIndex(r => r.Country == "finland");
List<Racer> Rlist = racers.FindAll(r => r.Wins > 20);
foreach (Racer a in racers)
{
Console.WriteLine("{0:A}", a);
}
//排序
racers.Sort();
racers.ForEach(Console.WriteLine);
racers.Sort(new RacerComparer(RacerComparer.ComparerType.Country));
racers.ForEach(Console.WriteLine);
//格式转换
List<Person> people = racers.ConvertAll<Person>(r => new Person(r.FirstName + " " + r.LastName));
//lookup类P265
var lookupracers = racers.ToLookup(r => r.Country);
foreach(Racer r in lookupracers["Michael"])
{
Console.WriteLine(r);
}
}
}
}
|
33bd65df36b84147d715912d554a04309caae0f8
|
C#
|
mjazbc/adventofcode2018
|
/Day14/Day14.cs
| 3.234375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Util;
namespace Day14
{
class Day14 : AdventPuzzle
{
protected override string SolveFirstPuzzle()
{
int input = ReadInputText<int>();
LinkedList<int> scoreBoard = new LinkedList<int>();
scoreBoard.AddFirst(3);
scoreBoard.AddLast(7);
var firstElf = scoreBoard.First;
var secondElf = scoreBoard.Last;
for(int i = 0; i < input + 10; i++)
{
int sum = firstElf.Value + secondElf.Value;
if (sum >= 10)
scoreBoard.AddLast(sum / 10);
scoreBoard.AddLast(sum % 10);
MoveForward(ref firstElf);
MoveForward(ref secondElf);
}
return string.Join("", scoreBoard.Skip(input).Take(10));
}
protected override string SolveSecondPuzzle()
{
int input = ReadInputText<int>();
LinkedList<int> scoreBoard = new LinkedList<int>();
scoreBoard.AddFirst(3);
scoreBoard.AddLast(7);
int inputLen = input.ToString().Length;
string inputString = input.ToString();
var firstElf = scoreBoard.First;
var secondElf = scoreBoard.Last;
string lastsequence = "37";
while(true)
{
int sum = firstElf.Value + secondElf.Value;
if (sum >= 10) {
scoreBoard.AddLast(sum / 10);
lastsequence += sum / 10;
if (lastsequence.Length > inputLen)
lastsequence = lastsequence.Substring(1);
if (lastsequence == inputString)
return (scoreBoard.Count - inputLen).ToString();
}
scoreBoard.AddLast(sum % 10);
lastsequence += sum % 10;
if (lastsequence.Length > inputLen)
lastsequence = lastsequence.Substring(1);
if (lastsequence == inputString)
return (scoreBoard.Count - inputLen).ToString();
MoveForward(ref firstElf);
MoveForward(ref secondElf);
}
}
private void MoveForward(ref LinkedListNode<int> elf)
{
int steps = elf.Value + 1;
for (int i = 0; i < steps; i++)
elf = elf.Next ?? elf.List.First;
}
}
}
|
c5e1a74cd4b3ed4efeb72add0ac60db5d4cb5f91
|
C#
|
VDSnuff/Codewars
|
/CodeWars/RunLengthEncoding.cs
| 3.640625
| 4
|
using NUnit.Framework;
using System;
using System.Linq;
namespace CodeWars
{
public static class RunLengthEncoding
{
#region Other members results
#endregion
//My first attempt => not proper (do not cover => aaaabbccca case).
public static string EncodingTest(string str)
{
string result = String.Empty;
int count = 1;
for (int i = 1; i < str.Length; i++)
{
if (str[i - 1] == str[i] && i + 1 != str.Length) count++;
else
{
if (i + 1 == str.Length) count++;
result += count + str[i - 1].ToString();
count = 1;
}
}
return result;
}
// From https://www.geeksforgeeks.org/run-length-encoding/
public static string Encoding_geeksforgeeks(string str)
{
string result = String.Empty;
for (int i = 0; i < str.Length; i++)
{
// Count occurrences of current character
int count = 1;
while (i < str.Length - 1 && str[i] == str[i + 1])
{
count++;
i++;
}
result += count.ToString() + str[i];
}
return result;
}
// Repeating from scratch to summarize
public static string Encoding(string str)
{
string result = String.Empty;
for (int i = 0; i < str.Length; i++)
{
int count = 1;
while (i < str.Length - 1 && str[i] == str[i + 1])
{
count++;
i++;
}
result += count.ToString() + str[i];
}
return result;
}
[TestFixture]
public class RunLengthEncodingTests
{
[Test]
public void SampleTests()
{
Assert.AreEqual("4a2b3c", RunLengthEncoding.Encoding("aaaabbccc"));
Assert.AreEqual("4a2b3c1a", RunLengthEncoding.Encoding("aaaabbccca"));
}
}
}
}
|
7d62fd253c1f4edd2805a6f740f3abbc7f15d152
|
C#
|
Pycz/FightWithShadow
|
/Epsilon/Epsilon/Radar.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Interfaces;
using CCStepsCoords;
// класс содержит набор методов для сканирования карты с целью поиска противника и составлеию баз аптечек и бонусов
namespace Epsilon {
internal class Radar {
// Fields
/// <summary>/// модель игрового поля
/// </summary>
private static MapSector[,] map; // табличное представление графа
/// <summary>/// память робота
/// </summary>
private Mind mind; // доступ к памяти робота осуществление обратного вызова
/// <summary>/// информация о только что просмотренных вершинах
/// </summary>
private Queue<MapSector> recycleSectors;
/// <summary>/// информация о только что просмотренных вершинах
/// </summary>
private IAPI api;
///Propeties
///Methods
/// <summary>/// была ли обработана вершина
/// </summary>
internal static bool usableSector(ICoordinates xy) {
return map[xy.getX (),xy.getY ()].usable;
}
//-----------------------------------------------
/// <summary> /// Получение типа для сектора карты из базы
/// </summary>
internal static TypesOfField getSectorsType(ICoordinates xy) { // тип клетки поля
return map[xy.getX (),xy.getY ()].type;
}
//-----------------------------------------------
/// <summary> /// выделение указателей на вершины графа определенного типа в соответсвующую базу
/// </summary>
private void simpleAddBase(MapSector sector,TypesOfField btypes,TypesOfField types){
if (types == TypesOfField.MEDKIT){ // то просто добавить в базу
mind.healthXY.AddFirst(sector);
}
if (types == TypesOfField.BONUS){
mind.moneyXY.AddFirst ( sector );
}
if (types == TypesOfField.HI){
if (!mind.hisMayBeXY.Contains ( sector )) {
mind.hisMayBeXY.AddFirst ( sector );
}
}
}
//-----------------------------------------------
/// <summary> /// пердсказание координат противника (вспомогательная ф- ия для whereHe())
/// </summary>
private void mayBeHere(int x,int y,LinkedList<MapSector> hisMayBeXY,MapSector sector){
ICoordinates xy=Helper.Coordinates(x,y);
if (EpsilonBot.api.isNorm(xy)){ // если внутри поля
TypesOfField type = api.getTypeOfField ( xy );
if ( type != TypesOfField.WALL){ // если не стена
if (!mind.He.WasFound) { // если не найден
if (type == TypesOfField.HI){ // если нашл то в базу заносим 1 значение - точные координаты
hisMayBeXY.Clear();
hisMayBeXY.AddFirst(sector);
mind.He.WasFound = true;
}
if (!mind.He.WasFound && type == TypesOfField.NOTHING && !api.isVisible ()) {
hisMayBeXY.AddFirst ( sector );// если пустая клетка, и его не видно то он может быть там
}
}
}
}
}
//-----------------------------------------------
/// <summary> /// Вычисление предположительного местоположения Противника относительно предыдущих координат
/// </summary>
private void whereHe(MapSector sector,TypesOfField btype,TypesOfField type){
if (!mind.He.WasFound) {
//int a = 1;
//int b = 0;
//for (int i = 1; i <= 4; i++) {
// mayBeHere ( sector.xy.getX () + a,sector.xy.getY () + b,mind.hisMayBeXY,sector );
// if (i == 1 || i==3) {
// a = -a;
// b = -b;
// }
// if (i == 2) {
// b = -a;
// a = 0;
// }
//}
mayBeHere ( sector.xy.getX () + 1,sector.xy.getY (),mind.hisMayBeXY,sector );
mayBeHere ( sector.xy.getX () - 1,sector.xy.getY (),mind.hisMayBeXY,sector );
mayBeHere ( sector.xy.getX (),sector.xy.getY () - 1,mind.hisMayBeXY,sector );
mayBeHere ( sector.xy.getX (),sector.xy.getY () + 1,mind.hisMayBeXY,sector );
}
}
//-----------------------------------------------
/// <summary> /// Анализ изменений содержимого сектора карты
/// </summary>
private void sectorAnalysis(MapSector sector,TypesOfField btype,TypesOfField type) {
if (btype == TypesOfField.HI) { // если до этого там был противник то вычисляем куда он направился
whereHe ( sector,btype,type );
simpleAddBase ( sector,btype,type ); // и перебиваем базу
}
if (btype == TypesOfField.NOTHING) { // если до этого небыло ничего
simpleAddBase ( sector,btype,type ); // просто перебиваем базу
}
if (btype == TypesOfField.MEDKIT || btype == TypesOfField.BONUS) { // была аптечка или бонус
if (type == TypesOfField.NOTHING) { // а теперь пусто то он там
//if (api.isVisible ( api.getCoordOfMe (),sector.xy/*api.getCoordOfEnemy ()*/ )) {
mayBeHere ( sector.xy.getX (),sector.xy.getY (),mind.hisMayBeXY,sector );
if (btype == TypesOfField.MEDKIT) {
mind.He.Health += Mind.cHealthM;
mind.He.WasFound = true;
}
if (btype == TypesOfField.BONUS) {
mind.He.Money += Mind.cMoneyM;
mind.He.WasFound = true;
}
if (mind.He.WasFound) {
mind.hisMayBeXY.Clear ();
mind.hisMayBeXY.AddFirst ( sector );
mind.He.XY = sector.xy;
}
if (btype == TypesOfField.ME) { // а теперь он знает где я
mind.I.WasFound = true;
}
//}
}
}
}
//-----------------------------------------------
/// <summary> /// анализ измений значений вершин
/// </summary>
internal void mapSectorReLoad(MapSector sector) {
TypesOfField type = api.getTypeOfField ( sector.xy );
TypesOfField btype = Radar.getSectorsType ( sector.xy );
if (btype != type) { // если тип поля изменился
if (type == TypesOfField.HI){// он
mayBeHere ( sector.xy.getX (),sector.xy.getY (),mind.hisMayBeXY,sector ); // обновить его координаты
}else{ // если что нибудь другое
this.sectorAnalysis ( sector,btype,type ); // анализируем прошлое значение
}
sector.type = api.getTypeOfField ( sector.xy ); // изменяем значения на новые на таблице
}
}
//-----------------------------------------------
/// <summary> /// сканирование карты с просчетом минимального пути до каждой вершины из расположения бота
/// </summary>
internal void scaning( ) {
int distance = 1;
Queue<MapSector> queue = new Queue<MapSector> ();
MapSector temp = new MapSector ( api.getCoordOfMe (),api.getCoordOfMe (),distance );
queue.Enqueue (temp);
int levelCount = 1; // кол-во вершин на данной волне
int nextLevelCount = 0; // на след волне
while ( queue.Count>0 ) {
while ( levelCount>0 ) {
temp = queue.Dequeue (); // достали вершину из очереди, пора узнать что в ней изменилось
if (api.isNorm(temp.xy))
{
this.mapSectorReLoad(temp); // анализ изменений в ячейке
queue.Concat ( temp.getAllUsableSectors ( distance,ref nextLevelCount ) ); //всех соседей данной вершины графа
levelCount--; // добавили в имеющуюся очередь
// обновили информацию о вершине
recycleSectors.Enqueue(temp);
}
}
levelCount = nextLevelCount;
nextLevelCount = 0;
distance++; // удаленность волны
}
}
//-----------------------------------------------
/// <summary>/// подготовка к новому сканированию использованных на данном ходу ячеек
/// </summary>
internal void clean() {
while (recycleSectors.Count > 0) {
recycleSectors.Dequeue ().cleanToStep ();
}
}
/// <summary>/// Конструктор
/// </summary>
internal Radar(Mind mind,IAPI api) {
map = new MapSector[api.getMaxX()+1,api.getMaxY()+1]; // создается поле для сканирования
map.Initialize ();
this.mind = mind;
this.api = api;
recycleSectors = new Queue<MapSector>();
ICoordinates xy = Helper.Coordinates ( api.getMinX (),api.getMinY () );
for (int i = api.getMinX (); i <= api.getMaxX (); i++) {
for (int j = api.getMinY (); j <= api.getMaxY (); j++) {
Helper.otherPositionOfThis ( xy,i,j );
if (api.isNorm(xy))
{
map[i, j] = new MapSector(xy, xy, 0);
if (api.getTypeOfField(xy) == TypesOfField.WALL)
{
map[i, j].type = TypesOfField.WALL;
}
else
{
map[i, j].type = TypesOfField.NOTHING;
}
}
}
}
}
}
}
|
b66af409830c4da52154c620343c3a858074f478
|
C#
|
210628-UTA-NET/Julian-He-P0
|
/StorefrontModels/Storefront.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
namespace StorefrontModels
{
public class Storefront
{
private string _name;
private string _address;
private List<LineItem> _inventory;
private List<Order> _orders;
private int _id;
public Storefront(){
}
public string Name {
get{
return _name;
}
set{
_name=value;
}
}
public string Address {
get{return _address;}
set{_address = value;}
}
public List<LineItem> Inventory{
get{
return _inventory;
}
set{
_inventory = value;
}
}
public List<Order> Orders { get{
return _orders;
} set{
_orders= value;
} }
public int ID{
get{
return _id;
}
set{
_id = value;
}
}
}
}
|
e52a09a99196ac78a4f5c11b1dc51c944ebc6298
|
C#
|
daniel-bytes/rps.net
|
/Rps.Domain/Model/GameBoard.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using Rps.Domain.Exceptions;
using Rps.Domain.Extensions;
namespace Rps.Domain.Model
{
public class GameBoard
{
private GameProperties properties;
private Token[,] tokens;
public GameBoard(GameProperties properties, IEnumerable<Token> tokens)
{
this.properties = properties;
this.tokens = new Token[properties.Bounds.Rows, properties.Bounds.Cols];
foreach (var token in tokens)
{
this.tokens[token.Row, token.Col] = token;
}
}
public GameProperties Properties { get { return properties; } }
public Bounds Bounds { get { return properties.Bounds; } }
public int NumRows { get { return properties.Bounds.Rows; } }
public int NumCols { get { return properties.Bounds.Cols; } }
public IEnumerable<Token> GetTokens()
{
for(int r = 0; r < NumRows; r++)
{
for (int c = 0; c < NumCols; c++)
{
var token = tokens[r, c];
if (token != null)
{
yield return tokens[r, c];
}
}
}
}
public Token Get(Point point)
{
Bounds.AssertContains(point);
return tokens[point.X, point.Y];
}
public Token Get(int row, int col)
{
return Get(new Point(row, col));
}
public Token GetByID(long tokenID)
{
return GetTokens().FirstOrDefault(x => x.ID == tokenID);
}
public void Remove(Point point)
{
tokens[point.X, point.Y] = null;
}
public IEnumerable<Point> GetValidMoves(Token token)
{
var points = new List<Point>();
if (token.Point.X > 0)
{
points.Add(token.Point.AddX(-1));
}
if (token.Point.Y > 0)
{
points.Add(token.Point.AddY(-1));
}
if (token.Point.X < (Bounds.Rows - 1))
{
points.Add(token.Point.AddX(1));
}
if (token.Point.Y < (Bounds.Cols - 1))
{
points.Add(token.Point.AddY(1));
}
return (from point in points
let tokenAtPoint = Get(point)
where tokenAtPoint == null
|| tokenAtPoint.PlayerID != token.PlayerID
select point
).ToList();
}
public static GameBoard Empty()
{
return new GameBoard(new GameProperties(), Enumerable.Empty<Token>());
}
public static GameBoard New(
GameProperties properties,
Player player1,
Player player2)
{
var rows = properties.Bounds.Rows;
var cols = properties.Bounds.Cols;
var rowsPerPlayer = properties.RowsPerPlayer;
var bombsPerPlayer = properties.BombsPerPlayer;
var tokens = new List<Token>();
var random = Core.Utility.Random.New();
foreach (var player in new[] { player1, player2 })
{
var playerTokenCount = (cols * rowsPerPlayer);
var rpsTokenCount = (playerTokenCount - 1 - bombsPerPlayer) / 3;
var coordinates = (from row in Enumerable.Range(0, rowsPerPlayer)
from col in Enumerable.Range(0, cols)
select Tuple.Create(
(player == player2) ? (rows - row - 1) : row,
col)).ToList();
var tokenTypes = new Dictionary<TokenType, int>
{
{ TokenType.Flag, 1 },
{ TokenType.Bomb, bombsPerPlayer },
{ TokenType.Rock, rpsTokenCount },
{ TokenType.Paper, rpsTokenCount },
{ TokenType.Scissor, rpsTokenCount }
};
tokenTypes[TokenType.Bomb] += (playerTokenCount - tokenTypes.Values.Sum()); // rounding errors go to bombs
Func<Tuple<int, int>> popRandomCoordinate = () => {
var idx = random.Next() % coordinates.Count;
var results = coordinates[idx];
coordinates.RemoveAt(idx);
return results;
};
foreach (var tokenType in tokenTypes)
{
for (int i = 0; i < tokenType.Value; i++)
{
var point = popRandomCoordinate();
tokens.Add(
new Token(0, player.ID, tokenType.Key, point.Item1, point.Item2)
);
}
}
}
var board = new GameBoard(properties, tokens);
return board;
}
}
}
|
cadf1ec98e0a3dc3958df044073c6a88dd6fc345
|
C#
|
JohnNickerson/MediaSync
|
/Core/Extensions/DirectoryInfoExtensions.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AssimilationSoftware.MediaSync.Core.Extensions
{
public static class DirectoryInfoExtensions
{
public static bool IsSubPathOf(this DirectoryInfo subPath, DirectoryInfo basePath)
{
// One arg is null.
if (subPath == null || basePath == null) return false;
// Paths are equal.
if (subPath.FullName.Equals(basePath.FullName, StringComparison.CurrentCultureIgnoreCase)) return true;
// Different roots.
if (!basePath.Root.FullName.Equals(subPath.Root.FullName, StringComparison.CurrentCultureIgnoreCase)) return false;
// subPath is root and paths are not equal.
if (subPath.Parent == null) return false;
// subPath is direct child of basePath.
if (basePath.FullName.Equals(subPath.Parent.FullName, StringComparison.CurrentCultureIgnoreCase)) return true;
// Check subPath.Parent.
return subPath.Parent.IsSubPathOf(basePath);
}
}
}
|
169d73c95b50b05e204ce767559a17da1329c8d6
|
C#
|
aranchafoz/ARADrive
|
/ARADrive/ClassLibrary/CAD/OfficeCAD.cs
| 3.0625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Collections;
using System.Configuration;
using OfficeENns;
namespace OfficeCADNS{
public class OfficeCAD {
// Get connection string needed to connect with the data base
private string s = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString ();
// Instance of OfficeEN
private OfficeEN office;
// We create connection, it will be used for the queries and other data base connections
private SqlConnection c;
// We create an array that will contain a number of offices
private ArrayList allOffices;
// Constructor
public OfficeCAD(){
c = new SqlConnection(s);
}
// Method that gets all the offices saved in the data base
public ArrayList getAllOffices(){
try{
c.Open();
allOffices = new ArrayList();
// This is the SQL query used to gat all the information about all the offices
SqlCommand com = new SqlCommand("Select * from T_Office", c);
SqlDataReader dr = com.ExecuteReader();
while(dr.Read()){
// Each result is saved into this auxiliar variable
OfficeEN aux = new OfficeEN((int)dr["code"], dr["name"].ToString(), dr["address"].ToString(), dr["city"].ToString(), (double)dr["cX"], (double)dr["cY"]);
// And then added to the ArrayList
allOffices.Add(aux);
}
dr.Close();
}finally{
c.Close();
}
return (allOffices);
}
// Method that gets a concrete office identified by its code
public OfficeEN getOffice(int code){
try{
c.Open();
// First we select all the information from the office identified by the code passes as a parameter
SqlCommand com = new SqlCommand("Select * from T_Office WHERE code="+code, c);
SqlDataReader dr = com.ExecuteReader();
// The result if used to instantiate a OfficeEN variable with will be returned
OfficeEN aux = new OfficeEN((int)dr["code"], dr["name"].ToString(), dr["address"].ToString(), dr["city"].ToString(), (double)dr["cX"], (double)dr["cY"]);
dr.Close();
return aux;
}finally{
c.Close();
}
}
}
}
|
ff98f01daaebe428801d675a7f49462923930707
|
C#
|
Pyroblasted/Spelprojekt
|
/Spelprojekt/Spelprojekt/Gui/GuiManager.cs
| 2.828125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spelprojekt.Gui.Components;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace Spelprojekt.Gui
{
public class GuiManager : DrawableGameComponent
{
List<BasicComponent> components = new List<BasicComponent>();
SpriteBatch spriteBatch;
public enum ChangeType
{
property, variable
}
public GuiManager(Game1 game, SpriteBatch spriteBatch)
: base(game)
{
this.spriteBatch = spriteBatch;
}
public T Get<T>(string name) where T : BasicComponent
{
T component = null;
components.ForEach(x =>
{
if (x.name == name) component = (T)x;
});
return component;
}
public override void Draw(GameTime gameTime)
{
spriteBatch.Begin();
components.ForEach(x => { if (x.visible) x.Draw(gameTime, spriteBatch); });
spriteBatch.End();
base.Draw(gameTime);
}
public override void Update(GameTime gameTime)
{
components.ForEach(x => { if (x.visible) x.Update(gameTime); });
base.Update(gameTime);
}
public void Add(BasicComponent comp)
{
components.Add(comp);
}
public void Remove(string name)
{
if(components.Contains(Get<BasicComponent>(name)))
components.Remove(Get<BasicComponent>(name));
}
public void Clear()
{
components.Clear();
}
public void RemoveMany(params string[] names)
{
foreach (string s in names)
{
Remove(s);
}
}
public List<BasicComponent> GetMany(params string[] names)
{
List<BasicComponent> comps = new List<BasicComponent>();
foreach (string s in names)
{
comps.Add(Get<BasicComponent>(s));
}
return comps;
}
public bool AnyHovering()
{
foreach (BasicComponent c in components)
{
if (c.CurrentHovering() && c.visible) return true;
}
return false;
}
}
}
|
4f2315d3d22d33d517efbf60f8d4675fc79f88d2
|
C#
|
TAPXYC/Statistick_Fuel
|
/Statistick/Resources/Classes/RegressionCalculator.cs
| 3.03125
| 3
|
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Factorization;
using MathNet.Numerics.Statistics;
using System;
using System.Collections.Generic;
class RegressionCalculator
{
public static void LinearLeastSquares(double[] x, double[] y, out double a, out double b)
{
double a11 = 0.0, a12 = 0.0, a22 = x.Length, b1 = 0.0, b2 = 0.0;
for (int i = 0; i < x.Length; i++)
{
a11 += x[i] * x[i];
a12 += x[i];
b1 += x[i] * y[i];
b2 += y[i];
}
double det = a11 * a22 - a12 * a12;
a = (b1 * a22 - a12 * b2) / det;
b = (a11 * b2 - b1 * a12) / det;
}
public static double GetDualCorrelation(double[] data1, double[] data2)
{
return Correlation.Pearson(data1, data2);
}
public static Matrix<double> GetDualCorrelation(List<double[]> data)
{
return Correlation.PearsonMatrix(data);
}
public static double GetParticleCorrelationCoeff(List<double[]> data)
{
double Res = 0;
Matrix<double> CorrelationMatrix = GetDualCorrelation(data);
Matrix<double> InverseMatrix = CorrelationMatrix.Inverse();
Vector<double> Diagonal = InverseMatrix.Diagonal();
Diagonal = Diagonal.PointwiseSqrt();
return Res;
}
public static double[,] GetParticleCorrelation(List<double[]> data)
{
Matrix<double> CorrelationMatrix = GetDualCorrelation(data);
Matrix<double> InverseMatrix = CorrelationMatrix.Inverse();
Vector<double> Diagonal = InverseMatrix.Diagonal();
double[,] Result = InverseMatrix.ToArray();
for(int i = 0; i < Result.GetLength(0); i++)
{
for (int j = 0; j < Result.GetLength(1); j++)
{
Result[i, j] = -Result[i, j] / Math.Sqrt(Diagonal[i] * Diagonal[j]);
}
}
return Result;
}
public static double GetCovariance(double[] data1, double[] data2)
{
return Statistics.Covariance(data1, data2);
}
}
|
449674da5af87c6f7be2f534b7adc4a7c3e7598b
|
C#
|
vipnormalhy/learn
|
/csharp/NetworkMonitor/NetworkMonitor/frmMain.cs
| 2.703125
| 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 MyNetworkInfo;
using System.Threading;
namespace NetworkMonitor
{
public partial class frmMain : Form
{
Thread _thread;
bool m_IsAlive;
MethodInvoker UIInvoke;
int m_Index;
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
m_Index = -1;
NetworkManager.Instance.StartMonitor();
m_IsAlive = true;
UIInvoke = new MethodInvoker(UpdateUI);
Initial();
_thread = new Thread(new ThreadStart(UpdateStatus));
_thread.Start();
}
private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
{
NetworkManager.Instance.Destory();
m_IsAlive = false;
}
void Initial()
{
foreach(NetworkInfo info in NetworkManager.Instance.Informations.Values)
{
lstAllNetwork.Items.Add(info.ConnectionID);
}
}
void UpdateStatus()
{
while(m_IsAlive)
{
try
{
Invoke(UIInvoke);
}catch{}
Thread.Sleep(300);
}
}
void UpdateUI()
{
if (m_Index >= 0)
{
string key = lstAllNetwork.Items[lstAllNetwork.SelectedIndex].ToString();
SetInfornation(NetworkManager.Instance.Informations[key]);
}
else
{
ClearInformation();
}
}
void SetInfornation(NetworkInfo info)
{
lblNetworkName.Text = info.ConnectionID;
lblDeviceName.Text = info.DeviceName;
lblAdapterType.Text = info.AdapterType;
lblMac.Text = info.MacAddress;
lblIP.Text = info.IP;
lblMask.Text = info.Mask;
lblGateway.Text = info.DefaultGateway;
lblStatus.Text = info.Status.ToString();
lblHelp.Text = info.GetHelp();
}
void ClearInformation()
{
lblNetworkName.Text = "";
lblDeviceName.Text = "";
lblAdapterType.Text = "";
lblMac.Text = "";
lblIP.Text = "";
lblMask.Text = "";
lblGateway.Text = "";
lblStatus.Text = "";
lblHelp.Text = "";
}
private void lstAllNetwork_SelectedIndexChanged(object sender, EventArgs e)
{
Console.WriteLine(lstAllNetwork.SelectedIndex);
m_Index = lstAllNetwork.SelectedIndex;
}
}
}
|
62a6a2f9183e04c9769a4d34fef7c6458715119f
|
C#
|
Engin-Boot/modular21-Sahlot02
|
/TelCo.ColorCoder/Model.cs
| 2.90625
| 3
|
using System;
using System.Diagnostics;
using System.Drawing;
namespace TelCo.ColorCoder
{
public class ColorMap
{
public readonly static Color[] colorMapMajor;
public readonly static Color[] colorMapMinor;
static ColorMap()
{
colorMapMajor = new Color[] { Color.White, Color.Red, Color.Black, Color.Yellow, Color.Violet };
colorMapMinor = new Color[] { Color.Blue, Color.Orange, Color.Green, Color.Brown, Color.SlateGray };
}
}
public class ColorPair
{
public Color majorColor { get; set; }
public Color minorColor { get; set; }
public override string ToString()
{
return string.Format("MajorColor:{0}, MinorColor:{1}", majorColor.Name, minorColor.Name);
}
}
}
|
ded6dcc219ee65dfdf8f2efbc4c52d7620e68251
|
C#
|
duyetln/dp
|
/csharp/Factory_Simplified/Maze.cs
| 3.46875
| 3
|
using System;
using System.Collections.Generic;
/*
Bare bones implementation for Maze
*/
namespace DesignPatterns.Factory_Simplified
{
abstract class Maze
{
List<Room> rooms = new List<Room>();
List<Wall> walls = new List<Wall>();
internal void addRoom(Room room)
{
rooms.Add(room);
}
internal void addWall(Wall wall)
{
walls.Add(wall);
}
abstract public void setUpRooms();
abstract public void setUpWalls();
}
class BasicMaze : Maze
{
public override void setUpRooms()
{
addRoom(new Room("Basic Room"));
}
public override void setUpWalls()
{
addWall(new Wall("Basic Wall"));
}
}
class HauntedMaze : BasicMaze, HolySpell
{
public void HolySpell()
{
Console.Out.WriteLine("Holy spell invoked!");
}
public override void setUpRooms()
{
addRoom(new HauntedRoom("Haunted Room"));
}
}
class EnchantedMaze : BasicMaze, MagicSpell
{
public void MagicSpell()
{
Console.Out.WriteLine("Magic spell invoked!");
}
public override void setUpWalls()
{
addWall(new EnchantedWall("Enchanted Wall"));
}
}
class HybridMaze : BasicMaze, MagicSpell, HolySpell
{
public void MagicSpell()
{
Console.Out.WriteLine("Magic spell invoked!");
}
public void HolySpell()
{
Console.Out.WriteLine("Holy spell invoked!");
}
public override void setUpRooms()
{
addRoom(new HauntedRoom("Haunted Room"));
}
public override void setUpWalls()
{
addWall(new EnchantedWall("Haunted Wall"));
}
}
}
|
1df5145edc12d891944983595a4f838ae9c1768a
|
C#
|
gabriel-moura2/PEOO4Bimestre
|
/Lista19/Ex01/Program.cs
| 3.859375
| 4
|
using System;
namespace Ex01
{
class Retangulo
{
private double b;
private double h;
public Retangulo(double b, double h)
{
this.b = b;
this.h = h;
}
public double GetBase()
{
return b;
}
public double GetAltura()
{
return h;
}
public double CalcArea()
{
return b * h;
}
public double CalcDiagonal()
{
return Math.Sqrt(b * b + h * h);
}
public override string ToString()
{
return $"{b} {h}";
}
}
class Quadrado : Retangulo
{
public Quadrado(double l) : base(l, l) { }
public override string ToString()
{
return $"{GetBase()}";
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
|
d7b7f5f4d716459100cdb66c6786faf1d589ffaa
|
C#
|
wfxr/ClusteringAlgorithm
|
/examples/demo-wpf/MainWindow.xaml.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Data;
using ClusteringAlgorithm;
using DevExpress.Xpf.Charts;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Double;
using Wfxr.Utility.Container;
namespace ChartTest {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
private List<double[]> _pointData;
public MainWindow() { InitializeComponent(); }
private int ClusterNumber => int.Parse(ClusterNumberBox.SelectedItem.ToString());
private double WeightedIndex => double.Parse(WeightedIndexBox.SelectedItem.ToString());
private int MaxIterations => int.Parse(MaxIterationsBox.SelectedItem.ToString());
private double MinImprovment => double.Parse(MinImprovmentBox.SelectedItem.ToString());
private void Window_Loaded(object sender, RoutedEventArgs e) {
ClusterNumberBox.ItemsSource = Enumerable.Range(2, 8);
ClusterNumberBox.SelectedIndex = 1;
WeightedIndexBox.ItemsSource = new List<double> {1.5, 2.0, 2.5, 3.0};
WeightedIndexBox.SelectedIndex = 1;
MaxIterationsBox.ItemsSource = new List<int> {100, 200, 500, 1000};
MaxIterationsBox.SelectedIndex = 1;
MinImprovmentBox.ItemsSource = new List<double> {1e-4, 1e-5, 1e-6, 1e-7};
MinImprovmentBox.SelectedIndex = 1;
_pointData = PointDataFromFile("PointData.txt");
var points = CreatePointList(_pointData);
AddSeriesOfPoints(points);
}
private List<Point> CreatePointList(Matrix<double> m) {
var row = m.RowCount;
var col = m.ColumnCount;
if (col != 2) throw new FormatException("not a n*2 matrix");
var points = new List<Point>();
for (var i = 0; i < row; ++i)
points.Add(new Point(m[i, 0], m[i, 1]));
return points;
}
private List<Point> CreatePointList(IEnumerable<double[]> list)
=> CreatePointList(DenseMatrix.OfRowArrays(list));
private List<List<Point>> GroupPoints(Matrix<double> m, int[] idx) {
var row = m.RowCount;
var col = m.ColumnCount;
var groupCount = idx.Max() + 1;
if (col != 2) throw new FormatException("not a n*2 matrix");
var group = new List<List<Point>>(groupCount).PopulateDefault();
for (var i = 0; i < row; ++i)
group[idx[i]].Add(new Point(m[i, 0], m[i, 1]));
return group;
}
private static List<double[]> PointDataFromFile(string path) {
var points = new List<double[]>();
var lines = File.ReadAllLines(path);
foreach (var line in lines) {
var xy = line.Split(new[] {' ', '\t'}, StringSplitOptions.RemoveEmptyEntries);
if (xy.Length == 0) continue;
if (xy.Length != 2)
throw new FormatException("there should be 2 number in one line");
var x = double.Parse(xy[0]);
var y = double.Parse(xy[1]);
points.Add(new[] {x, y});
}
return points;
}
private void RunButton_Click(object sender, RoutedEventArgs e) {
var matrix = DenseMatrix.OfRowArrays(_pointData);
ClusterReport report = null;
if (KmeansRadio.IsChecked == true) {
var kmeans = new Kmeans(matrix);
report = kmeans.Run(ClusterNumber, MaxIterations, MinImprovment);
}
else if (CmeansRadio.IsChecked == true) {
var cmeans = new Fcm(matrix);
report = cmeans.Run(ClusterNumber, WeightedIndex, MaxIterations,
MinImprovment);
}
if (report == null) return;
diagram.Series.Clear();
var groups = GroupPoints(report.Obs, report.Idx);
foreach (var group in groups)
AddSeriesOfPoints(group);
var centers = CreatePointList(report.Center);
AddSeriesOfPoints(centers, 10);
}
private void AddSeriesOfPoints(IReadOnlyCollection<Point> points, int pointSize = 4) {
// Create a point series.
var series = new PointSeries2D {
DataSource = points,
MarkerSize = pointSize,
ArgumentDataMember = "X",
ValueDataMember = "Y"
};
// Add it to series of the diagram
diagram.Series.Add(series);
}
}
[ValueConversion(typeof (bool), typeof (Visibility))]
public class BoolToVisibilityConverter : IValueConverter {
public BoolToVisibilityConverter() : this(true) { }
public BoolToVisibilityConverter(bool collapsewhenInvisible) {
CollapseWhenInvisible = collapsewhenInvisible;
}
public bool CollapseWhenInvisible { get; set; }
public Visibility FalseVisibility
=> CollapseWhenInvisible ? Visibility.Collapsed : Visibility.Hidden;
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
if (value == null)
return Visibility.Visible;
return (bool) value ? Visibility.Visible : FalseVisibility;
}
public object ConvertBack(object value, Type targetType, object parameter,
CultureInfo culture) {
if (value == null)
return true;
return ((Visibility) value == Visibility.Visible);
}
}
}
|
85b67b639526978892dfb42d63c43a6afad12381
|
C#
|
NagyDominik/CrownClean-BE
|
/CrownCleanApp.Core/ApplicationService/IOrderService.cs
| 2.890625
| 3
|
using CrownCleanApp.Core.DomainService.Filtering;
using CrownCleanApp.Core.Entity;
using System;
using System.Collections.Generic;
using System.Text;
namespace CrownCleanApp.Core.ApplicationService
{
public interface IOrderService
{
/// <summary>
/// Save an order to the database.
/// </summary>
/// <param name="order">The order that will be saved.</param>
/// <returns>The saved order.</returns>
Order AddOrder(Order order);
/// <summary>
/// Retrieve all orders from the database, possibly filtered.
/// </summary>
/// <param name="filter">A filter object used for pagination and filtering</param>
/// <returns></returns>
FilteredList<Order> GetAllOrders(OrderFilter filter);
/// <summary>
/// Return the orders of a specific customer
/// </summary>
/// <param name="filter">A filter object used for pagination and filtering</param>
/// <param name="id">The ID of the customer whose orders are returned.</param>
/// <returns>The orders of the specified user.</returns>
FilteredList<Order> GetOrdersOfACustomer(OrderFilter filter, int id);
/// <summary>
/// Retrieve an order based on ID.
/// </summary>
/// <param name="id">The ID of the order that will be retrieved.</param>
/// <returns>The order with the supplied ID if exists, null otherwise.</returns>
Order GetOrderByID(int id);
/// <summary>
/// Update an already existing order in the database.
/// </summary>
/// <param name="order">The order that will be updated.</param>
/// <returns>The updated order.</returns>
Order UpdateOrder(Order order);
/// <summary>
/// Approve an order with the given ID.
/// </summary>
/// <param name="id">The ID of the order that will be approved.</param>
/// <returns>The approved order if successfull, null otherwise.</returns>
Order ApproveOrder(int id);
/// <summary>
/// Delete an order with the given ID.
/// </summary>
/// <param name="id">The ID of the order that will be deleted.</param>
/// <returns>The deleted order, if existed, null otherwise.</returns>
Order DeleteOrder(int id);
}
}
|
2fc1d5548f302ecb41e73cbfefa5103ecbd2b711
|
C#
|
DinkyTesla/Cinema_Api_UltraPlay
|
/CinemAPI.Data.Implementation/MovieRepository.cs
| 2.953125
| 3
|
using CinemAPI.Data.EF;
using CinemAPI.Models;
using CinemAPI.Models.Contracts.Movie;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
namespace CinemAPI.Data.Implementation
{
public class MovieRepository : IMovieRepository
{
private readonly CinemaDbContext db;
public MovieRepository(CinemaDbContext db)
{
this.db = db;
}
public async Task<IMovie> GetById(int movieId)
{
return await this.db.Movies.FirstOrDefaultAsync(m => m.Id == movieId);
}
public async Task<IMovie> GetByNameAndDuration(string name, short duration)
{
return await this.db.Movies.FirstOrDefaultAsync(m => m.Name == name &&
m.DurationMinutes == duration);
}
public async Task Insert(IMovieCreation movie)
{
Movie newMovie = new Movie(movie.Name, movie.DurationMinutes);
this.db.Movies.Add(newMovie);
await this.db.SaveChangesAsync();
}
public async Task<string> GetMovieNameById(int id)
{
return await this.db.Movies
.Where(m => m.Id == id)
.Select(x => x.Name)
.FirstOrDefaultAsync();
}
}
}
|
165f2d15d557f1d15b23792d4092032ebec1e595
|
C#
|
NanoSector/Unity_CharacterScripts
|
/src/Character/PlayerMovement.cs
| 2.59375
| 3
|
using UnityEngine;
namespace Character
{
public class PlayerMovement : MonoBehaviour
{
public CharacterController2D controller;
public float runSpeed = 40f;
private float _horizontalMove;
private bool _jump;
private bool _crouch;
// Update is called once per frame
void Update()
{
_horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;
if (Input.GetButtonDown("Jump"))
{
_jump = true;
}
if (Input.GetButtonDown("Crouch"))
{
_crouch = true;
}
else if (Input.GetButtonUp("Crouch"))
{
_crouch = false;
}
}
void FixedUpdate()
{
// Move our character
controller.Move(_horizontalMove * Time.fixedDeltaTime, _crouch, _jump);
_jump = false;
}
}
}
|
dfe19392386766a401ef8255dd942075209ff69f
|
C#
|
Sway623/Mario-3902
|
/FreeBowser/FreeBowser/CSVParser.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using System.Collections;
namespace FreeBowser
{
class CSVParser
{
public CSVParser()
{
}
public void parse(Dictionary<string, List<Vector2>> spriteDict, List<string> csvLines, int screenHeight, int screenWidth)
{
int xPos = 0;
int yPos = 0;
int spriteWidth = 16;
int spriteHeight = 16;
int yShiftFactor = screenHeight - (csvLines.Count * spriteWidth);
foreach (string line in csvLines)
{
string[] sprites = line.Split(',');
xPos = 0;
foreach (string sprite in sprites)
{
List<Vector2> coords;
if (spriteDict.TryGetValue(sprite, out coords))
{
coords.Add(new Vector2(xPos, yPos + yShiftFactor));
spriteDict[sprite] = coords;
}
else if (sprite.Contains("warp"))
{
coords = new List<Vector2>();
coords.Add(new Vector2(xPos, yPos + yShiftFactor));
spriteDict.Add(sprite, coords);
}
xPos += spriteWidth;
}
yPos += spriteHeight;
}
}
}
}
|
501f47e66157ba1687a7d8c81d56c84c390d37dd
|
C#
|
TereshchenkoIL/GuitarForum
|
/Application/Services/TopicService.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AutoMapper;
using Contracts;
using Contracts.Interfaces;
using Contracts.Paging;
using Contracts.Services;
using Domain.Entities;
using Domain.Exceptions.CategoryExceptions;
using Domain.Exceptions.TopicExceptions;
using Domain.Exceptions.UserException;
using Domain.Repositories;
namespace Application.Services
{
public class TopicService : ITopicService
{
private readonly IUnitOfWork _unitOfWork;
private readonly IMapper _mapper;
private readonly IUserAccessor _userAccessor;
public TopicService(IUnitOfWork unitOfWork, IMapper mapper, IUserAccessor userAccessor)
{
_unitOfWork = unitOfWork;
_mapper = mapper;
_userAccessor = userAccessor;
}
public async Task<IEnumerable<TopicDto>> GetAllByCreatorUsernameAsync(string username, CancellationToken cancellationToken = default)
{
var creator = await _unitOfWork.UserRepository.GetByUsernameAsync(username, cancellationToken);
if (creator == null) throw new UserNotFound(username);
var topics = await _unitOfWork.TopicRepository.GetAllByCreatorIdAsync(creator.Id, cancellationToken);
var topicsDto =_mapper.Map<IEnumerable<TopicDto>>(topics);
await SetIsLiked( topicsDto, topics, cancellationToken);
return topicsDto;
}
public async Task<PagedList<TopicDto>> GetAllByCategoryIdAsync(Guid categoryId, PagingParams pagingParams, CancellationToken cancellationToken = default)
{
var category = await _unitOfWork.CategoryRepository.GetByIdAsync(categoryId, cancellationToken);
if (category == null) throw new CategoryNotFoundException(categoryId);
var topics = await _unitOfWork.TopicRepository.GetAllByCategoryIdAsync(categoryId, cancellationToken);
var topicsDto = _mapper.Map<IEnumerable<TopicDto>>(topics);
await SetIsLiked( topicsDto, topics, cancellationToken);
return PagedList<TopicDto>.Create(topicsDto, pagingParams.PageNumber, pagingParams.PageSize);
}
private async Task SetIsLiked( IEnumerable<TopicDto> topicsDto, IEnumerable<Topic> topics, CancellationToken cancellationToken)
{
var currentUser = await _unitOfWork.UserRepository.GetByUsernameAsync(_userAccessor.GetUsername(), cancellationToken);
foreach (var topic in topicsDto)
{
if (currentUser != null)
{
topic.IsLiked = topics.First(x => x.Id == topic.Id).Likes.Any(l => l.AppUserId == currentUser.Id);
}
}
}
public async Task<TopicDto> GetByIdAsync(Guid topicId, CancellationToken cancellationToken = default)
{
var topic = await _unitOfWork.TopicRepository.GetByIdAsync(topicId, cancellationToken);
if (topic == null) throw new TopicNotFoundException(topicId);
var topicDto = _mapper.Map<TopicDto>(topic);
var currentUser = await _unitOfWork.UserRepository.GetByUsernameAsync(_userAccessor.GetUsername(), cancellationToken);
if(currentUser != null)
topicDto.IsLiked = topic.Likes.Any(l => l.AppUserId == currentUser.Id);
return topicDto;
}
public async Task<PagedList<TopicDto>> GetAllAsync(PagingParams pagingParams, CancellationToken cancellationToken = default)
{
var topics = await _unitOfWork.TopicRepository.GetAllAsync(cancellationToken);
var topicsDto = _mapper.Map<IEnumerable<TopicDto>>(topics);
await SetIsLiked(topicsDto, topics, cancellationToken );
return PagedList<TopicDto>.Create(topicsDto, pagingParams.PageNumber, pagingParams.PageSize);
}
public async Task CreateAsync(TopicDto topicForCreation, CancellationToken cancellationToken = default)
{
var user = await _unitOfWork.UserRepository.GetByUsernameAsync(_userAccessor.GetUsername(), cancellationToken);
if (user == null) throw new UserNotFound(_userAccessor.GetUsername());
var category = await _unitOfWork.CategoryRepository.GetByIdAsync(topicForCreation.Category.Id,cancellationToken);
if (category == null) throw new CategoryNotFoundException(topicForCreation.Category.Id);
var topic = _mapper.Map<Topic>(topicForCreation);
topic.Creator = user;
topic.CreatedAt = DateTime.UtcNow;
topic.Category = category;
_unitOfWork.TopicRepository.Create(topic);
var result = await _unitOfWork.SaveChangesAsync(cancellationToken);
if (!result) throw new TopicCreateException("Failed to create topic");
}
public async Task DeleteAsync(Guid topicId, CancellationToken cancellationToken = default)
{
var topic = await _unitOfWork.TopicRepository.GetByIdAsync(topicId, cancellationToken);
if (topic == null) throw new TopicNotFoundException(topicId);
_unitOfWork.TopicRepository.Delete(topic);
var result = await _unitOfWork.SaveChangesAsync(cancellationToken);
if (!result) throw new TopicDeleteException("Failed to delete topic");
}
public async Task UpdateAsync(TopicDto topicForUpdation, CancellationToken cancellationToken = default)
{
var topic = await _unitOfWork.TopicRepository.GetByIdAsync(topicForUpdation.Id, cancellationToken);
if (topic == null) throw new TopicNotFoundException(topicForUpdation.Id);
var category = await _unitOfWork.CategoryRepository.GetByIdAsync(topicForUpdation.Category.Id, cancellationToken);
if (category == null) throw new CategoryNotFoundException(topicForUpdation.Category.Id);
topic.Body = topicForUpdation.Body;
topic.Title = topicForUpdation.Title;
topic.Category = category;
var result = await _unitOfWork.SaveChangesAsync(cancellationToken);
if (!result) throw new TopicUpdateException("Failed to update topic");
}
}
}
|
d9dcd14f39074791deff6c4faa6844bd586521c0
|
C#
|
GeorgiMateev/telerik-academy
|
/09.Methods/4.ArrayAnalys/ArrayAnalysis.cs
| 3.671875
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _4.ArrayAnalys
{
class ArrayAnalysis
{
static int CountNumberInArray(int[] numbers, int n)
{
int counter = 0;
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] == n)
{
counter++;
}
}
return counter;
}
static void Main(string[] args)
{
int[] numbers = new int[] {2,4,6,2,5,3,7,8,7,2,3,2,15,6,3,};
bool isCorrectNumber = false;
int number = 0;
while (!isCorrectNumber)
{
Console.Write("number = ");
isCorrectNumber = int.TryParse(Console.ReadLine(), out number);
}
int count = CountNumberInArray(numbers,number);
Console.WriteLine("Count: {0}",count);
Console.ReadKey();
}
}
}
|
2a78749fac1fa8a8274d297ff6c95d95db1121ee
|
C#
|
NasC0/Telerik_Homework
|
/C# part 2/4. NumeralSystems/4. DecimalToHexadecimal/DecimalToHexadecimal.cs
| 4.09375
| 4
|
using System;
using System.Collections.Generic;
class DecimalToHexadecimal
{
static string DecToHex(int number)
{
string hex = "";
while (number > 0)
{
int remainder = number % 16;
number = number / 16;
if (remainder == 10)
{
hex = hex + "A";
}
else if (remainder == 11)
{
hex = hex + "B";
}
else if (remainder == 12)
{
hex = hex + "C";
}
else if (remainder == 13)
{
hex = hex + "D";
}
else if (remainder == 14)
{
hex = hex + "E";
}
else if (remainder == 15)
{
hex = hex + "F";
}
else
{
hex = hex + remainder.ToString();
}
}
hex = Reverse(hex);
return hex;
}
static string Reverse(string text)
{
char[] cArray = text.ToCharArray();
string reverse = String.Empty;
for (int i = cArray.Length - 1; i > -1; i--)
{
reverse += cArray[i];
}
return reverse;
}
static void Main()
{
Console.Write("Enter the number you want converted to hex: ");
int number = int.Parse(Console.ReadLine());
string hex = DecToHex(number);
Console.WriteLine("Your converted number is: {0}", hex);
}
}
|
365a52bfd684d39f724679b494ff80c8e839cef4
|
C#
|
DrNorton/GiftKnacksProject.Api
|
/GiftKnacksProject.Api.Services/Storages/UserOnlineSignalService.cs
| 2.8125
| 3
|
using System.Collections.Generic;
using System.Linq;
using GiftKnacksProject.Api.Services.Interfaces;
namespace GiftKnacksProject.Api.Services.Storages
{
public class UserOnlineSignalService : IUserOnlineSignalService
{
private object _synch;
private List<UserConnectionSignalR> _usersOnline;
public UserOnlineSignalService()
{
_synch = new object();
_usersOnline =new List<UserConnectionSignalR>();
}
public void AddUserToOnline(long userId,string connectionId)
{
lock (_synch)
{
var findedUser = _usersOnline.FirstOrDefault(x => x.UserId == userId);
if (findedUser == null)
{
var newUserOnline = new UserConnectionSignalR(userId);
newUserOnline.AddConnection(connectionId);
_usersOnline.Add(newUserOnline);
}
else
{
findedUser.AddConnection(connectionId);
}
}
}
public void RemoveUserFromOnline(long userId, string connectionId)
{
lock (_synch)
{
var findedUser = _usersOnline.FirstOrDefault(x => x.UserId == userId);
if (findedUser != null)
{
findedUser.RemoveConnection(connectionId);
if (findedUser.IsEmpty())
{
_usersOnline.Remove(findedUser);
}
}
}
}
public bool GetOnlineStatus(long userId)
{
var findedUser = _usersOnline.FirstOrDefault(x => x.UserId == userId);
return findedUser != null;
}
public UserConnectionSignalR FindUser(long userId)
{
var findedUser = _usersOnline.FirstOrDefault(x => x.UserId == userId);
return findedUser;
}
}
}
|
6e9498cba358ae5a7977d1a7dd46c5d450c6019d
|
C#
|
NorikaDE/Coded-Documents
|
/Source/Norika.Documentation.Core.UnitTests/TestPrintableDocument.cs
| 2.71875
| 3
|
using System.Collections.Generic;
using Norika.Documentation.Core.Types;
namespace Norika.Documentation.Core.UnitTests
{
/// <summary>
/// Test implementation for test purposes
/// </summary>
public sealed class TestPrintableDocument : ITestPrintableDocument
{
/// <summary>
/// <inheritdoc cref="IPrintable.Print"/>
/// </summary>
/// <returns></returns>
public string Print()
{
return null;
}
public TestPrintableDocument()
{
Author = "NotRelevant";
Chapters = new List<IPrintableDocumentChapter>();
}
public string Author { get; }
public string Title { get; set; }
public string DefaultFileExtension { get; } = "bla";
public IList<IPrintableDocumentChapter> Chapters { get; }
public IPrintableDocumentChapter AddNewChapter(string title)
{
throw new System.NotImplementedException();
}
public T CreateElement<T>() where T : class, IPrintable
{
throw new System.NotImplementedException();
}
}
public interface ITestPrintableDocument : IPrintableDocument { }
}
|
6af41bbc68aab1cdbd721c75454987c1351fe2b6
|
C#
|
BorislavBorisov22/Telerik-2016-17-CSharp
|
/C# OOP - Homeworks/OOP_Principles_Part_Two/RangeException/StartUp.cs
| 3.859375
| 4
|
namespace RangeException
{
using System;
public class StartUp
{
public static void Main()
{
// Testing the exception for integers
// to get the exception for invalid integer enter a number outside of the given range
// on the console.
// to get the exception for invalid date first enter a valid integer on the
// console or comment the first try-catch block
// testing the invalid range excception for ints
try
{
Console.WriteLine("Enter a number in the range 1 - 100");
int number = int.Parse(Console.ReadLine());
if (number < 0 || number > 100)
{
throw new InvalidRangeException<int>("Number is outside the required range", 1, 100);
}
}
catch (InvalidRangeException<int> ex)
{
Console.WriteLine(ex.Message);
}
// testing the invalid range exception for dates
try
{
var testDate = new DateTime(2020, 12, 12);
DateTime minDate = new DateTime(1970, 1, 1);
DateTime maxDate = new DateTime(2013, 12, 31);
if (testDate < minDate || testDate > maxDate)
{
throw new InvalidRangeException<DateTime>("Date was outside of the specified range", minDate, maxDate);
}
}
catch (InvalidRangeException<DateTime> ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
|
1b4da9edf9408e2c676caa3c0b65e54c669633ce
|
C#
|
Taritsyn/WebMarkupMin
|
/test/WebMarkupMin.Benchmarks/StatisticsGenerationBenchmark.cs
| 2.5625
| 3
|
using System.IO;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Diagnosers;
using WebMarkupMin.Core;
namespace WebMarkupMin.Benchmarks
{
[MemoryDiagnoser]
public class StatisticsGenerationBenchmark
{
private static readonly HtmlMinifier s_minifier = new HtmlMinifier();
private static readonly string s_content = null;
static StatisticsGenerationBenchmark()
{
string absoluteDirectoryPath = Utils.GetAbsoluteDirectoryPath("../../../Files/html");
string absoluteFilePath = Path.Combine(absoluteDirectoryPath, "josh-ducks-periodic-table.html");
s_content = File.ReadAllText(absoluteFilePath);
}
[Benchmark(Baseline = true)]
public void StatisticsDisabled()
{
Process(false);
}
[Benchmark]
public void StatisticsEnabled()
{
Process(true);
}
private static void Process(bool generateStatistics)
{
string minifiedContent = s_minifier.Minify(s_content, generateStatistics).MinifiedContent;
}
}
}
|
60884e21647ddddb4440112c4d653b50a9275fa4
|
C#
|
felypeb/refaction
|
/RefactorMe.Model/Services/ProductService.cs
| 2.96875
| 3
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using RefactorMe.Model.Entities;
using RefactorMe.Model.Interfaces.Repository;
using RefactorMe.Model.Interfaces.Service;
namespace RefactorMe.Model.Services
{
public class ProductService : IProductService
{
private readonly IProductRepository _productRepository;
public ProductService(IProductRepository productRepository)
{
this._productRepository = productRepository;
}
public async Task<IEnumerable<Product>> ListAsync()
{
return await this._productRepository.GetAllAsync();
}
public async Task<IEnumerable<Product>> ListByNameAsync(string name)
{
return await this._productRepository.ListAsync(p => p.Name.Contains(name));
}
public async Task<Product> GetByIdAsync(Guid id)
{
return await this._productRepository.FirstOrDefaultAsync(p=>p.Id == id);
}
public async Task<Product> CreateAsync(Product product)
{
if (product.Id == Guid.Empty)
product.Id = Guid.NewGuid();
return await this._productRepository.CreateAsync(product);
}
public async Task RemoveAsync(Product product)
{
await this._productRepository.RemoveAsync(product);
}
public async Task UpdateAsync(Product product)
{
await this._productRepository.UpdateAsync(product);
}
}
}
|
59731e069c04baa227d244825832112421ff3207
|
C#
|
mucanson/TienlenCsharp
|
/Client/TCPModel.cs
| 2.953125
| 3
|
/*
* Created by SharpDevelop.
* User: chepchip
* Date: 11/11/2016
* Time: 12:35 PM
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
namespace Client
{
/// <summary>
/// Description of TCPModel.
/// </summary>
public class TCPModel
{
private TcpClient tcpclnt;
private Stream stm;
private byte[] byteSend;
private byte[] byteReceive;
private string IPofServer;
private int port;
public TCPModel(string ip, int p)
{
IPofServer = ip;
port = p;
tcpclnt = new TcpClient();
byteReceive = new byte[100];
}
//show information of client to update UI
public string UpdateInformation()
{
string str = "";
try
{
Socket s = tcpclnt.Client;
str = str + s.LocalEndPoint;
Console.WriteLine(str);
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
return str;
}
//Set up a connection to server and get stream for communication
public int ConnectToServer()
{
try
{
tcpclnt.Connect(IPofServer, port);
stm = tcpclnt.GetStream();
Console.WriteLine("OK!");
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
return -1;
}
return 1;
}
//Send data to server after connection is set up
public void SendData(string str)
{
try
{
ASCIIEncoding asen = new ASCIIEncoding();
byteSend = asen.GetBytes(str);
stm.Write(byteSend, 0, byteSend.Length);
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
//Read data from server after connection is set up
public string ReadData()
{
string str = "";
try
{
//count the length of data received
int k = stm.Read(byteReceive, 0, 100);
Console.WriteLine("Length of data received: " + k.ToString());
Console.WriteLine("From server: ");
//conver the byte recevied into string
char[] c = new char[k];
for (int i = 0; i < k; i++)
{
Console.Write(Convert.ToChar(byteReceive[i]));
c[i] = Convert.ToChar(byteReceive[i]);
}
str = new string(c);
}
catch (Exception e)
{
CloseConnection();
//str = "Error..... " + e.StackTrace;
//Console.WriteLine(str);
}
return str;
}
//close connection
public void CloseConnection()
{
tcpclnt.Close();
}
public TcpClient GetIP()
{
return tcpclnt ;
}
}
}
|
1f842f450e78019682e0f8ba90e8f16317d5a45f
|
C#
|
NERDLabStudio/Zoo-Rush-Roundup
|
/Assets/MPUIKit/Runtime/Scripts/Shapes/NStarPolygon.cs
| 2.515625
| 3
|
using System;
using UnityEngine;
namespace MPUIKIT {
/// <summary>
/// N-star polygon shape is equal sided uniform polygon shape with the ability to morph
/// to a star corresponding to the original shape. ie: an equilateral pentagon will morph
/// to a five sided star.
/// </summary>
[Serializable]
public struct NStarPolygon: IMPUIComponent {
[SerializeField] private float m_SideCount;
[SerializeField] private float m_Inset;
[SerializeField] private float m_CornerRadius;
[SerializeField] private Vector2 m_Offset;
/// <summary>
/// How many sides should there be in the shape. These sides are equal is size.
/// 3 sides create an equilateral triangle, 6 sides create a hexagon and so on
/// <para>Value of SideCount should remain between 3 and 10.</para>
/// </summary>
public float SideCount {
get => m_SideCount;
set {
m_SideCount = Mathf.Clamp(value, 3f, 10f);
if (ShouldModifySharedMat) {
SharedMat.SetFloat(SpNStarPolygonSideCount, m_SideCount);
}
OnComponentSettingsChanged?.Invoke(this, EventArgs.Empty);
Inset = m_Inset;
}
}
/// <summary>
/// Inset is the value that determine how much should the sides go inside the shape
/// and create a concave star shape. Each sides will break into half and their middle
/// point will go towards the center of the shape
/// <para>Value of inset should remain between 2 and (SideCount - 0.01). 2 is default
/// and means no breaking of the sides. </para>
/// </summary>
public float Inset {
get => m_Inset;
set {
m_Inset = Mathf.Clamp(value, 2f, SideCount - 0.01f);
if (ShouldModifySharedMat) {
SharedMat.SetFloat(SpNStarPolygonInset, m_Inset);
}
OnComponentSettingsChanged?.Invoke(this, EventArgs.Empty);
}
}
/// <summary>
/// Corner Radius of all the corners of the shape.
/// </summary>
public float CornerRadius {
get => m_CornerRadius;
set {
m_CornerRadius = Mathf.Max(value, 0);
if (ShouldModifySharedMat) {
SharedMat.SetFloat(SpNStarPolygonCornerRadius, m_CornerRadius);
}
OnComponentSettingsChanged?.Invoke(this, EventArgs.Empty);
}
}
/// <summary>
/// Position offset of the shape from the origin.
/// </summary>
public Vector2 Offset {
get => m_Offset;
set {
m_Offset = value;
if (ShouldModifySharedMat) {
SharedMat.SetVector(SpNStarPolygonOffset, m_Offset);
}
OnComponentSettingsChanged?.Invoke(this, EventArgs.Empty);
}
}
private static readonly int SpNStarPolygonSideCount = Shader.PropertyToID("_NStarPolygonSideCount");
private static readonly int SpNStarPolygonInset = Shader.PropertyToID("_NStarPolygonInset");
private static readonly int SpNStarPolygonCornerRadius = Shader.PropertyToID("_NStarPolygonCornerRadius");
private static readonly int SpNStarPolygonOffset = Shader.PropertyToID("_NStarPolygonOffset");
public Material SharedMat { get; set; }
public bool ShouldModifySharedMat { get; set; }
public RectTransform RectTransform { get; set; }
public void Init(Material sharedMat, Material renderMat, RectTransform rectTransform) {
SharedMat = sharedMat;
ShouldModifySharedMat = sharedMat == renderMat;
RectTransform = rectTransform;
OnValidate();
}
public event EventHandler OnComponentSettingsChanged;
public void OnValidate() {
SideCount = m_SideCount;
Inset = m_Inset;
CornerRadius = m_CornerRadius;
Offset = m_Offset;
}
public void InitValuesFromMaterial(ref Material material) {
m_SideCount = material.GetFloat(SpNStarPolygonSideCount);
m_Inset = material.GetFloat(SpNStarPolygonInset);
m_CornerRadius = material.GetFloat(SpNStarPolygonCornerRadius);
m_Offset = material.GetVector(SpNStarPolygonOffset);
}
public void ModifyMaterial(ref Material material, params object[] otherProperties) {
material.SetFloat(SpNStarPolygonSideCount, m_SideCount);
material.SetFloat(SpNStarPolygonInset, m_Inset);
material.SetFloat(SpNStarPolygonCornerRadius, m_CornerRadius);
material.SetVector(SpNStarPolygonOffset, m_Offset);
}
}
}
|
c6d249bebc646f95a1f9eb2d3921274f86b4de28
|
C#
|
sebasDeveloper94/API_MobilFit
|
/backMobilFitData_V1/Aplicacion/UsuariosAplicacionServicios.cs
| 2.875
| 3
|
using backDataMobilFit.Models;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace backMobilFitData.Aplicacion
{
class UsuariosAplicacionServicios
{
private string connection { get; set; }
//contructor
public UsuariosAplicacionServicios(string connection)
{
this.connection = connection;
}
//metodos
public List<Usuario> GetUsuarios()
{
SqlConnection sqlConnection = new SqlConnection(this.connection);
SqlCommand sqlCommand;
SqlDataReader reader;
List<Usuario> listUsuarios = new List<Usuario>();
string sql = string.Empty;
sql = "SELECT * FROM Usuario";
try
{
sqlCommand = new SqlCommand();
sqlConnection.Open();
reader = sqlCommand.ExecuteReader();
while (reader.Read())
{
listUsuarios.Add(new Usuario()
{
id_usuario = int.Parse(reader["id_usuario"].ToString()),
nombre = reader["nombre"].ToString(),
apellido_paterno = reader["apellido_paterno"].ToString(),
apellido_materno = reader["apellido_materno"].ToString(),
email = reader["email"].ToString(),
contraseña = reader["contrasenha"].ToString(),
nombre_usuario = reader["nombre_usuario"].ToString(),
fechaRegistro = DateTime.Parse(reader["fecha_registro"].ToString()),
peso = decimal.Parse(reader["peso"].ToString()),
altura = decimal.Parse(reader["altura"].ToString()),
id_tipoCuerpo = int.Parse(reader["id_tipocuerpo"].ToString()),
id_nivel = int.Parse(reader["id_nivel"].ToString())
});
}
sqlConnection.Close();
}
catch (Exception ex)
{
return null;
}
return listUsuarios;
}
public Usuario GetUsuario(int id_usuario)
{
SqlConnection sqlConnection = new SqlConnection(this.connection);
SqlCommand sqlCommand;
SqlDataReader reader;
Usuario objUsuarios = new Usuario();
string sql = string.Empty;
sql = "SELECT * FROM Usuario WHERE id_usuario =" + id_usuario;
try
{
sqlCommand = new SqlCommand();
sqlConnection.Open();
reader = sqlCommand.ExecuteReader();
while (reader.Read())
{
objUsuarios.id_usuario = int.Parse(reader["id_usuario"].ToString());
objUsuarios.nombre = reader["nombre"].ToString();
objUsuarios.apellido_paterno = reader["apellido_paterno"].ToString();
objUsuarios.apellido_materno = reader["apellido_materno"].ToString();
objUsuarios.email = reader["email"].ToString();
objUsuarios.contraseña = reader["contrasenha"].ToString();
objUsuarios.nombre_usuario = reader["nombre_usuario"].ToString();
objUsuarios.fechaRegistro = DateTime.Parse(reader["fecha_registro"].ToString());
objUsuarios.peso = decimal.Parse(reader["peso"].ToString());
objUsuarios.altura = decimal.Parse(reader["altura"].ToString());
objUsuarios.id_tipoCuerpo = int.Parse(reader["contraindicacion"].ToString());
objUsuarios.id_contraindicacion = int.Parse(reader["objetivo"].ToString());
objUsuarios.id_nivel = int.Parse(reader["id_nivel"].ToString());
}
sqlConnection.Close();
}
catch (Exception ex)
{
throw new Exception("El error fue ", ex);
}
return objUsuarios;
}
}
}
|
c90152190eb0b2e76a9c8f5caa80f0ab4acd362e
|
C#
|
FredrikLundvall/WireframeGame
|
/Lobby/LoginForm.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace BlowtorchesAndGunpowder
{
public partial class LoginForm : Form
{
public LoginForm(string aUsername = "", bool aAutomaticLogin = false)
{
InitializeComponent();
usernameTxt.Text = aUsername;
automaticLoginChb.Checked = aAutomaticLogin;
}
private void LoginForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
DialogResult = DialogResult.Cancel;
}
public LoginInfo getLoginInfo()
{
return new LoginInfo(usernameTxt.Text, SecurePasswordHasher.RepeatableHashForTransfer(passwordTxt.Text, usernameTxt.Text), automaticLoginChb.Checked);
}
}
}
|
5a57a606cebd01f70c53bf7cf8b1f616d0d1e123
|
C#
|
ahmed-ismaail/Book-Management-System
|
/File-Project-master/Project File/WindowsFormsApplication14/Form1.cs
| 2.96875
| 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 WindowsFormsApplication14
{
public partial class MainForm : Form
{
string year, name, serial, authnum, yearsearch, email; //Strings to be used all over the program :)
public MainForm()
{
InitializeComponent();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
private void Main_Paint(object sender, PaintEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e) //Displaying Button in the Main Panel
{
if (BookCheckBox.Checked == true) //To change panels between Main Panel and Displaying Books Panel
{
Display.Visible = true;
Main.Visible = false;
}
else //To change panels between Main Panel and Dsiplaying Authors Panel
{
Main.Visible = false;
DisplayingAuthors.Visible = true;
}
}
private void button2_Click(object sender, EventArgs e) //Searching Button in the Main Panel
{
if (BookCheckBox.Checked == true) //To Change panels between Main Panel and Searching Books Panel
{
Main.Visible = false;
SearchingPanel.Visible = true;
}
else //To Change panels between Main Panel and Searching Authors Panel
{
Main.Visible = false;
NameSearching.Visible = true;
}
}
private void Addddd_Click(object sender, EventArgs e) //Adding Button in the Main Panel
{
if (BookCheckBox.Checked == true) //To Change panels between Main Panel and Adding Books Panel
{
addnewbook.Visible = true;
Main.Visible = false;
}
else //To Change panels between Main Panel and Adding Authors Panel
{
Main.Visible = false;
AddingAuthorPanel.Visible = true;
}
}
private void label5_Click(object sender, EventArgs e)
{
}
private void add_Paint(object sender, PaintEventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e) //Serial Number of book TextBox
{
if (SerialTextBox.Text == "") return;
int tmp = SerialTextBox.SelectionStart; //to access the position of the of text entering
bool Checked = false;
for (int i = 0; i < SerialTextBox.TextLength; i++) //for checking whether the new text entered is Digit or not
{
if (!char.IsDigit(SerialTextBox.Text[i])) //ISDigit is a function to check if it's digit or not number
{
SerialTextBox.Text = SerialTextBox.Text.Remove(i, 1); //to remove the new text entered when it's not digit
Checked = true;
i--;
}
}
if (Checked) tmp--; //to remove the text entered if the text is not Digit(number)
SerialTextBox.SelectionStart = tmp; //to modify the position if the user made a wrong entry
serial = SerialTextBox.Text; //to copy the string in the textbox to the serial string
CheckTextBoxes(); //to call checktextboxes Function
}
private void textBox4_TextChanged(object sender, EventArgs e)
{
AuthorNumTextBox.MaxLength = 5; //to limit the lenght of the textbox
if (AuthorNumTextBox.Text == "") return;
int tmp = AuthorNumTextBox.SelectionStart; //to access the position of the of text entering
bool Checked = false;
for (int i = 0; i < AuthorNumTextBox.TextLength; i++) //for checking whether the new text entered is Digit or not
{
if (!char.IsDigit(AuthorNumTextBox.Text[i])) //ISDigit is a function to check if it's digit or not
{
AuthorNumTextBox.Text = AuthorNumTextBox.Text.Remove(i, 1); //to remove the new text entered when it's not digit(number)
Checked = true;
i--;
}
}
if (Checked) tmp--; //to remove the text entered if the text is not Digit(number)
AuthorNumTextBox.SelectionStart = tmp; //to modify the position if the user made a wrong entry
authnum = AuthorNumTextBox.Text; //to copy the string in the textbox to the authnum string
CheckTextBoxes(); //to call checktextboxes Function
}
private void checkBox1_CheckedChanged(object sender, EventArgs e) //book checkbox
{
if (BookCheckBox.Checked == true) //condition to enable the buttons of the main panel when BookCheckBox was chosen
{
AuthorCheckBox.Checked = false;
AddingButton.Enabled = true;
DisplayingButton.Enabled = true;
SearchingButton.Enabled = true;
}
if (BookCheckBox.Checked == false) //condition to disable the buttons of the main panel when BookCheckBox was not chosen
{
AddingButton.Enabled = false;
DisplayingButton.Enabled = false;
SearchingButton.Enabled = false;
}
}
private void CancelButton_Click(object sender, EventArgs e) //cancel button of the addingnewbook panel
{
addnewbook.Visible = false; //to access the main panel again and hide the addingnewbook panel
Main.Visible = true;
}
private void AuthorCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (AuthorCheckBox.Checked == true) //condition to enable the buttons of the main panel if the AuthorCheckBox was chosen
{
BookCheckBox.Checked = false;
AddingButton.Enabled = true;
DisplayingButton.Enabled = true;
SearchingButton.Enabled = true;
}
if (AuthorCheckBox.Checked == false) //condition to disable the buttons of the main panel if the AuthorCheckBox was not chosen
{
AddingButton.Enabled = false;
DisplayingButton.Enabled = false;
SearchingButton.Enabled = false;
}
}
private void DisplayHeading_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged_1(object sender, EventArgs e)
{
}
private void button2_Click_1(object sender, EventArgs e) //Displaying Button for Books
{
Book[] BookArray; //Array of struct of book
BookArray = BooksFunctions.read(); //calling read() function
if (BookArray == null)
{
MessageBox.Show("There are no Books to Display"); //If the Books File was empty
}
else
{
string[] Lines = new string[(BookArray.Length * 5) - 1]; //Array of strings to Put each field in a line with a seperator between each record
int index = 0;
for (int i = 0; i < BookArray.Length; i++) //Loop to put each field in the string array inorder to display them
{
Lines[index++] = "Serial Number: " + BookArray[i].serialNo;
Lines[index++] = "Book Name: " + BookArray[i].bookName;
Lines[index++] = "Publish Year: " + BookArray[i].publishYear;
Lines[index++] = "Author Number: " + BookArray[i].authorNo;
if (i != BookArray.Length - 1)
Lines[index++] = "----------------------------------------"; //to handle the last record inorder not to display seperator line after the last record
}
textBox1.Lines = Lines; //function textBox1.Lines is to put each single element in the array in a single line
}
}
private void ListBox_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button1_Click_1(object sender, EventArgs e) //Cancel button of the Displaying Book Panel inorder to enable the main panel again
{
Display.Visible = false;
Main.Visible = true;
textBox1.Text = "";
}
private void BTN_Searching_Click(object sender, EventArgs e) //Searching for Publish Year Button
{
Book[] books;
books = BooksFunctions.Search(yearsearch, 1); //to call searching function of the book by the Publish Year
if (books == null)
{
MessageBox.Show("This Book is not found");
TXT_Searching.Text = "";
}
else
{
string[] Lines = new string[(books.Length * 5) - 1]; //Array of strings to Put each field in a line with a seperator between each record
int index = 0;
for (int i = 0; i < books.Length; i++) //Loop to put each field in the string array inorder to display them
{
Lines[index++] = "Serial Number: " + books[i].serialNo;
Lines[index++] = "Book Name: " + books[i].bookName;
Lines[index++] = "Publish Year: " + books[i].publishYear;
Lines[index++] = "Author Number: " + books[i].authorNo;
if (i != books.Length - 1) //to handle the last record inorder not to display seperator line after the last record
Lines[index++] = "----------------------------------------";
}
TXT_Searching.Lines = Lines; //function Searching.Lines is to put each single element in the array in a single line
SearchingTextBox.Focus(); //To Handle a problem occurred when Displaying The Books inorder to change the mouse focus after displaying
}
}
private void BTN_Cancel_Click(object sender, EventArgs e) //Cancel Button in the Book searching Panel
{
SearchingPanel.Visible = false;
Main.Visible = true;
TXT_Searching.Text = "";
SearchingTextBox.Text = "";
}
private void textBox2_TextChanged_1(object sender, EventArgs e) //Book Searching Textbox
{
SearchingTextBox.MaxLength = 4; //To adjust the max length of the textbox
BTN_Searching.Enabled = true; //To Enable the Button after Changing the text in the textbox
if (SearchingTextBox.Text == "")
{
BTN_Searching.Enabled = false;
}
yearsearch = SearchingTextBox.Text;
}
private void TXT_Searching_TextChanged(object sender, EventArgs e)
{
}
private void label_Click(object sender, EventArgs e)
{
}
private void label6_Click(object sender, EventArgs e)
{
}
private void button1_Click_2(object sender, EventArgs e) //Searching Button in the Author Name Search Panel
{
Book[] books;
string num = AuthorFunctions.Searching_Author(name);
books = BooksFunctions.Search(num, 2); //To call the Searching Function()
if (books == null)
{
MessageBox.Show("Author name has no books available");
aftersearch.Text = "";
}
else
{
string[] Lines = new string[(books.Length * 5) - 1]; //Array of strings to Put each field in a line with a seperator between each record
int index = 0;
for (int i = 0; i < books.Length; i++) //Loop to put each field in the string array inorder to display them
{
Lines[index++] = "Serial Number: " + books[i].serialNo;
Lines[index++] = "Book Name: " + books[i].bookName;
Lines[index++] = "Publish Year: " + books[i].publishYear;
Lines[index++] = "Author Number: " + books[i].authorNo;
if (i != books.Length - 1)
Lines[index++] = "----------------------------------------"; //to handle the last record inorder not to display seperator line after the last record
}
aftersearch.Lines = Lines; //function aftersearch.Lines is to put each single element in the array in a single line
}
}
private void NameTextBox_TextChanged(object sender, EventArgs e)
{
NameTextBox.MaxLength = 20; //to Adjust the the Max Length of the Name TextBox
name = NameTextBox.Text;
CheckAuthorTextBoxes(); //To call the function for checking textboxes
}
private void EmailTextBox_TextChanged(object sender, EventArgs e)
{
EmailTextBox.MaxLength = 25; //to Adjust the Max Length of the Email TextBox
email = EmailTextBox.Text;
CheckAuthorTextBoxes(); //to call the function for checking textboxes
}
private void AddingnewAuthor_Click(object sender, EventArgs e) //Button of Add in the new Author adding Panel
{
Author s;
s.id = authnum;
s.authorName = name;
s.email = email;
if (AuthorFunctions.Author_Checker(s)) //To call the Checker Function {Go to definition for more details :) }
{
MessageBox.Show("There was a conflict in Author ID and was unsuccssfully added Please try again");
}
else
{
AuthorFunctions.Write_Author(s);
MessageBox.Show("Author was successfully added");
}
IDTextBox.Text = "";
NameTextBox.Text = "";
EmailTextBox.Text = "";
}
private void button3_Click(object sender, EventArgs e) //Cancel Button in the Adding Author Panel
{
Main.Visible = true;
AddingAuthorPanel.Visible = false;
}
private void cancel_btn_Click(object sender, EventArgs e) //Cancel Button in the Author Name Searching Panel
{
Main.Visible = true;
NameSearching.Visible = false;
NameSearchingtextbox.Text = "";
aftersearch.Text = "";
}
private void textBox3_TextChanged_1(object sender, EventArgs e) //Author ID textbox in the Adding Panel
{
if (IDTextBox.Text == "") return;
IDTextBox.MaxLength = 5; //To adjust the Max Length of the textbox
int tmp = IDTextBox.SelectionStart; //to access the position of the of text entering
bool check = false;
for (int i = 0; i < IDTextBox.TextLength; i++) //Loop for checking whether the new text entered is Digit or not
{
if (!char.IsDigit(IDTextBox.Text[i])) //IsDigit is a function to Check the Char entered if it is a Digit (number) or not
{
IDTextBox.Text = IDTextBox.Text.Remove(i, 1); //To Remove the char if the char was not Digit (number)
check = true;
i--;
}
}
if (check) tmp--;
IDTextBox.SelectionStart = tmp; //To set the position of the text entry inorder to write new char smoothly
authnum = IDTextBox.Text;
CheckAuthorTextBoxes(); //To call Check Author Text Boxes function {for more details Go to definition :) }
}
private void NameSearchingtextbox_TextChanged(object sender, EventArgs e) //Name Searching Text Box in Author Name Searching Panel
{
name = NameSearchingtextbox.Text;
namesearchingbutton.Enabled = true; //To enable the button after entering the string you wish to search for
}
private void aftersearch_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click_3(object sender, EventArgs e) //Cancel Button in the Displaying Author Panel
{
Main.Visible = true;
DisplayingAuthors.Visible = false;
AuthorsTextBos.Text = "";
}
private void Displaying_BTN_Click(object sender, EventArgs e) //Button to Display all Authors in the Displaying Author Panel
{
Author[] Authors;
Authors = AuthorFunctions.Author_read(); //Calling the read function { For more details go to definition :) }
if (Authors == null)
{
MessageBox.Show("There are no Authors to display");
}
else
{
string[] Lines = new string[(Authors.Length * 4) - 1]; //String Array to put each field in the the array + seperator between each record and -1 inorder not to put seperator in the last Line after the last record
int index = 0;
for (int i = 0; i < Authors.Length; i++)
{
Lines[index++] = "Author ID: " + Authors[i].id.ToString();
Lines[index++] = "Author Name: " + Authors[i].authorName.ToString();
Lines[index++] = "Email: " + Authors[i].email.ToString();
if (i != Authors.Length - 1)
Lines[index++] = "----------------------------------------"; //To put seperator after each record except the last one
}
AuthorsTextBos.Lines = Lines;
}
}
private void AuthorsTextBos_TextChanged(object sender, EventArgs e)
{
}
private void ClosingButton_Click(object sender, EventArgs e)
{
Close();
}
private void button4_Click(object sender, EventArgs e)
{
Close();
}
private void label11_Click(object sender, EventArgs e)
{
}
private void button5_Click(object sender, EventArgs e)
{
Close();
}
private void button6_Click(object sender, EventArgs e)
{
Close();
}
private void button7_Click(object sender, EventArgs e)
{
Close();
}
private void label8_Click(object sender, EventArgs e)
{
}
private void label10_Click(object sender, EventArgs e)
{
}
private void button9_Click(object sender, EventArgs e)
{
Close();
}
private void label7_Click(object sender, EventArgs e)
{
}
private void label4_Click(object sender, EventArgs e)
{
}
private void button10_Click(object sender, EventArgs e)
{
Close();
}
private void CheckAuthorTextBoxes()
{
if ((IDTextBox.Text != "") && (NameTextBox.Text != "") && (EmailTextBox.Text != ""))
{
AddingnewAuthor.Enabled = true; //If all textboxes are written the Adding button will be enabled
}
else
{
AddingnewAuthor.Enabled = false;
}
}
private void CheckTextBoxes()
{
if ((SerialTextBox.Text != "") && (BookNameTextBox.Text != "") && (PublishYearTextBox.Text != "") && (AuthorNumTextBox.Text != ""))
{
btn.Enabled = true; //If all textboxes are written the Adding button will be enabled
}
else
{
btn.Enabled = false;
}
}
private void textBox3_TextChanged(object sender, EventArgs e) //Publish Year Textbox
{
PublishYearTextBox.MaxLength = 4; //To adjust the Max Length of the Publish Year TextBox
if (PublishYearTextBox.Text == "") return;
int tmp = PublishYearTextBox.SelectionStart; //to access the position of the of text entering
bool Checked = false;
for (int i = 0; i < PublishYearTextBox.TextLength; i++) //for checking whether the new text entered is Digit or not
{
if (!char.IsDigit(PublishYearTextBox.Text[i])) //ISDigit is a function to check if it's digit or not
{
PublishYearTextBox.Text = PublishYearTextBox.Text.Remove(i, 1); //to remove the new text entered when it's not digit(number)
Checked = true;
i--;
}
}
if (Checked) tmp--;
PublishYearTextBox.SelectionStart = tmp; //To set the new position of the text after removing
year = PublishYearTextBox.Text;
CheckTextBoxes(); //to check the Text Boxes for more detials { go to definition :) }
}
private void textBox2_TextChanged(object sender, EventArgs e) //Book name textbox
{
name = BookNameTextBox.Text;
CheckTextBoxes();
}
private void btn_Click(object sender, EventArgs e) //Button of Adding new Book in the File
{
Book h;
h.serialNo = serial;
h.bookName = name;
h.publishYear = year;
h.authorNo = authnum;
if (BooksFunctions.Book_Checker(h)) //To Check if there was a conflict in the Serial Number
{
MessageBox.Show("There was a conflict in the Book serial number and was unsuccessfully added Please try again");
}
else
{
BooksFunctions.write(h);
MessageBox.Show("Book successfully added");
}
AuthorNumTextBox.Text = "";
SerialTextBox.Text = "";
PublishYearTextBox.Text = "";
BookNameTextBox.Text = "";
btn.Enabled = false; //To disable the Button of Add after adding the new book
}
}
}
|
bd304fd63cf14a9fbc10bc2ab62bff1d75386fe7
|
C#
|
YashBhartia00/Dots-and-Boxes
|
/dots And Boxes/Assets/Jsons.cs
| 2.765625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
[Serializable]
public class Matches
{
public string gameType, userName;
public bool found;
public board gameBoard;
public int timeCreated;
public Matches(string gameTypes, string userNames, board gameBoards, int timeCreateds, bool founds = false)
{
this.gameType = gameTypes;
this.userName = userNames;
this.found = founds;
this.timeCreated = timeCreateds;
}
}
public class board
{
public int[] positions = new int[10]; //10th for which player played last;
public board(int[] argpos)
{
this.positions = argpos;
}
}
public class boardDots
{
public int[,,] gridLine; // H/V , X, Y: value = Player
public int[] compactGridLines;
public int numberPlayer, moves;
public boardDots(int[,,] gridLines, int numberPlayers, int movess)
{
this.compactGridLines = new int[gridLines.GetLength(0) * gridLines.GetLength(1) * gridLines.GetLength(2)];
this.gridLine = gridLines;
this.numberPlayer = numberPlayers;
this.moves = movess;
}
public void randomize()
{
for(int i = 0; i < gridLine.GetLength(0); i++)
{
for (int j = 0; j < gridLine.GetLength(1); j++)
{
for (int k = 0; k < gridLine.GetLength(2); k++)
{
gridLine[i, j, k] = UnityEngine.Random.Range(1, numberPlayer +1);
}
}
}
}
public void updateCompact()
{
for (int i = 0; i < gridLine.GetLength(0); i++)
{
for (int j = 0; j < gridLine.GetLength(1); j++)
{
for (int k = 0; k < gridLine.GetLength(2); k++)
{
compactGridLines[i * (gridLine.GetLength(1)) * gridLine.GetLength(2) + j * gridLine.GetLength(2) + k] = gridLine[i, j, k];
}
}
}
}
public int[,,] updategrids()
{
int x,y,z;
for(int i = 0; i < compactGridLines.Length; i++)
{
x = i / (gridLine.GetLength(1) * gridLine.GetLength(2));
y = (i % (gridLine.GetLength(1) * gridLine.GetLength(2)))/gridLine.GetLength(2);
z = (i % (gridLine.GetLength(1) * gridLine.GetLength(2))) % gridLine.GetLength(2);
gridLine[x,y,z] = compactGridLines[i];
}
return gridLine;
}
}
|
b8de696b6bf52c2fff183d804b3e4d394a28049c
|
C#
|
slick-code/Tolkesentralen_v3
|
/Tolkesentralen-v3/Tolkesentralen-v3/Repository/DbSpraak.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using Tolkesentralen_v3.Models;
namespace Tolkesentralen_v3.Repository
{
public class DbSpraak
{
DbNetcont db = new DbNetcont();
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Registers the spraak described by nyttSpraak. </summary>
///
/// <remarks> Mojola, 19/05/2017. </remarks>
///
/// <param name="nyttSpraak"> The nytt spraak. </param>
///
/// <returns> True if it succeeds, false if it fails. </returns>
////////////////////////////////////////////////////////////////////////////////////////////////////
public bool RegSpraak(Spraak nyttSpraak)
{
try
{
Spraak spraak = db.Spraak.Find(nyttSpraak.navn);
if (spraak == null)
{
db.Spraak.Add(nyttSpraak);
db.SaveChanges();
}
else
{
var nySpraak = new Spraak()
{
navn = nyttSpraak.navn,
};
return true;
}
return false;
}
catch (Exception feil)
{
Debug.WriteLine("Exception Message: " + feil.Message);
return false;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Registers the tolk oppdrag. </summary>
///
/// <remarks> Mojola, 19/05/2017. </remarks>
///
/// <param name="sp"> The sp. </param>
/// <param name="tolkId"> Identifier for the tolk. </param>
///
/// <returns> True if it succeeds, false if it fails. </returns>
////////////////////////////////////////////////////////////////////////////////////////////////////
public bool regTolkOppdrag(Spraak sp, int tolkId)
{
try
{
Tolk tolk = db.Personer.OfType<Tolk>().FirstOrDefault(k => k.persId == tolkId);
if (tolk != null)
{
if (sp != null)
{
tolk.spraak.Add(sp);
}
else
{
return false;
}
db.SaveChanges();
return true;
}
return false;
}
catch (Exception feil)
{
Debug.WriteLine("Exception Message: " + feil.Message);
return false;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> List spraak. </summary>
///
/// <remarks> Mojola, 19/05/2017. </remarks>
///
/// <returns> A List<Spraak> </returns>
////////////////////////////////////////////////////////////////////////////////////////////////////
public List<Spraak> ListSpraak()
{
try
{
return db.Spraak.ToList();
}
catch (Exception feil)
{
Debug.WriteLine("Exception Message: " + feil.Message);
return null;
}
}
}
}
|
f8c75737b2b5dbbc98d43415b401e7015ccbac86
|
C#
|
gilvancm/aula250
|
/SalesWebMvc247/Models/ViewModels/ErrorViewModel.cs
| 2.796875
| 3
|
using System;
namespace SalesWebMvc247.Models.ViewModels
{
public class ErrorViewModel
{
//id interno da requisio ------RequestId
public string RequestId { get; set; }
//acresentar uma messagem custumizada neste objeto
public string Message { get; set; }
/// <summary>
// retorna pra funo com um massete pra ver se existe id interno se no nulo ou vazio----- !string.IsNullOrEmpty(RequestId);
/// </summary>
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
|
ca4484da36ba4df75c20e8191c12d206214d6a0c
|
C#
|
danielpetkovski/HomeworksCsharp
|
/SEDC.Homework03Bonus/SEDC.Task12/Program.cs
| 4.03125
| 4
|
using System;
namespace SEDC.Task12
{
class Program
{
/* Task 12:
Write a short program that prints each number from 1 to 100 on a new line.For each number that is divided by 3 print “Fizz” instead of the number.
For each number that is divided by 5 print “Buzz” instead of the number.
For each number that is divided by 3 and 5 print “FizzBuzz” instead of the number.*/
static void Main(string[] args)
{
for (int i = 1; i <= 100; i++)
{
if((i % 3 == 0) && (i % 5 == 0))
{
Console.WriteLine("FizzBuzz");
continue;
}
if(i % 3 == 0)
{
Console.WriteLine("Fizz");
continue;
}
if (i % 5 == 0)
{
Console.WriteLine("Buzz");
continue;
}
else
{
Console.WriteLine(i);
}
}
Console.ReadLine();
}
}
}
|
fc2276060643f6b9233cddf46373e17a3b0038b4
|
C#
|
jgyo/PluginManager
|
/VersionManagement/VersionCheck.cs
| 2.59375
| 3
|
namespace VersionManagement
{
using PluginManager.Core.ViewModels;
using System;
using System.Diagnostics;
using System.Linq;
/// <summary>
/// Defines the <see cref="VersionCheck" />.
/// </summary>
public class VersionCheck : ViewModel
{
/// <summary>
/// Initializes a new instance of the <see cref="VersionCheck"/> class.
/// </summary>
/// <param name="currentVersion">The currentVersion<see cref="string"/>.</param>
/// <param name="packageUrl">The packageUrl<see cref="string"/>.</param>
public VersionCheck(string currentVersion, string packageUrl)
{
if (string.IsNullOrEmpty(currentVersion))
{
throw new ArgumentException($"'{nameof(currentVersion)}' cannot be null or empty.", nameof(currentVersion));
}
if (string.IsNullOrEmpty(packageUrl))
{
throw new ArgumentException($"'{nameof(packageUrl)}' cannot be null or empty.", nameof(packageUrl));
}
CurrentVersion = currentVersion;
PackageUrl = packageUrl;
CurrentVersionInfo = new VersionInfo(CurrentVersion);
Versions = new VersionCollection(PackageUrl);
DoesUpdateExist = !CurrentVersionInfo.IsLatestVersion(Versions);
LatestVersionInfo = Versions.Max();
LastestVersionIsPrerelease = !string.IsNullOrEmpty(LatestVersionInfo.Suffix);
LatestVersionDownloadUrl = LatestVersionInfo.Download;
}
/// <summary>
/// Gets the CurrentVersion.
/// </summary>
public string CurrentVersion { get; }
/// <summary>
/// Gets the CurrentVersionInfo.
/// </summary>
public VersionInfo CurrentVersionInfo { get; }
/// <summary>
/// Gets a value indicating whether DoesUpdateExist.
/// </summary>
public bool DoesUpdateExist { get; }
/// <summary>
/// Gets a value indicating whether LastestVersionIsPrerelease.
/// </summary>
public bool LastestVersionIsPrerelease { get; }
/// <summary>
/// Gets the LatestVersionDownloadUrl.
/// </summary>
public string LatestVersionDownloadUrl { get; }
/// <summary>
/// Gets the LatestVersionInfo.
/// </summary>
public VersionInfo LatestVersionInfo { get; }
/// <summary>
/// Gets the PackageUrl.
/// </summary>
public string PackageUrl { get; }
/// <summary>
/// Gets the Versions.
/// </summary>
public VersionCollection Versions { get; }
/// <summary>
/// Open the default browser to the Download Site.
/// </summary>
public void OpenDownloadSite()
{
Process.Start(new ProcessStartInfo("cmd", $"/c start {LatestVersionDownloadUrl}") { CreateNoWindow = true });
}
}
}
|
d61f9d6fbe26ad5f5a6f66d91b030704f60959b7
|
C#
|
ahmetonurslmz/customerinfo
|
/CustomerInfo/Form1.cs
| 2.53125
| 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 CustomerInfo
{
public partial class Form1 : Form
{
Jobs jobs;
Cities cities;
Customers customers;
BindingSource binder = new BindingSource();
int totalCustomers;
int totalCities;
int totalJobs;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.fetchCustomers();
this.fetchJobs();
this.fetchCities();
}
public void fetchJobs()
{
jobs = new Jobs();
DataSet data_set = jobs.fetch();
totalCities = data_set.Tables[0].Rows.Count;
Dictionary<int, string> comboSource = new Dictionary<int, string>();
for (int i = 0; i < totalCities; i++)
{
DataRow table = data_set.Tables[0].Rows[i];
comboSource.Add(Convert.ToInt32(table.ItemArray.GetValue(0).ToString()), table.ItemArray.GetValue(1).ToString());
}
cbJob.DataSource = new BindingSource(comboSource, null);
cbJob.DisplayMember = "Value";
cbJob.ValueMember = "Key";
cbJob.SelectedIndex = -1;
cbSelectJob.DataSource = new BindingSource(comboSource, null);
cbSelectJob.DisplayMember = "Value";
cbSelectJob.ValueMember = "Key";
cbSelectJob.SelectedIndex = -1;
}
public void fetchCities()
{
cities = new Cities();
DataSet data_set = cities.fetch();
totalJobs = data_set.Tables[0].Rows.Count;
Dictionary<int, string> comboSource = new Dictionary<int, string>();
for (int i = 0; i < totalJobs; i++)
{
DataRow table = data_set.Tables[0].Rows[i];
comboSource.Add(Convert.ToInt32(table.ItemArray.GetValue(0).ToString()), table.ItemArray.GetValue(1).ToString());
}
cbCity.DataSource = new BindingSource(comboSource, null);
cbCity.DisplayMember = "Value";
cbCity.ValueMember = "Key";
cbCity.SelectedIndex = -1;
cbSelectCity.DataSource = new BindingSource(comboSource, null);
cbSelectCity.DisplayMember = "Value";
cbSelectCity.ValueMember = "Key";
cbSelectCity.SelectedIndex = -1;
}
public void fetchCustomers()
{
try
{
lvCustomers.Items.Clear();
customers = new Customers();
DataTable customersTable = customers.fetch();
totalCustomers = customersTable.Rows.Count;
foreach (DataRow row in customersTable.Rows)
{
ListViewItem item = new ListViewItem(row[0].ToString());
for (int i = 1; i < customersTable.Columns.Count; i++)
{
item.SubItems.Add(row[i].ToString());
}
lvCustomers.Items.Add(item);
}
}
catch (Exception error)
{
MessageBox.Show(error.Message.ToString(), "Alert", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnAddRecord_Click(object sender, EventArgs e)
{
this.createOrUpdateCustomer(0);
}
public void createOrUpdateCustomer(int customerId)
{
string customerName;
string customerFamilyName;
int customerJob;
int customerSalary;
int customerCity;
try
{
// customer name
if (txtName.TextLength != 0)
{
customerName = txtName.Text;
}
else
{
throw new Exception("You must enter customer name.");
}
// customer family name
if (txtFamilyName.TextLength != 0)
{
customerFamilyName = txtFamilyName.Text;
}
else
{
throw new Exception("You must enter customer family name.");
}
// customer job
if (cbJob.SelectedIndex > -1)
{
customerJob = ((KeyValuePair<int, string>)cbJob.SelectedItem).Key;
}
else
{
throw new Exception("You must select customer job.");
}
// customer salary
if (mTxtSalary.Text.ToString().Length != 0)
{
customerSalary = Convert.ToInt32(mTxtSalary.Text.ToString());
}
else
{
throw new Exception("You must enter customer salary.");
}
// customer city
if (cbCity.SelectedIndex > -1)
{
customerCity = ((KeyValuePair<int, string>)cbCity.SelectedItem).Key;
}
else
{
throw new Exception("You must select customer city.");
}
if (customerId > 0)
{
// update
customers = new Customers();
Boolean result = customers.update(customerId, customerName, customerFamilyName, customerJob, customerSalary, customerCity);
if (result)
{
this.fetchCustomers();
}
} else
{
// create
customers = new Customers();
Boolean result = customers.create(customerName, customerFamilyName, customerJob, customerSalary, customerCity);
if (result)
{
this.fetchCustomers();
this.clearForm();
}
}
}
catch (Exception error)
{
MessageBox.Show(error.Message.ToString(), "Alert", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnUpdateRecord_Click(object sender, EventArgs e)
{
this.createOrUpdateCustomer(Convert.ToInt32(lblIdValue.Text));
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
lblIdValue.Text = lvCustomers.Items[lvCustomers.FocusedItem.Index].SubItems[0].Text;
txtName.Text = lvCustomers.Items[lvCustomers.FocusedItem.Index].SubItems[1].Text;
txtFamilyName.Text = lvCustomers.Items[lvCustomers.FocusedItem.Index].SubItems[2].Text;
mTxtSalary.Text = lvCustomers.Items[lvCustomers.FocusedItem.Index].SubItems[4].Text;
cbJob.Text = lvCustomers.Items[lvCustomers.FocusedItem.Index].SubItems[3].Text;
cbCity.Text = lvCustomers.Items[lvCustomers.FocusedItem.Index].SubItems[5].Text;
btnUpdateRecord.Enabled = true;
btnDeleteRecord.Enabled = true;
}
public void clearForm()
{
lblIdValue.Text = "0";
txtName.Text = "";
txtFamilyName.Text = "";
cbJob.SelectedIndex = -1;
mTxtSalary.Text = null;
cbCity.SelectedIndex = -1;
btnUpdateRecord.Enabled = false;
btnDeleteRecord.Enabled = false;
}
private void btnClearForm_Click(object sender, EventArgs e)
{
this.clearForm();
}
private void btnDeleteRecord_Click(object sender, EventArgs e)
{
customers = new Customers();
Boolean result = customers.delete(Convert.ToInt32(lblIdValue.Text));
if (result)
{
this.fetchCustomers();
this.clearForm();
}
}
private void cbSelectJob_SelectedValueChanged(object sender, EventArgs e)
{
if (cbSelectJob.SelectedIndex > -1)
{
customers = new Customers();
int selectedValue = ((KeyValuePair<int, string>)cbSelectJob.SelectedItem).Key;
int count = customers.fetchByJobs(selectedValue);
lblSelectedJobCount.Text = count.ToString();
lblTotalCustomerCount.Text = totalCustomers.ToString();
prgressBarSelectedJob.Maximum = totalCustomers;
prgressBarSelectedJob.Value = count;
} else
{
prgressBarSelectedJob.Value = 0;
lblSelectedJobCount.Text = 0.ToString();
lblTotalCustomerCount.Text = 0.ToString();
}
}
private void cbSelectCity_SelectedValueChanged(object sender, EventArgs e)
{
if (cbSelectCity.SelectedIndex > -1)
{
customers = new Customers();
int selectedValue = ((KeyValuePair<int, string>)cbSelectCity.SelectedItem).Key;
int count = customers.fetchByCity(selectedValue);
lblSelectedCityCount.Text = count.ToString();
lblTotalCustomerCountCity.Text = totalCustomers.ToString();
prgressBarSelectedCity.Maximum = totalCustomers;
prgressBarSelectedCity.Value = count;
}
else
{
prgressBarSelectedCity.Value = 0;
lblSelectedCityCount.Text = 0.ToString();
lblTotalCustomerCountCity.Text = 0.ToString();
}
}
}
}
|
7771ba1397ecb64f8758fd4b092b685254b433f7
|
C#
|
zoro83/HomeWork
|
/FirtStage.Starter/Array c#/ex_31/ex_31/Program.cs
| 3.96875
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ex_31
{
class Program
{
/// <summary>
/// Enter 2 < N < 100 number for printing sequence
/// </summary>
/// <param name="n"></param>
static void Sequence(int n)
{
int count = 0;
int nextNumber = n;
while (nextNumber != 1)
{
if (nextNumber % 2 == 0)
{
nextNumber = nextNumber / 2;
count++;
}
else
{
nextNumber = 3 * nextNumber + 1;
count++;
}
//(nextNumber % 2 == 0)?nextNumber = nextNumber/2: nextNumber = 3 * nextNumber + 1;
}
int[] sequence = new int[count + 1];
sequence[0] = n;
for (int i = 0; i < sequence.Length - 1; i++)
{
if (sequence[i] % 2 == 0)
{
sequence[i + 1] = (sequence[i] / 2);
}
else
{
sequence[i + 1] = (3 * sequence[i] + 1);
}
Console.WriteLine($"{sequence[i]}");
}
Console.WriteLine(1);
}
static void Main(string[] args)
{
Console.Write("Enter 2 < N < 100 number for printing sequence \nN = ");
int N = int.Parse(Console.ReadLine());
if (N > 2 && N < 100)
{
Sequence(N);
}
else
Console.WriteLine("Wrong input");
Console.ReadKey();
}
}
}
|
bc7664564b767af368cdff1a5026fc6e626e8a35
|
C#
|
robertlarkins/code-golf
|
/CodeGolf.Tests/Equations/AngleBetweenClockHandsTests.cs
| 2.609375
| 3
|
using CodeGolf.Equations;
using FluentAssertions;
using Xunit;
namespace CodeGolf.Tests.Equations
{
public class AngleBetweenClockHandsTests
{
[Theory]
[InlineData("0000", 0)]
[InlineData("0010", 55.0)]
[InlineData("0020", 110.0)]
[InlineData("0030", 165.0)]
[InlineData("0040", 140.0)]
[InlineData("0050", 85.0)]
[InlineData("0150", 115.0)]
[InlineData("0240", 160.0)]
[InlineData("0725", 72.5)]
[InlineData("1020", 170.0)]
[InlineData("1350", 115.0)]
[InlineData("1725", 12.5)]
public void CalculateAngleInDegrees_StateUnderTest_ExpectedBehaviour(string time, double expected)
{
// Arrange
var angleBetweenClockHands = new AngleBetweenClockHands();
// Act
var result = angleBetweenClockHands.CalculateAngleInDegrees(time);
// Assert
result.Should().BeApproximately(expected, 1e-2);
}
[Theory]
[InlineData("0000", 0)]
[InlineData("0010", 55.0)]
[InlineData("0020", 110.0)]
[InlineData("0030", 165.0)]
[InlineData("0040", 140.0)]
[InlineData("0050", 85.0)]
[InlineData("0150", 115.0)]
[InlineData("0240", 160.0)]
[InlineData("0725", 72.5)]
[InlineData("1020", 170.0)]
[InlineData("1350", 115.0)]
[InlineData("1725", 12.5)]
public void CalculateAngleInDegreesGolfed_StateUnderTest_ExpectedBehaviour(string time, double expected)
{
// Arrange
var angleBetweenClockHands = new AngleBetweenClockHands();
// Act
var result = angleBetweenClockHands.CalculateAngleInDegreesGolfed(time);
// Assert
result.Should().BeApproximately(expected, 1e-2);
}
[Theory]
[InlineData("0000", 0)]
[InlineData("0010", 55.0)]
[InlineData("0020", 110.0)]
[InlineData("0030", 165.0)]
[InlineData("0040", 140.0)]
[InlineData("0050", 85.0)]
[InlineData("0150", 115.0)]
[InlineData("0240", 160.0)]
[InlineData("0725", 72.5)]
[InlineData("1020", 170.0)]
[InlineData("1350", 115.0)]
[InlineData("1725", 12.5)]
public void CalculateAngleInDegreesGolfed2_StateUnderTest_ExpectedBehaviour(string time, double expected)
{
// Arrange
var angleBetweenClockHands = new AngleBetweenClockHands();
// Act
var result = angleBetweenClockHands.CalculateAngleInDegreesGolfed2(time);
// Assert
result.Should().BeApproximately(expected, 1e-2);
}
}
}
|
17fdfd391272c9b0d1ade61aed6f088c44762ebe
|
C#
|
viksimenaite/Delegation_Composition
|
/Delegation_Composition/CakeFactory.cs
| 2.9375
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Delegation_Composition
{
class CakeFactory:ISuitability
{
private ISuitability suitabilityRealisation;
public CakeFactory(ISuitability suitabilityRealisation)
{
this.suitabilityRealisation = suitabilityRealisation;
}
public bool IsSuitableForLactoseIntolerantPeople(FoodProduct product)
{
return suitabilityRealisation.IsSuitableForLactoseIntolerantPeople(product);
}
public bool IsSuitableForNonMeatEaters(FoodProduct product)
{
return suitabilityRealisation.IsSuitableForNonMeatEaters(product);
}
public double CountPrice(FoodProduct product)
{
if (product.IntendedFor == EatingHabits.Vegan)
{
return product.BaseKgPrice + 8;
}
else if (product.IntendedFor == EatingHabits.Vegetarian)
{
return product.BaseKgPrice + 6;
}
else if (!product.ContainsLactose)
{
return product.BaseKgPrice + 4;
}
else
{
return product.BaseKgPrice + 2;
}
}
}
}
|
d69a0381f0d98cc6dd4131a299eed2b6d54eea35
|
C#
|
godxkey/FarseerWithNewBox2dVersion
|
/FarseerUnity/Assets/Plugins/FarseerComponents/Base/FarseerPhysics/Collision/AABBHelper.cs
| 2.578125
| 3
|
using Microsoft.Xna.Framework;
using VelcroPhysics.Shared;
using VelcroPhysics.Utilities;
namespace VelcroPhysics.Collision
{
public static class AABBHelper
{
public static void ComputeEdgeAABB(ref FVector2 start, ref FVector2 end, ref Transform transform, out AABB aabb)
{
FVector2 v1 = MathUtils.Mul(ref transform, ref start);
FVector2 v2 = MathUtils.Mul(ref transform, ref end);
aabb.LowerBound = FVector2.Min(v1, v2);
aabb.UpperBound = FVector2.Max(v1, v2);
FVector2 r = new FVector2(Settings.PolygonRadius, Settings.PolygonRadius);
aabb.LowerBound = aabb.LowerBound - r;
aabb.UpperBound = aabb.UpperBound + r;
}
public static void ComputeCircleAABB(ref FVector2 pos, float radius, ref Transform transform, out AABB aabb)
{
FVector2 p = transform.p + MathUtils.Mul(transform.q, pos);
aabb.LowerBound = new FVector2(p.X - radius, p.Y - radius);
aabb.UpperBound = new FVector2(p.X + radius, p.Y + radius);
}
public static void ComputePolygonAABB(Vertices vertices, ref Transform transform, out AABB aabb)
{
FVector2 lower = MathUtils.Mul(ref transform, vertices[0]);
FVector2 upper = lower;
for (int i = 1; i < vertices.Count; ++i)
{
FVector2 v = MathUtils.Mul(ref transform, vertices[i]);
lower = FVector2.Min(lower, v);
upper = FVector2.Max(upper, v);
}
FVector2 r = new FVector2(Settings.PolygonRadius, Settings.PolygonRadius);
aabb.LowerBound = lower - r;
aabb.UpperBound = upper + r;
}
}
}
|
9dc4a3a7ec57097ac4e746f543bd08996ac432ab
|
C#
|
guih2127/praticas-de-programacao
|
/aulas/aula02exercice/aula02atividade01/Program.cs
| 4.0625
| 4
|
using System;
namespace aula02atividade01
{
class Program
{
static void Main(string[] args)
{
int x, y, z;
int[] numbers = new int[3];
Console.WriteLine("Digite o valor de X");
x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Digite o valor de Y");
y = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Digite o valor de Z");
z = Convert.ToInt32(Console.ReadLine());
numbers[0] = x;
numbers[1] = y;
numbers[2] = z;
if (x > y && x > z)
{
Console.WriteLine("O maior número é X: " + x);
}
else if (y > x & y > z)
{
Console.WriteLine("O maior número é Y: " + y);
}
else if (z > x & z > y)
{
Console.WriteLine("O maior número é Z: " + z);
}
Array.Sort(numbers);
Console.WriteLine("Ordem crescente:");
foreach (int number in numbers)
{
Console.WriteLine(number);
}
Console.WriteLine("Aperte uma tecla para sair.");
Console.ReadKey();
}
}
}
|
7c7e37ed627868bfd504aa66987a3d61332a24de
|
C#
|
GhostXr/UnityFrameProject
|
/Assets/Scripts/UIFrameWork/Manager/QModuleManager.cs
| 2.5625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
namespace QUIFrameWork
{
public class QModuleManager : QSingleton<QModuleManager>
{
private Dictionary<string, QBaseModule> dicModules = null;
/// <summary>
/// Create this instance.
/// </summary>
public override void Create()
{
dicModules = new Dictionary<string, QBaseModule> ();
}
/// <summary>
/// Get the specified _name.
/// </summary>
/// <param name="_name">Name.</param>
public QBaseModule Get(string _name)
{
if (dicModules.ContainsKey (_name))
{
return dicModules [_name];
}
return null;
}
/// <summary>
/// Get this instance.
/// </summary>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public T Get<T>() where T : QBaseModule
{
Type t = typeof(T);
if (dicModules.ContainsKey (t.ToString ()))
return dicModules[t.ToString ()] as T;
return null;
}
#region Register
/// <summary>
/// Registers the module.
/// </summary>
/// <param name="_moudle">Moudle.</param>
public void RegisterModule(QBaseModule _moudle)
{
Type t = _moudle.GetType ();
Register (t.ToString (), _moudle);
}
/// <summary>
/// Register the specified _name and _module.
/// </summary>
/// <param name="_name">Name.</param>
/// <param name="_module">Module.</param>
public void Register(string _name, QBaseModule _module)
{
if (! dicModules.ContainsKey (_name))
dicModules.Add(_name, _module);
}
#endregion
#region UnRegister
/// <summary>
/// Uns the register module.
/// </summary>
/// <param name="_moudle">Moudle.</param>
public void UnRegisterModule(QBaseModule _moudle)
{
Type t = _moudle.GetType ();
UnRegister (t.ToString ());
}
/// <summary>
/// Uns the register.
/// </summary>
/// <param name="_name">Name.</param>
public void UnRegister(string _name)
{
if (dicModules.ContainsKey (_name))
{
QBaseModule module = dicModules [_name];
module.Release ();
dicModules.Remove(_name);
module = null;
}
}
/// <summary>
/// Uns the register all.
/// </summary>
public void UnRegisterAll()
{
List<string> _moduleList = new List<string> (dicModules.Keys);
for (int i = 0; i < _moduleList.Count; i++)
{
UnRegister(_moduleList[i]);
}
_moduleList.Clear ();
dicModules.Clear();
}
#endregion
}
}
|
4debb59c2531732b775633f061c099bb08cdf5ce
|
C#
|
MahbubAhmedTonmoy/cSharp__code
|
/IComparable_IComparer.cs
| 3.359375
| 3
|
using System;
using System.Collections.Generic;
namespace dddd
{
class customer{
public int cusId{get;set;}
public string Name{get;set;}
public string City {get;set;}
public double Balance {get;set;}
}
class student : IComparable<student>{
public int Sid{get;set;}
public string Name{get;set;}
public int Class {get;set;}
public float Marks{get;set;}
public int CompareTo(student s)
{
return this.Sid.CompareTo(s.Sid);
}
}
class comparer : IComparer<student>
{
public int Compare(student x, student y)
{
if(x.Marks > y.Marks) return -1;
else if(x.Marks < y.Marks) return 1;
else return 0;
}
}
class main{
public static void Main(){
List <customer> Customer = new List<customer>();
customer c1 = new customer(){cusId=101, Name="mahbub",City="Dhaka", Balance=20.99};
customer c2 = new customer(){cusId=102, Name="ahmed",City="Dhaka", Balance=20.99};
customer c3 = new customer(){cusId=103, Name="tonmoy",City="Dhaka", Balance=20.99};
customer c4 = new customer(){cusId=104, Name="tonni",City="Dhaka", Balance=20.99};
List <student> Student = new List<student>();
student s1 = new student(){Sid=110, Name="mahbub",Class=11, Marks=10.99f};
student s2 = new student(){Sid=105, Name="ahmed",Class=12, Marks=30.99f};
student s3 = new student(){Sid=103, Name="tonmoy",Class=13, Marks=20.99f};
student s4 = new student(){Sid=101, Name="tonni",Class=14, Marks=60.99f};
Customer.Add(c1); Customer.Add(c2); Customer.Add(c3); Customer.Add(c4);
Student.Add(s1); Student.Add(s2); Student.Add(s3); Student.Add(s4);
/* foreach(customer i in Customer){
Console.WriteLine(i.cusId+" "+i.Name+" "+i.City+" "+i.Balance);
}*/
comparer cmp = new comparer();
Student.Sort(cmp);
foreach(student i in Student){
Console.WriteLine(i.Name+" "+i.Marks+" "+i.Sid);
}
}
}
}
|