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
|
|---|---|---|---|---|---|---|
2f877c13e852065365d5e661d77b6ce994c882b0
|
C#
|
rjxby/ltc
|
/RomanToInteger/Program.cs
| 3.09375
| 3
|
using System;
namespace RomanToInteger
{
class Program
{
static void Main(string[] args)
{
var logic = new Logic();
Console.WriteLine($"III = {logic.RomanToInt("III")}");
Console.WriteLine($"IV = {logic.RomanToInt("IV")}");
Console.WriteLine($"MCMXCIV = {logic.RomanToInt("MCMXCIV")}");
Console.ReadLine();
}
}
}
|
d81894f207a581e02ee9abcc9d02919ebd4ccc11
|
C#
|
MagicAhn/UnityStudy2
|
/Day 2013-11-05 Second/Assets/Scripts/Hit.cs
| 2.515625
| 3
|
using System;
using System.ComponentModel;
using System.Linq;
using UnityEngine;
using System.Collections;
public class Hit : MonoBehaviour
{
public Texture2D BackgroundColor;
public Texture2D ForegroundColor;
private Single _keyDownTime;
private Single _timeSpan;
// Use this for initialization
void Start()
{
GameObject box = GameObject.Find("Box");
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
GameObject boxObj = (GameObject)Instantiate(box);
boxObj.transform.position = new Vector3(j - 2, 0.5f + i, 4);
}
}
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
// Ϸпʼ ʱ䣨Ϸ Ѿʼ ˶ʱ䣩
_keyDownTime = Time.realtimeSinceStartup;
}
}
else if (Input.GetMouseButtonUp(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if (hit.collider.gameObject.name.Equals("Box(Clone)"))
{
GameObject bullet = GameObject.CreatePrimitive(PrimitiveType.Sphere);
bullet.AddComponent<Rigidbody>();
bullet.transform.position = Camera.main.transform.position;
Vector3 v3 = hit.point - Camera.main.transform.position;
bullet.rigidbody.AddForce(v3 * (_timeSpan%5), ForceMode.Impulse);
bullet.AddComponent("DestoryAll");
// ͷ Ӧʱ ֤ 䲻 GUI ״̬
_keyDownTime = 0.0f;
_timeSpan = 0.0f;
}
}
}
}
void OnGUI()
{
GUI.DrawTexture(new Rect(10, 10, 100, 20), BackgroundColor);
// ֤ ֻҪ ȥ Ϳʼ
if (_keyDownTime > 0.0f)
{
// ֤ º ÿһ֡ Ч
_timeSpan = Time.realtimeSinceStartup - _keyDownTime;
//if (_timeSpan > 5.0f)
//{
// _timeSpan = 5.0f;
//}
GUI.DrawTexture(new Rect(10, 10, (_timeSpan%5 * 20), 20), ForegroundColor);
}
}
}
|
41958e5cb4f63617b4d973d28f9b02315bab5ed5
|
C#
|
hanseongv/MainPortfolio
|
/Assets/Scripts/Common/Util.cs
| 2.53125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
internal class Util
{
static public void SetLayer(GameObject go, int layer)
{
go.layer = layer;
Transform t = go.transform;
for (int i = 0, imax = t.childCount; i < imax; ++i)
{
Transform child = t.GetChild(i);
SetLayer(child.gameObject, layer);
}
}
public class TempRectInfo<T> where T : SingletonBase
{
public T t;
public RectTransform rt;
public TempRectInfo(T t) {
this.t = t;
}
public TempRectInfo(T t, RectTransform rt)
{
this.t = t;
this.rt = rt;
}
}
public static TempRectInfo<T> InstantiateSingleton<T>() where T : SingletonBase
{
// 1 씬에 있는 루트 오브젝트 돌면서 꺼져 있는 오브젝트 중에 T 타입이 있는지 확인하자.
T existSceneComponent = (T)GetAllObjectsOnlyInScene<T>();
if (existSceneComponent != null)
return new TempRectInfo<T>(existSceneComponent);
// 2. 리소스폴더(어셋번들) 경로 확인.
var type = typeof(T);
string name = type.ShortName();
GameObject resoruceGo = (GameObject)Resources.Load(name);
if (resoruceGo != null)
{
GameObject loadGo = Instantiate(resoruceGo);
var c = loadGo.GetComponent<T>();
Debug.Assert(c != null, $"{name} 로드한 게임오브젝트에 컴포넌트가 없다");
RectTransform rt = resoruceGo.GetComponent<RectTransform>();
return new TempRectInfo<T>(c, rt);
}
Debug.LogWarning($"주의! 씬과 리소스 폴더에 {name} 컴포넌트및 프리팹이 없어서 비어있는 클래스를 생성합니다!");
// 3. 인스턴스 생성
GameObject newComponent = new GameObject(name, type);
T t = (T)newComponent.GetComponent(typeof(T));
return new TempRectInfo<T>(t);
//return (T)newComponent.GetComponent(typeof(T));
}
static SingletonBase GetAllObjectsOnlyInScene<T>() where T : Component
{
var components = Resources.FindObjectsOfTypeAll(typeof(T));
foreach (UnityEngine.Object co in components)
{
Component component = co as Component;
GameObject go = component.gameObject;
if (go.scene.name == null) // 씬에 있는 오브젝트가 아니므로 제외한다.
continue;
if (go.hideFlags == HideFlags.NotEditable || go.hideFlags == HideFlags.HideAndDontSave || go.hideFlags == HideFlags.HideInHierarchy)
continue;
return (SingletonBase)component;
}
return null;
}
#region Instantiate 래핑
internal static GameObject Instantiate(string prefabPath)
{
GameObject o = (GameObject)Resources.Load(prefabPath);
return Instantiate(o, Vector3.zero, Quaternion.identity);
}
internal static GameObject Instantiate(string prefabPath, Transform parent)
{
GameObject _object = (GameObject)Resources.Load(prefabPath);
GameObject newGo = Object.Instantiate(_object, parent);
InitObject(_object, newGo);
return newGo;
}
private static void InitObject(UnityEngine.Object original, UnityEngine.Object newCompont)
{
newCompont.name = original.name;
}
internal static GameObject Instantiate(GameObject prefab)
{
return Util.Instantiate(prefab, Vector3.zero, Quaternion.identity);
}
internal static GameObject Instantiate(GameObject prefab, Vector3 worldPosition)
{
return Util.Instantiate(prefab, worldPosition, Quaternion.identity);
}
internal static GameObject Instantiate(Object _object, Transform parent)
{
GameObject newGo = (GameObject)Object.Instantiate(_object, parent);
InitObject(_object, newGo);
return newGo;
}
internal static GameObject Instantiate(GameObject prefab, Vector3 position, Quaternion rotation)
{
GameObject newGo = Object.Instantiate(prefab, position, rotation);
InitObject(prefab, newGo);
return newGo;
}
internal static T Instantiate<T>(T prefab) where T : Component
{
return Instantiate<T>(prefab, Vector3.zero, Quaternion.identity);
}
internal static T Instantiate<T>(T prefab, Vector3 position) where T : Component
{
return Instantiate<T>(prefab, position, Quaternion.identity);
}
internal static T Instantiate<T>(T prefab, Vector3 position, Quaternion rotation) where T : Component
{
T newGo = UnityEngine.Object.Instantiate<T>(prefab, position, rotation);
InitObject(prefab, newGo);
return newGo;
}
#endregion Instantiate 래핑
}
|
268e30af314d99f165bf566a1f994ceff897b660
|
C#
|
semenovDA/pulse
|
/graphics/ACFChart.cs
| 2.578125
| 3
|
using Newtonsoft.Json.Linq;
using pulse.collection;
using pulse.forms;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
namespace pulse.graphics
{
public partial class ACFChart : Component
{
public ACFChart(Signal signal)
{
InitializeComponent();
chart.Size = new Size(1000, 300);
FillChart(signal);
setView();
}
private void FillChart(Signal signal)
{
var acf = signal.ComputeACF();
for(int i = 0; i < acf["lags"].Count(); i++)
{
var x = ((JValue)acf["lags"][i]).Value;
var y = ((JValue)acf["acf_x"][i]).Value;
chart.Series[0].Points.AddXY(x, y);
}
}
private void setView()
{
var length = chart.Series[0].Points.Last().XValue;
chart.ChartAreas[0].AxisX.ScaleView.Zoom(0, length / 5);
}
public void Show(string title = "Автокорреляционная функция")
{
var emptyFrom = new Empty();
emptyFrom.Text = title;
emptyFrom.workspace.Controls.Add(chart);
emptyFrom.Show();
}
}
}
|
49f4e2f7e7902430228ae2bd23b28a8cd27f2a95
|
C#
|
anish-varghese/X-Force
|
/BackEnd/src/src/Experion.Marina.Core/Common/MarinaException.cs
| 2.796875
| 3
|
using System;
namespace Experion.Marina.Core
{
/// <summary>
/// Keys to indicate various exceptions in the application
/// </summary>
public enum ErrorCode : int
{
/// <summary>
/// Unknown
/// </summary>
Unknown = 100,
/// <summary>
/// The SMTP configuration unknown
/// </summary>
SmtpConfigurationUnknown = 101,
/// <summary>
/// The email template not found
/// </summary>
EmailTemplateNotFound = 102,
/// <summary>
/// The email template error
/// </summary>
EmailTemplateError = 103,
/// <summary>
/// The invalid token
/// </summary>
InvalidToken = 104,
/// <summary>
/// The invalid token
/// </summary>
SessionTimeout = 105,
/// <summary>
/// The authentication failed
/// </summary>
AuthenticationFailed = 106,
}
public class MarinaException : Exception
{
#region Constructor
/// <summary>
/// Default Constructor
/// </summary>
public MarinaException()
{
ErrorCode = ErrorCode.Unknown;
}
/// <summary>
/// Constructor initializing ExceptionKey property.
/// </summary>
/// <param name="errorCode">The error code.</param>
public MarinaException(ErrorCode errorCode)
{
ErrorCode = errorCode;
}
#endregion Constructor
#region Properties
/// <summary>
/// Gets or sets exception key.
/// </summary>
/// <value>
/// The error code.
/// </value>
public ErrorCode ErrorCode { get; set; }
#endregion Properties
}
}
|
cd1cd1b5dcbb54cbec7fa3f014bebd3f69c8b3ed
|
C#
|
shendongnian/download4
|
/code8/1481027-40611688-131619319-1.cs
| 2.671875
| 3
|
//I have now edited the code to better reflect your real data
public void ShowMoves(Vector2 playerPosition, int diceNumber, bool[] blocks)
{
int x = (int)playerPosition.x;
int y = (int)playerPosition.y;
if(tileMap.GetUpperBound(0) < x + 1)
{
if(tileMap[x + 1, y].tag == "walkableGrid" && blocks[0])
{
/*Light up the tile*/
if(diceNumber > 0)
ShowMoves(new Vector2(x + 1, y), diceNumber - 1, new bool[] { x != tileMap.GetUpperBound(0), false, y != tileMap.GetUpperBound(1), y != 0 });
}
}
if(x - 1 >= 0)
{
if(tileMap[x - 1, y].tag == "walkableGrid" && blocks[1])
{
/*Light up the tile*/
if(diceNumber > 0)
ShowMoves(new Vector2(x - 1, y), diceNumber - 1, new bool[] { false, x != 0, y != tileMap.GetUpperBound(1), y != 0 });
}
}
if(tileMap.GetUpperBound(1) < y + 1)
{
if(tileMap[x, y + 1].tag == "walkableGrid" && blocks[2])
{
/*Light up the tile*/
if(diceNumber > 0)
ShowMoves(new Vector2(x, y + 1), diceNumber - 1, new bool[] { x != tileMap.GetUpperBound(0), x != 0, y != tileMap.GetUpperBound(1), false });
}
}
if(y - 1 >= 0)
{
if(tileMap[x, y - 1].tag == "walkableGrid" && blocks[3])
{
/*Light up the tile*/
if(diceNumber > 0)
ShowMoves(new Vector2(x, y - 1), diceNumber - 1, new bool[] { x != tileMap.GetUpperBound(0), x != 0, false, y != 0 });
}
}
}
|
27788b30d642b04660b765bb6e07c16cd524cd66
|
C#
|
mariyaVR/OOPAdvanced
|
/3/IteratorsAndComparators/5.ComparingObjects/Person.cs
| 3.78125
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _5.ComparingObjects
{
public class Person: IComparable<Person>
{
private string name;
private int age;
private string town;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
public string Town
{
get
{
return town;
}
set
{
town = value;
}
}
public Person(string name, int age, string town)
{
this.Name = name;
this.Age = age;
this.Town = town;
}
public int CompareTo(Person other)
{
int comparison = 0;
if (this.Name.CompareTo(other.Name) != 0)
{
comparison = this.Name.CompareTo(other.Name);
}
if (this.Age.CompareTo(other.Age) != 0)
{
comparison = this.Age.CompareTo(other.Age);
}
if (this.Town.CompareTo(other.Town) != 0)
{
comparison = this.Town.CompareTo(other.Town);
}
return comparison;
}
}
}
|
35eaab865af20cb763453cc3020fd41633dac350
|
C#
|
SobekCM/SobekCM-Web-Application
|
/Sample_PlugIn_Library/Sample_Custom_METS_Section_FavColor.cs
| 2.921875
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using SobekCM.Resource_Object;
using SobekCM.Resource_Object.METS_Sec_ReaderWriters;
namespace Sample_PlugIn_Library
{
class Sample_Custom_METS_Section_FavColor : XML_Writing_Base_Type, iPackage_dmdSec_ReaderWriter
{
/// <summary> Writes the dmdSec for the entire package to the text writer </summary>
/// <param name="Output_Stream">Stream to which the formatted text is written </param>
/// <param name="METS_Item">Package with all the metadata to save</param>
/// <param name="Options"> Dictionary of any options which this METS section writer may utilize</param>
/// <returns>TRUE if successful, otherwise FALSE </returns>
public bool Write_dmdSec(TextWriter Output_Stream, SobekCM_Item METS_Item, Dictionary<string, object> Options)
{
// Ensure this metadata module extension exists and has data
Sample_FavColor_Metadata_Module taxonInfo = METS_Item.Get_Metadata_Module(Sample_FavColor_Metadata_Module.Module_Name_Static) as Sample_FavColor_Metadata_Module;
if ((taxonInfo == null) || (!taxonInfo.hasData))
return true;
Output_Stream.WriteLine("<MyFavColor>");
if (!String.IsNullOrEmpty(taxonInfo.Absolute_Favorite_Color))
{
Output_Stream.WriteLine("<absoluteFavoriteColor>" + Convert_String_To_XML_Safe(taxonInfo.Absolute_Favorite_Color) + "</absoluteFavoriteColor>");
}
foreach (string thisCOlor in taxonInfo.Other_Favorite_Color)
{
Output_Stream.WriteLine("<additionalFavoriteColor>" + Convert_String_To_XML_Safe(thisCOlor) + "</additionalFavoriteColor>");
}
Output_Stream.WriteLine("</MyFavColor>");
return true;
}
/// <summary> Reads the dmdSec at the current position in the XmlTextReader and associates it with the
/// entire package </summary>
/// <param name="Input_XmlReader"> Open XmlReader from which to read the metadata </param>
/// <param name="Return_Package"> Package into which to read the metadata</param>
/// <param name="Options"> Dictionary of any options which this METS section reader may utilize</param>
/// <returns> TRUE if successful, otherwise FALSE</returns>
public bool Read_dmdSec(XmlReader Input_XmlReader, SobekCM_Item Return_Package, Dictionary<string, object> Options)
{
// Ensure this metadata module extension exists
Sample_FavColor_Metadata_Module taxonInfo = Return_Package.Get_Metadata_Module(Sample_FavColor_Metadata_Module.Module_Name_Static) as Sample_FavColor_Metadata_Module;
if (taxonInfo == null)
{
taxonInfo = new Sample_FavColor_Metadata_Module();
Return_Package.Add_Metadata_Module(Sample_FavColor_Metadata_Module.Module_Name_Static, taxonInfo);
}
// Loop through reading each XML node
do
{
// If this is the end of this section, return
if ((Input_XmlReader.NodeType == XmlNodeType.EndElement) && ((Input_XmlReader.Name == "METS:mdWrap") || (Input_XmlReader.Name == "mdWrap")))
return true;
// get the right division information based on node type
if (Input_XmlReader.NodeType == XmlNodeType.Element)
{
string name = Input_XmlReader.Name.ToLower();
switch (name)
{
case "absoluteFavoriteColor":
Input_XmlReader.Read();
if ((Input_XmlReader.NodeType == XmlNodeType.Text) && (Input_XmlReader.Value.Trim().Length > 0))
{
taxonInfo.Absolute_Favorite_Color = Input_XmlReader.Value.Trim();
}
break;
case "additionalFavoriteColor":
Input_XmlReader.Read();
if ((Input_XmlReader.NodeType == XmlNodeType.Text) && (Input_XmlReader.Value.Trim().Length > 0))
{
taxonInfo.Other_Favorite_Color.Add(Input_XmlReader.Value.Trim());
}
break;
}
}
} while (Input_XmlReader.Read());
return true;
}
/// <summary> Flag indicates if this active reader/writer will write a dmdSec </summary>
/// <param name="METS_Item"> Package with all the metadata to save</param>
/// <param name="Options"> Dictionary of any options which this METS section writer may utilize</param>
/// <returns> TRUE if the package has data to be written, otherwise fALSE </returns>
public bool Include_dmdSec(SobekCM_Item METS_Item, Dictionary<string, object> Options)
{
// Ensure this metadata module extension exists and has data
Sample_FavColor_Metadata_Module taxonInfo = METS_Item.Get_Metadata_Module(Sample_FavColor_Metadata_Module.Module_Name_Static) as Sample_FavColor_Metadata_Module;
if ((taxonInfo == null) || (!taxonInfo.hasData))
return false;
return true;
}
/// <summary> Flag indicates if this active reader/writer needs to append schema reference information
/// to the METS XML header by analyzing the contents of the digital resource item </summary>
/// <param name="METS_Item"> Package with all the metadata to save</param>
/// <returns> TRUE if the schema should be attached, otherwise fALSE </returns>
public bool Schema_Reference_Required_Package(SobekCM_Item METS_Item)
{
return false;
}
/// <summary> Returns the schema namespace (xmlns) information to be written in the XML/METS Header</summary>
/// <param name="METS_Item"> Package with all the metadata to save</param>
/// <returns> Formatted schema namespace info for the METS header</returns>
public string[] Schema_Namespace(SobekCM_Item METS_Item)
{
string[] returnVal = new string[0];
return returnVal;
}
/// <summary> Returns the schema location information to be written in the XML/METS Header</summary>
/// <param name="METS_Item"> Package with all the metadata to save</param>
/// <returns> Formatted schema location for the METS header</returns>
public string[] Schema_Location(SobekCM_Item METS_Item)
{
string[] returnVal = new string[0];
return returnVal;
}
}
}
|
ab22196c6fd475337a64c85d4ac7323dce4350ae
|
C#
|
skohub/MenuTv
|
/Repositories/BeerRepository.cs
| 3.265625
| 3
|
using System.Collections.Generic;
using System.Linq;
using MenuTv.Entities;
namespace MenuTv.Repositories
{
public class BeerRepository : IUnitOfWork
{
private readonly BeerContext _context;
public BeerRepository(BeerContext context)
{
_context = context;
}
public IEnumerable<Beer> FindAll()
{
return _context.Beers
.OrderBy(x => x.Name)
.ToList();
}
public IEnumerable<Beer> FindAvailable()
{
return _context.Beers
.Where(x => x.Available)
.OrderBy(x => x.Name)
.ToList();
}
public Beer Find(int id)
{
return _context.Beers.SingleOrDefault(x => x.Id == id);
}
public void Create(Beer beer)
{
_context.Beers.Add(beer);
}
public void Update(Beer beer)
{
_context.Beers.Update(beer);
}
public void Remove(int id)
{
var beer = Find(id);
if (beer == null) return;
_context.Beers.Remove(beer);
}
public bool Exists(int id)
{
return _context.Beers.Any(e => e.Id == id);
}
public void SaveChanges() {
_context.SaveChanges();
}
}
}
|
aed76ee15414f17741dd271f8e2aa63701b3b3a5
|
C#
|
shendongnian/download4
|
/first_version_download2/311566-25744710-73137156-2.cs
| 2.625
| 3
|
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
public class UnmanagedDialogParent : NativeWindow {
private Form dialog;
public DialogResult ShowDialog(IntPtr parent, Form dlg) {
if (!IsWindow(parent)) throw new ArgumentException("Parent is not a valid window");
dialog = dlg;
this.AssignHandle(parent);
DialogResult retval = DialogResult.Cancel;
try {
retval = dlg.ShowDialog(this);
}
finally {
this.ReleaseHandle();
}
return retval;
}
protected override void WndProc(ref Message m) {
if (m.Msg == WM_DESTROY) dialog.Close();
base.WndProc(ref m);
}
// Pinvoke:
private const int WM_DESTROY = 2;
[DllImport("user32.dll")]
private static extern bool IsWindow(IntPtr hWnd);
}
|
fe09249b49dd8c2586cd63857ad7c5d3df28065b
|
C#
|
alexanderkurilenko/EPAM.KnowledgeTestingSystem
|
/BLL/Services.Implementation/TestService.cs
| 2.8125
| 3
|
using BLL.Entities;
using BLL.Mapper;
using DAL.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BLL.Services.Implementation
{
public class TestService:ITestService
{
private readonly IUnitOfWork uow;
private readonly ITestRepository repo;
public TestService(IUnitOfWork uow, ITestRepository rep)
{
this.uow = uow;
this.repo = rep;
}
public TestEntity GetTestById(int id)
{
if (id < 0)
throw new ArgumentOutOfRangeException();
return repo.Get(id).ToBll();
}
public IEnumerable<TestEntity> GetAllTestEntities()
{
return repo.GetAll().Select(t => t.ToBll());
}
public void CreateTest(TestEntity test)
{
if (test == null)
throw new ArgumentNullException();
repo.Create(test.ToDal());
uow.Save();
}
public void DeleteTest(TestEntity test)
{
if (test == null)
throw new ArgumentNullException();
repo.Delete(test.Id);
uow.Save();
}
public void UpdateTest(TestEntity test)
{
if (test == null)
throw new ArgumentNullException();
repo.Update(test.ToDal());
uow.Save();
}
public IEnumerable<TestEntity> GetTestByName(string name)
{
if (name == null)
throw new ArgumentNullException();
var test = repo.GetTestByName(name);
if (test == null)
return null;
return test.Select(t => t.ToBll());
}
}
}
|
7e9b3e046957cbdb834b8aaaa4c0846630a3ec23
|
C#
|
shreq/OE
|
/zad1/zad1/Program.cs
| 2.875
| 3
|
using GeneticSharp.Domain;
using GeneticSharp.Domain.Chromosomes;
using GeneticSharp.Domain.Crossovers;
using GeneticSharp.Domain.Populations;
using System;
using System.IO;
using zad1.EventHandlers;
using zad1.selection;
namespace zad1
{
class Program
{
static void Main(string[] _)
{
const int NUMBER_OF_BITS = 2 * 8 * sizeof(float);
ParameterSelection parameters = ConsoleParameterSelectionFactory.CreateSelection();
var chromosome = new FloatingPointChromosome(
new double[parameters.Variables.Length].Fill(parameters.LowerBound),
new double[parameters.Variables.Length].Fill(parameters.UpperBound),
new int[parameters.Variables.Length].Fill(NUMBER_OF_BITS),
new int[parameters.Variables.Length].Fill(2)
);
var population = new Population(50, 50, chromosome);
var fitness = new FunctionMinimumFitness()
{
FunctionVariables = parameters.Variables,
Expression = parameters.Expression
};
var geneticAlgorithm = new GeneticAlgorithm(population, fitness, parameters.Selection, parameters.Crossover, parameters.Mutation)
{
Termination = parameters.Termination
};
var filepath = "./results_" + (parameters.AdaptiveOn ? "AGA" : "SGA") +
"_" + parameters.Selection.GetType().Name +
"_" + parameters.Crossover.GetType().Name +
"_" + parameters.Mutation.GetType().Name +
"_" + parameters.Termination.GetType().Name + ".csv";
geneticAlgorithm.GenerationRan += new WriterEventHandler(filepath).Handle;
geneticAlgorithm.GenerationRan += new ConsoleLogEventHandler(parameters.Variables).Handle;
if (parameters.AdaptiveOn)
{
geneticAlgorithm.GenerationRan += new AdaptiveStrategyEventHandler().Handle;
}
geneticAlgorithm.Start();
var finalPhenotype = (geneticAlgorithm.BestChromosome as FloatingPointChromosome).ToFloatingPoints();
var finalVariableValues = "Parameters:";
for (int i = 0; i < parameters.Variables.Length; i++)
{
finalVariableValues += "\n" + parameters.Variables[i] + " = " + finalPhenotype[i];
}
var finalFitness = (geneticAlgorithm.BestChromosome as FloatingPointChromosome).Fitness.Value;
Console.WriteLine("\n\n- - - Final result: - - -" +
"\nNumber of generations: " + geneticAlgorithm.GenerationsNumber +
"\n\nFitness: " + finalFitness +
"\n\n" + finalVariableValues +
"\n\nRange: " + parameters.LowerBound + ", " + parameters.UpperBound +
"\n\nf(" + String.Join(", ", parameters.Variables) + ") = " + parameters.Expression +
" = " + (-finalFitness));
Console.ReadKey();
}
}
}
|
54430016e0fc050862c021f3217a970179b7bffb
|
C#
|
matvey192/cs18-dec
|
/Лабораторная работа 7/Задача 20/Program.cs
| 3.5
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Задача_20
{
class Program
{
static void Main(string[] args)
{
string b = Console.ReadLine();
string[] bill = b.Split(' '); // text
string num = Console.ReadLine();
string[] nums = num.Split(' '); // numbers
int i = 0;
int ic = 0;
int[] numss = new int[nums.Length]; // to int
while (i < nums.Length)
{
numss[i] = int.Parse(nums[i]);
ic = numss[i]; // number go to ic 0;2;3
if (ic < bill.Length) { Console.WriteLine(bill[ic]); }
else { Console.WriteLine("Фрагмент на индексе " +nums[i]+ " отсутствует"); }
ic = 0;
i++;
}
}
}
}
|
6900cb796e43cdb09a18de95d6eeede3769d5331
|
C#
|
emilrr/SoftUni-Fundamental-Level
|
/01. Advanced C#/Homeworks/04. Strings-And-Text-Processing-Homework/04.TextFilter/TextFilter.cs
| 3.265625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
class TextFilter
{
static void Main()
{
string[] wordsArr = Console.ReadLine().Split(',');
string quote =Console.ReadLine();
Console.WriteLine();
quote = ReplaceWordsInText(wordsArr, quote);
Console.WriteLine(quote);
}
public static string ReplaceWordsInText(string[] wordsArr, string quote)
{
for (int i = 0; i < wordsArr.Length; i++)
{
int lenght = 0;
lenght = wordsArr[i].Length;
quote = Regex.Replace(quote, wordsArr[i], new string('*', lenght));
}
return quote;
}
}
|
f07bdc9f1a24e95b901fe503a6a768ea0d675b79
|
C#
|
yellow001/Game_Demo_P
|
/Assets/YUtility/Common/Extend/ValueChangeEx.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using YUtility.Common.Event;
namespace YUtility.Common.Extend {
public static class ValueChangeEx {
public static void ChangeValue(this float src, float dst, float duration, Action<float> changeFun, AnimationCurve curve = null, bool ignoreTime = false, Action callback = null) {
float temp = src;
float offset = dst - src;
EventMgr.Ins.AddTimeEvent(duration, callback, (t, p) => {
if (curve != null && curve.length > 0) {
p = curve.Evaluate(p);
}
src = temp + offset * p;
changeFun(src);
}, ignoreTime);
}
public static void ChangeValue(this Vector2 src, Vector2 dst, float duration, Action<Vector2> changeFun, AnimationCurve curve = null, bool ignoreTime = false, Action callback = null) {
Vector2 temp = src;
Vector2 offset = dst - src;
EventMgr.Ins.AddTimeEvent(duration, callback, (t, p) => {
if (curve != null && curve.length > 0) {
p = curve.Evaluate(p);
}
src = temp + offset * p;
changeFun(src);
}, ignoreTime);
}
public static void ChangeVaule(this Vector3 src, Vector3 dst, float duration, Action<Vector3> changeFun, AnimationCurve curve = null, bool ignoreTime = false, Action callback = null) {
Vector3 temp = src;
Vector3 offset = dst - src;
EventMgr.Ins.AddTimeEvent(duration, callback, (t, p) => {
if (curve != null && curve.length > 0) {
p = curve.Evaluate(p);
}
src = temp + offset * p;
changeFun(src);
}, ignoreTime);
}
public static void ChangeVaule(this Color src, Color dst, float duration, Action<Color> changeFun, AnimationCurve curve = null, bool ignoreTime = false, Action callback = null) {
Color temp = src;
Color offset = dst - src;
EventMgr.Ins.AddTimeEvent(duration, callback, (t, p) => {
if (curve != null && curve.length > 0) {
p = curve.Evaluate(p);
}
src = temp + offset * p;
changeFun(src);
}, ignoreTime);
}
}
}
|
afa4a13cda3cb310b45cd6d67f59e35fac7f2871
|
C#
|
pruebaSA/SA_UK
|
/wwwroot/widget.salonaddict.co.uk/System.Data.OracleClient/System/Data/OracleClient/DbSqlParserColumn.cs
| 2.734375
| 3
|
namespace System.Data.OracleClient
{
using System;
internal sealed class DbSqlParserColumn
{
private string _alias;
private string _columnName;
private string _databaseName;
private bool _isKey;
private bool _isUnique;
private string _schemaName;
private string _tableName;
internal DbSqlParserColumn(string databaseName, string schemaName, string tableName, string columnName, string alias)
{
this._databaseName = databaseName;
this._schemaName = schemaName;
this._tableName = tableName;
this._columnName = columnName;
this._alias = alias;
}
internal void CopySchemaInfoFrom(DbSqlParserColumn completedColumn)
{
this._databaseName = completedColumn.DatabaseName;
this._schemaName = completedColumn.SchemaName;
this._tableName = completedColumn.TableName;
this._columnName = completedColumn.ColumnName;
this._isKey = completedColumn.IsKey;
this._isUnique = completedColumn.IsUnique;
}
internal void CopySchemaInfoFrom(DbSqlParserTable table)
{
this._databaseName = table.DatabaseName;
this._schemaName = table.SchemaName;
this._tableName = table.TableName;
this._isKey = false;
this._isUnique = false;
}
internal void SetConstraint(ConstraintType constraintType)
{
switch (constraintType)
{
case ConstraintType.PrimaryKey:
this._isKey = true;
return;
case ConstraintType.UniqueKey:
case ConstraintType.UniqueConstraint:
this._isUnique = this._isKey = true;
return;
}
}
internal string ColumnName
{
get
{
if (this._columnName != null)
{
return this._columnName;
}
return string.Empty;
}
}
internal string DatabaseName
{
get
{
if (this._databaseName != null)
{
return this._databaseName;
}
return string.Empty;
}
}
internal bool IsAliased =>
(this._alias != null);
internal bool IsExpression =>
(this._columnName == null);
internal bool IsKey =>
this._isKey;
internal bool IsUnique =>
this._isUnique;
internal string SchemaName
{
get
{
if (this._schemaName != null)
{
return this._schemaName;
}
return string.Empty;
}
}
internal string TableName
{
get
{
if (this._tableName != null)
{
return this._tableName;
}
return string.Empty;
}
}
internal enum ConstraintType
{
PrimaryKey = 1,
UniqueConstraint = 3,
UniqueKey = 2
}
}
}
|
c5d6231f84f8c8a3d0205e40c986c7ceb06ed3cc
|
C#
|
alugili/Default-Interface-Methods-CSharp-8
|
/DefualtInterfaceMethodsDemo/SimpleExamples/DefaultInterfaceMethod.cs
| 2.78125
| 3
|
using System;
namespace DefualtInterfaceMethodsDemo.SimpleExamples
{
// ------------------------Default Interface Methods---------------------------
interface IDefualtInterfaceMethod
{
public void DefaultMethod()
{
Console.WriteLine("I’m a default method");
}
}
class DefaultInterfaceMethod : IDefualtInterfaceMethod
{
}
}
|
8849c8af8b359bc751db7db62cdda4e36bcea4a3
|
C#
|
skwasjer/MockHttp
|
/test/MockHttp.Json.Tests/Newtonsoft/NewtonsoftAdapterTests.cs
| 2.609375
| 3
|
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace MockHttp.Json.Newtonsoft;
public class NewtonsoftAdapterTests
{
[Theory]
[ClassData(typeof(SerializerTestCases))]
public void Given_an_object_when_serializing_it_should_return_expected(object value, string expectedJson)
{
var sut = new NewtonsoftAdapter();
// Act
string actual = sut.Serialize(value);
// Assert
actual.Should().Be(expectedJson);
}
[Fact]
public void Given_that_options_are_provided_when_serializing_it_should_honor_options()
{
object value = new { propertyName = "value" };
const string expectedJson = "{\"property_name\":\"value\"}";
var contractResolver = new DefaultContractResolver { NamingStrategy = new SnakeCaseNamingStrategy() };
var sut = new NewtonsoftAdapter(new JsonSerializerSettings { ContractResolver = contractResolver });
// Act
string actual = sut.Serialize(value);
// Assert
actual.Should().Be(expectedJson);
}
}
|
11d24c687e9f8acc865d179e8b380e6351af5b04
|
C#
|
abdonkov/HackBulgaria-CSharp
|
/Week05/ProblemSet-02-Inheritance/Animals/Animal.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Animals
{
abstract class Animal
{
public string Name { get; protected set; }
public abstract string Move();
public abstract string Eat();
public abstract string GiveBirth();
}
}
|
6c7980209dcea162ea5b947d49934e24d4a6c785
|
C#
|
carlosga/blatternfly
|
/src/blatternfly/GlobalHeightBreakpoints.cs
| 2.96875
| 3
|
namespace Blatternfly;
internal static class GlobalHeightBreakpoints
{
internal const int ExtraSmall = 0;
internal const int Small = 0;
internal const int Medium = 40; // 40rem
internal const int Large = 48; // 48rem
internal const int ExtraLarge = 60; // 60rem
internal const int ExtraLarge2 = 80; // 80rem
internal static Breakpoint? GetBreakpoint(int? height)
{
return height switch
{
null => null,
>= ExtraLarge2 => Breakpoint.ExtraLarge2,
>= ExtraLarge => Breakpoint.ExtraLarge,
>= Large => Breakpoint.Large,
>= Medium => Breakpoint.Medium,
>= Small => Breakpoint.Small,
_ => Breakpoint.Default
};
}
internal static string GetBreakpointString(int? height)
{
return height switch
{
null => null,
>= ExtraLarge2 => "2xl",
>= ExtraLarge => "xl",
>= Large => "lg",
>= Medium => "md",
>= Small => "sm",
_ => "default"
};
}
}
|
4f23ff147682274929860cc2987ad1aa23034dfb
|
C#
|
ZombieFleshEaters/LittleBreadLoaf
|
/littlebreadloaf/EmailHelper.cs
| 2.609375
| 3
|
using Microsoft.Extensions.Configuration;
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace littlebreadloaf
{
public static class EmailHelper
{
const string Mailgun_Api_Key_Preamble = "api:";
public static async Task<HttpResponseMessage> SendEmail(IConfiguration configuration,
string from,
string to,
string subject,
string message,
string attachmentName,
Stream attachment)
{
using (var client = new HttpClient { BaseAddress = new Uri(configuration["Mailgun.Uri.Base"]) })
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(Encoding.ASCII.GetBytes(Mailgun_Api_Key_Preamble + configuration["Mailgun.Private.APIKey"])));
var content = new MultipartFormDataContent
{
{ new StringContent(from), "from" },
{ new StringContent(to), "to" },
{ new StringContent(subject), "subject" },
{ new StringContent(message), "html" }
};
if (!string.IsNullOrEmpty(configuration["LittleBreadLoad.InternalEmail"]))
{
content.Add(new StringContent(configuration["LittleBreadLoad.InternalEmail"]), "bcc");
}
if (attachment != null)
{
content.Add(CreateAttachmentContent(attachment, attachmentName, "application/pdf"));
}
return await client.PostAsync($"{configuration["Mailgun.Uri.Request"]}/messages",
content).ConfigureAwait(false);
}
}
private static StreamContent CreateAttachmentContent(Stream stream, string fileName, string contentType)
{
var fileContent = new StreamContent(stream);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "\"attachment[]\"",
FileName = "\"" + fileName + "\""
}; // the extra quotes are key here
fileContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
return fileContent;
}
}
public class MailGunResponse
{
public string message { get; set; }
public string id { get; set; }
}
}
|
098fc26d909cd91249b5c427ee8dbf00bdf99d11
|
C#
|
btshft/Zeus
|
/src/Zeus/Shared/Try/Try.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Zeus.Shared.Try
{
public static class Try
{
public static Task<TryResult<T>[]> WhenAll<T>(IEnumerable<Task<T>> tasks)
{
var wrappedTasks = tasks.Select(
task => task.ContinueWith(
t => t.IsFaulted
? new TryResult<T>(t.Exception)
: new TryResult<T>(t.Result)));
return Task.WhenAll(wrappedTasks);
}
public static async Task<TryResult> ExecuteAsync(Func<Task> asyncAction)
{
try
{
await asyncAction();
return TryResult.Succeed;
}
catch (Exception e)
{
return new TryResult(e);
}
}
}
}
|
4bcfffc4ce28ce60425d31382ac53fcba6a13016
|
C#
|
ufjl0683/sshmc
|
/V2DLE/CmdItem.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Comm
{
public enum RangeType
{
Rannge,Select,Const
}
public class CmdItem
{
public RangeType RangeType;
public int Min, Max;
public SelectValue[] SelectValues;
public int Bytes;
public string ItemName;
public System.Collections.ArrayList SubItems = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList());
public CmdItem(string Name,int bytes, int lowvalue, int highValue)
{
this.RangeType = RangeType.Rannge;
Min = lowvalue;
Max = highValue;
this.Bytes = bytes;
this.ItemName = Name;
}
public CmdItem(string Name,int bytes, SelectValue[] selectValues)
{
this.RangeType = RangeType.Select;
this.SelectValues = selectValues;
this.Bytes = bytes;
this.ItemName = Name;
}
public CmdItem(string name, int bytes, int val)
{
this.RangeType = RangeType.Const;
Min = val;
Max = val;
this.Bytes = bytes;
this.ItemName = name;
}
public bool HasSubItems
{
get
{
return (SubItems.Count==0) ? false : true;
}
}
public void AddSubItems(CmdItem item)
{
SubItems.Add(item);
}
public int SubItemsCnt
{
get
{
return SubItems.Count;
}
}
public override string ToString()
{
//return base.ToString();
return string.Format("({0},{1},{2},SubItems={3})", ItemName, Bytes, RangeType, SubItemsCnt);
}
public Type DataType
{
get
{
switch (Bytes)
{
case 1:
return typeof(byte);
case 2:
return typeof(ushort);
case 3:
return typeof(uint);
case 4:
return typeof(uint);
//case 8:
// return typeof(ulong);
default:
return typeof(ulong);
}
}
}
}
}
|
2ee72101ddd9fa3b10a25abd6ee3e774894b2542
|
C#
|
Luminating/KSIS45
|
/CSaN/CSaN/HttpStorage/ServiceMethod/HttpMethodHead.cs
| 2.609375
| 3
|
using System;
using System.IO;
using System.Net;
using System.Text;
namespace HttpStorage.ServiceMethod
{
class HttpMethodHead : HttpServiceMethod
{
public HttpMethodHead() : base("HEAD")
{
}
public override void Handle(HttpListenerRequest request, HttpListenerResponse response)
{
base.Handle(request, response);
string relativepath = request.RawUrl.Trim('/');
if (File.Exists(relativepath))
{
FileInfo info = new FileInfo(relativepath);
response.ContentLength64 = info.Length;
response.Headers.Add("Content-Loaction", info.Name);
response.Headers.Add("Content-Type", info.Extension);
response.Headers.Add("Date", info.LastWriteTimeUtc.ToString());
}
else
{
response.StatusCode = 404;
response.ContentLength64 = 0;
}
response.OutputStream.Close();
}
}
}
|
b284d48880830e8e521260bbf23a093e90559ccd
|
C#
|
sh932111/BrainProject
|
/Stu/Stu/Manager/WordManager.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using Stu.Class;
namespace Stu.Manager
{
class WordManager
{
private JSONArray definitionList = null;/*詞性*/
private JSONArray translateList = null; /*詞性的解釋*/
private JSONArray exampleList = null; /*詞性的造句*/
private string enWord = null;
public int Count = -1;
private JSONObject wordItem = null;
public WordManager(JSONObject word_item)
{
this.wordItem = word_item;
this.definitionList = wordItem.getJSONArray("definitionList");
this.translateList = wordItem.getJSONArray("translateList");
this.exampleList = wordItem.getJSONArray("exampleList");
this.enWord = wordItem.getString("enWord");
this.Count = this.definitionList.Count;
}
public JSONObject getDefinition(int index)
{
return definitionList.getJSONObject(index);
}
public JSONObject getTranslate(int index)
{
return translateList.getJSONObject(index);
}
public JSONObject getExample(int index)
{
return exampleList.getJSONObject(index);
}
public string getWord()
{
return enWord;
}
}
}
|
2c778f630e0d882e3df14a6a6db1adefe9d183cc
|
C#
|
gugacoder/deckin
|
/Server/Keep.Paper/Design.Rendering/Choice.cs
| 2.921875
| 3
|
using System;
namespace Keep.Paper.Design.Rendering
{
/// <summary>
/// Directives
//
/// TYPE/SUBTYPE
/// A single, precise MIME type, like text/html.
///
/// TYPE/*
/// A MIME type, but without any subtype. image/* will match image/png, image/svg, image/gif and any other image types.
///
/// */*
/// Any MIME type
///
/// ;q= (q-factor weighting)
/// Any value used is placed in an order of preference expressed using relative quality value called the weight.
/// It varies from 0 to 1 up to 3 decimal positions.
/// The higher the value then the higher its priority.
/// Default is one.
/// </summary>
public class Choice
{
public string Value { get; set; }
public decimal Weight { get; set; }
public decimal WeightModifier =>
Value?.Contains("*/*") == true
? 0.0M
: Value?.Contains("*/") == true
? 0.3M
: Value?.Contains("/*") == true
? 0.6M
: 1.0M;
}
}
|
ec671a7f5cac93a5ddf7c62ef2c048d12ca9d8ac
|
C#
|
auriou/DataBusinessService
|
/DataBusinessService/Common/AutoProperty.cs
| 2.546875
| 3
|
using System;
namespace DataBusinessService.Common
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class AutoProperty : Attribute
{
public AutoProperty(string name, Type type)
{
Name = name;
Type = type;
}
public Type Type { get; private set; }
public string Name { get; private set; }
}
}
|
0a82167b0762b5c7425c0c4aa72aa1384b2ae0b3
|
C#
|
isscuss/learn.github.io
|
/ConsoleApplication3/线程池/Program.cs
| 2.8125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace 线程池
{
class Program
{
static void Test(object state)
{
Console.WriteLine("任务开始啦:" + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(2000);
Console.WriteLine("任务结束");
}
static void Main(string[] args)
{
ThreadPool.QueueUserWorkItem(Test);//开启一个工作线程
ThreadPool.QueueUserWorkItem(Test);//开启一个工作线程
ThreadPool.QueueUserWorkItem(Test);//开启一个工作线程
Console.WriteLine("这是主体线程");
ThreadPool.QueueUserWorkItem(Test);//开启一个工作线程;
ThreadPool.QueueUserWorkItem(Test);//开启一个工作线程
ThreadPool.QueueUserWorkItem(Test);//开启一个工作线程
ThreadPool.QueueUserWorkItem(Test);//开启一个工作线程
ThreadPool.QueueUserWorkItem(Test);//开启一个工作线程
Console.ReadKey();
}
}
}
|
58d5b7c651c847477dc41e5b22e809615e66c6bb
|
C#
|
JasonDevStudio/Cnita
|
/CnitaSolution/Common/Library.Common/EncryptDecrypt.cs
| 3.390625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
namespace Library.Common
{
public class EncryptDecrypt
{
#region 加/解密方法
private static string CryKey = "Xky_Lq_Py_Hu_Lp_Jhj_Zxt";//密钥
/// <summary>
/// 加密字符串
/// </summary>
public static string Encrypt(string PlainText)
{
System.Security.Cryptography.DESCryptoServiceProvider key = new System.Security.Cryptography.DESCryptoServiceProvider();
byte[] bk = System.Text.Encoding.Unicode.GetBytes(CryKey);
byte[] bs = new byte[8];
for (int i = 0; i < bs.Length; i++)
{
bs[i] = bk[i];
}
key.Key = bs;
key.IV = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.Security.Cryptography.CryptoStream encStream = new System.Security.Cryptography.CryptoStream(ms, key.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
System.IO.StreamWriter sw = new System.IO.StreamWriter(encStream);
sw.WriteLine(PlainText);
sw.Close();
encStream.Close();
byte[] buffer = ms.ToArray();
ms.Close();
string s = "";
for (int i = 0; i < buffer.Length; i++)
{
s += buffer[i].ToString("X2");
}
return s;
}
/// <summary>
/// 解密字符串
/// </summary>
public static string Decrypt(string CypherText)
{
System.Security.Cryptography.DESCryptoServiceProvider key = new System.Security.Cryptography.DESCryptoServiceProvider();
byte[] bk = System.Text.Encoding.Unicode.GetBytes(CryKey);
byte[] bs = new byte[8];
for (int i = 0; i < bs.Length; i++)
{
bs[i] = bk[i];
}
key.Key = bs;
key.IV = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
byte[] bc = new byte[CypherText.Length / 2];
for (int i = 0; i < bc.Length; i++)
{
try
{
bc[i] = Convert.ToByte(CypherText.Substring(2 * i, 2), 16);
}
catch { }
}
System.IO.MemoryStream ms = new System.IO.MemoryStream(bc);
System.Security.Cryptography.CryptoStream encStream = new System.Security.Cryptography.CryptoStream(ms, key.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Read);
System.IO.StreamReader sr = new System.IO.StreamReader(encStream);
string val = sr.ReadLine();
sr.Close();
encStream.Close();
ms.Close();
return val;
}
#endregion
#region 不可逆加密方法
/// <summary>
/// MD5加密不可逆
/// </summary>
/// <param name="str">要加密的字符窜</param>
/// <returns>返回加密后的字符窜</returns>
public static string EncryptByMD5Hash(string str)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] encryptedBytes = md5.ComputeHash(Encoding.ASCII.GetBytes(str));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < encryptedBytes.Length; i++)
{
sb.AppendFormat("{0:x2}", encryptedBytes[i]);
}
return sb.ToString();
//Encoding.ASCII.GetBytes(inputString)用于以ASCII方式将一个字符串转换成一个字节数组,
//原因是ComputeHash方法只接收Byte[]参数,后面的内容就是将加密后的Byte[]连成一个字符串,
//AppendFormat中的格式字符串{0:x2}是指将数组中每一个字符格式化为十六进制,精度为2
}
#endregion
}
}
|
d01114c8270c0eaeff698b63a98034c46c2ec03c
|
C#
|
Bajena/Miner
|
/Miner/GameInterface/MenuEntries/MenuEntry.cs
| 2.984375
| 3
|
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Miner.GameCore;
using Miner.GameInterface.GameScreens;
namespace Miner.GameInterface.MenuEntries
{
/// <summary>
/// Reprezentuje opcj w menu gry.
/// </summary>
public class MenuEntry
{
float _selectionFade;
private bool _isSelected;
/// <summary>
/// Czy opcja jest wybrana?
/// </summary>
public bool IsSelected
{
get { return _isSelected; }
private set
{
var temp = _isSelected;
_isSelected = value;
if (temp && !value)
OnDeselected();
else if (!temp && value)
OnSelected();
}
}
/// <summary>
/// Tekst opcji
/// </summary>
public string Text { get; set; }
/// <summary>
/// Pozycja na ekranie
/// </summary>
public Vector2 Position { get; set; }
/// <summary>
/// Zdarzenie wywoywane, kiedy uytkownik uruchomi t opcj
/// </summary>
public event EventHandler Entered;
/// <summary>
/// Metoda wywoujca zdarzenie Entered
/// </summary>
protected internal virtual void OnEnter()
{
if (Entered != null)
Entered(this, null);
}
/// <summary>
/// Zdarzenie wywoywane, gdy ta opcja staje si aktywna
/// </summary>
public event EventHandler Selected;
/// <summary>
/// Metoda wywoujca zdarzenie Selected
/// </summary>
protected internal virtual void OnSelected()
{
if (Selected != null)
Selected(this, null);
}
/// <summary>
/// Zdarzenie wywoywane, gdy ta opcja przestaje by aktywna
/// </summary>
public event EventHandler Deselected;
/// <summary>
/// Metoda wywoujca zdarzenie Deselected
/// </summary>
protected internal virtual void OnDeselected()
{
if (Deselected != null)
Deselected(this, null);
}
public MenuEntry(string text)
{
Text = text;
}
public virtual void Update(MenuScreen screen, bool isSelected, GameTime gameTime)
{
IsSelected = isSelected;
float fadeSpeed = (float)gameTime.ElapsedGameTime.TotalSeconds * 4;
_selectionFade = IsSelected ? Math.Min(_selectionFade + fadeSpeed, 1) : Math.Max(_selectionFade - fadeSpeed, 0);
}
public virtual void Draw(MenuScreen screen,GameTime gameTime)
{
Color color = IsSelected ? Color.Yellow : Color.White;
ScreenManager screenManager = screen.ScreenManager;
SpriteBatch spriteBatch = screenManager.SpriteBatch;
SpriteFont font = screenManager.Font;
Vector2 origin = new Vector2(0, font.LineSpacing / 2);
spriteBatch.DrawString(font, Text, Position, color, 0, origin, 1, SpriteEffects.None, 0);
}
public virtual int GetHeight(MenuScreen screen)
{
return screen.ScreenManager.Font.LineSpacing;
}
public virtual int GetWidth(MenuScreen screen)
{
return (int)screen.ScreenManager.Font.MeasureString(Text).X;
}
}
}
|
e857e601cdb50d16e484f0ac07e09daedfc5059e
|
C#
|
dburka001/SimulationFramework
|
/MicrosSimFramework.DataSource/MicroSim.DataSource.Entities/Enums/Gender.cs
| 3.28125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MicroSim.DataSource.Entities
{
/// <summary>
/// Gender enum
/// </summary>
public enum Gender : byte { Total, Male, Female }
/// <summary>
/// GenderExtensions
/// </summary>
public static class GenderExtensions
{
/// <summary>
/// Parses the specified gender.
/// </summary>
/// <param name="gender">The gender.</param>
/// <returns></returns>
/// <exception cref="System.NotImplementedException"></exception>
public static Gender Parse(string gender)
{
switch (gender)
{
case "T": return Gender.Total;
case "M": return Gender.Male;
case "F": return Gender.Female;
case "1": return Gender.Male;
case "2": return Gender.Female;
default: return (Gender)Enum.Parse(typeof(Gender), gender);
}
}
}
}
|
dc8352eea68fac275d3beadb198f7e461267fda4
|
C#
|
vmelamed/vm
|
/Aspects/Security/Cryptography/Ciphers/tests/NullStreamTest.cs
| 2.640625
| 3
|
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace vm.Aspects.Security.Cryptography.Ciphers.Tests
{
/// <summary>
/// Summary description for NullStreamTest
/// </summary>
[TestClass]
public class NullStreamTest
{
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext { get; set; }
#region Additional test attributes
//
// You can use the following additional attributes as you write your tests:
//
// Use ClassInitialize to run code before running the first test in the class
// [ClassInitialize()]
// public static void MyClassInitialize(TestContext testContext) { }
//
// Use ClassCleanup to run code after all tests in a class have run
// [ClassCleanup()]
// public static void MyClassCleanup() { }
//
// Use TestInitialize to run code before running each test
// [TestInitialize()]
// public void MyTestInitialize() { }
//
// Use TestCleanup to run code after each test has run
// [TestCleanup()]
// public void MyTestCleanup() { }
//
#endregion
[TestMethod]
public void ConstructorTest()
{
var target = new NullStream();
Assert.IsTrue(target.CanWrite);
Assert.IsTrue(target.CanRead);
Assert.IsFalse(target.CanSeek);
Assert.AreEqual(0, target.Position);
Assert.AreEqual(0, target.Length);
}
[TestMethod]
public void PositionTest()
{
var target = new NullStream();
Assert.AreEqual(0, target.Position);
target.Position = 10;
Assert.AreEqual(0, target.Position);
}
[TestMethod]
public void SetLengthTest()
{
var target = new NullStream();
Assert.AreEqual(0, target.Length);
target.SetLength(10);
Assert.AreEqual(0, target.Length);
}
[TestMethod]
public void ReadTest()
{
var target = new NullStream();
var buffer = new byte[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Assert.AreEqual(0, target.Read(buffer, 0, buffer.Length));
Assert.IsTrue(buffer.SequenceEqual(new byte[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }));
}
[TestMethod]
public void ReadAsyncTest()
{
var target = new NullStream();
var buffer = new byte[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Assert.AreEqual(0, target.ReadAsync(buffer, 0, buffer.Length).Result);
Assert.IsTrue(buffer.SequenceEqual(new byte[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }));
}
[TestMethod]
public void WriteTest()
{
var target = new NullStream();
var buffer = new byte[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Assert.AreEqual(0, target.Position);
Assert.AreEqual(0, target.Length);
target.Write(buffer, 0, buffer.Length);
Assert.AreEqual(0, target.Position);
Assert.AreEqual(0, target.Length);
}
[TestMethod]
public void WriteAsyncTest()
{
var target = new NullStream();
var buffer = new byte[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Assert.AreEqual(0, target.Position);
Assert.AreEqual(0, target.Length);
target.WriteAsync(buffer, 0, buffer.Length).Wait();
Assert.AreEqual(0, target.Position);
Assert.AreEqual(0, target.Length);
}
[TestMethod]
public void CopyToAsyncTest()
{
var target = new NullStream();
target.Write(new byte[] { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }, 0, 10);
using (var stream = new MemoryStream())
{
target.CopyToAsync(stream).Wait();
Assert.AreEqual(0, stream.Position);
Assert.AreEqual(0, stream.Length);
}
}
[TestMethod]
public void SeekTest()
{
var target = new NullStream();
Assert.AreEqual(0, target.Position);
target.Seek(10, SeekOrigin.Begin);
Assert.AreEqual(0, target.Position);
}
}
}
|
225ee53262122b71aa0e9a913fa4274ffcfebad7
|
C#
|
Stoyan66/Strings-and-Regex---Exercise
|
/Trainegram/Program.cs
| 3.1875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace Trainegram
{
class Program
{
static void Main(string[] args)
{
string input = Console.ReadLine();
string pattern = @"^(<\[[^A-Za-z0-9\n]*]\.)(\.\[[A-Za-z0-9]*]\.)*$";
// Знакът "^" значи всичко различно от посоченото след него. Знакът "*" значи, че може да го има 0 или повече пъти.
// Знакът "^" и "$" служат, за да се покаже началото и краят на стринга.
// Полза се multiline в Regex101
// \n - нов ред.
while (input != "Traincode!")
{
if (Regex.IsMatch(input, pattern))
{
Console.WriteLine(input);
}
input = Console.ReadLine();
}
}
}
}
|
200ee1ae3e6a6452ade2e20999190407ffa7e580
|
C#
|
firatozbay/UnityPoolManager
|
/Assets/Scripts/Poolee.cs
| 2.8125
| 3
|
using UnityEngine;
namespace PoolSystem
{
public class Poolee : MonoBehaviour
{
public PoolType PoolType { get; private set; }
public int Key { get; private set; }
private ISpawnable[] _spawnables;
private IDespawnable[] _despawnables;
public void Init(PoolType poolType, int key)
{
PoolType = poolType;
Key = key;
_spawnables = GetComponentsInChildren<ISpawnable>();
_despawnables = GetComponentsInChildren<IDespawnable>();
}
public void Spawn()
{
foreach (var spawnable in _spawnables)
{
spawnable.OnSpawn();
}
gameObject.SetActive(true);
}
public void Despawn()
{
foreach (var despawnable in _despawnables)
{
despawnable.OnDespawn();
}
gameObject.SetActive(false);
}
}
}
|
9011660ed9e0f5db060fceafde0ef1b1335b0da0
|
C#
|
hon454/MyUnityLibrary
|
/Assets/Scripts/MyUnityLibrary/Managers/GameSpeedManager.cs
| 2.75
| 3
|
using System.Collections;
using MyUnityLibrary.Patterns;
using MyUnityLibrary.Utilities;
using UnityEngine;
public sealed class GameSpeedManager : MonoSingleton<GameSpeedManager>
{
public float DefaultTimeScale { get; set; } = 1f;
public bool CanChangeGameSpeed { get; set; } = true;
public bool CanInterrupt { get; set; } = true;
private Coroutine _coroutine;
public void ResetGameSpeed()
{
Time.timeScale = DefaultTimeScale;
}
public void PauseGame()
{
Time.timeScale = 0f;
}
public void StopChangingGameSpeed()
{
if (_coroutine == null)
{
return;
}
StopCoroutine(_coroutine);
_coroutine = null;
ResetGameSpeed();
}
public void ChangeGameSpeed(float timeScale)
{
Time.timeScale = timeScale;
}
public void ChangeGameSpeedForSeconds(float durationSeconds, float timeScale)
{
if (!CanChangeGameSpeed)
{
return;
}
if (_coroutine != null && !CanInterrupt)
{
if (!CanInterrupt)
{
return;
}
StopCoroutine(_coroutine);
}
_coroutine = StartCoroutine(ChangeGameSpeedForSecondsRoutine(durationSeconds, timeScale));
}
public void ChangeGameSpeedForAnimationCurve(float durationSeconds, AnimationCurve animationCurve)
{
if (!CanChangeGameSpeed)
{
return;
}
if (_coroutine != null && !CanInterrupt)
{
if (!CanInterrupt)
{
return;
}
StopCoroutine(_coroutine);
}
_coroutine = StartCoroutine(ChangeGameSpeedForAnimationCurveRoutine(durationSeconds, animationCurve));
}
private IEnumerator ChangeGameSpeedForSecondsRoutine(float durationSeconds, float timeScale)
{
Time.timeScale = timeScale;
yield return new WaitForRealSeconds(durationSeconds);
ResetGameSpeed();
_coroutine = null;
}
private IEnumerator ChangeGameSpeedForAnimationCurveRoutine(float durationSeconds, AnimationCurve animationCurve)
{
float beginRealtime = Time.realtimeSinceStartup;
while (Time.realtimeSinceStartup - beginRealtime < durationSeconds)
{
float time = (Time.realtimeSinceStartup - beginRealtime) / durationSeconds;
Time.timeScale = Mathf.Clamp(animationCurve.Evaluate(time), 0f, 1f);
yield return null;
}
ResetGameSpeed();
_coroutine = null;
}
}
|
442a990d09eb2f8c88d99bf81f81677ba2198389
|
C#
|
shendongnian/download4
|
/code6/971302-24636066-68904719-2.cs
| 3.203125
| 3
|
int v = int.Parse(Console.ReadLine());
for (int i= 0; i <= arr1.Length -1; i++)
{
if (arr1[i] == v) {
Console.Write(arr1[i].ToString() + " ");
}
}
Console.WriteLine();
|
5c7a421ab83d99aade967978e89d43d09a2ce96e
|
C#
|
HubertSpringer/BlockCipher
|
/Szyfrator/Form1.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Szyfrator
{
public partial class Form1 : Form
{
Nihilist nihilist ;
Options options;
public Form1()
{
InitializeComponent();
nihilist = new Nihilist();
options = new Options();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private string load_File()
{
Stream myStream = null;
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.RestoreDirectory = true;
openFileDialog.InitialDirectory = "C:\\";
openFileDialog.Filter = "txt files (*.txt)|*.txt";
openFileDialog.FilterIndex = 1;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog.OpenFile()) != null)
{
using (myStream)
{
byte[] buffer = new byte[myStream.Length + 10];
myStream.Read(buffer, 0, (int)myStream.Length);
return System.Text.Encoding.Default.GetString(buffer);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
return null;
}
private void save_File(String message)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "txt files (*.txt)|*.txt";
saveFileDialog.FilterIndex = 1;
saveFileDialog.RestoreDirectory = true;
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
File.WriteAllText(saveFileDialog.FileName,message);
}
}
private void defaultToolStripMenuItem_Click(object sender, EventArgs e)
{
text_box_keyword.Text = "WORDS";
text_box_message.Text = "an example of transposition";
}
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
//nie uzywane
}
private void keywordToolStripMenuItem_Click(object sender, EventArgs e)
{
text_box_keyword.Text = load_File();
}
private void messageToolStripMenuItem_Click(object sender, EventArgs e)
{
text_box_message.Text = load_File();
}
private void cryptogramToolStripMenuItem_Click(object sender, EventArgs e)
{
text_box_cryptogram.Text = load_File();
}
private void keywordToolStripMenuItem1_Click(object sender, EventArgs e)
{
save_File(text_box_keyword.Text);
}
private void messageToolStripMenuItem1_Click(object sender, EventArgs e)
{
save_File(text_box_message.Text);
}
private void button_encrypt_Click_1(object sender, EventArgs e)
{
options_update();
text_box_cryptogram.Text = nihilist.encrypt(text_box_keyword.Text, text_box_message.Text,options);
label_cryptogram_2.Text = text_box_cryptogram.Text.Length.ToString();
}
private void button_decrypt_Click_1(object sender, EventArgs e)
{
options_update();
text_box_message.Text = nihilist.decrypt(text_box_keyword.Text, text_box_cryptogram.Text, options);
label_message_2.Text = text_box_message.Text.Length.ToString();
}
private void cryptogramToolStripMenuItem1_Click_1(object sender, EventArgs e)
{
save_File(text_box_cryptogram.Text);
}
private void text_box_keyword_TextChanged(object sender, EventArgs e)
{
label_keyword_2.Text = text_box_keyword.Text.Length.ToString();
}
private void text_box_message_TextChanged(object sender, EventArgs e)
{
label_message_2.Text = text_box_message.Text.Length.ToString();
}
private void options_update()
{
options.update(checkBox1.Checked, checkBox2.Checked, checkBox3.Checked, checkBox4.Checked,text_box_cryptogram_replace.Text);
}
private void label3_Click(object sender, EventArgs e)
{
}
}
}
|
053e896e8bc0c749d3f42ada23ac2245d1a0669a
|
C#
|
jpiv/RouglelikeCardGame
|
/Library/Collab/Download/Assets/Scripts/RockEl.cs
| 2.59375
| 3
|
using System.Collections.Generic;
using UnityEngine;
public class RockEl : Enemy {
private float spawnHP = 0f;
private bool hasSplit = false;
public override void TakeDamage(float damage) {
float baseHP = this.GetHP();
base.TakeDamage(damage);
float splitPoint = 0.25f;
float spawnHPMultiplier = 0.125f;
if (this.GetHP() <= splitPoint * this.GetMaxHP() && !this.hasSplit) {
this.spawnHP = spawnHPMultiplier * baseHP;
this.SetHP(0f);
this.hasSplit = true;
}
}
public override void OnDeath() {
List<Enemy> spawnedEls = Battlefield.instance.AddEnemies(
new List<GameObject>(new GameObject[2] { Enemies.allEnemies[2], Enemies.allEnemies[2] })
);
foreach (Enemy spawnedEl in spawnedEls) {
Timer.TimeoutAction(() => spawnedEl.SetHP(this.spawnHP), 0f);
}
}
}
|
b1c8a567c4e63e380a65fbd00548ed9528b9dcf0
|
C#
|
beatthat/property-interfaces
|
/Runtime/property-interfaces/InvocableExt.cs
| 2.734375
| 3
|
using BeatThat.TransformPathExt;
using UnityEngine;
namespace BeatThat.Properties{
public static class InvocableExt
{
/// <summary>
/// ext method lets you call a sibling <c>Invocable</c> like this:
///
/// <c>
/// this.Invoke<MyInvocableComp>();
/// </c>
/// </summary>
public static void Invoke<T>(this Component c,
MissingComponentOptions opts = MissingComponentOptions.AddAndWarn) where T : Component, Invocable
{
if(c == null) {
Debug.LogWarning("Invoke " + typeof(T) + " called on null component");
return;
}
var invocable = c.GetComponent<T>();
if(invocable != null) {
invocable.Invoke();
return;
}
switch(opts) {
case MissingComponentOptions.Add:
invocable = c.gameObject.AddComponent<T>();
invocable.Invoke();
break;
case MissingComponentOptions.AddAndWarn:
Debug.LogWarning("Adding missing component of type " + typeof(T).Name + " to " + c.Path());
invocable = c.gameObject.AddComponent<T>();
invocable.Invoke();
break;
case MissingComponentOptions.CancelAndWarn:
Debug.LogWarning("Failed to set property on " + c.Path() + " due to missing component of type " + typeof(T).Name);
break;
case MissingComponentOptions.ThrowException:
throw new MissingComponentException("Failed to set property on " + c.Path() + " due to missing component of type " + typeof(T).Name);
}
}
}
}
|
264c3c189eaec6d10a6a9d9a32b5bfd20e69d739
|
C#
|
huysentruitw/barcoder
|
/src/Barcoder/DataMatrix/DataMatrixCode.cs
| 2.828125
| 3
|
using Barcoder.Utils;
namespace Barcoder.DataMatrix
{
public sealed class DataMatrixCode : IBarcode
{
private readonly CodeSize _size;
private readonly BitList _data;
internal DataMatrixCode(CodeSize size)
{
_size = size;
Bounds = new Bounds(size.Columns, size.Rows);
Metadata = new Metadata(BarcodeType.DataMatrix, 2);
_data = new BitList(size.Rows * size.Columns);
}
internal void Set(int x, int y, bool value)
=> _data.SetBit(x * _size.Rows + y, value);
internal bool Get(int x, int y)
=> _data.GetBit(x * _size.Rows + y);
public string Content { get; internal set; }
public Bounds Bounds { get; }
public int Margin => 5;
public Metadata Metadata { get; }
public bool At(int x, int y) => Get(x, y);
}
}
|
47eec48c8cd346393ad4bd71bf9e9aa8b37e806a
|
C#
|
hncoffee/MVCTest
|
/MVCTest/Controllers/EmployeeController.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC.Models;
using MVC.ViewModels;
namespace MVC.Controllers
{
public class EmployeeController : Controller
{
// GET: Test
public string GetString()
{
return "Hello World is old now, It's time for wassup bro;";
}
//public ActionResult GetView()
//{
// Employee emp = new Employee();
// emp.FirstName = "Alisha";
// emp.LastName = "Marla";
// emp.Salary = 4853;
// EmployeeViewModel vmEmp = new EmployeeViewModel();
// vmEmp.EmployeeName = emp.FirstName + " " + emp.LastName;
// vmEmp.Salary = emp.Salary.ToString("C");
// if (emp.Salary > 5500)
// {
// vmEmp.SalaryColor = "yellow";
// }
// else
// {
// vmEmp.SalaryColor = "green";
// }
// return View("MyView", vmEmp);
//}
public ActionResult Index()
{
EmployeeListViewModel empListViewModel = new EmployeeListViewModel();
EmployeeBusinessLayer empBal = new EmployeeBusinessLayer();
List<Employee> employees = empBal.GetEmployees();
List<EmployeeViewModel> empViewModels = new List<EmployeeViewModel>();
foreach(Employee emp in employees)
{
EmployeeViewModel empViewModel = new EmployeeViewModel();
empViewModel.EmployeeName = emp.FirstName + " " + emp.LastName;
empViewModel.Salary = emp.Salary.ToString("C");
if(emp.Salary>5000)
{ empViewModel.SalaryColor = "yellow"; }
else
{ empViewModel.SalaryColor = "green"; }
empViewModels.Add(empViewModel);
}
empListViewModel.Employees = empViewModels;
empListViewModel.UserName = "Admin";
return View("Index", empListViewModel);
}
public ActionResult AddNew()
{
return View("CreateEmployee");
}
public ActionResult SaveEmployee(Employee e, string BtnSubmit)
{
switch(BtnSubmit)
{
case "Save Employee":
EmployeeBusinessLayer empBal = new EmployeeBusinessLayer();
empBal.SaveEmployee(e);
return RedirectToAction("Index");
case "Cancel":
return RedirectToAction("Index");
}
return new EmptyResult();
}
}
}
|
3a46acc40caa99d556defc71c57876b41a9c762f
|
C#
|
danielfbolin/NewMonopoly-WTAMU-2020
|
/Assets/Scripts/GamePlay/ChangeColor.cs
| 2.703125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChangeColor : MonoBehaviour
{
Transform[] childObjects;
public List<Transform> childColorList = new List<Transform>();
void OnDrawGizmos()
{
Gizmos.color = Color.red;
FillNodes();
for( int i=0; i< childColorList.Count; i++)
{
Vector3 currentPos = childColorList[i].position;
if(i>0)
{
Vector3 prePos = childColorList[i-1].position;
Gizmos.DrawLine(prePos,currentPos);
}
}
}
void FillNodes()
{
childColorList.Clear();
childObjects = GetComponentsInChildren<Transform>();
foreach (Transform child in childObjects)
{
if ( child != this.transform)
{
childColorList.Add(child);
}
}
}
}
|
dabe7edbcf7de0c0b5cae1ae9bb9ea87a22c69b4
|
C#
|
carlos8520/dataStructure
|
/PracticaListasDobles/PracticaVectoresOrdenados/PracticaVectoresOrdenados/Producto.cs
| 3.09375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PracticaVectoresOrdenados
{
class Producto
{
private int _id;
private string _nombre;
private int _cantidad;
private int _costo;
private Producto _atras;
private Producto _siguiente;
public int id
{
get { return _id; }
}
public string nombre
{
get { return _nombre; }
}
public int cantidad
{
get { return _cantidad; }
}
public int costo
{
get { return _costo; }
}
public Producto atras
{
get { return _atras; }
set { _atras = value; }
}
public Producto siguiente
{
get { return _siguiente; }
set { _siguiente = value; }
}
public Producto(int id, string nombre, int cantidad, int costo)
{
_id = id;
_nombre = nombre;
_cantidad = cantidad;
_costo = costo;
_siguiente = null;
_atras = null;
}
public override string ToString()
{
return "El id del producto es: " + _id + ", el nombre es: " + _nombre +
", la cantidad de stock del producto es: " + _cantidad + " y su costo por unidad: $" + _costo;
}
}
}
|
c35686412a0e0d7b4a86c94302512030e6bb0461
|
C#
|
ziyunhx/storm-net-adapter
|
/src/Storm.Net.Adapter/Data/Command.cs
| 2.53125
| 3
|
using System.Collections.Generic;
namespace Storm
{
public class Command
{
/// <summary>
/// the command type.
/// </summary>
public string command { set; get; }
/// <summary>
/// The id for the tuple. Leave this out for an unreliable emit. The id can be a string or a number.
/// </summary>
public string id { set; get; }
/// <summary>
/// The id of the stream this tuple was emitted to. Leave this empty to emit to default stream.
/// </summary>
public string stream { set; get; }
/// <summary>
/// If doing an emit direct, indicate the task to send the tuple to
/// </summary>
public int task { set; get; }
/// <summary>
/// All the values in this tuple
/// </summary>
public object[] tuple { set; get; }
/// <summary>
/// the message to log
/// </summary>
public string msg { set; get; }
/// <summary>
/// The id of the component that created this tuple
/// </summary>
public string comp { set; get; }
}
}
|
74aee1c35a1f128cc1f1730d5249e9712cdf1929
|
C#
|
Pride7K/C-sharp-Estudo
|
/Herancas/ByteBank/ByteBank/Funcionarios/Gerente.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using ByteBank.Sistemas;
namespace ByteBank.Funcionarios
{
public class Gerente: FuncionarioAutenticavel
{
public Gerente(double salario,string cpf) : base(salario,cpf)
{
Salario = salario;
CPF = cpf;
}
public override void AumentarSalario()
{
Salario = Salario + ((5 / 100) * Salario);
}
public override double GetBonificacao()
{
return Salario * 0.25;
}
}
}
|
9bc0ed327f1d0d970766c20d580e2df91c9e8dce
|
C#
|
sebnor31/CSharp-Tutorials
|
/C# For Programmers/PracticeExamples/MaximumFinder/MaximumFinder.cs
| 4.03125
| 4
|
public class MaximumFinder
{
public void DetermineMaximum()
{
// Prompt for and input three floating-point values
System.Console.WriteLine("Enter 3 floating-point values:\n");
double number1 = System.Convert.ToDouble( System.Console.ReadLine() );
double number2 = System.Convert.ToDouble( System.Console.ReadLine() );
double number3 = System.Convert.ToDouble( System.Console.ReadLine() );
// Determine the maximum value
double max = Maximum(number1, number2, number3);
// Display maximum value
System.Console.WriteLine("Maximum is: " + max);
}// end method DetermineMaximum
private double Maximum(double x, double y, double z)
{
double max;
max = System.Math.Max(x, y);
max = System.Math.Max(max, z);
return max;
}// end method Maximum
}// end class MaximumFinder
|
468241955fc9a356c0f68955a2682d2a53a39645
|
C#
|
esd-org-uk/flexible-open-geographies
|
/Esd.FlexibleOpenGeographies/UnitsOfWork/DeleteAreaTypeResource.cs
| 2.65625
| 3
|
using System.Linq;
namespace Esd.FlexibleOpenGeographies.UnitsOfWork
{
internal class DeleteAreaTypeResource : IUnitOfWork
{
private readonly IContextFactory _contextFactory;
private readonly int _resourceId;
public DeleteAreaTypeResource(IContextFactory contextFactory, int resourceId)
{
_contextFactory = contextFactory;
_resourceId = resourceId;
}
public void Execute()
{
using (var context = _contextFactory.Create())
{
var resource = context.AreaTypeResources.SingleOrDefault(x => x.AreaTypeResourceId == _resourceId);
if (resource == null) return;
context.AreaTypeResources.Remove(resource);
context.SaveChanges();
}
}
}
}
|
c6292051b25a3aef45116e32a24c064f0efdfe5b
|
C#
|
PollockT/BitSlicerSharp
|
/Slicer.Engine.Scanning/Snapshots/SnapshotElementComparer.cs
| 2.65625
| 3
|
using Slicer.Engine.Scanning.Scanners.Constraints;
namespace Slicer.Engine.Scanning.Snapshots
{
using Squalr.Engine.Common.DataTypes;
using Squalr.Engine.Common.Extensions;
using Scanning.Scanners.Constraints;
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
/// <summary>
/// Defines a reference to an element within a snapshot region.
/// </summary>
public class SnapshotElementComparer
{
/// <summary>
/// Initializes a new instance of the <see cref="SnapshotElementComparer" /> class.
/// </summary>
/// <param name="region">The parent region that contains this element.</param>
/// <param name="pointerIncrementMode">The method by which to increment element pointers.</param>
/// <param name="constraints">The constraints to use for the element comparisons.</param>
public unsafe SnapshotElementComparer(SnapshotRegion region, PointerIncrementMode pointerIncrementMode, DataTypeBase dataType)
{
this.Region = region;
this.CurrentTypeCode = Type.GetTypeCode(dataType);
// The garbage collector can relocate variables at runtime. Since we use unsafe pointers, we need to keep these pinned
this.CurrentValuesHandle = GCHandle.Alloc(this.Region.ReadGroup.CurrentValues, GCHandleType.Pinned);
this.PreviousValuesHandle = GCHandle.Alloc(this.Region.ReadGroup.PreviousValues, GCHandleType.Pinned);
this.InitializePointers();
this.SetConstraintFunctions();
this.SetPointerFunction(pointerIncrementMode);
}
/// <summary>
/// Initializes a new instance of the <see cref="SnapshotElementComparer" /> class.
/// </summary>
/// <param name="region">The parent region that contains this element.</param>
/// <param name="pointerIncrementMode">The method by which to increment element pointers.</param>
/// <param name="constraints">The constraints to use for the element comparisons.</param>
public unsafe SnapshotElementComparer(SnapshotRegion region, PointerIncrementMode pointerIncrementMode, Constraint constraints, DataTypeBase dataType) : this(region, pointerIncrementMode, dataType)
{
this.ElementCompare = this.BuildCompareActions(constraints);
}
/// <summary>
/// Finalizes an instance of the <see cref="SnapshotElementComparer" /> class.
/// </summary>
~SnapshotElementComparer()
{
// Let the GC do what it wants now
this.CurrentValuesHandle.Free();
this.PreviousValuesHandle.Free();
}
/// <summary>
/// Gets an action to increment only the needed pointers.
/// </summary>
public Action IncrementPointers { get; private set; }
/// <summary>
/// Gets an action based on the element iterator scan constraint.
/// </summary>
public Func<Boolean> ElementCompare { get; private set; }
/// <summary>
/// Gets a function which determines if this element has changed.
/// </summary>
private Func<Boolean> Changed { get; set; }
/// <summary>
/// Gets a function which determines if this element has not changed.
/// </summary>
private Func<Boolean> Unchanged { get; set; }
/// <summary>
/// Gets a function which determines if this element has increased.
/// </summary>
private Func<Boolean> Increased { get; set; }
/// <summary>
/// Gets a function which determines if this element has decreased.
/// </summary>
private Func<Boolean> Decreased { get; set; }
/// <summary>
/// Gets a function which determines if this element has a value equal to the given value.
/// </summary>
private Func<Object, Boolean> EqualToValue { get; set; }
/// <summary>
/// Gets a function which determines if this element has a value not equal to the given value.
/// </summary>
private Func<Object, Boolean> NotEqualToValue { get; set; }
/// <summary>
/// Gets a function which determines if this element has a value greater than to the given value.
/// </summary>
private Func<Object, Boolean> GreaterThanValue { get; set; }
/// <summary>
/// Gets a function which determines if this element has a value greater than or equal to the given value.
/// </summary>
private Func<Object, Boolean> GreaterThanOrEqualToValue { get; set; }
/// <summary>
/// Gets a function which determines if this element has a value less than to the given value.
/// </summary>
private Func<Object, Boolean> LessThanValue { get; set; }
/// <summary>
/// Gets a function which determines if this element has a value less than to the given value.
/// </summary>
private Func<Object, Boolean> LessThanOrEqualToValue { get; set; }
/// <summary>
/// Gets a function which determines if the element has increased it's value by the given value.
/// </summary>
private Func<Object, Boolean> IncreasedByValue { get; set; }
/// <summary>
/// Gets a function which determines if the element has decreased it's value by the given value.
/// </summary>
private Func<Object, Boolean> DecreasedByValue { get; set; }
/// <summary>
/// Enums determining which pointers need to be updated every iteration.
/// </summary>
public enum PointerIncrementMode
{
/// <summary>
/// Increment all pointers.
/// </summary>
AllPointers,
/// <summary>
/// Only increment current and previous value pointers.
/// </summary>
ValuesOnly,
/// <summary>
/// Only increment label pointers.
/// </summary>
LabelsOnly,
/// <summary>
/// Only increment current value pointer.
/// </summary>
CurrentOnly,
/// <summary>
/// Increment all pointers except the previous value pointer.
/// </summary>
NoPrevious,
}
/// <summary>
/// Gets the base address of this element.
/// </summary>
public UInt64 BaseAddress
{
get
{
return this.Region.BaseAddress.Add(this.ElementIndex);
}
}
/// <summary>
/// Gets or sets the label associated with this element.
/// </summary>
public Object ElementLabel
{
get
{
return this.Region.ReadGroup.ElementLabels[this.CurrentLabelIndex];
}
set
{
this.Region.ReadGroup.ElementLabels[this.CurrentLabelIndex] = value;
}
}
/// <summary>
/// Gets or sets a garbage collector handle to the current value array.
/// </summary>
private GCHandle CurrentValuesHandle { get; set; }
/// <summary>
/// Gets or sets a garbage collector handle to the previous value array.
/// </summary>
private GCHandle PreviousValuesHandle { get; set; }
/// <summary>
/// Gets or sets the parent snapshot region.
/// </summary>
private SnapshotRegion Region { get; set; }
/// <summary>
/// Gets or sets the pointer to the current value.
/// </summary>
private unsafe Byte* CurrentValuePointer { get; set; }
/// <summary>
/// Gets or sets the pointer to the previous value.
/// </summary>
private unsafe Byte* PreviousValuePointer { get; set; }
/// <summary>
/// Gets or sets the index of this element, used for setting and getting the label.
/// Note that we cannot have a pointer to the label, as it is a non-blittable type.
/// </summary>
private Int32 CurrentLabelIndex { get; set; }
/// <summary>
/// Gets the index of this element.
/// </summary>
private unsafe Int32 ElementIndex
{
get
{
// Use the incremented current value pointer or label index to figure out the index of this element
if (this.CurrentLabelIndex != 0)
{
return this.CurrentLabelIndex;
}
else if (this.CurrentValuePointer != null)
{
fixed (Byte* pointerBase = &this.Region.ReadGroup.CurrentValues[this.Region.ReadGroupOffset])
{
return (Int32)(this.CurrentValuePointer - pointerBase);
}
}
else if (this.PreviousValuePointer != null)
{
fixed (Byte* pointerBase = &this.Region.ReadGroup.PreviousValues[this.Region.ReadGroupOffset])
{
return (Int32)(this.PreviousValuePointer - pointerBase);
}
}
else
{
return 0;
}
}
}
/// <summary>
/// Gets or sets the type code associated with the data type of this element.
/// </summary>
private TypeCode CurrentTypeCode { get; set; }
/// <summary>
/// Sets a custom comparison function to use in scanning.
/// </summary>
/// <param name="customCompare"></param>
public void SetCustomCompareAction(Func<Boolean> customCompare)
{
this.ElementCompare = customCompare;
}
/// <summary>
/// Gets the current value of this element.
/// </summary>
/// <returns>The current value of this element.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe Object GetCurrentValue()
{
return this.LoadValue(this.CurrentValuePointer);
}
/// <summary>
/// Gets the previous value of this element.
/// </summary>
/// <returns>The previous value of this element.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe Object GetPreviousValue()
{
return this.LoadValue(this.PreviousValuePointer);
}
/// <summary>
/// Gets the label of this element.
/// </summary>
/// <returns>The label of this element.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe Object GetElementLabel()
{
return this.Region.ReadGroup.ElementLabels == null ? null : this.Region.ReadGroup.ElementLabels[this.CurrentLabelIndex];
}
/// <summary>
/// Sets the label of this element.
/// </summary>
/// <param name="newLabel">The new element label.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void SetElementLabel(Object newLabel)
{
this.Region.ReadGroup.ElementLabels[this.CurrentLabelIndex] = newLabel;
}
/// <summary>
/// Determines if this element has a current value associated with it.
/// </summary>
/// <returns>True if a current value is present.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe Boolean HasCurrentValue()
{
if (this.CurrentValuePointer == (Byte*)0)
{
return false;
}
return true;
}
/// <summary>
/// Determines if this element has a previous value associated with it.
/// </summary>
/// <returns>True if a previous value is present.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe Boolean HasPreviousValue()
{
if (this.PreviousValuePointer == (Byte*)0)
{
return false;
}
return true;
}
/// <summary>
/// Initializes snapshot value reference pointers
/// </summary>
private unsafe void InitializePointers()
{
this.CurrentLabelIndex = 0;
if (this.Region.ReadGroup.CurrentValues != null && this.Region.ReadGroup.CurrentValues.Length > 0)
{
fixed (Byte* pointerBase = &this.Region.ReadGroup.CurrentValues[this.Region.ReadGroupOffset])
{
this.CurrentValuePointer = pointerBase;
}
}
else
{
this.CurrentValuePointer = null;
}
if (this.Region.ReadGroup.PreviousValues != null && this.Region.ReadGroup.PreviousValues.Length > 0)
{
fixed (Byte* pointerBase = &this.Region.ReadGroup.PreviousValues[this.Region.ReadGroupOffset])
{
this.PreviousValuePointer = pointerBase;
}
}
else
{
this.PreviousValuePointer = null;
}
}
/// <summary>
/// Initializes all constraint functions for value comparisons.
/// </summary>
private unsafe void SetConstraintFunctions()
{
switch (this.CurrentTypeCode)
{
case TypeCode.Byte:
this.Changed = () => { return *this.CurrentValuePointer != *this.PreviousValuePointer; };
this.Unchanged = () => { return *this.CurrentValuePointer == *this.PreviousValuePointer; };
this.Increased = () => { return *this.CurrentValuePointer > *this.PreviousValuePointer; };
this.Decreased = () => { return *this.CurrentValuePointer < *this.PreviousValuePointer; };
this.EqualToValue = (value) => { return *this.CurrentValuePointer == (Byte)value; };
this.NotEqualToValue = (value) => { return *this.CurrentValuePointer != (Byte)value; };
this.GreaterThanValue = (value) => { return *this.CurrentValuePointer > (Byte)value; };
this.GreaterThanOrEqualToValue = (value) => { return *this.CurrentValuePointer >= (Byte)value; };
this.LessThanValue = (value) => { return *this.CurrentValuePointer < (Byte)value; };
this.LessThanOrEqualToValue = (value) => { return *this.CurrentValuePointer <= (Byte)value; };
this.IncreasedByValue = (value) => { return *this.CurrentValuePointer == unchecked(*this.PreviousValuePointer + (Byte)value); };
this.DecreasedByValue = (value) => { return *this.CurrentValuePointer == unchecked(*this.PreviousValuePointer - (Byte)value); };
break;
case TypeCode.SByte:
this.Changed = () => { return *(SByte*)this.CurrentValuePointer != *(SByte*)this.PreviousValuePointer; };
this.Unchanged = () => { return *(SByte*)this.CurrentValuePointer == *(SByte*)this.PreviousValuePointer; };
this.Increased = () => { return *(SByte*)this.CurrentValuePointer > *(SByte*)this.PreviousValuePointer; };
this.Decreased = () => { return *(SByte*)this.CurrentValuePointer < *(SByte*)this.PreviousValuePointer; };
this.EqualToValue = (value) => { return *(SByte*)this.CurrentValuePointer == (SByte)value; };
this.NotEqualToValue = (value) => { return *(SByte*)this.CurrentValuePointer != (SByte)value; };
this.GreaterThanValue = (value) => { return *(SByte*)this.CurrentValuePointer > (SByte)value; };
this.GreaterThanOrEqualToValue = (value) => { return *(SByte*)this.CurrentValuePointer >= (SByte)value; };
this.LessThanValue = (value) => { return *(SByte*)this.CurrentValuePointer < (SByte)value; };
this.LessThanOrEqualToValue = (value) => { return *(SByte*)this.CurrentValuePointer <= (SByte)value; };
this.IncreasedByValue = (value) => { return *(SByte*)this.CurrentValuePointer == unchecked(*(SByte*)this.PreviousValuePointer + (SByte)value); };
this.DecreasedByValue = (value) => { return *(SByte*)this.CurrentValuePointer == unchecked(*(SByte*)this.PreviousValuePointer - (SByte)value); };
break;
case TypeCode.Int16:
this.Changed = () => { return *(Int16*)this.CurrentValuePointer != *(Int16*)this.PreviousValuePointer; };
this.Unchanged = () => { return *(Int16*)this.CurrentValuePointer == *(Int16*)this.PreviousValuePointer; };
this.Increased = () => { return *(Int16*)this.CurrentValuePointer > *(Int16*)this.PreviousValuePointer; };
this.Decreased = () => { return *(Int16*)this.CurrentValuePointer < *(Int16*)this.PreviousValuePointer; };
this.EqualToValue = (value) => { return *(Int16*)this.CurrentValuePointer == (Int16)value; };
this.NotEqualToValue = (value) => { return *(Int16*)this.CurrentValuePointer != (Int16)value; };
this.GreaterThanValue = (value) => { return *(Int16*)this.CurrentValuePointer > (Int16)value; };
this.GreaterThanOrEqualToValue = (value) => { return *(Int16*)this.CurrentValuePointer >= (Int16)value; };
this.LessThanValue = (value) => { return *(Int16*)this.CurrentValuePointer < (Int16)value; };
this.LessThanOrEqualToValue = (value) => { return *(Int16*)this.CurrentValuePointer <= (Int16)value; };
this.IncreasedByValue = (value) => { return *(Int16*)this.CurrentValuePointer == unchecked(*(Int16*)this.PreviousValuePointer + (Int16)value); };
this.DecreasedByValue = (value) => { return *(Int16*)this.CurrentValuePointer == unchecked(*(Int16*)this.PreviousValuePointer - (Int16)value); };
break;
case TypeCode.Int32:
this.Changed = () => { return *(Int32*)this.CurrentValuePointer != *(Int32*)this.PreviousValuePointer; };
this.Unchanged = () => { return *(Int32*)this.CurrentValuePointer == *(Int32*)this.PreviousValuePointer; };
this.Increased = () => { return *(Int32*)this.CurrentValuePointer > *(Int32*)this.PreviousValuePointer; };
this.Decreased = () => { return *(Int32*)this.CurrentValuePointer < *(Int32*)this.PreviousValuePointer; };
this.EqualToValue = (value) => { return *(Int32*)this.CurrentValuePointer == (Int32)value; };
this.NotEqualToValue = (value) => { return *(Int32*)this.CurrentValuePointer != (Int32)value; };
this.GreaterThanValue = (value) => { return *(Int32*)this.CurrentValuePointer > (Int32)value; };
this.GreaterThanOrEqualToValue = (value) => { return *(Int32*)this.CurrentValuePointer >= (Int32)value; };
this.LessThanValue = (value) => { return *(Int32*)this.CurrentValuePointer < (Int32)value; };
this.LessThanOrEqualToValue = (value) => { return *(Int32*)this.CurrentValuePointer <= (Int32)value; };
this.IncreasedByValue = (value) => { return *(Int32*)this.CurrentValuePointer == unchecked(*(Int32*)this.PreviousValuePointer + (Int32)value); };
this.DecreasedByValue = (value) => { return *(Int32*)this.CurrentValuePointer == unchecked(*(Int32*)this.PreviousValuePointer - (Int32)value); };
break;
case TypeCode.Int64:
this.Changed = () => { return *(Int64*)this.CurrentValuePointer != *(Int64*)this.PreviousValuePointer; };
this.Unchanged = () => { return *(Int64*)this.CurrentValuePointer == *(Int64*)this.PreviousValuePointer; };
this.Increased = () => { return *(Int64*)this.CurrentValuePointer > *(Int64*)this.PreviousValuePointer; };
this.Decreased = () => { return *(Int64*)this.CurrentValuePointer < *(Int64*)this.PreviousValuePointer; };
this.EqualToValue = (value) => { return *(Int64*)this.CurrentValuePointer == (Int64)value; };
this.NotEqualToValue = (value) => { return *(Int64*)this.CurrentValuePointer != (Int64)value; };
this.GreaterThanValue = (value) => { return *(Int64*)this.CurrentValuePointer > (Int64)value; };
this.GreaterThanOrEqualToValue = (value) => { return *(Int64*)this.CurrentValuePointer >= (Int64)value; };
this.LessThanValue = (value) => { return *(Int64*)this.CurrentValuePointer < (Int64)value; };
this.LessThanOrEqualToValue = (value) => { return *(Int64*)this.CurrentValuePointer <= (Int64)value; };
this.IncreasedByValue = (value) => { return *(Int64*)this.CurrentValuePointer == unchecked(*(Int64*)this.PreviousValuePointer + (Int64)value); };
this.DecreasedByValue = (value) => { return *(Int64*)this.CurrentValuePointer == unchecked(*(Int64*)this.PreviousValuePointer - (Int64)value); };
break;
case TypeCode.UInt16:
this.Changed = () => { return *(UInt16*)this.CurrentValuePointer != *(UInt16*)this.PreviousValuePointer; };
this.Unchanged = () => { return *(UInt16*)this.CurrentValuePointer == *(UInt16*)this.PreviousValuePointer; };
this.Increased = () => { return *(UInt16*)this.CurrentValuePointer > *(UInt16*)this.PreviousValuePointer; };
this.Decreased = () => { return *(UInt16*)this.CurrentValuePointer < *(UInt16*)this.PreviousValuePointer; };
this.EqualToValue = (value) => { return *(UInt16*)this.CurrentValuePointer == (UInt16)value; };
this.NotEqualToValue = (value) => { return *(UInt16*)this.CurrentValuePointer != (UInt16)value; };
this.GreaterThanValue = (value) => { return *(UInt16*)this.CurrentValuePointer > (UInt16)value; };
this.GreaterThanOrEqualToValue = (value) => { return *(UInt16*)this.CurrentValuePointer >= (UInt16)value; };
this.LessThanValue = (value) => { return *(UInt16*)this.CurrentValuePointer < (UInt16)value; };
this.LessThanOrEqualToValue = (value) => { return *(UInt16*)this.CurrentValuePointer <= (UInt16)value; };
this.IncreasedByValue = (value) => { return *(UInt16*)this.CurrentValuePointer == unchecked(*(UInt16*)this.PreviousValuePointer + (UInt16)value); };
this.DecreasedByValue = (value) => { return *(UInt16*)this.CurrentValuePointer == unchecked(*(UInt16*)this.PreviousValuePointer - (UInt16)value); };
break;
case TypeCode.UInt32:
this.Changed = () => { return *(UInt32*)this.CurrentValuePointer != *(UInt32*)this.PreviousValuePointer; };
this.Unchanged = () => { return *(UInt32*)this.CurrentValuePointer == *(UInt32*)this.PreviousValuePointer; };
this.Increased = () => { return *(UInt32*)this.CurrentValuePointer > *(UInt32*)this.PreviousValuePointer; };
this.Decreased = () => { return *(UInt32*)this.CurrentValuePointer < *(UInt32*)this.PreviousValuePointer; };
this.EqualToValue = (value) => { return *(UInt32*)this.CurrentValuePointer == (UInt32)value; };
this.NotEqualToValue = (value) => { return *(UInt32*)this.CurrentValuePointer != (UInt32)value; };
this.GreaterThanValue = (value) => { return *(UInt32*)this.CurrentValuePointer > (UInt32)value; };
this.GreaterThanOrEqualToValue = (value) => { return *(UInt32*)this.CurrentValuePointer >= (UInt32)value; };
this.LessThanValue = (value) => { return *(UInt32*)this.CurrentValuePointer < (UInt32)value; };
this.LessThanOrEqualToValue = (value) => { return *(UInt32*)this.CurrentValuePointer <= (UInt32)value; };
this.IncreasedByValue = (value) => { return *(UInt32*)this.CurrentValuePointer == unchecked(*(UInt32*)this.PreviousValuePointer + (UInt32)value); };
this.DecreasedByValue = (value) => { return *(UInt32*)this.CurrentValuePointer == unchecked(*(UInt32*)this.PreviousValuePointer - (UInt32)value); };
break;
case TypeCode.UInt64:
this.Changed = () => { return *(UInt64*)this.CurrentValuePointer != *(UInt64*)this.PreviousValuePointer; };
this.Unchanged = () => { return *(UInt64*)this.CurrentValuePointer == *(UInt64*)this.PreviousValuePointer; };
this.Increased = () => { return *(UInt64*)this.CurrentValuePointer > *(UInt64*)this.PreviousValuePointer; };
this.Decreased = () => { return *(UInt64*)this.CurrentValuePointer < *(UInt64*)this.PreviousValuePointer; };
this.EqualToValue = (value) => { return *(UInt64*)this.CurrentValuePointer == (UInt64)value; };
this.NotEqualToValue = (value) => { return *(UInt64*)this.CurrentValuePointer != (UInt64)value; };
this.GreaterThanValue = (value) => { return *(UInt64*)this.CurrentValuePointer > (UInt64)value; };
this.GreaterThanOrEqualToValue = (value) => { return *(UInt64*)this.CurrentValuePointer >= (UInt64)value; };
this.LessThanValue = (value) => { return *(UInt64*)this.CurrentValuePointer < (UInt64)value; };
this.LessThanOrEqualToValue = (value) => { return *(UInt64*)this.CurrentValuePointer <= (UInt64)value; };
this.IncreasedByValue = (value) => { return *(UInt64*)this.CurrentValuePointer == unchecked(*(UInt64*)this.PreviousValuePointer + (UInt64)value); };
this.DecreasedByValue = (value) => { return *(UInt64*)this.CurrentValuePointer == unchecked(*(UInt64*)this.PreviousValuePointer - (UInt64)value); };
break;
case TypeCode.Single:
this.Changed = () => { return !(*(Single*)this.CurrentValuePointer).AlmostEquals(*(Single*)this.PreviousValuePointer); };
this.Unchanged = () => { return (*(Single*)this.CurrentValuePointer).AlmostEquals(*(Single*)this.PreviousValuePointer); };
this.Increased = () => { return *(Single*)this.CurrentValuePointer > *(Single*)this.PreviousValuePointer; };
this.Decreased = () => { return *(Single*)this.CurrentValuePointer < *(Single*)this.PreviousValuePointer; };
this.EqualToValue = (value) => { return (*(Single*)this.CurrentValuePointer).AlmostEquals((Single)value); };
this.NotEqualToValue = (value) => { return !(*(Single*)this.CurrentValuePointer).AlmostEquals((Single)value); };
this.GreaterThanValue = (value) => { return *(Single*)this.CurrentValuePointer > (Single)value; };
this.GreaterThanOrEqualToValue = (value) => { return *(Single*)this.CurrentValuePointer >= (Single)value; };
this.LessThanValue = (value) => { return *(Single*)this.CurrentValuePointer < (Single)value; };
this.LessThanOrEqualToValue = (value) => { return *(Single*)this.CurrentValuePointer <= (Single)value; };
this.IncreasedByValue = (value) => { return (*(Single*)this.CurrentValuePointer).AlmostEquals(unchecked(*(Single*)this.PreviousValuePointer + (Single)value)); };
this.DecreasedByValue = (value) => { return (*(Single*)this.CurrentValuePointer).AlmostEquals(unchecked(*(Single*)this.PreviousValuePointer - (Single)value)); };
break;
case TypeCode.Double:
this.Changed = () => { return !(*(Double*)this.CurrentValuePointer).AlmostEquals(*(Double*)this.PreviousValuePointer); };
this.Unchanged = () => { return (*(Double*)this.CurrentValuePointer).AlmostEquals(*(Double*)this.PreviousValuePointer); };
this.Increased = () => { return *(Double*)this.CurrentValuePointer > *(Double*)this.PreviousValuePointer; };
this.Decreased = () => { return *(Double*)this.CurrentValuePointer < *(Double*)this.PreviousValuePointer; };
this.EqualToValue = (value) => { return (*(Double*)this.CurrentValuePointer).AlmostEquals((Double)value); };
this.NotEqualToValue = (value) => { return !(*(Double*)this.CurrentValuePointer).AlmostEquals((Double)value); };
this.GreaterThanValue = (value) => { return *(Double*)this.CurrentValuePointer > (Double)value; };
this.GreaterThanOrEqualToValue = (value) => { return *(Double*)this.CurrentValuePointer >= (Double)value; };
this.LessThanValue = (value) => { return *(Double*)this.CurrentValuePointer < (Double)value; };
this.LessThanOrEqualToValue = (value) => { return *(Double*)this.CurrentValuePointer <= (Double)value; };
this.IncreasedByValue = (value) => { return (*(Double*)this.CurrentValuePointer).AlmostEquals(unchecked(*(Double*)this.PreviousValuePointer + (Double)value)); };
this.DecreasedByValue = (value) => { return (*(Double*)this.CurrentValuePointer).AlmostEquals(unchecked(*(Double*)this.PreviousValuePointer - (Double)value)); };
break;
default:
throw new ArgumentException();
}
}
/// <summary>
/// Initializes the pointer incrementing function based on the provided parameters.
/// </summary>
/// <param name="pointerIncrementMode">The method by which to increment pointers.</param>
private unsafe void SetPointerFunction(PointerIncrementMode pointerIncrementMode)
{
Int32 alignment = ScanSettings.Alignment;
if (alignment == 1)
{
switch (pointerIncrementMode)
{
case PointerIncrementMode.AllPointers:
this.IncrementPointers = () =>
{
this.CurrentLabelIndex++;
this.CurrentValuePointer++;
this.PreviousValuePointer++;
};
break;
case PointerIncrementMode.CurrentOnly:
this.IncrementPointers = () =>
{
this.CurrentValuePointer++;
};
break;
case PointerIncrementMode.LabelsOnly:
this.IncrementPointers = () =>
{
this.CurrentLabelIndex++;
};
break;
case PointerIncrementMode.NoPrevious:
this.IncrementPointers = () =>
{
this.CurrentLabelIndex++;
this.CurrentValuePointer++;
};
break;
case PointerIncrementMode.ValuesOnly:
this.IncrementPointers = () =>
{
this.CurrentValuePointer++;
this.PreviousValuePointer++;
};
break;
}
}
else
{
switch (pointerIncrementMode)
{
case PointerIncrementMode.AllPointers:
this.IncrementPointers = () =>
{
this.CurrentLabelIndex += alignment;
this.CurrentValuePointer += alignment;
this.PreviousValuePointer += alignment;
};
break;
case PointerIncrementMode.CurrentOnly:
this.IncrementPointers = () =>
{
this.CurrentValuePointer += alignment;
};
break;
case PointerIncrementMode.LabelsOnly:
this.IncrementPointers = () =>
{
this.CurrentLabelIndex += alignment;
};
break;
case PointerIncrementMode.NoPrevious:
this.IncrementPointers = () =>
{
this.CurrentLabelIndex += alignment;
this.CurrentValuePointer += alignment;
};
break;
case PointerIncrementMode.ValuesOnly:
this.IncrementPointers = () =>
{
this.CurrentValuePointer += alignment;
this.PreviousValuePointer += alignment;
};
break;
}
}
}
/// <summary>
/// Sets the default compare action to use for this element.
/// </summary>
/// <param name="constraint">The constraint(s) to use for the element quick action.</param>
private Func<Boolean> BuildCompareActions(Constraint constraint)
{
switch (constraint)
{
case OperationConstraint operationConstraint:
if (operationConstraint.Left == null || operationConstraint.Right == null)
{
throw new ArgumentException("An operation constraint must have both a left and right child");
}
switch (operationConstraint.BinaryOperation)
{
case OperationConstraint.OperationType.AND:
return () =>
{
Boolean resultLeft = this.BuildCompareActions(operationConstraint.Left).Invoke();
Boolean resultRight = this.BuildCompareActions(operationConstraint.Right).Invoke();
return resultLeft & resultRight;
};
case OperationConstraint.OperationType.OR:
return () =>
{
Boolean resultLeft = this.BuildCompareActions(operationConstraint.Left).Invoke();
Boolean resultRight = this.BuildCompareActions(operationConstraint.Right).Invoke();
return resultLeft | resultRight;
};
case OperationConstraint.OperationType.XOR:
return () =>
{
Boolean resultLeft = this.BuildCompareActions(operationConstraint.Left).Invoke();
Boolean resultRight = this.BuildCompareActions(operationConstraint.Right).Invoke();
return resultLeft ^ resultRight;
};
default:
throw new ArgumentException("Unkown operation type");
}
case ScanConstraint scanConstraint:
switch (scanConstraint.Constraint)
{
case ScanConstraint.ConstraintType.Unchanged:
return this.Unchanged;
case ScanConstraint.ConstraintType.Changed:
return this.Changed;
case ScanConstraint.ConstraintType.Increased:
return this.Increased;
case ScanConstraint.ConstraintType.Decreased:
return this.Decreased;
case ScanConstraint.ConstraintType.IncreasedByX:
return () => this.IncreasedByValue(scanConstraint.ConstraintValue);
case ScanConstraint.ConstraintType.DecreasedByX:
return () => this.DecreasedByValue(scanConstraint.ConstraintValue);
case ScanConstraint.ConstraintType.Equal:
return () => this.EqualToValue(scanConstraint.ConstraintValue);
case ScanConstraint.ConstraintType.NotEqual:
return () => this.NotEqualToValue(scanConstraint.ConstraintValue);
case ScanConstraint.ConstraintType.GreaterThan:
return () => this.GreaterThanValue(scanConstraint.ConstraintValue);
case ScanConstraint.ConstraintType.GreaterThanOrEqual:
return () => this.GreaterThanOrEqualToValue(scanConstraint.ConstraintValue);
case ScanConstraint.ConstraintType.LessThan:
return () => this.LessThanValue(scanConstraint.ConstraintValue);
case ScanConstraint.ConstraintType.LessThanOrEqual:
return () => this.LessThanOrEqualToValue(scanConstraint.ConstraintValue);
default:
throw new Exception("Unknown constraint type");
}
default:
throw new ArgumentException("Invalid constraint");
}
}
/// <summary>
/// Loads the value of this snapshot element from the given array.
/// </summary>
/// <param name="array">The byte array from which to read a value.</param>
/// <returns>The value at the start of this array casted as the proper data type.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private unsafe Object LoadValue(Byte* array)
{
switch (this.CurrentTypeCode)
{
case TypeCode.Byte:
return *array;
case TypeCode.SByte:
return *(SByte*)array;
case TypeCode.Int16:
return *(Int16*)array;
case TypeCode.Int32:
return *(Int32*)array;
case TypeCode.Int64:
return *(Int64*)array;
case TypeCode.UInt16:
return *(UInt16*)array;
case TypeCode.UInt32:
return *(UInt32*)array;
case TypeCode.UInt64:
return *(UInt64*)array;
case TypeCode.Single:
return *(Single*)array;
case TypeCode.Double:
return *(Double*)array;
default:
throw new ArgumentException();
}
}
}
//// End class
}
//// End namespace
|
7528dc3600767abeca3930479985f1c550e5edec
|
C#
|
cuiyp7777/NetPro
|
/WebBasicApp/04反射and特性and工厂/01Factory.cs
| 3.140625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using static WebBasicApp._04反射and特性and工厂._00Attribute;
namespace WebBasicApp._04反射and特性and工厂
{
//定义工厂接口,产品接口与产品类型的枚举
/// <summary>
/// 屋子零件
/// </summary>
public enum RoomParts
{
Roof,
Window,
Pillar
}
/// <summary>
/// 工厂类
/// </summary>
public class Factory
{
public IProduct Produce(RoomParts part)
{
// 通过反射从IProduct接口中获得属性从而获得所有产品列表
//参数1:Iproduct接口,type:ProductListAttribute
ProductListAttribute attr =
(ProductListAttribute)Attribute.GetCustomAttribute(typeof(IProduct), typeof(ProductListAttribute));
// 遍历所有的实现产品零件类型
foreach (var type in attr.ProductList)
{
// 利用反射查找其属性
ProductAttribute pa =
(ProductAttribute)Attribute.GetCustomAttribute(type, typeof(ProductAttribute));
// 确定是否是需要到的零件
if (pa.RoomPart == part)
{
// 利用反射动态创建产品零件类型实例
object product = Assembly.GetExecutingAssembly().CreateInstance(type.FullName);
return product as IProduct;
}
}
return null;
}
}
}
|
a7e357b624faf18235f1257664bf964384e5896a
|
C#
|
ZeusAFK/TeraEmulator
|
/Tera_Emulator_Source/GameServer/Network/Server/SpTradeHideWindow.cs
| 2.546875
| 3
|
using System.IO;
using Data.Structures.Player;
namespace Network.Server
{
public class SpTradeHideWindow : ASendPacket
{
protected Player Player1;
protected Player Player2;
protected int TradeId;
protected int Type;
public SpTradeHideWindow(Player player1, Player player2, int tradeId, int type = 1)
{
Player1 = player1;
Player2 = player2;
TradeId = tradeId;
Type = type;
}
public override void Write(BinaryWriter writer)
{
WriteUid(writer, Player1);
WriteUid(writer, Player2);
WriteD(writer, TradeId);
WriteD(writer, Type);
}
}
}
|
5e2583855ac3ed34ad522ea0b5f0efb7de68aa43
|
C#
|
PoLaKoSz/WeAreOne.Scraper
|
/tests/Integration/TestClassBase.cs
| 3
| 3
|
using PoLaKoSz.WeAreOne.Models;
using System.Collections.Generic;
using System.IO;
namespace PoLaKoSz.WeAreOne.Tests.Integration
{
internal abstract class TestClassBase
{
private readonly string _path;
private readonly string _module;
/// <summary>
/// Set to true when You want to add a new StaticResource .html file.
/// </summary>
private readonly bool _shouldCreateNewTracklist;
protected readonly HttpClientMock HttpClient;
/// <summary>
/// Initialize a new instance.
/// </summary>
/// <param name="module">Non null name of the module (subdirectory).</param>
public TestClassBase(string module)
{
_module = module;
_path = Path.Combine("StaticResources", _module);
_shouldCreateNewTracklist = !true;
HttpClient = new HttpClientMock();
}
/// <summary>
/// Get the source code from a previously saved HTML file.
/// </summary>
protected void SetServerResponse(string fileName)
{
HttpClient.ResponseFromServer = File.ReadAllBytes(Path.Combine(_path, $"{fileName}.html"));
}
/// <summary>
/// Saves the tracklist to a file to make a new StaticResource
/// addig more faster.
/// </summary>
/// <param name="tracklist">Non null <see cref="Music"/> collection.</param>
protected void GenerateStaticTracklist(List<Music> tracklist)
{
if (!_shouldCreateNewTracklist)
return;
File.Delete($"{_module}.txt");
foreach (var music in tracklist)
{
File.AppendAllText($"{_module}.txt", $"\t\t\t\t\tnew Music(\"{music.Name}\"),\n");
}
}
}
}
|
09a88eab1ba0e4c95c78ed6a7710d5fbe28f1576
|
C#
|
leilaweicman/gdd2017
|
/src/UberFrba/Classes/Rendicion.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Classes
{
public class Rendicion : Base
{
List<SqlParameter> parameterList = new List<SqlParameter>();
#region atributos
private int _nroRendicion;
private string _chofer;
private string _fecha;
private string _turno;
private decimal _total;
#endregion
public int nro_Rendicion
{
get { return _nroRendicion; }
set { _nroRendicion = value; }
}
public string Chofer
{
get { return _chofer; }
set { _chofer = value; }
}
public string Fecha
{
get { return _fecha; }
set { _fecha = value; }
}
public string Turno
{
get { return _turno; }
set { _turno = value; }
}
public decimal Total
{
get { return _total; }
set { _total = value; }
}
public override string NombreTabla()
{
return "Rendicion";
}
public override string NombreEntidad()
{
return "Rendicion";
}
public override void DataRowToObject(DataRow dr)
{
// Esto es tal cual lo devuelve el stored de la DB
this.nro_Rendicion = Convert.ToInt32(dr["NroRendicion"]);
this.Total =Convert.ToDecimal(dr["ImporteTotal"]);
this.Turno = dr["Descripcion"].ToString();
this.Fecha = dr["Fecha"].ToString();
this.Chofer = dr["Nombre"].ToString();
}
public static DataSet obtenerTodos()
{
Rendicion rend = new Rendicion();
return rend.TraerListado(rend.parameterList, "");
}
}
}
|
d71eb0f72a8d340320a6937983817d5047a67a4f
|
C#
|
Olymo/ExampleApi
|
/ExampleApi/Validations/AddProductValidation.cs
| 2.78125
| 3
|
using ExampleApi.Entities;
using FluentValidation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ExampleApi.Validations
{
public class AddProductValidation : AbstractValidator<Product>
{
public AddProductValidation()
{
RuleFor(x => x.Name)
.NotEmpty()
.WithMessage("Name is required");
RuleFor(x => x.Price)
.NotEmpty()
.WithMessage("Price is required")
.GreaterThan(0)
.WithMessage("Price must be greather than 0");
RuleFor(x => x.CategoryId)
.NotEmpty()
.WithMessage("Price is required")
.Must(id => InMemmoryDatabase.Categories.Any(y => y.Id == id))
.WithMessage("Category not exist");
}
}
}
|
89113e6f325e046b5faaf086cab553fb9b60d243
|
C#
|
Kawser-nerd/CLCDSA
|
/Source Codes/CodeJamData/15/04/7.cs
| 2.984375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace km.gcj.gcj2015
{
class Program
{
static System.Diagnostics.Stopwatch sw;
/// <summary> プログラムのスタートポイント </summary>
/// <param name="args"> 第一引数に入力ファイルを指定 </param>
static void Main(string[] args)
{
sw = new System.Diagnostics.Stopwatch();
sw.Start();
Logic(args);
sw.Stop();
Console.WriteLine(sw.Elapsed);
Console.ReadLine();
}
private static void Logic(string[] args)
{
Problem p = Problem.createProblem(args);
if (p==null) {
return;
}
// 試行回数を取得し、ループする。
long repeat = p.getNextInt64s().ToArray()[0];
for (int i = 0; i < repeat; i++)
{
// MainLoop
var xrc = p.getNextInt64s().ToArray();
var x = xrc[0];
var r = xrc[1];
var c = xrc[2];
bool canFill = true;
// 平面充填できるか?
canFill &= (r * c % x == 0);
// 辺の長さ的に収まらない形を選べるか?
var edge = (x + 1) / 2;
canFill &= (edge <= r && edge <= c);
// 7-omino以上ではないか?(充填不可能な形状を選べるか?)
// ■■■
// ■□■
// ■■□
canFill &= (x <= 6);
// 4-ominoの妨害図形TまたはZ(幅2で常に有効)
// ■■■
// □■□
// 4x3以上はどの図形をどの図形が含まれても充填可能
if (x == 4 && (r==2||c==2))
{
canFill = false;
}
// 5-ominoの妨害図形M(幅3かつ長さ限定)
// ■■□
// □■■
// □□■
// □□□□■■□□□□
// □□□□□■■□□□
// □□□□□□■□□□
// 5x4以上はどの図形をどの図形が含まれても充填可能
if (x == 5 && ((r == 3 && c < 10) || (c == 3 && r < 10)))
{
canFill = false;
}
// 6-ominoの妨害図形Gun(幅3で常に有効)
// ■■■□
// □□■■
// □□□■
// 6x4以上は?
if (x == 6 && (r == 3 || c == 3))
{
canFill = false;
}
var answer = canFill ? "GABRIEL" : "RICHARD";
// \(・ω・\) (/・ω・)/
p.WriteAnswerFullLine(answer);
if (i % 10 == 0) Console.WriteLine("{0}\t->{1}", i, sw.Elapsed);
}
}
class Quaternion
{
public bool Minus = false;
public char Identifier = '1';
public static Quaternion operator *(Quaternion left, Quaternion right)
{
bool minus = left.Minus ^ right.Minus;
char identifier = '1';
if (left.Identifier=='1')
{
identifier = right.Identifier;
}
else if (left.Identifier == right.Identifier)
{
minus ^= true;
identifier = '1';
}
else if (left.Identifier == 'i' && right.Identifier == 'j')
{
identifier = 'k';
}
else if (left.Identifier == 'j' && right.Identifier == 'i')
{
minus ^= true;
identifier = 'k';
}
else if (left.Identifier == 'j' && right.Identifier == 'k')
{
identifier = 'i';
}
else if (left.Identifier == 'k' && right.Identifier == 'j')
{
minus ^= true;
identifier = 'i';
}
else if (left.Identifier == 'k' && right.Identifier == 'i')
{
identifier = 'j';
}
else if (left.Identifier == 'i' && right.Identifier == 'k')
{
minus ^= true;
identifier = 'j';
}
return new Quaternion { Identifier = identifier, Minus = minus };
}
}
private static Int64 gcd(Int64 a, Int64 b)
{
if (a > b)
{
var c = a;
a = b;
b = c;
}
if (b % a == 0)
{
return a;
}
else
{
return gcd(a, b % a);
}
}
}
class Diner
{
public int Pancakes;
public int getShares(int maxPancake)
{
for (int i = 0; i < Math.Sqrt(Pancakes); i++)
{
if ((this.Pancakes + i) / (i+1) <= maxPancake)
{
return i;
}
}
return 0;
}
public IEnumerable<EatPattern> getEatPatterns()
{
for (int i = 0; i < Math.Sqrt(Pancakes); i++)
{
yield return new EatPattern { Shares = i, Pancakes = (this.Pancakes + (i-1)) / i };
}
yield break;
}
}
struct EatPattern
{
public int Shares;
public int Pancakes;
}
}
|
79617070a056bb5998e6a5c4c22ec9f68cccc0dc
|
C#
|
Krzysiek102/FootballTableGenerator
|
/FootbalTableGenerator.Core/MatchRegulations.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FootbalTableGenerator.Core
{
public class MatchRegulations
{
public const int NumerOfPointForWin = 3;
public const int NumerOfPointForDraw = 1;
public void AddPointsAndGoals(FootballMatch match, TeamResultsSummary hostResults, TeamResultsSummary guestResults)
{
if (match.NumberOfGoalsScoredByHosts > match.NumberOfGoalsScoredByGuests)
{
hostResults.Points += NumerOfPointForWin;
}
else if (match.NumberOfGoalsScoredByHosts < match.NumberOfGoalsScoredByGuests)
{
guestResults.Points += NumerOfPointForWin;
}
else
{
hostResults.Points += NumerOfPointForDraw;
guestResults.Points += NumerOfPointForDraw;
}
hostResults.GoalsScored += match.NumberOfGoalsScoredByHosts;
hostResults.GoalsLost += match.NumberOfGoalsScoredByGuests;
guestResults.GoalsScored += match.NumberOfGoalsScoredByGuests;
guestResults.GoalsLost += match.NumberOfGoalsScoredByHosts;
}
}
}
|
272ed3f2562ba27e8e235b087c08aaf04937e62f
|
C#
|
gukiub/portifolio
|
/C#/01.10.18/CalculadoraDeDistanciaPercorrida/CalculadoraDeDistanciaPercorrida/Form1.cs
| 2.84375
| 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 CalculadoraDeDistanciaPercorrida
{
public partial class calcularKm : Form
{
public calcularKm()
{
InitializeComponent();
}
private void LimparTela() {
txtVelocidade.Clear();
txtHoras.Clear();
listaSaida.ClearSelected();
}
private void btnCalcula_Click(object sender, EventArgs e)
{
int velocidade;
int horas;
int distancia;
listaSaida.Items.Clear();
if (int.TryParse(txtVelocidade.Text, out velocidade) && int.TryParse(txtHoras.Text, out horas))
{
for (int i = 1; i <= horas; i++)
{
distancia = velocidade * i;
listaSaida.Items.Add("Depois da Hora " + i + " o veiculo viajou " + distancia.ToString("n") + " quilometros");
}
}
else
MessageBox.Show("Por favor, Digite valores válidos", "Entrada Inválida");
}
private void calcularKm_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 27)
{
LimparTela();
}
}
}
}
|
255435f2aae9c7ca6368e81b00197b2d69ea89e9
|
C#
|
francoisperron/yose-csharp
|
/yose-csharp/World2/UiChallenges/TooBigNumberResult.cs
| 2.71875
| 3
|
using System;
namespace Yose.World2.UiChallenges
{
public class TooBigNumberResult : IPrimeFactorsResult
{
public bool Matches(string number)
{
return Convert.ToInt32(number) > 1000000;
}
public object Response(string number)
{
return "too big number (>1e6)";
}
}
}
|
c050dd3ae144e2d18d0c2feb03214f78a1f78f96
|
C#
|
dmaa1909-Marc/3rdSemesterProject
|
/ApplicationServer/DB/ColorsDB.cs
| 3.109375
| 3
|
using Dapper;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Web;
namespace ApplicationServer.DB {
public class ColorsDB : IColorsDB {
private static string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
public IEnumerable<Color> GetColors() {
string query = "SELECT Color FROM Color";
try {
using(SqlConnection con = new SqlConnection(connectionString)) {
IEnumerable<string> colorNames = con.Query<string>(query);
List<Color> colors = new List<Color>();
foreach(string namedColor in colorNames) {
colors.Add(Color.FromName(namedColor));
Debug.WriteLine(Color.FromName(namedColor).Name);
}
return colors;
}
}
catch(Exception e) {
Debug.WriteLine(e);
throw;
}
}
public void AddColor(Color color) {
string query = "INSERT INTO Color VALUES (@Name)";
if(color.IsNamedColor) {
using(SqlConnection con = new SqlConnection(connectionString)) {
con.ExecuteScalar(query, color);// new { Color = color.Name });
}
}
else {
throw new ArgumentException("Color must be a named color");
}
}
}
}
|
38a3053e053960b2a5a421d0755030fd98a1721d
|
C#
|
Caglakirazkaya/Product-Tracking
|
/PRODUCT_TRACKING/PRODUCT_TRACKING/Models/Managers/UserManagers.cs
| 2.640625
| 3
|
using PRODUCT_TRACKING.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PRODUCT_TRACKING.Models.Managers
{
public class UserManagers
{
Context c = new Context();
public List<User> ActivtyUser()
{
List<User> getUser = c.Users.ToList();
List<User> UserList = (from i in getUser.ToList()
where i.Activity == false
select new User
{
Activity=i.Activity,
Id=i.Id,
Name=i.Name,
Password=i.Password,
Surname=i.Surname,
username=i.username
}).ToList();
return UserList;
}
public List<User> ListUser()
{
List<User> getUser = c.Users.ToList();
List<User> UserList = (from i in getUser.ToList()
where i.Activity == true
select new User
{
Activity = i.Activity,
Id = i.Id,
Name = i.Name,
Password = i.Password,
Surname = i.Surname,
username = i.username
}).ToList();
return UserList;
}
public void AddAuthority(User users)
{
Role newrol = c.Roles.FirstOrDefault(a => a.RoleName == "Authority");
if(newrol==null)
{
newrol.RoleName = "Authority";
c.Roles.Add(newrol);
newrol = c.Roles.FirstOrDefault(a => a.RoleName == "Authority");
}
UserRole userRole = new UserRole();
userRole.UserID = users.Id;
userRole.RoleID = newrol.Id;
c.UserRoles.Add(userRole);
c.SaveChanges();
}
public void AddCustomer(User users)
{
Role newrol = c.Roles.FirstOrDefault(a => a.RoleName == "Customer");
if (newrol == null)
{
newrol.RoleName = "Customer";
c.Roles.Add(newrol);
newrol = c.Roles.FirstOrDefault(a => a.RoleName == "Customer");
}
UserRole userRole = new UserRole();
userRole.UserID = users.Id;
userRole.RoleID = newrol.Id;
c.UserRoles.Add(userRole);
c.SaveChanges();
}
}
}
|
a1b69bc453c81e1bd5416caafdee6f9ed5b9a9aa
|
C#
|
edisonbrito/CleanArchitectureTemplate
|
/src/Praxio.Tools.Arquitetura.Infra.Data/NHibernateDataAccess/Repositories/Repository.cs
| 2.578125
| 3
|
using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using NHibernate;
using NHibernate.Linq;
using Praxio.Tools.Arquitetura.Application.Interfaces.Repositories;
using Praxio.Tools.Arquitetura.Domain.Entities.Base;
using Praxio.Tools.Arquitetura.Infra.Data.NHibernateDataAccess.DataModels;
namespace Praxio.Tools.Arquitetura.Infra.Data.NHibernateDataAccess.Repositories
{
public class Repository<TDomainModel, TDataModel> : IRepository<TDomainModel>
where TDomainModel : DomainModel
where TDataModel : DataModel
{
protected readonly ISessionFactory _sessionFactory;
protected readonly IMapper _mapper;
public Repository(ISessionFactory sessionFactory, IMapper mapper)
{
_sessionFactory = sessionFactory;
_mapper = mapper;
}
public async Task<TDomainModel> Inserir(TDomainModel domainModel)
{
var dataModel = _mapper.Map<TDataModel>(domainModel);
using (var session = _sessionFactory.OpenSession())
{
await session.SaveAsync(dataModel);
await session.FlushAsync();
domainModel.Id = dataModel.Id;
return domainModel;
}
}
public async Task<TDomainModel> Alterar(TDomainModel domainModel)
{
var dataModel = _mapper.Map<TDataModel>(domainModel);
using (var session = _sessionFactory.OpenSession())
{
await session.UpdateAsync(dataModel);
await session.FlushAsync();
return domainModel;
}
}
public async Task Excluir(int id)
{
using (var session = _sessionFactory.OpenSession())
{
await session.DeleteAsync(await session.LoadAsync<TDataModel>(id));
await session.FlushAsync();
}
}
public async Task<TDomainModel> ObterPorId(int id)
{
using (var session = _sessionFactory.OpenSession())
{
var dataModel = await session.GetAsync<TDataModel>(id);
return _mapper.Map<TDomainModel>(dataModel);
}
}
public async Task<IEnumerable<TDomainModel>> ObterLista()
{
using (var session = _sessionFactory.OpenSession())
{
var lista = await session.Query<TDataModel>().ToListAsync();
return _mapper.Map<IEnumerable<TDomainModel>>(lista);
}
}
public async Task<bool> Existe(int id)
{
using (var session = _sessionFactory.OpenSession())
{
return await session.Query<TDataModel>().AnyAsync(a => a.Id == id);
}
}
}
}
|
210b158eee14bf152e4a2ab7abf7e704f82564b0
|
C#
|
Sunil-Kumar-Gouda/SunilGraphC_Sharp
|
/Graph/Graph/ShortestPath/BellmanFord.cs
| 3.3125
| 3
|
using GraphADT.Directed;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Graph.ShortestPath
{
public class BellmanFord
{
DirectedGraph G;
int[] _distance;
public IReadOnlyCollection<int> Distance { get { return Array.AsReadOnly(_distance); } }
public BellmanFord(DirectedGraph G,int s)
{
this.G = G;
MST(G, s);
}
private void MST(DirectedGraph G,int s)
{
if (G == null || G.V <= 1)
return;
_distance = Enumerable.Repeat(int.MaxValue, G.V).ToArray();
_distance[s] = 0;
for (int i = 0; i < G.V - 1; i++)
{
for(int j=0;j<G.V;j++)
{
foreach (DirectedEdge edge in G[j])
{
if(_distance[edge.To]>_distance[edge.From]+edge.Weight)
{
_distance[edge.To] = _distance[edge.From] + edge.Weight;
}
}
}
}
}
}
}
|
d2138082c463b2c32f32a141e4112f125b74730d
|
C#
|
dzhabrailov/csharp-programming
|
/02-DataTypesAndVariables/05. BoolVariable/CheckBoolVar.cs
| 4.21875
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BoolVariable
{
class CheckBoolVar
{
/// <summary> Problem 5
/// Boolean Variable
/// Declare a Boolean variable called isFemale and assign an
/// appropriate value corresponding to your gender. Print it on the console.
/// </summary>
static void Main()
{
bool isFemale = false;
Console.WriteLine("Is your gender is female?");
Console.WriteLine("Enter your choose: Male(m) or Female(f)?");
string choose = Console.ReadLine();
if (choose == "Female" || choose == "female" || choose == "f" || choose == "F")
{
//isFemale is true when your gender is female
Console.WriteLine(!isFemale);
}
else if (choose == "Male" || choose == "male" || choose == "m" || choose == "M")
{
//false when your gender is different of female
Console.WriteLine(isFemale);
}
else
{
Console.WriteLine("Your choice is not correct! Try again! Male or Female?");
}
}
}
}
|
977fe58b716847b0fc2e46a7f1d947f8d9e51918
|
C#
|
mark-s/Seatbelt
|
/Seatbelt/Probes/SystemChecks/UserEnvVariables.cs
| 2.859375
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace Seatbelt.Probes.SystemChecks
{
public class UserEnvVariables :IProbe
{
public static string ProbeName => "UserEnvVariables";
public string List()
{
var sb = new StringBuilder();
try
{
// dumps out current user environment variables
sb.AppendProbeHeaderLine("User Environment Variables");
var srt = new SortedDictionary<string, string>();
foreach (DictionaryEntry env in Environment.GetEnvironmentVariables())
{
srt.Add((string)env.Key, (string)env.Value);
}
foreach (var kvp in srt)
{
sb.AppendLine($" {kvp.Key,-35} : {kvp.Value}");
}
}
catch (Exception ex)
{
sb.AppendExceptionLine(ex);
}
return sb.ToString();
}
}
}
|
80859a4c52c76d2fff363ae1ff2adc82078cc18b
|
C#
|
sergeylenkov/JumpingJoe
|
/JumpingJoe/JumpingJoe.cs
| 2.5625
| 3
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
namespace JumpingJoe
{
/// <summary>
/// This is the main type for your game.
/// </summary>
public class JumpingJoe : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D background;
List<Sprite> obstacles = new List<Sprite>();
List<Sprite> cloudsLayer1 = new List<Sprite>();
List<Sprite> cloudsLayer2 = new List<Sprite>();
List<Sprite> cloudsLayer3 = new List<Sprite>();
Player joe;
double spawnTimer = 0;
double spawnTime = 2.0;
double nextSpawnTime = 0.0;
double cloudLayer1Timer = 0;
double spawnCloudTime = 5.0;
double nextSpawnCloudTime = 0;
double cloudLayer2Timer = 0;
double spawnCloud2Time = 8.0;
double nextSpawnCloud2Time = 0;
double cloudLayer3Timer = 0;
double spawnCloud3Time = 8.0;
double nextSpawnCloud3Time = 0;
public JumpingJoe()
{
graphics = new GraphicsDeviceManager(this);
graphics.PreferredBackBufferWidth = 1200;
graphics.PreferredBackBufferHeight = 800;
graphics.ApplyChanges();
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
background = Content.Load<Texture2D>("Background");
joe = new Player(Content);
joe.Position = new Vector2(50, graphics.PreferredBackBufferHeight - 155);
joe.Scale = 0.8f;
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// game-specific content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
BeforeUpdate(gameTime);
foreach (var obstacle in obstacles)
{
obstacle.Position.X = obstacle.Position.X - ((float)gameTime.ElapsedGameTime.TotalSeconds * obstacle.Speed);
}
foreach (var cloud in cloudsLayer1)
{
cloud.Position.X = cloud.Position.X - ((float)gameTime.ElapsedGameTime.TotalSeconds * cloud.Speed);
}
foreach (var cloud in cloudsLayer2)
{
cloud.Position.X = cloud.Position.X - ((float)gameTime.ElapsedGameTime.TotalSeconds * cloud.Speed);
}
foreach (var cloud in cloudsLayer3)
{
cloud.Position.X = cloud.Position.X - ((float)gameTime.ElapsedGameTime.TotalSeconds * cloud.Speed);
}
if (Keyboard.GetState().IsKeyDown(Keys.Space))
{
joe.Jump();
}
joe.Update(gameTime);
AfterUpdate();
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.Draw(background, new Rectangle(0, 0, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight), Color.White);
foreach (var obstacle in obstacles)
{
obstacle.Draw(spriteBatch);
}
foreach (var cloud in cloudsLayer3)
{
cloud.Draw(spriteBatch);
}
foreach (var cloud in cloudsLayer2)
{
cloud.Draw(spriteBatch);
}
foreach (var cloud in cloudsLayer1)
{
cloud.Draw(spriteBatch);
}
joe.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
private void Spawn()
{
Random random = new Random();
int type = random.Next(0, 4);
Sprite obstacle;
switch (type)
{
case 0:
obstacle = new Sprite(Content.Load<Texture2D>("Cactus1"), new Rectangle(0, 0, 150, 150));
break;
case 1:
obstacle = new Sprite(Content.Load<Texture2D>("Cactus2"), new Rectangle(0, 0, 150, 150));
break;
case 2:
obstacle = new Sprite(Content.Load<Texture2D>("Stone1"), new Rectangle(0, 0, 150, 150));
break;
case 3:
obstacle = new Sprite(Content.Load<Texture2D>("Stone2"), new Rectangle(0, 0, 150, 150));
break;
default:
obstacle = new Sprite(Content.Load<Texture2D>("Cactus1"), new Rectangle(0, 0, 150, 150));
break;
}
obstacle.Position = new Vector2(graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight - 110);
obstacle.Scale = 0.5f;
obstacle.Speed = 120.0f;
obstacles.Add(obstacle);
}
private void SpawnCloud(int layer)
{
Random random = new Random();
if (layer == 0)
{
int type = random.Next(1, 4);
Sprite cloud = new Sprite(Content.Load<Texture2D>($"Cloud1_{type}"), new Rectangle(0, 0, 150, 150));
cloud.Position = new Vector2(graphics.PreferredBackBufferWidth, 100 + random.Next(0, 10));
cloud.Scale = 0.8f;
cloud.Speed = 60.0f + random.Next(0, 10);
cloudsLayer1.Add(cloud);
}
if (layer == 1)
{
int type = random.Next(1, 3);
Sprite cloud = new Sprite(Content.Load<Texture2D>($"Cloud2_{type}"), new Rectangle(0, 0, 150, 150));
cloud.Position = new Vector2(graphics.PreferredBackBufferWidth, 80 + random.Next(0, 10));
cloud.Scale = 0.8f;
cloud.Speed = 40.0f + random.Next(0, 10); ;
cloudsLayer2.Add(cloud);
}
if (layer == 2)
{
int type = random.Next(1, 2);
Sprite cloud = new Sprite(Content.Load<Texture2D>($"Cloud3_{type}"), new Rectangle(0, 0, 150, 150));
cloud.Position = new Vector2(graphics.PreferredBackBufferWidth, 60 + random.Next(0, 10));
cloud.Scale = 0.8f;
cloud.Speed = 20.0f + random.Next(0, 10);
cloudsLayer3.Add(cloud);
}
}
private void BeforeUpdate(GameTime gameTime)
{
spawnTimer += gameTime.ElapsedGameTime.TotalSeconds;
if (spawnTimer > nextSpawnTime)
{
Spawn();
spawnTimer = 0.0;
Random random = new Random();
nextSpawnTime = spawnTime + random.Next(1, 20) / 10.0f;
}
cloudLayer1Timer += gameTime.ElapsedGameTime.TotalSeconds;
if (cloudLayer1Timer > nextSpawnCloudTime)
{
SpawnCloud(0);
cloudLayer1Timer = 0.0;
Random random = new Random();
nextSpawnCloudTime = spawnCloudTime + random.Next(1, 20) / 10.0f;
}
cloudLayer2Timer += gameTime.ElapsedGameTime.TotalSeconds;
if (cloudLayer2Timer > nextSpawnCloud2Time)
{
SpawnCloud(1);
cloudLayer2Timer = 0.0;
Random random = new Random();
nextSpawnCloud2Time = spawnCloud2Time + random.Next(1, 20) / 10.0f;
}
cloudLayer3Timer += gameTime.ElapsedGameTime.TotalSeconds;
if (cloudLayer3Timer > nextSpawnCloud3Time)
{
SpawnCloud(2);
cloudLayer3Timer = 0.0;
Random random = new Random();
nextSpawnCloud3Time = spawnCloud3Time + random.Next(1, 20) / 10.0f;
}
}
private void AfterUpdate()
{
obstacles.RemoveAll(obstacle => obstacle.Position.Y < -100);
cloudsLayer1.RemoveAll(cloud => cloud.Position.Y < -100);
cloudsLayer2.RemoveAll(cloud => cloud.Position.Y < -100);
cloudsLayer3.RemoveAll(cloud => cloud.Position.Y < -100);
}
}
}
|
7c1500dd1dc6029a35b33aa800582eda0db9fd42
|
C#
|
Technically-Possible/RobotWars-Ultimate
|
/RobotsStore/MedicBot.txt
| 3.03125
| 3
|
using RobotWars;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RobotsStore.Robots
{
public class MedicRobot : IRobot
{
public Int64 Health { get; set; }
public string GetName()
{
return "Medic Robot";
}
public List<RobotAction> MyTurn(List<RobotAction> competitors)
{
var Strongestvictim = competitors.OrderByDescending(c => c.Health).FirstOrDefault(); //FINDS THE STRONGEST
var weakestVictim = competitors.OrderBy(c => c.Health).FirstOrDefault(); //FINDS THE WEAKEST
if (weakestVictim.Name == "Vortex Robot")
{
if (weakestVictim.Name == "Vortex Robot")
{
weakestVictim.Attacks = -100;
Console.Beep();
}
else
{
Strongestvictim.Attacks = -30;
}
}
if (Strongestvictim.Name == "Vortex Robot")
{
if (Strongestvictim.Name == "Vortex Robot")
{
Strongestvictim.Attacks = -20;
Console.Beep();
}
else
{
Strongestvictim.Attacks = -30;
}
}
return competitors;
}
public void UpdateHealth(Int64 health)
{
Health = health;
}
}
}
|
61f5c2f3bfdf94b656e7ac0235a038fa2bffa577
|
C#
|
grasmanek94/t22-4
|
/ITTF_Server/Station.cs
| 3.21875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
namespace ITTF_Server
{
public class Station : IComparable<Station>
{
public string StationName { get; private set; }
public Train LastTrain { get; set; }
public Train NextTrain { get; set; }
public IPEndPoint Address { get; set; }
public Station(string name) //make new station
{
if(name == null)
{
throw new ArgumentNullException("name");
}
StationName = name;
}
public int CompareTo(Station other) //sort stations in list
{
if (other == null)
{
return 1; // All instances are greater than null
}
return StationName.CompareTo(other.StationName);
}
}
}
|
f34b79b89ca82314d41f5df3b1f6a69af9c8eda6
|
C#
|
SharpKit/SharpKit-SDK
|
/Defs/Qooxdoo/util/ColorUtil.cs
| 2.890625
| 3
|
// Generated by SharpKit.QooxDoo.Generator
using System;
using System.Collections.Generic;
using SharpKit.Html;
using SharpKit.JavaScript;
namespace qx.util
{
/// <summary>
/// <para>Methods to convert colors between different color spaces.</para>
/// </summary>
[JsType(JsMode.Prototype, Name = "qx.util.ColorUtil", OmitOptionalParameters = true, Export = false)]
public partial class ColorUtil
{
#region Methods
public ColorUtil() { throw new NotImplementedException(); }
/// <summary>
/// <para>Try to convert an incoming string to an RGB array.
/// Support named colors, RGB strings, hex3 and hex6 values.</para>
/// </summary>
/// <param name="str">any string</param>
/// <returns>returns an array of red, green, blue on a successful transformation</returns>
[JsMethod(Name = "cssStringToRgb")]
public static JsArray CssStringToRgb(string str) { throw new NotImplementedException(); }
/// <summary>
/// <para>Converts a hex3 (#xxx) string to a hex6 (#xxxxxx) string.</para>
/// </summary>
/// <param name="value">a hex3 (#xxx) string</param>
/// <returns>The hex6 (#xxxxxx) string or the passed value when the passed value is not an hex3 (#xxx) value.</returns>
[JsMethod(Name = "hex3StringToHex6String")]
public static string Hex3StringToHex6String(string value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Converts a hex3 string to an RGB array</para>
/// </summary>
/// <param name="value">a hex3 (#xxx) string</param>
/// <returns>an array with red, green, blue</returns>
[JsMethod(Name = "hex3StringToRgb")]
public static JsArray Hex3StringToRgb(string value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Converts a hex6 string to an RGB array</para>
/// </summary>
/// <param name="value">a hex6 (#xxxxxx) string</param>
/// <returns>an array with red, green, blue</returns>
[JsMethod(Name = "hex6StringToRgb")]
public static JsArray Hex6StringToRgb(string value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Converts a hex string to an RGB array</para>
/// </summary>
/// <param name="value">a hex3 (#xxx) or hex6 (#xxxxxx) string</param>
/// <returns>an array with red, green, blue</returns>
[JsMethod(Name = "hexStringToRgb")]
public static JsArray HexStringToRgb(string value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Convert HSB colors to RGB</para>
/// </summary>
/// <param name="hsb">an array with hue, saturation and brightness</param>
/// <returns>an array with red, green, blue</returns>
[JsMethod(Name = "hsbToRgb")]
public static double HsbToRgb(double hsb) { throw new NotImplementedException(); }
/// <summary>
/// <para>Detects if a string is a valid CSS color string</para>
/// </summary>
/// <param name="str">any string</param>
/// <returns>true when the incoming value is a valid CSS color string</returns>
[JsMethod(Name = "isCssString")]
public static bool IsCssString(string str) { throw new NotImplementedException(); }
/// <summary>
/// <para>Detects if a string is a valid hex3 string</para>
/// </summary>
/// <param name="str">any string</param>
/// <returns>true when the incoming value is a valid hex3 string</returns>
[JsMethod(Name = "isHex3String")]
public static bool IsHex3String(string str) { throw new NotImplementedException(); }
/// <summary>
/// <para>Detects if a string is a valid hex6 string</para>
/// </summary>
/// <param name="str">any string</param>
/// <returns>true when the incoming value is a valid hex6 string</returns>
[JsMethod(Name = "isHex6String")]
public static bool IsHex6String(string str) { throw new NotImplementedException(); }
/// <summary>
/// <para>Whether the incoming value is a named color.</para>
/// </summary>
/// <param name="value">the color value to test</param>
/// <returns>true if the color is a named color</returns>
[JsMethod(Name = "isNamedColor")]
public static bool IsNamedColor(string value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Detects if a string is a valid RGBA string</para>
/// </summary>
/// <param name="str">any string</param>
/// <returns>true when the incoming value is a valid RGBA string</returns>
[JsMethod(Name = "isRgbaString")]
public static bool IsRgbaString(string str) { throw new NotImplementedException(); }
/// <summary>
/// <para>Detects if a string is a valid RGB string</para>
/// </summary>
/// <param name="str">any string</param>
/// <returns>true when the incoming value is a valid RGB string</returns>
[JsMethod(Name = "isRgbString")]
public static bool IsRgbString(string str) { throw new NotImplementedException(); }
/// <summary>
/// <para>Whether the incoming value is a system color.</para>
/// </summary>
/// <param name="value">the color value to test</param>
/// <returns>true if the color is a system color</returns>
[JsMethod(Name = "isSystemColor")]
public static bool IsSystemColor(string value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Whether the incoming value is a themed color.</para>
/// </summary>
/// <param name="value">the color value to test</param>
/// <returns>true if the color is a themed color</returns>
[JsMethod(Name = "isThemedColor")]
public static bool IsThemedColor(string value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Detects if a string is a valid qooxdoo color</para>
/// </summary>
/// <param name="str">any string</param>
/// <returns>true when the incoming value is a valid qooxdoo color</returns>
[JsMethod(Name = "isValidPropertyValue")]
public static bool IsValidPropertyValue(string str) { throw new NotImplementedException(); }
/// <summary>
/// <para>Creates a random color.</para>
/// </summary>
/// <returns>a valid qooxdoo/CSS rgb color string.</returns>
[JsMethod(Name = "randomColor")]
public static string RandomColor() { throw new NotImplementedException(); }
/// <summary>
/// <para>Converts a RGB array to an hex6 string</para>
/// </summary>
/// <param name="rgb">an array with red, green and blue</param>
/// <returns>a hex6 string (#xxxxxx)</returns>
[JsMethod(Name = "rgbToHexString")]
public static string RgbToHexString(JsArray rgb) { throw new NotImplementedException(); }
/// <summary>
/// <para>Convert RGB colors to HSB</para>
/// </summary>
/// <param name="rgb">red, blue and green as array</param>
/// <returns>an array with hue, saturation and brightness</returns>
[JsMethod(Name = "rgbToHsb")]
public static JsArray RgbToHsb(double rgb) { throw new NotImplementedException(); }
/// <summary>
/// <para>Converts a RGB array to an RGB string</para>
/// </summary>
/// <param name="rgb">an array with red, green and blue</param>
/// <returns>a RGB string</returns>
[JsMethod(Name = "rgbToRgbString")]
public static string RgbToRgbString(JsArray rgb) { throw new NotImplementedException(); }
/// <summary>
/// <para>Try to convert an incoming string to an RGB array.
/// Supports themed, named and system colors, but also RGB strings,
/// hex3 and hex6 values.</para>
/// </summary>
/// <param name="str">any string</param>
/// <returns>returns an array of red, green, blue on a successful transformation</returns>
[JsMethod(Name = "stringToRgb")]
public static JsArray StringToRgb(string str) { throw new NotImplementedException(); }
/// <summary>
/// <para>Try to convert an incoming string to an RGB string, which can be used
/// for all color properties.
/// Supports themed, named and system colors, but also RGB strings,
/// hex3 and hex6 values.</para>
/// </summary>
/// <param name="str">any string</param>
/// <returns>a RGB string</returns>
[JsMethod(Name = "stringToRgbString")]
public static string StringToRgbString(string str) { throw new NotImplementedException(); }
/// <summary>
/// <para>Whether the color theme manager is loaded. Generally
/// part of the GUI of qooxdoo.</para>
/// </summary>
/// <returns>true when color theme support is ready.</returns>
[JsMethod(Name = "supportsThemes")]
public static bool SupportsThemes() { throw new NotImplementedException(); }
#endregion Methods
}
}
|
c70c00ad33125c3f20d46ffc1c470050f85f9176
|
C#
|
JoanIat312/410
|
/IAT410/AntLion/AntProjectTrial/Assets/Scripts/BulletSpawn.cs
| 2.515625
| 3
|
using UnityEngine;
using System.Collections;
public class BulletSpawn : MonoBehaviour
{
public GameObject bObject;
public float fireRate;
private float timestamp;
// Use this for initialization
void Start()
{
transform.position = GameObject.Find("jackhammer-gun").transform.position;
fireRate = .5f;
}
// Update is called once per frame
void FixedUpdate()
{
}
void Update()
{
if ((Input.GetMouseButton(0)) && (Time.time >= timestamp))
{
Debug.Log("left pressed");
Spawn();
}
}
void Spawn()
{
timestamp = Time.time + fireRate;
GameObject newBullet = Instantiate(bObject, new Vector3(transform.position.x, transform.position.y, transform.position.z), transform.rotation) as GameObject;
//newBullet.transform.position = transform.position;
newBullet.tag = "bullets";
Debug.Log("new bullet created");
}
public void SetFireRate(float newRate) {
this.fireRate = newRate;
Debug.Log("new fire rate!");
}
}
|
32d8342463db6c3137e8bf779ce7641128562015
|
C#
|
aajayagrahari/PDP_API
|
/PowerDesignPro.Data/Framework/Repository/EntityBaseRepository.cs
| 2.859375
| 3
|
using PowerDesignPro.Data.Framework.Interface;
using PowerDesignPro.Data.Models;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System;
using System.Collections.Generic;
namespace PowerDesignPro.Data.Framework.Repository
{
public class EntityBaseRepository<T> : IEntityBaseRepository<T>
where T : class, IEntity, new()
{
private ApplicationDbContext _dataContext;
protected readonly IDbSet<T> Dbset;
public EntityBaseRepository(IDbFactory databaseFactory)
{
DatabaseFactory = databaseFactory;
Dbset = DataContext.Set<T>();
}
protected IDbFactory DatabaseFactory
{
get; private set;
}
protected ApplicationDbContext DataContext
{
get { return _dataContext ?? (_dataContext = DatabaseFactory.Get()); }
}
public virtual T Add(T entity)
{
var result = Dbset.Add(entity);
DataContext.Entry(entity).State = EntityState.Added;
return result;
}
public virtual T Update(T entity)
{
var result = Dbset.Attach(entity);
DataContext.Entry(entity).State = EntityState.Modified;
return result;
}
public virtual void Delete(T entity)
{
Dbset.Remove(entity);
}
public virtual void Commit()
{
DataContext.SaveChanges();
}
public IQueryable<T> GetAll(Expression<Func<T, bool>> predicate)
{
return Dbset.Where(predicate);
}
public T Find(int id)
{
return Dbset.Find(id);
}
public T GetSingle(Expression<Func<T, bool>> predicate)
{
return Dbset.FirstOrDefault(predicate);
}
public IQueryable<T> GetAll()
{
return Dbset;
}
public IEnumerable<T> AllIncluding(params Expression<Func<T, object>>[] includeProperties)
{
IQueryable<T> set = Dbset;
foreach (var includeProperty in includeProperties)
{
set = set.Include(includeProperty);
}
return set;
}
}
}
|
159da40325799be5bc9e7d4332332a448b210ce0
|
C#
|
didiercauvin/Etudes
|
/Hospital/AdministrationContext/Patient.cs
| 2.625
| 3
|
using BuildingBlocks;
using System;
namespace AdministrationContext
{
public class Patient : AggregateRoot
{
public string Name { get; }
public string FirstName { get; }
public DateTime Birthdate { get; }
public string Adresse1 { get; }
public string Adresse2 { get; }
public string PostalCode { get; }
public string City { get; }
private Patient(
string name,
string firstName,
DateTime birthdate,
string adresse1,
string adresse2,
string postalCode,
string city)
{
Name = name;
FirstName = firstName;
Birthdate = birthdate;
Adresse1 = adresse1;
Adresse2 = adresse2;
PostalCode = postalCode;
City = city;
ApplyChange(new PatientRegistered(Id));
}
public static Patient Create(
string name,
string firstName,
DateTime birthdate,
string adresse1,
string adresse2,
string postalCode,
string city)
{
return new Patient(name, firstName, birthdate, adresse1, adresse2, postalCode, city);
}
protected override void RegisterAppliers()
{
RegisterApplier<PatientRegistered>(this.Apply);
}
private void Apply(PatientRegistered patient)
{
}
}
}
|
1e9c933237a439759ec34f7fc332bf5d52aca09b
|
C#
|
ricecrispy/clerk-data
|
/src/clerk-data-data-access/Repository/IMemberRepository.cs
| 2.734375
| 3
|
using clerk_data_data_access.Models;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace clerk_data_data_access.Repository
{
public interface IMemberRepository
{
/// <summary>
/// Create a Member object in the database.
/// </summary>
/// <param name="member"></param>
/// <returns></returns>
Task CreateMemberAsync(Member member);
/// <summary>
/// Retrieve a Member object with the matching bioguide ID.
/// </summary>
/// <param name="memberBioGuideId"></param>
/// <returns></returns>
Task<Member> GetMemberAsync(string memberBioGuideId);
/// <summary>
/// Search and retrieve all Member objects.
/// </summary>
/// <returns></returns>
Task<IEnumerable<Member>> SearchMembersAsync();
/// <summary>
/// Update a Member object with matching bioguide ID.
/// </summary>
/// <param name="memberBioGuideId"></param>
/// <param name="member"></param>
/// <returns></returns>
Task UpdateMemberAsync(string memberBioGuideId, Member member);
/// <summary>
/// Delete a Member object with matching bioguide ID.
/// </summary>
/// <param name="memberBioGuideId"></param>
/// <returns></returns>
Task DeleteMemberAsync(string memberBioGuideId);
/// <summary>
/// Add state information and CommitteeAssignment objects to a Member object.
/// </summary>
/// <param name="member"></param>
/// <returns></returns>
Task<Member> GetStateAndCommitteeAssignmentsAsync(Member member);
}
}
|
4c0aab135672b9a9c442c4f561a050c860bece8e
|
C#
|
ProgrammerMaf/PokerBot
|
/ConsoleClient/Program.cs
| 3.078125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PokerObjects;
using PokerPlayer;
using SingleRoung;
using UserPlayer;
namespace ConsoleClient
{
class Program
{
static void Main(string[] args)
{
var cards = Card.GetAllCards().ToList();
var rand = new Random(DateTime.Now.DayOfYear);
var indexCards = rand.Next(cards.Count());
var id = 0;
var firstPlayer = new UserPlayer.UserPlayer(++id, 300);
var secondPlayer = new Player(++id, 200) {GetBet = (_, __, ___, ____) => 10};
var game =
new SingleRound(new List<PlayerBase> { firstPlayer, secondPlayer}, cards, 2, 2);
while (game.Round != Round.Finish)
{
Console.WriteLine($"банк: {game.Pot}");
Console.WriteLine("Карты на столе: ");
foreach (var card in game.DeckOnTable)
Console.Write($"{card} ");
Console.WriteLine(".");
game = game.PlayRound();
}
Console.WriteLine("Выиграли: ");
foreach (var winner in game.SelectWinners())
{
Console.WriteLine(winner);
}
Console.ReadLine();
}
}
public static class ListExtension
{
public static T GetAndRemove<T>(this List<T> list, int index)
{
var e = list[index];
list.RemoveAt(index);
return e;
}
}
}
|
f7994d6fb95a426fc2cda19c3e7500791623a04e
|
C#
|
bobbanks/Xamarin.Spikes
|
/Spikes/Spikes/Pages/MainPage.cs
| 2.65625
| 3
|
using System;
using Xamarin.Forms;
using Spikes.Pages;
namespace Spikes {
public class MainPage : BaseView {
private ListView listView;
public MainPage() {
var layout = new StackLayout() {
VerticalOptions = LayoutOptions.FillAndExpand,
BackgroundColor = Color.White
};
listView = new ListView() {
RowHeight = 40,
ItemsSource = new string[] {
"Json",
"MVVM",
"WebView",
"Quiz",
"Download"
}
};
listView.ItemTapped += HandleItemTapped;
layout.Children.Add(listView);
Title = "Spikes";
Content = layout;
}
private void HandleItemTapped (object sender, ItemTappedEventArgs e)
{
listView.SelectedItem = null;
var item = (string)e.Item;
switch (item) {
case "Json":
Navigation.PushAsync(new JsonWebServicePage());
break;
case "MVVM":
Navigation.PushAsync(new BeerListView());
break;
case "WebView":
Navigation.PushAsync(new WebViewPage());
break;
case "Quiz":
Navigation.PushAsync(new QuizView());
break;
case "Download":
Navigation.PushAsync(new DownloadView());
break;
default:
throw new ArgumentOutOfRangeException("Unknown page");
}
}
}
}
|
0ef42832b0a43bfbc4e576e0c871d6da28a7a843
|
C#
|
paulyoder/autonotify
|
/src/AutoNotify/AutoNotifyAttribute.cs
| 3.078125
| 3
|
using System;
namespace AutoNotify
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, Inherited = false, AllowMultiple = false)]
public sealed class AutoNotifyAttribute : Attribute
{
public AutoNotifyAttribute()
{
Fire = FireOptions.Always;
}
/// <summary>
/// Under what circumstances to fire the event.
/// </summary>
/// <remarks>Defaults to <see cref="FireOptions.Always"/>.</remarks>
public FireOptions Fire { get; set; }
/// <summary>
/// A type that inherits from DependencyMap{T} or DependencyMap, used for setting up dependent properties.
/// </summary>
public Type DependencyMap { get; set; }
}
public enum FireOptions
{
/// <summary>
/// Fire the event any time a setter is called.
/// </summary>
Always,
/// <summary>
/// Fire the event only when the given value is different than the previous value.
/// </summary>
OnlyOnChange
}
}
|
833212ed0d8461d887028b4556b92e0f10a9dabd
|
C#
|
lazicsasalaki/AI-Final
|
/LaMountain_AI_Final/LaMountain_AI_Final/Gene.cs
| 3.328125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
namespace LaMountain_AI_Final
{
class Gene
{
int color;
int fitnessValue;
public Gene(int _color)
{
color = _color;
fitnessValue = int.MaxValue;
}
public int CalcFitnessValue(int _color)
{
if (fitnessValue == int.MaxValue)
{
fitnessValue = Math.Abs(_color - color);
}
return fitnessValue;
}
public int GeneColor
{
get { return color; }
}
public void SetColor(int _color)
{
color = _color;
fitnessValue = int.MaxValue;
}
public int Fitness
{
get { return fitnessValue; }
}
}
}
|
a71f6656ba11c9d806b1f259a1b0b02a3346bf14
|
C#
|
BrooklynGabe/Naive-2FA-Password
|
/TwoFactor.API/Models/TwoFactorService.cs
| 2.765625
| 3
|
using System;
using System.Linq;
using TwoFactor.Common;
using TwoFactor.DataAccess;
namespace TwoFactor.API.Models
{
public class TwoFactorService
{
public TwoFactorService()
{
_context = new TwoFactorContext();
_reader = new OneTimeSecretReader(_context);
_options = new TimeBasedOneTimeOptions();
_interval = new ValidUntilCalculator();
// Hard-coded 5 minutes
_options.TimeInterval = 300;
}
public bool DoesSecretExistForUser(string UserLoginName)
{
var now = DateTime.Now;
var expires = _interval.RoundTimeUpToNearest(now, TimeSpan.FromSeconds(_options.TimeInterval));
return _reader
.Any(s =>
s.UserLoginName == UserLoginName.Trim()
&& now <= s.ValidUntil);
}
public bool VerifyPasswordForUser(string UserLoginName, string OneTimePassword)
{
var now = DateTime.Now;
var expires = _interval.RoundTimeUpToNearest(now, TimeSpan.FromSeconds(_options.TimeInterval));
var existingSecret = _reader
.Where(s =>
s.UserLoginName == UserLoginName.Trim()
&& now <= s.ValidUntil )
.Select(s => s.Secret)
.FirstOrDefault();
if (existingSecret == null)
return false;
var secretProvider = new ExistingSecretProvider(existingSecret);
var generator = new TimeBasedOneTimeGenerator(secretProvider, _options, _interval);
var generatedPassword = generator.GeneratePassword();
return OneTimePassword == generatedPassword;
}
public void SetSecretForUser(string UserLoginName)
{
var now = DateTime.Now;
var expires = _interval.RoundTimeUpToNearest(now, TimeSpan.FromSeconds(_options.TimeInterval));
var secretProvider = new ActiveNullSecretProvider();
var command = new SaveSecretForUserCommand(_context)
{
Secret = secretProvider.Secret,
ValidUntil = expires
};
command.UserLoginName = UserLoginName.Trim();
try
{
command.Execute();
}
catch
{
//TODO: Some Exception Handling
}
}
public void DeleteSecretForUser(string UserLoginName)
{
var command = new DeleteSecretForUserCommand(_context);
command.UserLoginName = UserLoginName.Trim();
try
{
command.Execute();
}
catch
{
//TODO: Some Exception Handling
}
}
private readonly IOneTimePasswordOptions _options;
private readonly IRoundTimeUp _interval;
private readonly TwoFactorContext _context;
private readonly OneTimeSecretReader _reader;
}
}
|
bafe3a781e70ea9ddaaf8b19b2018b9611a74c36
|
C#
|
freakingawesome/FreakingAwesome.Data
|
/FreakingAwesome.Data.Examples/ResultExtensions/AsyncUsageExamples.cs
| 2.8125
| 3
|
using System.Threading.Tasks;
namespace FreakingAwesome.Data.Examples.ResultExtensions
{
public class AsyncUsageExamples
{
public async Task<string> Promote_with_async_methods_in_the_beginning_of_the_chain(long id)
{
var gateway = new EmailGateway();
return await GetByIdAsync(id)
.EnsureAsync(customer => customer.CanBePromoted(), "The customer has the highest status possible")
.OnSuccessAsync(customer => customer.Promote())
.OnSuccessAsync(customer => gateway.SendPromotionNotification(customer.Email))
.OnBothAsync(result => result.IsSuccess ? "Ok" : result.Error.FormatString());
}
public async Task<string> Promote_with_async_methods_in_the_beginning_and_in_the_middle_of_the_chain(long id)
{
var gateway = new EmailGateway();
return await GetByIdAsync(id)
.EnsureAsync(customer => customer.CanBePromoted(), "The customer has the highest status possible")
.OnSuccessAsync(customer => customer.PromoteAsync())
.OnSuccessAsync(customer => gateway.SendPromotionNotificationAsync(customer.Email))
.OnBothAsync(result => result.IsSuccess ? "Ok" : result.Error.FormatString());
}
public Task<Result<Customer>> GetByIdAsync(long id)
{
return Task.FromResult(Result.Ok(new Customer()));
}
public Result<Customer> GetById(long id)
{
return Result.Ok(new Customer());
}
public class Customer
{
public string Email { get; }
public Customer()
{
}
public bool CanBePromoted()
{
return true;
}
public void Promote()
{
}
public Task PromoteAsync()
{
return Task.FromResult(1);
}
}
public class EmailGateway
{
public Result SendPromotionNotification(string email)
{
return Result.Ok();
}
public Task<Result> SendPromotionNotificationAsync(string email)
{
return Task.FromResult(Result.Ok());
}
}
}
}
|
b39e549938bf8d0f165b10a450d62e0d57bb5939
|
C#
|
harmonc/ToasterGame
|
/Assets/Scripts/SpawnerScript.cs
| 2.59375
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnerScript : MonoBehaviour {
public GameObject enemy;
public GameObject enemy2;
private float targetTime = 0.0f;
// Use this for initialization
void Start () {
}
void Update(){
targetTime -= Time.deltaTime;
if (targetTime <= 0.0f)
{
SpawnEnemy();
targetTime = 1.5f;
}
}
void SpawnEnemy()
{
GameObject enemyToSpawn;
if (Random.Range(0.0f, 1.0f) >= 0.5f)
{
enemyToSpawn = enemy;
}
else
{
enemyToSpawn = enemy2;
}
GameObject e = Instantiate (enemyToSpawn, new Vector3 (Random.Range (-3.0f, 3.0f), 7, 1), transform.rotation);
e.SetActive(true);
}
}
|
191bf2815fe2bdc52c550ba80832baf612f2e887
|
C#
|
HardWorkerFree/MailingsWPF
|
/MailingsWPF/MainWindow.xaml.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Xml;
using Microsoft.Win32;
namespace MailingsWPF
{
/// <summary>
/// Логика взаимодействия для MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private ObservableCollection<Mailing> _observableMailings;
private Regex _regex;
private Thread _thread;
private ProgressDialog _progressDialog;
private bool _stopThread;
public MainWindow()
{
InitializeComponent();
this._regex = new Regex(@"^[0-9]$");
needToGenerateTextBox.PreviewTextInput += NeedToGenerateTextBox_PreviewTextInput;
}
private void NeedToGenerateTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e) //ограничиваем текст бокс на ввод только натуральных чисел от 0 до 99 999
{
Match match = _regex.Match(e.Text);
TextBox natualNumberTextBox = sender as TextBox;
bool isNaturalNumber = (natualNumberTextBox.Text != "") && (natualNumberTextBox.Text.Length < 6) && (match.Success);
if (!isNaturalNumber)
{
(sender as TextBox).Text = "1";
e.Handled = true;
}
}
private void generateMailingsButton_Click(object sender, RoutedEventArgs e)
{
int mailingsAmount = Convert.ToInt32(needToGenerateTextBox.Text);
this._progressDialog = new ProgressDialog();
this._progressDialog.loadingProgressBar.Minimum = 0;
this._progressDialog.loadingProgressBar.Maximum = mailingsAmount;
this._stopThread = false;
this._thread = new Thread(new ParameterizedThreadStart(MailingsGeneratorThread));
this._thread.Start(mailingsAmount);
if (this._progressDialog.ShowDialog() == true)
{
this._stopThread = true;
}
}
private void MailingsGeneratorThread(object amount)
{
int mailingsAmount = (int)amount;
List<Mailing> generatedMailings = GenerateMailings(mailingsAmount);
this._observableMailings = new ObservableCollection<Mailing>(generatedMailings);
try
{
Dispatcher.Invoke(() => mailingsDataGrid.ItemsSource = this._observableMailings);
Dispatcher.Invoke(() => this._progressDialog.Close());
Dispatcher.Invoke(() => UpdateMailingsAmount());
}
catch(Exception ex)
{
}
}
/// <summary>
/// Возвращает список из случайо сгенерированных почтовых отправлений.
/// </summary>
/// <param name="mailingsAmount">Количество почтовых отправлений, которое необходимо сгенерировать.</param>
/// <returns>Список из случайо сгенерированных почтовых отправлений.</returns>
private List<Mailing> GenerateMailings(int mailingsAmount)
{
Mailing mailing;
List<Mailing> mailings = new List<Mailing>();
Random random = new Random();
DateTime randomDateTime;
int randomDay;
int randomMonth;
int randomYear;
int randomZipCodeSender;
int randomZipCodeRecipient;
int randomPackageWeight;
int i = 0;
ApartmentState threadApartmentState = Thread.CurrentThread.GetApartmentState();
while(i < mailingsAmount && !_stopThread)
{
randomYear = random.Next(2001, 2016);
randomMonth = random.Next(1, 13);
randomDay = random.Next(1, 29);
randomDateTime = new DateTime(randomYear, randomMonth, randomDay);
randomZipCodeSender = random.Next(100000, 1000000);
randomZipCodeRecipient = random.Next(100000, 1000000);
randomPackageWeight = random.Next(10, 50000);
mailing = new Mailing(randomDateTime, randomZipCodeSender, randomZipCodeRecipient, randomPackageWeight);
mailings.Add(mailing);
Thread.Sleep(100);
try
{
Dispatcher.Invoke(() => this._progressDialog.loadingProgressBar.Value = i);
}
catch(Exception ex)
{
}
i++;
}
return mailings;
}
private void mailingsDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
bool isItemSelected = ((sender as DataGrid).SelectedIndex != -1);
if (isItemSelected)
{
SelectedMailTextBox.Text = "Выбрано отправление: " + ((sender as DataGrid).SelectedIndex + 1);
}
}
private void UpdateMailingsAmount()
{
MailingsAmountTextBox.Text = "Всего почтовых отправлений: " + mailingsDataGrid.Items.Count.ToString();
}
private void saveMailingsButton_Click(object sender, RoutedEventArgs e)
{
WriteMailingsToXML();
}
private void WriteMailingsToXML()
{
XmlWriterSettings xmlSettings = new XmlWriterSettings();
xmlSettings.Indent = true;
xmlSettings.IndentChars = "\t";
xmlSettings.NewLineOnAttributes = true;
XmlWriter xmlWriter = XmlWriter.Create(@"mailings.xml",xmlSettings);
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("mailings");
foreach(Mailing mailing in this._observableMailings)
{
xmlWriter.WriteStartElement("mailing");
xmlWriter.WriteAttributeString("MailingDate", mailing.MailingDate.ToLongDateString());
xmlWriter.WriteAttributeString("ZipCodeOfSender", mailing.ZipCodeOfSender.ToString());
xmlWriter.WriteAttributeString("ZipCodeOfRecipient", mailing.ZipCodeOfRecipient.ToString());
xmlWriter.WriteAttributeString("PackageWeightInGrams", mailing.PackageWeightInGrams.ToString());
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndDocument();
xmlWriter.Close();
}
private void loadMailingsButton_Click(object sender, RoutedEventArgs e)
{
string fileName;
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.DefaultExt = ".xml";
fileDialog.Filter = "XML files (*.xml)|*.xml";
if (fileDialog.ShowDialog() == true)
{
fileName = fileDialog.FileName;
LoadMailingsFromXML(fileName);
}
}
private void LoadMailingsFromXML(string fileName)
{
List<Mailing> mailingsList = new List<Mailing>();
XmlDocument xmlDocument = new XmlDocument();
try
{
xmlDocument.Load(fileName);
XmlNodeList xmlNodeList = xmlDocument.SelectNodes("mailings");
xmlNodeList = xmlNodeList[0].ChildNodes;
DateTime mailingDate;
int zipCodeSender;
int zipCodeRecipient;
int packageWeight;
foreach(XmlNode node in xmlNodeList)
{
mailingDate = Convert.ToDateTime(node.Attributes.GetNamedItem("MailingDate").Value.ToString());
zipCodeSender = Convert.ToInt32(node.Attributes.GetNamedItem("ZipCodeOfSender").Value.ToString());
zipCodeRecipient = Convert.ToInt32(node.Attributes.GetNamedItem("ZipCodeOfRecipient").Value.ToString());
packageWeight = Convert.ToInt32(node.Attributes.GetNamedItem("PackageWeightInGrams").Value.ToString());
mailingsList.Add(new Mailing(mailingDate, zipCodeSender, zipCodeRecipient, packageWeight));
}
this._observableMailings = new ObservableCollection<Mailing>(mailingsList);
mailingsDataGrid.ItemsSource = this._observableMailings;
UpdateMailingsAmount();
}
catch(Exception ex)
{
}
}
}
}
|
b7325d35c63bde79a03987b8739db51c1dec1839
|
C#
|
janektichy/herokuTodoApp
|
/firstORM/firstORM/Services/TodoService.cs
| 2.796875
| 3
|
using firstORM.Database;
using firstORM.Models.Entities;
using firstORM.Todos;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace firstORM.Services
{
public class TodoService
{
private ApplicationDbContext DbContext { get; }
public TodoService(ApplicationDbContext dbContext)
{
DbContext = dbContext;
}
public Todo FindById(long id)
{
return DbContext.Todos.Find(id);
}
public Todo AddTodo(Todo todo)
{
var savedTodo = DbContext.Todos.Add(todo).Entity;
DbContext.SaveChanges();
return savedTodo;
}
public List<Todo> FindAll()
{
var allTodos = DbContext.Todos.Include(a => a.Assignee).ToList();
return allTodos;
}
public void RemoveTodo(Todo todo)
{
DbContext.Todos.Remove(todo);
DbContext.SaveChanges();
}
public bool EditTodo(long id, string title, bool isUrgent, bool isDone, string assignee)
{
Todo selectedTodo = DbContext.Todos.FirstOrDefault(t => t.Id == id);
if (title is not null)
{
selectedTodo.Title = title;
}
bool doesAssigneeExist = false;
if (assignee is not null)
{
foreach (var item in DbContext.Assignees)
{
if (item.Name == assignee)
{
doesAssigneeExist = true;
selectedTodo.AssigneeId = item.Id;
}
}
}
else
{
doesAssigneeExist = true;
}
selectedTodo.IsUrgent = isUrgent;
selectedTodo.IsDone = isDone;
DbContext.SaveChanges();
return doesAssigneeExist;
}
}
}
|
71f56a42a074358ad1c5d6bd7ad14dc14b3050f0
|
C#
|
yazilimfikirleri/16-WhileDoWhile
|
/14-WhileDoWhile/Program.cs
| 3.734375
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _16_WhileDoWhile
{
class Program
{
static void Main(string[] args)
{
//For döngüsü gibi, Bir işi belirli sayıda yapmamızı sağlayan döngüdür.For döngüsünden farklı olarak döngü başlangıç değeri ve iterasyon bilgisi döngü içerisinde belirtilmez.
//int i = 1;
//while (i <= 100)
//{
// Console.WriteLine(i);
// i++;
//}
//Console.Read();
//While Döngüsü Kullanarak 1'den 10'a kadar çarpım tablosunu ekranda yazdırma.
//int y = 1;
//while (y <= 10)
//{
// int z = 1;
// while (z <= 10)
// {
// Console.WriteLine($"{y}x{z}={y * z}");
// z++;
// }
// Console.WriteLine("------");
// y++;
//}
//Console.Read();
//Do..While
//Do while döngüsü, while döngüsü ile aynı yapıya sahiptir. While döngüsünde ki gibi iterasyon ve döngünün başlangıç değeri döngü dışarısında belirtilir. Tek farkı, Do While döngüsü ne olursa olsun en az 1 kez çalışır. Diğer döngüler şart sağlandığında çalışırken, do while döngüsü şart ne olursa olsun bir kez çalışacaktır.
//int sayi = 1;
//do
//{
// Console.WriteLine("sayı=" + sayi);
// sayi++;
//}
//while (sayi <= 100);
//Console.Read();
int x, y, sonuc;
string devam;
do
{
y = 1;
Console.WriteLine("Çarpım tablosu oluşturulacak sayıyı girin.");
x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(x + " Çarpım tablosu");
while (y <= 10)
{
sonuc = y * x;
Console.WriteLine(y + "*" + x + "=" + sonuc);
y++;
}
Console.WriteLine("başka bir çarpım tablosu oluşturmak ister misin?(E/H)");
devam = Console.ReadLine();
}
while (devam == "E" || devam == "e");
}
}
}
|
986bf16144a8c9e49ce223d7d1c468420a52a3bd
|
C#
|
patdaman/dlR_ManageMachineVars
|
/Lib/CommonUtils.AppConfiguration/CommandLineConfigProvider.cs
| 3
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CommonUtils.AppConfiguration
{
///-------------------------------------------------------------------------------------------------
/// <summary> Used to provide config values from the command line. </summary>
///
/// <remarks> Pdelosreyes, 2/8/2017. </remarks>
///-------------------------------------------------------------------------------------------------
public class CommandLineConfigProvider : IAppConfigurationProvider
{
private List<string> Args = null;
public CommandLineConfigProvider(string[] args)
{
Args = new List<string>(args);
}
public object GetValue(string key)
{
if (key == null)
throw new ArgumentNullException();
if (Args == null)
throw new Exception("Args was null. CommandLineConfigProvider was not configured correctly.");
int index = GetIndex(key);
object value = null;
if(index>-1)
{
value = Args[index + 1];
}
return value;
}
private int GetIndex(string key)
{
int index = -1;
index = Args.IndexOf($"-{key}");
if( index == -1)
index = Args.IndexOf($"--{key}");
if(index == -1)
index = Args.IndexOf($"/{key}");
return index;
}
}
}
|
6c528c7760b40b605f8417599f59d45af8ee5a57
|
C#
|
LiruJ/LiruGameHelper
|
/LiruGameHelper/Signals/Signal.cs
| 3.109375
| 3
|
using LiruGameHelper.Exceptions;
using System;
using System.Collections.Generic;
namespace LiruGameHelper.Signals
{
/// <summary> Allows for SignalConnections to disconnect without having access to any other functions. </summary>
internal interface ISignal
{
void Disconnect(SignalConnection connection);
}
internal struct Binding
{
#region Properties
/// <summary> <c>true</c> if the bound event should only fire once. </summary>
public bool OneTime { get; }
/// <summary> The ID of the binding. </summary>
public uint ID { get; }
/// <summary> The action bound to the ID. </summary>
public Action Action { get; }
#endregion
#region Constructors
public Binding(uint id, Action action, bool oneTime)
{
ID = id;
Action = action;
OneTime = oneTime;
}
#endregion
}
internal struct Binding<T1>
{
#region Properties
/// <summary> <c>true</c> if the bound event should only fire once. </summary>
public bool OneTime { get; set; }
/// <summary> The ID of the binding, represents the index within the signal. </summary>
public uint ID { get; set; }
/// <summary> The action bound to the ID. </summary>
public Action<T1> Action { get; set; }
#endregion
#region Constructors
public Binding(uint id, Action<T1> action, bool oneTime)
{
ID = id;
Action = action;
OneTime = oneTime;
}
#endregion
}
internal struct Binding<T1, T2>
{
#region Properties
/// <summary> <c>true</c> if the bound event should only fire once. </summary>
public bool OneTime { get; set; }
/// <summary> The ID of the binding. </summary>
public uint ID { get; set; }
/// <summary> The action bound to the ID. </summary>
public Action<T1, T2> Action { get; set; }
#endregion
#region Constructors
public Binding(uint id, Action<T1, T2> action, bool oneTime)
{
ID = id;
Action = action;
OneTime = oneTime;
}
#endregion
}
/// <summary> Represents a Signal with no return value and no parameters. </summary>
public class Signal : ISignal, IConnectableSignal
{
#region Binding Fields
/// <summary> The collection of functions that are bound to this signal. </summary>
private readonly Dictionary<uint, Binding> bindings = new Dictionary<uint, Binding>();
/// <summary> A collection of bindings that is populated from the main collection every time <see cref="Invoke"/> is called. </summary>
private readonly List<Binding> bindingsCopy = new List<Binding>();
/// <summary> The total amount of functions that have been bound to this signal, including the ones that were removed. </summary>
private uint totalBindings = 0;
#endregion
#region Properties
/// <summary> The total number of bindings this signal has. </summary>
public int BindingsCount => bindings.Count;
#endregion
#region Connection Functions
/// <summary> Connect the given function to this signal, calling it when the signal is invoked. </summary>
/// <param name="action"> The function that is invoked. </param>
/// <returns> A <see cref="SignalConnection"/> for the created binding. </returns>
public SignalConnection Connect(Action action) => connect(action, false);
/// <summary> Connect the given function to this <see cref="Signal"/>, calling it when invoked then immediately disconnecting. </summary>
/// <param name="action"> The function that is invoked. </param>
/// <returns> A <see cref="SignalConnection"/> for the created binding. </returns>
public SignalConnection ConnectOneTime(Action action) => connect(action, true);
/// <summary> Connects the given <paramref name="action"/> with the given <paramref name="oneTime"/> flag. </summary>
/// <param name="action"> The function that is invoked. </param>
/// <param name="oneTime"> <c>true</c> if the function should only be called once; otherwise <c>false</c>. </param>
/// <returns> A <see cref="SignalConnection"/> for the created binding. </returns>
private SignalConnection connect(Action action, bool oneTime)
{
// Add the new binding to the array
bindings.Add(totalBindings, new Binding(totalBindings, action, oneTime));
// As a new binding was just added, increment the total and current amount of bindings
totalBindings++;
// Return a new connection.
return new SignalConnection(totalBindings, this);
}
/// <summary> Disconnects the given connection. connection.Disconnect() is also valid. </summary>
/// <param name="connection"> The connection to disconnect. </param>
public void Disconnect(SignalConnection connection)
{
// Check that the connection's signal is this signal, otherwise throw an exception.
if (connection.ConnectedSignal != this) throw new InvalidDisconnectionException("SignalConnection given to Signal does not belong to this Signal.");
// Get the binding that the connection represents.
if (!bindings.TryGetValue(connection.ID, out Binding binding)) throw new InvalidDisconnectionException("Connection ID does not exist.");
// Disconnect the binding.
disconnect(binding.ID);
}
/// <summary> Disconnects all bound functions from this signal. </summary>
public void DisconnectAll() => bindings.Clear();
/// <summary> Disconnects the binding with the given <paramref name="bindingID"/> from this signal. </summary>
/// <param name="bindingID"> The ID of the binding to remove. </param>
private void disconnect(uint bindingID) => bindings.Remove(bindingID);
#endregion
#region Invocation Functions
/// <summary> Calls all of the bound functions. </summary>
public void Invoke()
{
// Copy the bindings, so that the signal can be worked on from any called function.
bindingsCopy.Clear();
foreach (Binding binding in bindings.Values)
bindingsCopy.Add(binding);
// Invoke each action.
foreach (Binding binding in bindingsCopy)
{
// Invoke the action.
binding.Action.Invoke();
// If the binding was one time, disonnect it.
if (binding.OneTime) disconnect(binding.ID);
}
}
#endregion
}
public class Signal<T1> : ISignal, IConnectableSignal<T1>
{
#region Binding Fields
/// <summary> The collection of functions that are bound to this signal. </summary>
private readonly Dictionary<uint, Binding<T1>> bindings = new Dictionary<uint, Binding<T1>>();
/// <summary> A collection of bindings that is populated from the main collection every time <see cref="Invoke"/> is called. </summary>
private readonly List<Binding<T1>> bindingsCopy = new List<Binding<T1>>();
/// <summary> The total amount of functions that have been bound to this signal, including the ones that were removed. </summary>
private uint totalBindings = 0;
#endregion
#region Properties
/// <summary> The total number of bindings this signal has. </summary>
public int BindingsCount => bindings.Count;
#endregion
#region Connection Functions
/// <summary> Connect the given function to this signal, calling it when the signal is invoked. </summary>
/// <param name="action"> The function that is invoked. </param>
/// <returns> A <see cref="SignalConnection"/> for the created binding. </returns>
public SignalConnection Connect(Action<T1> action) => connect(action, false);
/// <summary> Connect the given function to this <see cref="Signal"/>, calling it when invoked then immediately disconnecting. </summary>
/// <param name="action"> The function that is invoked. </param>
/// <returns> A <see cref="SignalConnection"/> for the created binding. </returns>
public SignalConnection ConnectOneTime(Action<T1> action) => connect(action, true);
/// <summary> Connects the given <paramref name="action"/> with the given <paramref name="oneTime"/> flag. </summary>
/// <param name="action"> The function that is invoked. </param>
/// <param name="oneTime"> <c>true</c> if the function should only be called once; otherwise <c>false</c>. </param>
/// <returns> A <see cref="SignalConnection"/> for the created binding. </returns>
private SignalConnection connect(Action<T1> action, bool oneTime)
{
// Add the new binding to the array
bindings.Add(totalBindings, new Binding<T1>(totalBindings, action, oneTime));
// As a new binding was just added, increment the total and current amount of bindings
totalBindings++;
// Return a new connection.
return new SignalConnection(totalBindings, this);
}
/// <summary> Disconnects the given connection. connection.Disconnect() is also valid. </summary>
/// <param name="connection"> The connection to disconnect. </param>
public void Disconnect(SignalConnection connection)
{
// Check that the connection's signal is this signal, otherwise throw an exception.
if (connection.ConnectedSignal != this) throw new InvalidDisconnectionException("SignalConnection given to Signal does not belong to this Signal.");
// Get the binding that the connection represents.
if (!bindings.TryGetValue(connection.ID, out Binding<T1> binding)) throw new InvalidDisconnectionException("Connection ID does not exist.");
// Disconnect the binding.
disconnect(binding.ID);
}
/// <summary> Disconnects all bound functions from this signal. </summary>
public void DisconnectAll() => bindings.Clear();
/// <summary> Disconnects the binding with the given <paramref name="bindingID"/> from this signal. </summary>
/// <param name="bindingID"> The ID of the binding to remove. </param>
private void disconnect(uint bindingID) => bindings.Remove(bindingID);
#endregion
#region Invocation Functions
/// <summary> Calls all of the bound functions with the given argument. </summary>
/// <param name="input"> The given argument. </param>
public void Invoke(T1 input)
{
// Copy the bindings, so that the signal can be worked on from any called function.
bindingsCopy.Clear();
foreach (Binding<T1> binding in bindings.Values)
bindingsCopy.Add(binding);
// Invoke each action.
foreach (Binding<T1> binding in bindingsCopy)
{
// Invoke the action.
binding.Action.Invoke(input);
// If the binding was one time, disonnect it.
if (binding.OneTime) disconnect(binding.ID);
}
}
#endregion
}
public class Signal<T1, T2> : ISignal, IConnectableSignal<T1, T2>
{
#region Binding Fields
/// <summary> The collection of functions that are bound to this signal. </summary>
private readonly Dictionary<uint, Binding<T1, T2>> bindings = new Dictionary<uint, Binding<T1, T2>>();
/// <summary> A collection of bindings that is populated from the main collection every time <see cref="Invoke"/> is called. </summary>
private readonly List<Binding<T1, T2>> bindingsCopy = new List<Binding<T1, T2>>();
/// <summary> The total amount of functions that have been bound to this signal, including the ones that were removed. </summary>
private uint totalBindings = 0;
#endregion
#region Properties
/// <summary> The total number of bindings this signal has. </summary>
public int BindingsCount => bindings.Count;
#endregion
#region Connection Functions
/// <summary> Connect the given function to this signal, calling it when the signal is invoked. </summary>
/// <param name="action"> The function that is invoked. </param>
/// <returns> A <see cref="SignalConnection"/> for the created binding. </returns>
public SignalConnection Connect(Action<T1, T2> action) => connect(action, false);
/// <summary> Connect the given function to this <see cref="Signal"/>, calling it when invoked then immediately disconnecting. </summary>
/// <param name="action"> The function that is invoked. </param>
/// <returns> A <see cref="SignalConnection"/> for the created binding. </returns>
public SignalConnection ConnectOneTime(Action<T1, T2> action) => connect(action, true);
/// <summary> Connects the given <paramref name="action"/> with the given <paramref name="oneTime"/> flag. </summary>
/// <param name="action"> The function that is invoked. </param>
/// <param name="oneTime"> <c>true</c> if the function should only be called once; otherwise <c>false</c>. </param>
/// <returns> A <see cref="SignalConnection"/> for the created binding. </returns>
private SignalConnection connect(Action<T1, T2> action, bool oneTime)
{
// Add the new binding to the array
bindings.Add(totalBindings, new Binding<T1, T2>(totalBindings, action, oneTime));
// As a new binding was just added, increment the total and current amount of bindings
totalBindings++;
// Return a new connection.
return new SignalConnection(totalBindings, this);
}
/// <summary> Disconnects the given connection. connection.Disconnect() is also valid. </summary>
/// <param name="connection"> The connection to disconnect. </param>
public void Disconnect(SignalConnection connection)
{
// Check that the connection's signal is this signal, otherwise throw an exception.
if (connection.ConnectedSignal != this) throw new InvalidDisconnectionException("SignalConnection given to Signal does not belong to this Signal.");
// Get the binding that the connection represents.
if (!bindings.TryGetValue(connection.ID, out Binding<T1, T2> binding)) throw new InvalidDisconnectionException("Connection ID does not exist.");
// Disconnect the binding.
disconnect(binding.ID);
}
/// <summary> Disconnects all bound functions from this signal. </summary>
public void DisconnectAll() => bindings.Clear();
/// <summary> Disconnects the binding with the given <paramref name="bindingID"/> from this signal. </summary>
/// <param name="bindingID"> The ID of the binding to remove. </param>
private void disconnect(uint bindingID) => bindings.Remove(bindingID);
#endregion
#region Invocation Functions
/// <summary> Calls all of the bound functions with the given arguments. </summary>
/// <param name="input"> The given argument. </param>
/// <param name="input"> The second given argument. </param>
public void Invoke(T1 firstInput, T2 secondInput)
{
// Copy the bindings, so that the signal can be worked on from any called function.
bindingsCopy.Clear();
foreach (Binding<T1, T2> binding in bindings.Values)
bindingsCopy.Add(binding);
// Invoke each action.
foreach (Binding<T1, T2> binding in bindingsCopy)
{
// Invoke the action.
binding.Action.Invoke(firstInput, secondInput);
// If the binding was one time, disonnect it.
if (binding.OneTime) disconnect(binding.ID);
}
}
#endregion
}
}
|
d9b45d3310778f09cd8c31dcb921846d678f2727
|
C#
|
RamKrish786/EvenlyDivisible
|
/TestEvenlyDivisible/Program.cs
| 3.4375
| 3
|
using System;
namespace TestEvenlyDivisible
{
public class Program
{
public static void Main(string[] args)
{
bool isContinue = true;
Input obj = new Input();
while (isContinue)
{
//TODO : we need to remove below try catch block still we have try parse for each input, not doing any business logic by Exceptions and want to re-try something that may fail.
try
{
invalidLow:
Console.WriteLine("Please enter the Min value : ");
int minNumber;
var low = Console.ReadLine();
if (!int.TryParse(low, out minNumber))
{
Console.WriteLine("Please enter the valid Min value.");
goto invalidLow;
}
obj.Start = Convert.ToInt32(low);
if (obj.Start <= 0)
{
Console.WriteLine("Please enter the valid Min value.");
goto invalidLow;
}
invalidHigh:
Console.WriteLine("Please enter the Max value : ");
var high = Console.ReadLine();
if (!int.TryParse(high, out minNumber))
{
Console.WriteLine("Please Enter the valid Max value. ");
goto invalidHigh;
}
obj.End = Convert.ToInt32(high);
if (obj.End <= 0)
{
Console.WriteLine("Please Enter the valid Max value. ");
goto invalidHigh;
}
if (obj.Start > obj.End)
{
Console.WriteLine("Please Enter the valid values for Min and Max. ");
goto invalidLow;
}
invalidA:
Console.WriteLine("Please enter the vlaue for First Divisible");
var firstDivisible = Console.ReadLine();
if (!int.TryParse(firstDivisible, out minNumber))
{
Console.WriteLine("Please Enter the valid First Divisible value.");
goto invalidA;
}
obj.FirstDivisible = Convert.ToInt32(firstDivisible);
if (obj.FirstDivisible <= 0)
{
Console.WriteLine("Please Enter the valid First Divisible value. ");
goto invalidA;
}
invalidB:
Console.WriteLine("Please enter the vlaue for Second Divisible");
var secondDivisible = Console.ReadLine();
if (!int.TryParse(secondDivisible, out minNumber))
{
Console.WriteLine("Please Enter the valid Second Divisible value. ");
goto invalidB;
}
obj.SecondDivisible = Convert.ToInt32(secondDivisible);
if (obj.SecondDivisible <= 0)
{
Console.WriteLine("Please Enter the valid Second Divisible value.");
goto invalidB;
}
Console.WriteLine("Output : ");
CheckEvenlyDivisible(obj);
invalidChoice:
Console.WriteLine("Please enter Y to continue else N : ");
var val = Console.ReadLine();
if (val.Equals("N", StringComparison.InvariantCultureIgnoreCase))
{
isContinue = false;
}
else if (val.Equals("Y", StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine("Welcome back!");
}
else
{
Console.WriteLine("Please enter valid choice");
goto invalidChoice;
}
}
catch(Exception)
{
//TODO: Do we really need this option since the application getting crashed, or can we give the down time for the user until system is up
invalidExceptionChoice:
Console.WriteLine("Internal Application Error occured, still want to continue please press Y else N : ");
var val = Console.ReadLine();
if (val.Equals("N", StringComparison.InvariantCultureIgnoreCase))
{
isContinue = false;
}
else if (val.Equals("Y", StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine("Welcome back!");
}
else
{
Console.WriteLine("Please enter valid choice");
goto invalidExceptionChoice;
}
}
}
}
private static void CheckEvenlyDivisible(Input obj)
{
for (int i = obj.Start; i <= obj.End; i++)
{
if (i % obj.FirstDivisible == 0 && i % obj.SecondDivisible == 0)
{
Console.WriteLine("FancyPants");
}
else if (i % obj.FirstDivisible == 0)
{
Console.WriteLine("Fancy");
}
else if (i % obj.SecondDivisible == 0)
{
Console.WriteLine("Pants");
}
else
{
Console.WriteLine(i);
}
}
}
}
}
|
7ffdd65324158c6747fdd517c736cb6707d7f7cc
|
C#
|
mattan212/LeetCode
|
/UnitTests/NextPermutationTests.cs
| 3.25
| 3
|
using System.Linq;
using LeetCodeProjects;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTests
{
[TestClass]
public class NextPermutationTests
{
[TestMethod]
public void MyTestMethod1()
{
//Arrange
var input = new int[3] {1, 3, 2};
var expected = new int[3] {2, 1, 3};
//Act
var solver = new NextPermutation.Solution();
solver.NextPermutation(input);
//Assert
Assert.AreEqual(expected.Aggregate("", (c, n) => c + n + ""), input.Aggregate("", (c, n) => c + n + ""));
}
[TestMethod]
public void MyTestMethod2()
{
//Arrange
var input = new int[3] { 1, 5, 1 };
var expected = new int[3] { 5, 1, 1 };
//Act
var solver = new NextPermutation.Solution();
solver.NextPermutation(input);
//Assert
Assert.AreEqual(expected.Aggregate("", (c, n) => c + n + ""), input.Aggregate("", (c, n) => c + n + ""));
}
[TestMethod]
public void MyTestMethod3()
{
//Arrange
var input = new int[3] { 1, 0, 2 };
var expected = new int[3] { 1, 2, 0 };
//Act
var solver = new NextPermutation.Solution();
solver.NextPermutation(input);
//Assert
Assert.AreEqual(expected.Aggregate("", (c, n) => c + n + ""), input.Aggregate("", (c, n) => c + n + ""));
}
[TestMethod]
public void MyTestMethod4()
{
//Arrange
var input = new int[9] { 0, 4, 1, 2, 2, 1, 1, 0, 4 };
var expected = new int[9] { 0, 4, 1, 2, 2, 1, 1, 4, 0 };
//Act
var solver = new NextPermutation.Solution();
solver.NextPermutation(input);
//Assert
Assert.AreEqual(expected.Aggregate("", (c, n) => c + n + ""), input.Aggregate("", (c, n) => c + n + ""));
}
[TestMethod]
public void MyTestMethod5()
{
//Arrange
var input = new int[4] { 1, 2, 1, 5 };
var expected = new int[4] { 1, 2, 5, 1 };
//Act
var solver = new NextPermutation.Solution();
solver.NextPermutation(input);
//Assert
Assert.AreEqual(expected.Aggregate("", (c, n) => c + n + ""), input.Aggregate("", (c, n) => c + n + ""));
}
[TestMethod]
public void MyTestMethod6()
{
//Arrange
var input = new int[3] { 3, 2, 1 };
var expected = new int[3] { 1, 2, 3 };
//Act
var solver = new NextPermutation.Solution();
solver.NextPermutation(input);
//Assert
Assert.AreEqual(expected.Aggregate("", (c, n) => c + n + ""), input.Aggregate("", (c, n) => c + n + ""));
}
}
}
|
2b93dfc0f682b20438d11a37be470eca88f4b745
|
C#
|
jmcfet/skiaAndroidStart
|
/androidSkia/MainActivity.cs
| 2.671875
| 3
|
using Android.App;
using Android.Widget;
using Android.OS;
using SkiaSharp.Views.Android;
using SkiaSharp;
using System.Collections.Generic;
using System.Drawing;
namespace androidSkia
{
[Activity(Label = "androidSkia", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
SKCanvasView canvasView;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
canvasView = FindViewById<SKCanvasView>(Resource.Id.canvasView);
canvasView.PaintSurface += CanvasView_PaintSurface;
}
private void CanvasView_PaintSurface(object sender, SKPaintSurfaceEventArgs e)
{
SKCanvas canvas = e.Surface.Canvas;
canvas.Clear();
var circleFill = new SKPaint
{
IsAntialias = true,
Style = SKPaintStyle.Fill,
Color = SKColors.Blue
};
// DRAWING SHAPES
// draw the circle fill
canvas.DrawCircle(100, 100, 40, circleFill);
}
}
}
|
19e0f84e93c8f6a7806f154c459c4d0391082c46
|
C#
|
Udenrigsministeriet/iati-api
|
/Um.DataServices.Test/Unit/XmlFilePagingTest.cs
| 2.53125
| 3
|
using NUnit.Framework;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Collections.Generic;
using Um.DataServices.XmlFilePaging;
using System;
namespace Um.DataServices.Test.Unit
{
[TestFixture]
public class XmlFilePagingTest
{
[Test]
public void TestCalculatePageSize()
{
var actual = XmlFilePager.CalculatePageSize(0, 10);
Assert.That(actual, Is.EqualTo(0));
actual = XmlFilePager.CalculatePageSize(9, 10);
Assert.That(actual, Is.EqualTo(1));
actual = XmlFilePager.CalculatePageSize(11, 10);
Assert.That(actual, Is.EqualTo(2));
}
[Test]
public void TestReadRootAndElementsFromXmlDocument()
{
var xml = GetXmlExample();
using (var stringReader = new StringReader(xml))
using (var xmlReader = XmlReader.Create(stringReader))
{
var actual = XmlFilePager.ReadRootAndElementsFromXmlDocument(xmlReader, "iati-activity");
Assert.That(actual.DocumentRoot.Name.LocalName, Is.EqualTo("iati-activities"));
Assert.That(actual.Elements.Count, Is.EqualTo(2));
}
}
[Test]
public void TestPageAndIndexElements()
{
var rootAndElements = ReadRootAndElements(GetXmlExample());
var actual = XmlFilePager.PageAndIndexElements(rootAndElements, 1).ToList();
Assert.That(actual.Count, Is.EqualTo(2));
var actualEntry = actual.Single(x => x.Key == 1);
Assert.That(actualEntry.Value, Is.InstanceOf(typeof(XDocument)));
}
[Test]
public void TestCreateNewXDocumentFromExistingRoot()
{
var rootAndElements = ReadRootAndElements(GetXmlExample());
var originalRootName = rootAndElements.DocumentRoot.Name.LocalName;
var originalElementName = rootAndElements.Elements.First().Name.LocalName;
var originalElementCount = rootAndElements.Elements.Count();
var actual = XmlFilePager.CreateNewXDocumentFromExistingRoot(rootAndElements.DocumentRoot, rootAndElements.Elements);
Assert.That(actual.Root.Name.LocalName, Is.EqualTo(originalRootName));
var actualElements = actual.Descendants(originalElementName).ToList();
Assert.That(actualElements.Count, Is.EqualTo(originalElementCount));
}
[Test]
public void TestIEnumerablePage()
{
var numbers = new[] { 1, 2, 3, 4, 5 };
var actual = numbers.Page(1).ToArray();
Assert.That(actual.Length, Is.EqualTo(numbers.Length));
actual = numbers.Page(3).ToArray();
Assert.That(actual.Length, Is.EqualTo(2));
actual = numbers.Page(5).ToArray();
Assert.That(actual.Length, Is.EqualTo(1));
}
[Test]
public void TestUriCombine()
{
Assert.That(new Uri("test1", UriKind.RelativeOrAbsolute).Combine("test2").ToString(), Is.EqualTo("test1/test2"));
Assert.That(new Uri("test1/", UriKind.RelativeOrAbsolute).Combine("test2").ToString(), Is.EqualTo("test1/test2"));
Assert.That(new Uri("test1", UriKind.RelativeOrAbsolute).Combine("/test2").ToString(), Is.EqualTo("test1/test2"));
Assert.That(new Uri("test1/", UriKind.RelativeOrAbsolute).Combine("/test2").ToString(), Is.EqualTo("test1/test2"));
Assert.That(new Uri("/test1/", UriKind.RelativeOrAbsolute).Combine("/test2/").ToString(), Is.EqualTo("/test1/test2/"));
Assert.That(new Uri("", UriKind.RelativeOrAbsolute).Combine("/test2/").ToString(), Is.EqualTo("/test2/"));
Assert.That(new Uri("/test1/", UriKind.RelativeOrAbsolute).Combine("").ToString(), Is.EqualTo("/test1/"));
}
private static XmlFilePager.DocumentParts ReadRootAndElements(string xml)
{
using (var stringReader = new StringReader(xml))
using (var xmlReader = XmlReader.Create(stringReader))
{
return XmlFilePager.ReadRootAndElementsFromXmlDocument(xmlReader, "iati-activity");
}
}
private static string GetXmlExample()
{
return @"<?xml version=""1.0"" encoding=""utf-8""?>
<iati-activities version=""1.03"" generated-datetime=""2014-10-26T22:40:01.617"">
<iati-activity version=""1.03"" last-updated-datetime=""2014-10-26T04:57:22+00:00"" xml:lang=""en"" default-currency=""DKK"" hierarchy=""1"">
<iati-identifier>DK-1-1000</iati-identifier>
<other-identifier owner-ref=""DK-1"" owner-name=""Ministry of Foreign Affairs, Denmark"">104.BKF.24-25.</other-identifier>
<other-identifier owner-ref=""DK-1"" owner-name=""Status"">Projektets formål er at styrke det forebyggende arbejde mod omskæring af kvinder såvel gennem den nationale komité som gennem de lokale provinskomiteer. I bevillingen er der lagt særlig vægt på at stille midler til rådighed for afholdelse af målrettede oplysningskampagner. Sideløbende hermed er der i 10 provinser, hvor kvindelig omskæring er mest udbredt, blevet afholdt intensive seminarer. I bevillingen har der endvidere været afsat midler til afholdelse af uddannelsesseminarer. Målgrupperne for disse har særligt været paramedicinsk personale og socialhjælpere i provinserne samt landsbyjorde-mødre og repræsentanter for kvinde-NGO'er. Projektet forløb godt, og det afsluttedes i 1999. Der er herefter startet en fase II (104.BKF.24-88).</other-identifier>
<other-identifier owner-ref=""DK-1"" owner-name=""Risk Development"" />
<title>Appui au Comité National de Lutte contre la Pratique de l'Excision des femmes (CNLPE)</title>
<activity-status>Completed</activity-status>
<activity-date type=""start-planned"" iso-date=""1996-01-01"">1996-01-01</activity-date>
<activity-date type=""end-planned"" iso-date=""1998-12-31"">1998-12-31</activity-date>
<reporting-org ref=""DK-1"" type=""10"" xml:lang=""en"">Ministry of Foreign Affairs, Denmark</reporting-org>
<participating-org role=""Extending"" ref=""DK-1"" type=""10"" xml:lang=""en"">Ministry of Foreign Affairs, Denmark</participating-org>
<recipient-country percentage=""100"" code=""BF"" xml:lang=""en"">Burkina Faso</recipient-country>
<collaboration-type code=""1"">Bilateral</collaboration-type>
<default-flow-type code=""10"">ODA</default-flow-type>
<default-aid-type code=""C01"">Project-type interventions</default-aid-type>
<default-finance-type code=""110"">Aid grant excluding debt reorganisation</default-finance-type>
<related-activity type=""2"" ref=""DK-1-1000-803"" xml:lang=""en"">Appui au Comité National de Lutte contre la Pratique de l'Excision des femmes (CNLPE)</related-activity>
</iati-activity>
<iati-activity version=""1.03"" last-updated-datetime=""2014-10-26T04:57:22+00:00"" xml:lang=""en"" default-currency=""DKK"" hierarchy=""1"">
<iati-identifier>DK-1-100023</iati-identifier>
<other-identifier owner-ref=""DK-1"" owner-name=""Ministry of Foreign Affairs, Denmark"">104.Vietnam.30.m/53</other-identifier>
<other-identifier owner-ref=""DK-1"" owner-name=""Status"">Alle aktiviteter er fysisk afsluttet. Der ventes i øjeblikket på, at provinserne skal refunderer renterne fra de penge, der er blevet investeret.</other-identifier>
<other-identifier owner-ref=""DK-1"" owner-name=""Risk Development"">Ingen væsentlige risikoelementer.</other-identifier>
<title>Support to Improvement of Sanitary Conditions in Peri-urban Areas of Buon Ma Thuot with Focus on the Poor and Ethnic Minorities</title>
<description type=""1"" xml:lang=""en"">Projektet har til formål at forbedre levevilkårene for fattige og etniske minoriteter, som bor i randområderne til byen Buon Ma Thuot gennem forbedret adgang til sanitære forhold. Projektet omfatter aktiviteter såsom konstruktion af simple latriner for private husholdninger, sanitet og vand for skoler, træning og uddannelse af lokalt personale, oplysningskampagner og andre aktiviteter.
Det forventes, at 66000 mennesker har fået adgang til forbedret sanitære forhold ved projektets afslutning. Projektet blev startet i december 2003.</description>
<activity-status>Completed</activity-status>
<activity-date type=""start-planned"" iso-date=""2003-01-01"">2003-01-01</activity-date>
<activity-date type=""end-planned"" iso-date=""2007-12-31"">2007-12-31</activity-date>
<reporting-org ref=""DK-1"" type=""10"" xml:lang=""en"">Ministry of Foreign Affairs, Denmark</reporting-org>
<participating-org role=""Extending"" ref=""DK-1"" type=""10"" xml:lang=""en"">Ministry of Foreign Affairs, Denmark</participating-org>
<recipient-country percentage=""100"" code=""VN"" xml:lang=""en"">Vietnam</recipient-country>
<collaboration-type code=""1"">Bilateral</collaboration-type>
<default-flow-type code=""10"">ODA</default-flow-type>
<default-aid-type code=""C01"">Project-type interventions</default-aid-type>
<default-finance-type code=""110"">Aid grant excluding debt reorganisation</default-finance-type>
<sector vocabulary=""DAC"" code=""14030"" percentage=""100"" xml:lang=""en"">Basic drinking water supply and basic sanitation</sector>
<related-activity type=""2"" ref=""DK-1-100023-14033"" xml:lang=""en"">Support to Improvement of Sanitary Conditions in Peri-urban Areas of Buon Ma Thuot with Focus on the Poor and Ethnic Minorities</related-activity>
</iati-activity>
</iati-activities>
";
}
}
}
|
2e88890f4e569b1185d3685e76432b4308c0a316
|
C#
|
TheUnknownGentlemen/RocketBot
|
/PokemonGo.WPF/Converters/TeamToImagePathConverter.cs
| 2.6875
| 3
|
using System;
using System.Globalization;
using System.Windows.Data;
namespace PokemonGo.WPF.Converters
{
public class TeamToImagePathConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var teamName = (string)value;
if(teamName != null)
return $"pack://siteoforigin:,,,/Images/Player/team_{teamName.ToLowerInvariant()}.png";
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
|
8aac7eae37be3a19b4bf6c60966e1e922e4da39b
|
C#
|
lain076/pcaccrepository
|
/Udemy/cs/projets_cs/magicNumber/MagicNumber/Program.cs
| 3.6875
| 4
|
using System;
namespace MyApp // Note: actual namespace depends on the project name.
{
internal class Program
{
private const int MinimalLimit = 1;
private const int MaximalLimit = 10;
private static int GenerateNumberToFind(int maximumNumber = 10)
{
var randomizer = new Random();
return randomizer.Next(1, maximumNumber);
}
private static int GetUserChoice()
{
var numericUserChoice=0;
while(numericUserChoice == 0)
{
Console.WriteLine("Choose a number between 1 and 10");
string? userChoice = Console.ReadLine();
try
{
numericUserChoice = int.Parse(userChoice);
}
catch
{
Console.WriteLine("Error not a number");
}
}
return numericUserChoice;
}
private static Boolean CheckUserChoice(int randomizedNumber,int userChoice)
{
Boolean result = false;
if(userChoice == randomizedNumber)
{
Console.WriteLine("Right");
result = true;
}
if (userChoice < randomizedNumber)
{
Console.WriteLine("Down");
result = false;
}
if (userChoice > randomizedNumber)
{
Console.WriteLine("Greater");
result = false;
}
return result;
}
static Boolean NumberBetweenLimits(int userChoice,int minimalLimit,int maximalLimit)
{
if(userChoice < minimalLimit)
{
Console.WriteLine("Number under min limit");
return false;
}
if(userChoice > maximalLimit)
{
Console.WriteLine("Number greater max limit");
return false;
}
return true;
}
static void Main(string[] args)
{
var numberFound = false;
int numberToFind = GenerateNumberToFind();
int userChoice;
var lives = 5;
while (!numberFound)
{
userChoice = GetUserChoice();
if(NumberBetweenLimits(userChoice,MinimalLimit,MaximalLimit))
{
numberFound = CheckUserChoice(numberToFind, userChoice);
}
lives--;
if (lives == 0)
{
Console.WriteLine("You loose");
numberFound = true;
}
}
}
}
}
|
af3521cf6b093eae042a38f27c34bbe40454c4b5
|
C#
|
hetzermj/AutomationBaseFramework
|
/SeleniumBase/PageObjects/BasePage.cs
| 2.515625
| 3
|
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using System;
using System.Threading;
namespace SeleniumBase.PageObjects
{
public class BasePage
{
public BasePage(IWebDriver driver)
{
this._driver = driver;
}
public const int IMPLICITWAITTIMEOUT = 20;
protected IWebDriver _driver { get; set; }
public void StopPageLoad()
{
IJavaScriptExecutor js = (IJavaScriptExecutor)_driver;
js.ExecuteScript("return window.stop");
}
public IWebElement ExpandRootElement(IWebElement element)
{
IWebElement ele = (IWebElement)((IJavaScriptExecutor)_driver)
.ExecuteScript("return arguments[0].shadowRoot", element);
return ele;
}
public IWebElement GetFirstChild(IWebElement element)
{
IWebElement ele = (IWebElement)((IJavaScriptExecutor)_driver)
.ExecuteScript("return arguments[0].firstChild", element);
return ele;
}
private void ExecuteJavascript(string javascript)
{
IJavaScriptExecutor js = (IJavaScriptExecutor)_driver;
js.ExecuteScript(javascript);
}
public void SetAttributeOfElement(IWebElement el, string attribute, string input)
{
IJavaScriptExecutor executor = (IJavaScriptExecutor)_driver;
string script = "document.getElementById(\"" + el.GetAttribute("id") + "\").setAttribute(\"" + attribute + "\", \"" + input + "\");";
executor.ExecuteScript(script);
}
public void ClickCheckBox(bool desiredState, By chk_Identifier)
{
IWebElement cb = this._driver.FindElement(chk_Identifier);
if (desiredState != cb.Selected)
cb.Click();
}
public void WaitForPageLoadToComplete(int intTimeOutFromSeconds = 120)
{
var wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(intTimeOutFromSeconds));
wait.Until(d => ((IJavaScriptExecutor)_driver).ExecuteScript("return document.readyState").Equals("complete"));
}
public void WaitForAjax()
{
IJavaScriptExecutor executor = (IJavaScriptExecutor)_driver;
if ((Boolean)executor.ExecuteScript("return window.jQuery != undefined"))
{
while (!(Boolean)executor.ExecuteScript("return jQuery.active == 0"))
{
Thread.Sleep(100);
}
}
}
}
}
|
9856b51cec0a5b5036aac24a14ba73ac0e7e8668
|
C#
|
PseudoNuke/assist-purchase
|
/AssistAPurchase/SupportingFunctions/ProductConfigureSupporterFunctions.cs
| 3.046875
| 3
|
using System.Collections.Generic;
using AssistAPurchase.Models;
namespace AssistAPurchase.SupportingFunctions
{
public static class ProductConfigureSupporterFunctions
{
public static bool CheckForNullOrMismatchProductNumber(MonitoringItems product, string productNumber)
{
if (product == null || product.ProductNumber != productNumber)
{
return true;
}
return false;
}
public static List<MonitoringItems> GetItemsAboveTheGivenPrice(string price, List<MonitoringItems> monitoringItems)
{
List<MonitoringItems> finalItemsWithPriceAboveCategory = new List<MonitoringItems>();
foreach (MonitoringItems item in monitoringItems)
{
if (float.Parse(item.Price) > float.Parse(price))
{
finalItemsWithPriceAboveCategory.Add(item);
}
}
return finalItemsWithPriceAboveCategory;
}
public static List<MonitoringItems> GetItemsBelowTheGivenPrice(string price, List<MonitoringItems> monitoringItems)
{
List<MonitoringItems> finalItemsWithPriceBelowCategory = new List<MonitoringItems>();
foreach (MonitoringItems item in monitoringItems)
{
if (float.Parse(item.Price) <= float.Parse(price))
{
finalItemsWithPriceBelowCategory.Add(item);
}
}
return finalItemsWithPriceBelowCategory;
}
public static List<MonitoringItems> GetItemsAboveTheGivenScreenSize(string screenSize, List<MonitoringItems> monitoringItems)
{
List<MonitoringItems> finalItemWithScreenSizeAboveCategory = new List<MonitoringItems>();
foreach (MonitoringItems item in monitoringItems)
{
if (float.Parse(item.ScreenSize) > float.Parse(screenSize))
finalItemWithScreenSizeAboveCategory.Add(item);
}
return finalItemWithScreenSizeAboveCategory;
}
public static List<MonitoringItems> GetItemsBelowTheGivenScreenSize(string screenSize, List<MonitoringItems> monitoringItems)
{
List<MonitoringItems> finalItemWithScreenSizeBelowCategory = new List<MonitoringItems>();
foreach (MonitoringItems item in monitoringItems)
{
if (float.Parse(item.ScreenSize) <= float.Parse(screenSize))
finalItemWithScreenSizeBelowCategory.Add(item);
}
return finalItemWithScreenSizeBelowCategory;
}
}
}
|
df74a7c4c55b7a274423b7520f869686e2a8c364
|
C#
|
sk-0520/Pe
|
/Source/Pe/Test/Test/TestIO.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.Interfaces;
namespace ContentTypeTextNet.Pe.Test
{
/// <summary>
/// IO系のテスト系インフラ。
/// </summary>
public static class TestIO
{
#region property
private static string RootDirectoryName { get; } = "_test_io_";
private static bool InitializedProjectDirectory { get; set; }
private static ISet<string> InitializedClassDirectory { get; set; } = new HashSet<string>();
private static ISet<string> InitializedMethodDirectory { get; set; } = new HashSet<string>();
#endregion
#region function
private static DirectoryInfo GetProjectDirectory()
{
var projectTestPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!;
var projectTestDirPath = Path.Combine(projectTestPath, RootDirectoryName);
return new DirectoryInfo(projectTestDirPath);
}
private static DirectoryInfo GetClassDirectory(object test)
{
var project = GetProjectDirectory();
var classTestDirPath = Path.Combine(project.FullName, test.GetType().FullName ?? throw new Exception(test.ToString()));
return new DirectoryInfo(classTestDirPath);
}
private static DirectoryInfo GetMethodDirectory(object test, string callerMemberName, int callerLineNumber)
{
var classTestDirPath = GetClassDirectory(test);
var methodTestDirPath = Path.Combine(classTestDirPath.FullName, callerMemberName + "-L" + callerLineNumber.ToString(CultureInfo.InvariantCulture));
return new DirectoryInfo(methodTestDirPath);
}
public static DirectoryInfo CreateDirectory(DirectoryInfo dir)
{
dir.Refresh();
if(dir.Exists) {
dir.Delete(true);
}
dir.Create();
return dir;
}
/// <summary>
/// テストプロジェクト用テスト初期化。
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public static DirectoryInfo InitializeProject()
{
if(InitializedProjectDirectory) {
throw new TestException();
}
var dir = GetProjectDirectory();
var result = CreateDirectory(dir);
InitializedProjectDirectory = true;
return result;
}
/// <summary>
/// テストクラス用テスト初期化。
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public static DirectoryInfo InitializeClass(Type type)
{
var dir = GetClassDirectory(type);
if(InitializedClassDirectory.Contains(dir.FullName)) {
throw new TestException();
}
var result = CreateDirectory(dir);
InitializedClassDirectory.Add(dir.FullName);
return result;
}
/// <summary>
/// テストメソッド用テスト初期化。
/// </summary>
/// <param name="test"></param>
/// <param name="callerMemberName"></param>
/// <returns></returns>
public static DirectoryInfo InitializeMethod(object test, [CallerMemberName] string callerMemberName = "", [CallerLineNumber] int callerLineNumber = 0)
{
var dir = GetMethodDirectory(test, callerMemberName, callerLineNumber);
if(InitializedMethodDirectory.Contains(dir.FullName)) {
throw new TestException();
}
var result = CreateDirectory(dir);
InitializedMethodDirectory.Add(dir.FullName);
return result;
}
public static DirectoryInfo CreateDirectory(DirectoryInfo directory, string name)
{
var dirPath = Path.Combine(directory.FullName, name);
return Directory.CreateDirectory(dirPath);
}
public static FileInfo CreateEmptyFile(DirectoryInfo directory, string name)
{
var filePath = Path.Combine(directory.FullName, name);
using(File.Create(filePath)) {
}
return new FileInfo(filePath);
}
public static FileInfo CreateTextFile(DirectoryInfo directory, string name, string content, Encoding encoding)
{
var filePath = Path.Combine(directory.FullName, name);
using(var stream = File.Create(filePath)) {
using var writer = new StreamWriter(stream, encoding);
writer.Write(content);
}
return new FileInfo(filePath);
}
public static FileInfo CreateTextFile(DirectoryInfo directory, string name, string content) => CreateTextFile(directory, name, content, Encoding.UTF8);
#endregion
}
}
|
60b23ff42b1d702ecd1d3fc644a25a0ba40544ae
|
C#
|
enra64/TemporaryDungeonDwarf
|
/DungeonDwarf/StartScreen.cs
| 2.890625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SFML.Graphics;
using SFML.Window;
namespace DungeonDwarf
{
class StartScreen
{
private RenderWindow win;
private Sprite background, startText;
private int currentAlphaPercent = 100;
private bool fadeOut = true;
public StartScreen(RenderWindow _w)
{
win = _w;
Texture bg = new Texture("textures/menu/startBG.png");
bg.Smooth = true;
background = new Sprite(bg);
background.Scale = new Vector2f((float)win.Size.X / (float)bg.Size.X, (float)win.Size.Y / (float)bg.Size.Y);
Texture text = new Texture("textures/menu/startButton.png");
startText = new Sprite(text);
startText.Scale = background.Scale;
startText.Position = new Vector2f(win.Size.X / 2 - startText.GetGlobalBounds().Left / 2, win.Size.Y / 2 - startText.GetGlobalBounds().Top / 2 + 30f);
}
public void Update(){
win.DispatchEvents();
if (currentAlphaPercent == 0)
fadeOut = false;
if (currentAlphaPercent == 100)
fadeOut = true;
if (fadeOut)
currentAlphaPercent--;
else
currentAlphaPercent++;
int alphaInt = (255*currentAlphaPercent)/100;
byte alpha = (byte)alphaInt;
startText.Color = new Color(255, 255, 255, alpha);
}
public void Draw()
{
win.Clear();
win.Draw(background);
win.Draw(startText);
win.Display();
}
}
}
|
16d19c7acece6693ee3537a4cfef87721b3d6edb
|
C#
|
Frinen/.net-food-shop
|
/Food_Store/Food_Store/Controllers/ItemsController.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Food_Store.Common;
using Food_Store.Models;
using Microsoft.AspNetCore.Authorization;
using Food_Store.ViewModels;
namespace Food_Store.Controllers
{
[Authorize(Roles = "admin")]
public class ItemsController : Controller
{
private readonly ShopContext _context;
public ItemsController(ShopContext context)
{
_context = context;
}
// GET: Items
public async Task<IActionResult> Index(string TypeString)
{
var dbList = _context.Items.Include(x => x.ItemType);
var finalList = new List<ItemModel>();
foreach (var dbItem in dbList )
{
finalList.Add(new ItemModel()
{
Description = dbItem.Description,
Name = dbItem.Name,
Path = dbItem.Path,
Price = dbItem.Price,
Id = dbItem.Id,
TypeOfItem = _context.Types.FirstOrDefault(x=> x.Id == dbItem.ItemType[0].ItTypeId).Name
});
}
if (!String.IsNullOrEmpty(TypeString))
{
finalList = finalList.Where(x => x.TypeOfItem == TypeString).ToList();
}
return View(finalList);
}
// GET: Items/Details/5
public async Task<IActionResult> Details(Guid? id)
{
if (id == null)
{
return NotFound();
}
var item = await _context.Items
.FirstOrDefaultAsync(m => m.Id == id);
if (item == null)
{
return NotFound();
}
return View(item);
}
// GET: Items/Create
public IActionResult Create()
{
return View();
}
// POST: Items/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Name,Price,Description,Path,Id,TypeOfItem")] ItemModel itemModel)
{
var item = new Item();
if (ModelState.IsValid)
{
item.Id = Guid.NewGuid();
item.Description = itemModel.Description;
item.Name = itemModel.Name;
item.Path = itemModel.Path;
item.Price = itemModel.Price;
_context.Items.Add(item);
await _context.SaveChangesAsync();
var itemType = new ItemType();
itemType.ItemId = item.Id;
itemType.ItTypeId = _context.Types.FirstOrDefault(x => x.Name == itemModel.TypeOfItem).Id;
_context.itemTypes.Add(itemType);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(item);
}
// GET: Items/Edit/5
public async Task<IActionResult> Edit(Guid? id)
{
if (id == null)
{
return NotFound();
}
var item = await _context.Items.FindAsync(id);
if (item == null)
{
return NotFound();
}
return View(item);
}
// POST: Items/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Guid id, [Bind("Name,Price,Description,Path,Id")] Item item)
{
if (id != item.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(item);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ItemExists(item.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(item);
}
// GET: Items/Delete/5
public async Task<IActionResult> Delete(Guid? id)
{
if (id == null)
{
return NotFound();
}
var item = await _context.Items
.FirstOrDefaultAsync(m => m.Id == id);
if (item == null)
{
return NotFound();
}
return View(item);
}
// POST: Items/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(Guid id)
{
var item = await _context.Items.FindAsync(id);
_context.Items.Remove(item);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool ItemExists(Guid id)
{
return _context.Items.Any(e => e.Id == id);
}
}
public class MyListTable
{
public string Key { get; set; }
public string Display { get; set; }
}
}
|
e142c13447786cac52e4694fd628301c82cf7e44
|
C#
|
ReynaldAdolphe/CSharp-7-First-Look
|
/Ch02/02_04/Begin/CSharp7_FirstLook/Deconstruction/Program.cs
| 3.765625
| 4
|
using System;
namespace Deconstruction
{
class Program
{
static void Main(string[] args)
{
// TODO - Deconstruction Demo
(string authorName, string bookTitle, long pubYear) = GetNewCS7_Tuple();
Console.WriteLine("Author: {0} \nBook: {1} Year: {2}\n",
authorName, bookTitle, pubYear);
}
static public (string name, string title, long year) GetNewCS7_Tuple()
{
string name = "Reynald Adolphe";
string title = ".NET Programming";
long year = 2017;
// Tuple literal - Returns a tuple type of three values
return (name, title, year);
}
}
}
|
1940e9461cdf22413db7e0f85fc47a4992023df1
|
C#
|
GodLesZ/ZeusEngine
|
/Shared/Zeus.Library/IO/Tools.cs
| 3.109375
| 3
|
using System;
using System.IO;
using System.Text;
namespace Zeus.Library.IO {
public class Tools {
public static void EnsureDirectory(string dir) {
// @TODO: Working with Mono on Linux?
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, dir);
if (Directory.Exists(path) == false) {
Directory.CreateDirectory(path);
}
}
public static void FormatBuffer(TextWriter output, Stream input, int length) {
output.WriteLine(" 0 1 2 3 4 5 6 7 8 9 A B C D E F");
output.WriteLine(" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
var byteIndex = 0;
var whole = length >> 4;
var rem = length & 0xF;
for (var i = 0; i < whole; ++i, byteIndex += 16) {
var bytes = new StringBuilder(49);
var chars = new StringBuilder(16);
for (var j = 0; j < 16; ++j) {
var c = input.ReadByte();
bytes.Append(c.ToString("X2"));
if (j != 7) {
bytes.Append(' ');
} else {
bytes.Append(" ");
}
if (c >= 32 && c < 128) {
chars.Append((char)c);
} else {
chars.Append('.');
}
}
output.Write(byteIndex.ToString("X4"));
output.Write(" ");
output.Write(bytes.ToString());
output.Write(" ");
output.WriteLine(chars.ToString());
}
if (rem == 0) {
return;
}
var byteBuffer = new StringBuilder(49);
var charBuffer = new StringBuilder(rem);
for (var j = 0; j < 16; ++j) {
if (j < rem) {
var c = input.ReadByte();
byteBuffer.Append(c.ToString("X2"));
if (j != 7) {
byteBuffer.Append(' ');
} else {
byteBuffer.Append(" ");
}
if (c >= 32 && c < 128) {
charBuffer.Append((char)c);
} else {
charBuffer.Append('.');
}
} else {
byteBuffer.Append(" ");
}
}
output.Write(byteIndex.ToString("X4"));
output.Write(" ");
output.Write(byteBuffer.ToString());
output.Write(" ");
output.WriteLine(charBuffer.ToString());
}
}
}
|
f8cd86b39a8350ca025e142ba8fd9d6fe24c2d99
|
C#
|
shendongnian/download4
|
/code4/664914-15896184-38805675-2.cs
| 2.53125
| 3
|
public bool Execute(Item item, ID commandId, string comment)
{
var workflowId = item[FieldIDs.Workflow];
if (String.IsNullOrEmpty(workflowId))
{
throw new WorkflowException("Item is not in a workflow");
}
IWorkflow workflow = item.Database.WorkflowProvider.GetWorkflow(workflowId);
var workflowResult = workflow.Execute(commandId.ToString(), item, comment, false, new object[0]);
if (!workflowResult.Succeeded)
{
var message = workflowResult.Message;
if (String.IsNullOrEmpty(message))
{
message = "IWorkflow.Execute() failed for unknown reason.";
}
throw new Exception(message);
}
return true;
}
|
44968b6c7b617b8ec9b8109cee1f3ea8bbb60f6e
|
C#
|
apomarinov/Telerik-Academy
|
/C# 1/Operators-and-Expressions/OddOrEvenIntegers/OddOrEvenIntegers.cs
| 3.5625
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OddOrEvenIntegers
{
class OddOrEvenIntegers
{
static void Main(string[] args)
{
IsOdd(3);
IsOdd(2);
IsOdd(-2);
IsOdd(-1);
IsOdd(0);
}
static void IsOdd(int num)
{
Console.WriteLine(num + ": " + (num % 2 != 0));
}
}
}
|
3f84c0994028d9d6b61833c2dbdabf56ebd71ca0
|
C#
|
Laeng/StarCitizen_maro
|
/SCTools/SCTools/Adapters/RepositoriesListViewAdapter.cs
| 2.640625
| 3
|
using System.Collections.Generic;
using System.Windows.Forms;
using NSW.StarCitizen.Tools.Localization;
using NSW.StarCitizen.Tools.Properties;
using NSW.StarCitizen.Tools.Settings;
namespace NSW.StarCitizen.Tools.Adapters
{
public class RepositoriesListViewAdapter
{
private const string COLUMN_KEY_NAME = "chName";
private const string COLUMN_KEY_PATH = "chPath";
private readonly ListView _listView;
public int RepositoriesCount => _listView.Items.Count;
public RepositoriesListViewAdapter(ListView listView)
{
_listView = listView;
Initialize();
}
public void UpdateLocalization()
{
foreach (var column in _listView.Columns)
{
if (column is ColumnHeader columnHeader)
{
switch (columnHeader.Name)
{
case COLUMN_KEY_NAME:
columnHeader.Text = Resources.Localization_Name_Text;
break;
case COLUMN_KEY_PATH:
columnHeader.Text = Resources.Localization_Path_Text;
break;
}
}
}
}
public void SetRepositoriesList(IEnumerable<ILocalizationRepository> repositories)
{
_listView.Items.Clear();
foreach (var repository in repositories)
{
var item = _listView.Items.Add(repository.Name, repository.Name);
item.Tag = repository;
item.SubItems.Add(repository.Repository);
}
}
public void SetRepositoriesList(IEnumerable<LocalizationSource> repositories)
{
_listView.Items.Clear();
foreach (var repository in repositories)
{
var item = _listView.Items.Add(repository.Name, repository.Name);
item.Tag = repository;
item.SubItems.Add(repository.Repository);
}
}
public ILocalizationRepository? GetSelectedRepository()
{
if (_listView.SelectedItems.Count > 0 &&
_listView.SelectedItems[0]?.Tag is ILocalizationRepository repository)
{
return repository;
}
return null;
}
public LocalizationSource? GetSelectedSource()
{
if (_listView.SelectedItems.Count > 0 &&
_listView.SelectedItems[0]?.Tag is LocalizationSource source)
{
return source;
}
return null;
}
public void RemoveSelectedItem()
{
if (_listView.SelectedItems.Count > 0)
{
_listView.Items.Remove(_listView.SelectedItems[0]);
}
}
private void Initialize()
{
var item = _listView.Columns.Add(COLUMN_KEY_NAME, Resources.Localization_Name_Text);
item.Width = _listView.Width / 2 - 5;
_listView.Columns.Add(COLUMN_KEY_PATH, Resources.Localization_Path_Text, _listView.Width - item.Width - 5);
}
}
}
|
f9bbb92c9fa79847bd4512eba060493990325172
|
C#
|
oldmannus/PitGit
|
/Assets/Scripts/Utilities/FlagSet.cs
| 3.109375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Pit.Utilities
{
public class FlagSet
{
int[] _fields = new int[0];
protected void Reset()
{
_fields = new int[0];
}
/// <summary>
/// Note flag must be an 0-1 count, not a bitfield
/// </summary>
/// <param name="flag"></param>
protected void Add(int flag)
{
int fieldNdx = flag / sizeof(int);
int offset = flag % sizeof(int);
// add more fields if necessary
if (_fields.Length < fieldNdx + 1)
Array.Resize<int>(ref _fields, fieldNdx + 1);
_fields[fieldNdx] |= 1 << offset;
}
public void Add(FlagSet set)
{
if (set._fields.Length > _fields.Length)
Array.Resize<int>(ref _fields, set._fields.Length);
for (int ndx = 0; ndx < set._fields.Length; ndx++)
{
_fields[ndx] |= set._fields[ndx];
}
}
protected void Remove(int flag)
{
int fieldNdx = flag / sizeof(int);
int offset = flag % sizeof(int);
// add more fields if necessary. stupid to do on remove, but meh
if (_fields.Length < fieldNdx + 1)
Array.Resize<int>(ref _fields, fieldNdx + 1);
_fields[fieldNdx] &= ~(1 << offset);
}
public void Remove(FlagSet set)
{
if (set._fields.Length > _fields.Length)
Array.Resize<int>(ref _fields, set._fields.Length);
for (int ndx = 0; ndx < set._fields.Length; ndx++)
{
_fields[ndx] &= ~(set._fields[ndx]);
}
}
public bool HasFlag(int flag)
{
int fieldNdx = flag / sizeof(int);
int offset = flag % sizeof(int);
// add more fields if necessary. stupid to do on remove, but meh
if (_fields.Length < fieldNdx + 1)
Array.Resize<int>(ref _fields, fieldNdx + 1);
return (_fields[fieldNdx] & (1 << offset)) != 0;
}
/// <summary>
/// Does THIS set have the flags in the parameter
/// </summary>
/// <param name="set"></param>
/// <returns></returns>
public bool HasFlags(FlagSet set)
{
if (set._fields.Length > _fields.Length)
Array.Resize<int>(ref _fields, set._fields.Length);
for (int ndx = 0; ndx < set._fields.Length; ndx++)
{
int and = set._fields[ndx] & _fields[ndx];
if (and != set._fields[ndx])
return false;
}
return true;
}
public void CopyFrom(FlagSet set)
{
if (set._fields.Length > _fields.Length)
Array.Resize<int>(ref _fields, set._fields.Length);
for (int ndx = 0; ndx < set._fields.Length; ndx++)
{
_fields[ndx] = set._fields[ndx];
}
}
}
}
|