Datasets:

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
8681efb109eafd00e530e7fa94d7b113e8cff078
C#
DarknessSwitch/clinic_db
/clinic_db/UI_Controls/PatientList.cs
2.546875
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace clinic_db { public partial class PatientList : UserControl { public PatientList() { InitializeComponent(); } private void PatientList_Paint(object sender, PaintEventArgs e) { } void lb_Click(object sender, EventArgs e) { LinkLabel casted = (LinkLabel)sender; PatientProfile profile = new PatientProfile(casted.Text); Form f = new Form(); f.Controls.Add(profile); f.Size = profile.Size; f.Show(); profile.Show(); f.FormClosing += f_FormClosing; } void f_FormClosing(object sender, FormClosingEventArgs e) { LoadEntries(); } public void LoadEntries() { this.tableLayoutPanel1.Controls.Clear(); List<PatientModel> patients = DbConnector.GetInstance().GetPatientList(); this.tableLayoutPanel1.RowCount = patients.Count; this.tableLayoutPanel1.Update(); for (int i = 0; i < patients.Count; i++) { LinkLabel lb = new LinkLabel(); lb.AutoSize = true; lb.Font = new Font("Calibri",12); lb.Text = patients[i].Name; lb.Show(); lb.Click += lb_Click; Label lb1 = new Label(); lb1.Text = patients[i].Age.ToString(); lb1.Font= new Font("Calibri",12); lb1.Show(); Label lb2 = new Label(); lb2.AutoSize = true; lb2.Text = patients[i].Address; lb2.Font = new Font("Calibri", 12); lb2.Show(); DeleteButton b = new DeleteButton(patients[i].id, "patient"); b.Click += b_Click; this.tableLayoutPanel1.Controls.Add(lb, 0, i); this.tableLayoutPanel1.Controls.Add(lb1, 1, i); this.tableLayoutPanel1.Controls.Add(lb2, 2, i); this.tableLayoutPanel1.Controls.Add(b, 3, i); } } void b_Click(object sender, EventArgs e) { DeleteButton casted = (DeleteButton)sender; casted.ExecuteDeletion(); LoadEntries(); } private void PatientList_Load(object sender, EventArgs e) { } private void AddButton_Click(object sender, EventArgs e) { AddPatientForm f = new AddPatientForm(this); this.Parent.Parent.Enabled = false; f.Show(); } } }
3aab89c753d02d0eabecc7a746040561bbcf2fe3
C#
uvbs/backlog-agile
/B_SOURCE/Agile/Generated Code/Agile.Data/Bases/ReleaseProviderBase.generatedCore.cs
2.515625
3
#region Using directives using System; using System.Data; using System.Data.Common; using System.Collections; using System.Collections.Generic; using Agile.Entities; using Agile.Data; #endregion namespace Agile.Data.Bases { ///<summary> /// This class is the base class for any <see cref="ReleaseProviderBase"/> implementation. /// It exposes CRUD methods as well as selecting on index, foreign keys and custom stored procedures. ///</summary> public abstract partial class ReleaseProviderBaseCore : EntityProviderBase<Agile.Entities.Release, Agile.Entities.ReleaseKey> { #region Get from Many To Many Relationship Functions #endregion #region Delete Methods /// <summary> /// Deletes a row from the DataSource. /// </summary> /// <param name="transactionManager">A <see cref="TransactionManager"/> object.</param> /// <param name="key">The unique identifier of the row to delete.</param> /// <returns>Returns true if operation suceeded.</returns> public override bool Delete(TransactionManager transactionManager, Agile.Entities.ReleaseKey key) { return Delete(transactionManager, key.ReleaseId); } /// <summary> /// Deletes a row from the DataSource. /// </summary> /// <param name="_releaseId">. Primary Key.</param> /// <remarks>Deletes based on primary key(s).</remarks> /// <returns>Returns true if operation suceeded.</returns> public bool Delete(System.Int32 _releaseId) { return Delete(null, _releaseId); } /// <summary> /// Deletes a row from the DataSource. /// </summary> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="_releaseId">. Primary Key.</param> /// <remarks>Deletes based on primary key(s).</remarks> /// <returns>Returns true if operation suceeded.</returns> public abstract bool Delete(TransactionManager transactionManager, System.Int32 _releaseId); #endregion Delete Methods #region Get By Foreign Key Functions #endregion #region Get By Index Functions /// <summary> /// Gets a row from the DataSource based on its primary key. /// </summary> /// <param name="transactionManager">A <see cref="TransactionManager"/> object.</param> /// <param name="key">The unique identifier of the row to retrieve.</param> /// <param name="start">Row number at which to start reading, the first row is 0.</param> /// <param name="pageLength">Number of rows to return.</param> /// <returns>Returns an instance of the Entity class.</returns> public override Agile.Entities.Release Get(TransactionManager transactionManager, Agile.Entities.ReleaseKey key, int start, int pageLength) { return GetByReleaseId(transactionManager, key.ReleaseId, start, pageLength); } /// <summary> /// Gets rows from the datasource based on the primary key PK_tblRelease index. /// </summary> /// <param name="_releaseId"></param> /// <returns>Returns an instance of the <see cref="Agile.Entities.Release"/> class.</returns> public Agile.Entities.Release GetByReleaseId(System.Int32 _releaseId) { int count = -1; return GetByReleaseId(null,_releaseId, 0, int.MaxValue, out count); } /// <summary> /// Gets rows from the datasource based on the PK_tblRelease index. /// </summary> /// <param name="_releaseId"></param> /// <param name="start">Row number at which to start reading, the first row is 0.</param> /// <param name="pageLength">Number of rows to return.</param> /// <remarks></remarks> /// <returns>Returns an instance of the <see cref="Agile.Entities.Release"/> class.</returns> public Agile.Entities.Release GetByReleaseId(System.Int32 _releaseId, int start, int pageLength) { int count = -1; return GetByReleaseId(null, _releaseId, start, pageLength, out count); } /// <summary> /// Gets rows from the datasource based on the PK_tblRelease index. /// </summary> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="_releaseId"></param> /// <remarks></remarks> /// <returns>Returns an instance of the <see cref="Agile.Entities.Release"/> class.</returns> public Agile.Entities.Release GetByReleaseId(TransactionManager transactionManager, System.Int32 _releaseId) { int count = -1; return GetByReleaseId(transactionManager, _releaseId, 0, int.MaxValue, out count); } /// <summary> /// Gets rows from the datasource based on the PK_tblRelease index. /// </summary> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="_releaseId"></param> /// <param name="start">Row number at which to start reading, the first row is 0.</param> /// <param name="pageLength">Number of rows to return.</param> /// <remarks></remarks> /// <returns>Returns an instance of the <see cref="Agile.Entities.Release"/> class.</returns> public Agile.Entities.Release GetByReleaseId(TransactionManager transactionManager, System.Int32 _releaseId, int start, int pageLength) { int count = -1; return GetByReleaseId(transactionManager, _releaseId, start, pageLength, out count); } /// <summary> /// Gets rows from the datasource based on the PK_tblRelease index. /// </summary> /// <param name="_releaseId"></param> /// <param name="start">Row number at which to start reading, the first row is 0.</param> /// <param name="pageLength">Number of rows to return.</param> /// <param name="count">out parameter to get total records for query</param> /// <remarks></remarks> /// <returns>Returns an instance of the <see cref="Agile.Entities.Release"/> class.</returns> public Agile.Entities.Release GetByReleaseId(System.Int32 _releaseId, int start, int pageLength, out int count) { return GetByReleaseId(null, _releaseId, start, pageLength, out count); } /// <summary> /// Gets rows from the datasource based on the PK_tblRelease index. /// </summary> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="_releaseId"></param> /// <param name="start">Row number at which to start reading, the first row is 0.</param> /// <param name="pageLength">Number of rows to return.</param> /// <param name="count">The total number of records.</param> /// <returns>Returns an instance of the <see cref="Agile.Entities.Release"/> class.</returns> public abstract Agile.Entities.Release GetByReleaseId(TransactionManager transactionManager, System.Int32 _releaseId, int start, int pageLength, out int count); #endregion "Get By Index Functions" #region Custom Methods #endregion #region Helper Functions /// <summary> /// Fill a TList&lt;Release&gt; From a DataReader. /// </summary> /// <param name="reader">Datareader</param> /// <param name="rows">The collection to fill</param> /// <param name="start">Row number at which to start reading, the first row is 0.</param> /// <param name="pageLength">number of rows.</param> /// <returns>a <see cref="TList&lt;Release&gt;"/></returns> public static TList<Release> Fill(IDataReader reader, TList<Release> rows, int start, int pageLength) { NetTiersProvider currentProvider = DataRepository.Provider; bool useEntityFactory = currentProvider.UseEntityFactory; bool enableEntityTracking = currentProvider.EnableEntityTracking; LoadPolicy currentLoadPolicy = currentProvider.CurrentLoadPolicy; Type entityCreationFactoryType = currentProvider.EntityCreationalFactoryType; // advance to the starting row for (int i = 0; i < start; i++) { if (!reader.Read()) return rows; // not enough rows, just return } for (int i = 0; i < pageLength; i++) { if (!reader.Read()) break; // we are done string key = null; Agile.Entities.Release c = null; if (useEntityFactory) { key = new System.Text.StringBuilder("Release") .Append("|").Append((System.Int32)reader[((int)ReleaseColumn.ReleaseId - 1)]).ToString(); c = EntityManager.LocateOrCreate<Release>( key.ToString(), // EntityTrackingKey "Release", //Creational Type entityCreationFactoryType, //Factory used to create entity enableEntityTracking); // Track this entity? } else { c = new Agile.Entities.Release(); } if (!enableEntityTracking || c.EntityState == EntityState.Added || (enableEntityTracking && ( (currentLoadPolicy == LoadPolicy.PreserveChanges && c.EntityState == EntityState.Unchanged) || (currentLoadPolicy == LoadPolicy.DiscardChanges && c.EntityState != EntityState.Unchanged) ) )) { c.SuppressEntityEvents = true; c.ReleaseId = (System.Int32)reader[((int)ReleaseColumn.ReleaseId - 1)]; c.ProjectId = (System.Int32)reader[((int)ReleaseColumn.ProjectId - 1)]; c.ReleaseDate = (System.DateTime)reader[((int)ReleaseColumn.ReleaseDate - 1)]; c.ReleaseName = (reader.IsDBNull(((int)ReleaseColumn.ReleaseName - 1)))?null:(System.String)reader[((int)ReleaseColumn.ReleaseName - 1)]; c.ReleaseNote = (reader.IsDBNull(((int)ReleaseColumn.ReleaseNote - 1)))?null:(System.String)reader[((int)ReleaseColumn.ReleaseNote - 1)]; c.Active = (reader.IsDBNull(((int)ReleaseColumn.Active - 1)))?null:(System.Boolean?)reader[((int)ReleaseColumn.Active - 1)]; c.UserId = (reader.IsDBNull(((int)ReleaseColumn.UserId - 1)))?null:(System.Int32?)reader[((int)ReleaseColumn.UserId - 1)]; c.LastUserUpdate = (reader.IsDBNull(((int)ReleaseColumn.LastUserUpdate - 1)))?null:(System.Int32?)reader[((int)ReleaseColumn.LastUserUpdate - 1)]; c.LastDateUpdate = (reader.IsDBNull(((int)ReleaseColumn.LastDateUpdate - 1)))?null:(System.DateTime?)reader[((int)ReleaseColumn.LastDateUpdate - 1)]; c.EntityTrackingKey = key; c.AcceptChanges(); c.SuppressEntityEvents = false; } rows.Add(c); } return rows; } /// <summary> /// Refreshes the <see cref="Agile.Entities.Release"/> object from the <see cref="IDataReader"/>. /// </summary> /// <param name="reader">The <see cref="IDataReader"/> to read from.</param> /// <param name="entity">The <see cref="Agile.Entities.Release"/> object to refresh.</param> public static void RefreshEntity(IDataReader reader, Agile.Entities.Release entity) { if (!reader.Read()) return; entity.ReleaseId = (System.Int32)reader[((int)ReleaseColumn.ReleaseId - 1)]; entity.ProjectId = (System.Int32)reader[((int)ReleaseColumn.ProjectId - 1)]; entity.ReleaseDate = (System.DateTime)reader[((int)ReleaseColumn.ReleaseDate - 1)]; entity.ReleaseName = (reader.IsDBNull(((int)ReleaseColumn.ReleaseName - 1)))?null:(System.String)reader[((int)ReleaseColumn.ReleaseName - 1)]; entity.ReleaseNote = (reader.IsDBNull(((int)ReleaseColumn.ReleaseNote - 1)))?null:(System.String)reader[((int)ReleaseColumn.ReleaseNote - 1)]; entity.Active = (reader.IsDBNull(((int)ReleaseColumn.Active - 1)))?null:(System.Boolean?)reader[((int)ReleaseColumn.Active - 1)]; entity.UserId = (reader.IsDBNull(((int)ReleaseColumn.UserId - 1)))?null:(System.Int32?)reader[((int)ReleaseColumn.UserId - 1)]; entity.LastUserUpdate = (reader.IsDBNull(((int)ReleaseColumn.LastUserUpdate - 1)))?null:(System.Int32?)reader[((int)ReleaseColumn.LastUserUpdate - 1)]; entity.LastDateUpdate = (reader.IsDBNull(((int)ReleaseColumn.LastDateUpdate - 1)))?null:(System.DateTime?)reader[((int)ReleaseColumn.LastDateUpdate - 1)]; entity.AcceptChanges(); } /// <summary> /// Refreshes the <see cref="Agile.Entities.Release"/> object from the <see cref="DataSet"/>. /// </summary> /// <param name="dataSet">The <see cref="DataSet"/> to read from.</param> /// <param name="entity">The <see cref="Agile.Entities.Release"/> object.</param> public static void RefreshEntity(DataSet dataSet, Agile.Entities.Release entity) { DataRow dataRow = dataSet.Tables[0].Rows[0]; entity.ReleaseId = (System.Int32)dataRow["ReleaseID"]; entity.ProjectId = (System.Int32)dataRow["ProjectID"]; entity.ReleaseDate = (System.DateTime)dataRow["ReleaseDate"]; entity.ReleaseName = Convert.IsDBNull(dataRow["ReleaseName"]) ? null : (System.String)dataRow["ReleaseName"]; entity.ReleaseNote = Convert.IsDBNull(dataRow["ReleaseNote"]) ? null : (System.String)dataRow["ReleaseNote"]; entity.Active = Convert.IsDBNull(dataRow["Active"]) ? null : (System.Boolean?)dataRow["Active"]; entity.UserId = Convert.IsDBNull(dataRow["UserID"]) ? null : (System.Int32?)dataRow["UserID"]; entity.LastUserUpdate = Convert.IsDBNull(dataRow["LastUserUpdate"]) ? null : (System.Int32?)dataRow["LastUserUpdate"]; entity.LastDateUpdate = Convert.IsDBNull(dataRow["LastDateUpdate"]) ? null : (System.DateTime?)dataRow["LastDateUpdate"]; entity.AcceptChanges(); } #endregion #region DeepLoad Methods /// <summary> /// Deep Loads the <see cref="IEntity"/> object with criteria based of the child /// property collections only N Levels Deep based on the <see cref="DeepLoadType"/>. /// </summary> /// <remarks> /// Use this method with caution as it is possible to DeepLoad with Recursion and traverse an entire object graph. /// </remarks> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="entity">The <see cref="Agile.Entities.Release"/> object to load.</param> /// <param name="deep">Boolean. A flag that indicates whether to recursively save all Property Collection that are descendants of this instance. If True, saves the complete object graph below this object. If False, saves this object only. </param> /// <param name="deepLoadType">DeepLoadType Enumeration to Include/Exclude object property collections from Load.</param> /// <param name="childTypes">Agile.Entities.Release Property Collection Type Array To Include or Exclude from Load</param> /// <param name="innerList">A collection of child types for easy access.</param> /// <exception cref="ArgumentNullException">entity or childTypes is null.</exception> /// <exception cref="ArgumentException">deepLoadType has invalid value.</exception> public override void DeepLoad(TransactionManager transactionManager, Agile.Entities.Release entity, bool deep, DeepLoadType deepLoadType, System.Type[] childTypes, DeepSession innerList) { if(entity == null) return; //used to hold DeepLoad method delegates and fire after all the local children have been loaded. Dictionary<string, KeyValuePair<Delegate, object>> deepHandles = new Dictionary<string, KeyValuePair<Delegate, object>>(); // Deep load child collections - Call GetByReleaseId methods when available #region DieRequestCollection //Relationship Type One : Many if (CanDeepLoad(entity, "List<DieRequest>|DieRequestCollection", deepLoadType, innerList)) { #if NETTIERS_DEBUG System.Diagnostics.Debug.WriteLine("- property 'DieRequestCollection' loaded. key " + entity.EntityTrackingKey); #endif entity.DieRequestCollection = DataRepository.DieRequestProvider.GetByCompletedReleaseId(transactionManager, entity.ReleaseId); if (deep && entity.DieRequestCollection.Count > 0) { deepHandles.Add("DieRequestCollection", new KeyValuePair<Delegate, object>((DeepLoadHandle<DieRequest>) DataRepository.DieRequestProvider.DeepLoad, new object[] { transactionManager, entity.DieRequestCollection, deep, deepLoadType, childTypes, innerList } )); } } #endregion //Fire all DeepLoad Items foreach(KeyValuePair<Delegate, object> pair in deepHandles.Values) { pair.Key.DynamicInvoke((object[])pair.Value); } deepHandles = null; } #endregion #region DeepSave Methods /// <summary> /// Deep Save the entire object graph of the Agile.Entities.Release object with criteria based of the child /// Type property array and DeepSaveType. /// </summary> /// <param name="transactionManager">The transaction manager.</param> /// <param name="entity">Agile.Entities.Release instance</param> /// <param name="deepSaveType">DeepSaveType Enumeration to Include/Exclude object property collections from Save.</param> /// <param name="childTypes">Agile.Entities.Release Property Collection Type Array To Include or Exclude from Save</param> /// <param name="innerList">A Hashtable of child types for easy access.</param> public override bool DeepSave(TransactionManager transactionManager, Agile.Entities.Release entity, DeepSaveType deepSaveType, System.Type[] childTypes, DeepSession innerList) { if (entity == null) return false; #region Composite Parent Properties //Save Source Composite Properties, however, don't call deep save on them. //So they only get saved a single level deep. #endregion Composite Parent Properties // Save Root Entity through Provider if (!entity.IsDeleted) this.Save(transactionManager, entity); //used to hold DeepSave method delegates and fire after all the local children have been saved. Dictionary<string, KeyValuePair<Delegate, object>> deepHandles = new Dictionary<string, KeyValuePair<Delegate, object>>(); #region List<DieRequest> if (CanDeepSave(entity.DieRequestCollection, "List<DieRequest>|DieRequestCollection", deepSaveType, innerList)) { // update each child parent id with the real parent id (mostly used on insert) foreach(DieRequest child in entity.DieRequestCollection) { if(child.CompletedReleaseIdSource != null) { child.CompletedReleaseId = child.CompletedReleaseIdSource.ReleaseId; } else { child.CompletedReleaseId = entity.ReleaseId; } } if (entity.DieRequestCollection.Count > 0 || entity.DieRequestCollection.DeletedItems.Count > 0) { //DataRepository.DieRequestProvider.Save(transactionManager, entity.DieRequestCollection); deepHandles.Add("DieRequestCollection", new KeyValuePair<Delegate, object>((DeepSaveHandle< DieRequest >) DataRepository.DieRequestProvider.DeepSave, new object[] { transactionManager, entity.DieRequestCollection, deepSaveType, childTypes, innerList } )); } } #endregion //Fire all DeepSave Items foreach(KeyValuePair<Delegate, object> pair in deepHandles.Values) { pair.Key.DynamicInvoke((object[])pair.Value); } // Save Root Entity through Provider, if not already saved in delete mode if (entity.IsDeleted) this.Save(transactionManager, entity); deepHandles = null; return true; } #endregion } // end class #region ReleaseChildEntityTypes ///<summary> /// Enumeration used to expose the different child entity types /// for child properties in <c>Agile.Entities.Release</c> ///</summary> public enum ReleaseChildEntityTypes { ///<summary> /// Collection of <c>Release</c> as OneToMany for DieRequestCollection ///</summary> [ChildEntityType(typeof(TList<DieRequest>))] DieRequestCollection, } #endregion ReleaseChildEntityTypes #region ReleaseFilterBuilder /// <summary> /// A strongly-typed instance of the <see cref="SqlFilterBuilder&lt;ReleaseColumn&gt;"/> class /// that is used exclusively with a <see cref="Release"/> object. /// </summary> [CLSCompliant(true)] public class ReleaseFilterBuilder : SqlFilterBuilder<ReleaseColumn> { #region Constructors /// <summary> /// Initializes a new instance of the ReleaseFilterBuilder class. /// </summary> public ReleaseFilterBuilder() : base() { } /// <summary> /// Initializes a new instance of the ReleaseFilterBuilder class. /// </summary> /// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param> public ReleaseFilterBuilder(bool ignoreCase) : base(ignoreCase) { } /// <summary> /// Initializes a new instance of the ReleaseFilterBuilder class. /// </summary> /// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param> /// <param name="useAnd">Specifies whether to combine statements using AND or OR.</param> public ReleaseFilterBuilder(bool ignoreCase, bool useAnd) : base(ignoreCase, useAnd) { } #endregion Constructors } #endregion ReleaseFilterBuilder #region ReleaseParameterBuilder /// <summary> /// A strongly-typed instance of the <see cref="ParameterizedSqlFilterBuilder&lt;ReleaseColumn&gt;"/> class /// that is used exclusively with a <see cref="Release"/> object. /// </summary> [CLSCompliant(true)] public class ReleaseParameterBuilder : ParameterizedSqlFilterBuilder<ReleaseColumn> { #region Constructors /// <summary> /// Initializes a new instance of the ReleaseParameterBuilder class. /// </summary> public ReleaseParameterBuilder() : base() { } /// <summary> /// Initializes a new instance of the ReleaseParameterBuilder class. /// </summary> /// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param> public ReleaseParameterBuilder(bool ignoreCase) : base(ignoreCase) { } /// <summary> /// Initializes a new instance of the ReleaseParameterBuilder class. /// </summary> /// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param> /// <param name="useAnd">Specifies whether to combine statements using AND or OR.</param> public ReleaseParameterBuilder(bool ignoreCase, bool useAnd) : base(ignoreCase, useAnd) { } #endregion Constructors } #endregion ReleaseParameterBuilder #region ReleaseSortBuilder /// <summary> /// A strongly-typed instance of the <see cref="SqlSortBuilder&lt;ReleaseColumn&gt;"/> class /// that is used exclusively with a <see cref="Release"/> object. /// </summary> [CLSCompliant(true)] public class ReleaseSortBuilder : SqlSortBuilder<ReleaseColumn> { #region Constructors /// <summary> /// Initializes a new instance of the ReleaseSqlSortBuilder class. /// </summary> public ReleaseSortBuilder() : base() { } #endregion Constructors } #endregion ReleaseSortBuilder } // end namespace
985d5e56c909fb48abdb28a3da93b5a18faba7d8
C#
RatiRajanPanikar/C-_TDD_BDD
/UnitTestProject1/ServiceCodeUnitTests.cs
2.8125
3
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using OOP_Project; namespace Tests { [TestClass] public class ServiceCodeUnitTests { [TestMethod] public void positiveServiceCode() { //Arrange var servCode = new ServiceCodes(); servCode.ServiceCode = "VYO09675"; servCode.Cost = 45.50; //Act var actual = servCode.ServiceCode; var actual2 = servCode.Cost; //Assert Assert.AreEqual("VYO09675", actual); Assert.AreEqual(45.50, actual2); } //[TestMethod] //public void NullServiceCode() //{ // //Arrange // var sc1 = new ServiceCodes // { // ServiceCode = null // }; // var expected = Exception("Cannot be null"); // //Act // var actual = sc1.ServiceCode; // //Assert // Assert.AreEqual(expected, actual); //} [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void MethodTest() { var obj = new ServiceCodes(null); } } }
db1a0e58a6f58ec9aa36e1ea36d712d12c959a30
C#
Batshaw/Tournament-Tracker
/TrackerUI/TournamentCreatorForm.cs
2.625
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using TrackerLibrary; using TrackerLibrary.Models; namespace TrackerUI { public partial class TournamentCreatorForm : Form, IPrizeRequester , ITeamRequester { ITournamentRequester callingForm; private List<TeamModel> availabelTeams = GlobalConfig.Connection.GetTeam_All(); private List<TeamModel> selectedTeams = new List<TeamModel>(); private List<PrizeModel> selectedPrizes = GlobalConfig.Connection.GetPrizes_All(); public TournamentCreatorForm(ITournamentRequester caller) { InitializeComponent(); callingForm = caller; WireUpLists(); } public void WireUpLists() { teamSelectDropDown.DataSource = null; teamSelectDropDown.DataSource = availabelTeams; teamSelectDropDown.DisplayMember = "TeamName"; teamsPlayersListBox.DataSource = null; teamsPlayersListBox.DataSource = selectedTeams; teamsPlayersListBox.DisplayMember = "TeamName"; prizeListBox.DataSource = null; prizeListBox.DataSource = selectedPrizes; prizeListBox.DisplayMember = "PlaceName"; } private void addTeamButton_Click(object sender, EventArgs e) { TeamModel p = (TeamModel)(teamSelectDropDown.SelectedItem); if (p != null) { selectedTeams.Add(p); availabelTeams.Remove(p); } WireUpLists(); } private void deleteTeamButton_Click(object sender, EventArgs e) { TeamModel p = (TeamModel)(teamsPlayersListBox.SelectedItem); if (p != null) { availabelTeams.Add(p); selectedTeams.Remove(p); } WireUpLists(); } private void deletePrizeButton_Click(object sender, EventArgs e) { PrizeModel p = (PrizeModel)(prizeListBox.SelectedItem); if (p != null) { selectedPrizes.Remove(p); } WireUpLists(); } private void createPrizeButton_Click(object sender, EventArgs e) { // Call the PrizeCreatorFOrm PrizeCreatorForm prizeForm = new PrizeCreatorForm(this); prizeForm.Show(); /* Finding solution by myself PrizeCreatorForm prizeForm = new PrizeCreatorForm(); this.Hide(); prizeForm.Show(); */ } public void PrizeComplete(PrizeModel model) { // Take the PrizeModel and put it into our list of selected prizes selectedPrizes.Add(model); WireUpLists(); } private void teamCreatorLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { // Call the TeamCreatorForm TeamCreatorForm teamForm = new TeamCreatorForm(this); teamForm.Show(); } public void TeamComplete(TeamModel model) { availabelTeams.Add(model); WireUpLists(); } private void createTournamentButton_Click(object sender, EventArgs e) { // Validate data decimal fee = 0; // Check if it could convert to decimal and output it to fee bool feeAceeptable = decimal.TryParse(entryFeeTextBox.Text, out fee); if (!feeAceeptable) { MessageBox.Show("You need to enter a valid Entry Fee", "Invalid Fee", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // Create Tournament Entry TournamentModel tm = new TournamentModel(); tm.TournamentName = tournamentNameTextBox.Text; tm.EntryFee = fee; // decimal.Parse(entryFeeTextBox.Text); tm.Prizes = selectedPrizes; tm.EnteredTeam = selectedTeams; // Wire our matchups TournamentLogic.CreateRounds(tm); // Creat all of the prizes entries // Creat all of the team entries GlobalConfig.Connection.CreateTournament(tm); // call this function to move all the matchups with only 1 entry into the next round TournamentLogic.UpdateTournamentResult(tm); // sending the created tournamnet direct to the dashboard callingForm.TournamentComplete(tm); this.Close(); } } }
b99af5b1d2fc6917fd3ca34ccf14b999a6acf49c
C#
Aravind5559797/Rocky
/Controllers/ApplicationController.cs
2.859375
3
using Microsoft.AspNetCore.Mvc; using Rocky.Data; using Rocky.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Rocky.Controllers { public class ApplicationController : Controller { private readonly ApplicationDbContext _db; public ApplicationController(ApplicationDbContext db) { this._db = db; } //GET INDEX public IActionResult Index() { IEnumerable<Application> objList = _db.Application; return View(objList); } //GET CREATE public IActionResult Create() { return View(); } //POST CREATE [HttpPost] [ValidateAntiForgeryToken] public IActionResult Create(Application obj) { if (ModelState.IsValid) { _db.Application.Add(obj); //save the changes _db.SaveChanges(); // redirect to another action ; in this case, to index. // Since , we are redirecting to the same controller, we don't need to indicate the controller return RedirectToAction("Index"); } return View(obj); } //GET EDIT public IActionResult Edit(int? id) { if (id==0 || id == null) { return NotFound(); } var obj = _db.Application.Find(id); if (obj == null) { return NotFound(); } return View(obj); } //POST EDIT //states the the action is for POST request [HttpPost] //appends an anit-frogery token to form data (for security) [ValidateAntiForgeryToken] public IActionResult Edit(Application obj) { if (ModelState.IsValid) { _db.Application.Update(obj); _db.SaveChanges(); return RedirectToAction("Index"); } return View(obj); } //GET DELETE public IActionResult Delete(int? id) { if (id == 0 || id == null) { return NotFound(); } var obj = _db.Application.Find(id); if (obj == null) { return NotFound(); } return View(obj); } //POST_DELETE //states the the action is for POST request [HttpPost] //appends an anit-frogery token to form data (for security) [ValidateAntiForgeryToken] public IActionResult DeletePost(int? id) { //Find retreives result based on the Primary key provided var obj = _db.Application.Find(id); //remove category object to the database _db.Application.Remove(obj); //save the changes _db.SaveChanges(); // redirect to another action ; in this case, to index. // Since , we are redirecting to the same controller, we don't need to indicate the controller return RedirectToAction("Index"); } } }
3d7058e00e4dc99e2c117c1aacd767ac0387b85f
C#
Dharmesh1979/design-patterns-in-csharp
/Mediator/Mediator/Program.cs
3.15625
3
using System; namespace Mediator { /* Mediator paterni aralarında iletişim kuracak nesnelerin(colleague) birbirlerini bilmeksizin merkezi bir(mediator) nesne üzerinden haberleşmesini öngürür. Örnek olarak havaalanı modellemesini ele alalım: Üçakların pist kullanımı için birbirleriyle haberleşmesi halinde ortaya büyük bir karmaşa çıkar. Fakat her uçak kontrol kulesi gibi merkezi bir unsur ile haberleşirse bir sıkıntı yaşanmaz. Bu paternin uygulanmasında 4 temel unsur vardır: - ConcreteColleague => İletişim kuracak sınıflar - Colleague => ConcreteColleague sınıfları tarafından kalıtılacak soyut sınıf - ConcreteMediator => ConcreteColleague sınıflarının iletişimini yönetecek merkezi sınıf - Mediator => ConcreteMediator sınıfları tarafından kalıtılacak soyut sınıf Bu örnekte; ConcreteColleague=NormalSubscriber&Moderator, Colleague=Subscriber, ConcreteMediator=SoftwareRoom, Mediator=Room sınıfları olarak tanımlanmıştır. */ class Program { static void Main(string[] args) { Subscriber s1 = new NormalSubscriber("normal1"); Subscriber s2 = new NormalSubscriber("normal2"); Subscriber s3 = new NormalSubscriber("normal3"); Subscriber s4 = new NormalSubscriber("normal4"); Subscriber s5 = new Moderator("furkan"); SoftwareRoom softwareRoom = new SoftwareRoom(); softwareRoom.AddSubscriber(s1); softwareRoom.AddSubscriber(s2); softwareRoom.AddSubscriber(s3); softwareRoom.AddSubscriber(s4); softwareRoom.AddSubscriber(s5); softwareRoom.BroadcastSendMessage(s5, "Herkese selam"); softwareRoom.SendMessage(s2, s3, "Ders ne zaman?"); softwareRoom.SendMessage(s3, s2, "14:30 da"); softwareRoom.SendMessage(s1, s4, "Dün aksamki maç kaç kaç bitti?"); softwareRoom.SendMessage(s4, s1, "2-1"); Console.ReadKey(); } } }
c06296752f96ed73cb9cb40c99d513a1c21ad105
C#
sergbas/MyGrammar
/MyGrammar/Parser/Rule.cs
2.71875
3
using System; namespace MyGrammar.Parser { public class Rule { private LogicalExpression condition; private Conclusion conclusion; public Rule() { } public Rule(LogicalExpression condition, Conclusion conclusion) { this.condition = condition; this.conclusion = conclusion; } public LogicalExpression getCondition() { return condition; } public void setCondition(LogicalExpression condition) { this.condition = condition; } public Conclusion getConclusion() { return conclusion; } public void setConclusion(String conclusion) { this.conclusion = new Conclusion(conclusion); } } }
37e10a771f23a2edd17d6f702d462c5477c9cafe
C#
fluce/aoc19
/Day16/Program.cs
3.078125
3
using System; using System.Linq; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Day16 { public class FFT { public FFT() { } public static Action<string> Log {get;set;} public string Apply(string input, int phaseCount) { return string.Join("",Apply(input.ToCharArray().Select(x=>Convert.ToByte(x)-48).Select(x=>(byte)x).ToArray(), phaseCount).Take(8)); } public string ApplyFull(string input) { var inputi=input.ToCharArray().Select(x=>Convert.ToByte(x)-48); var allinput=Enumerable.Range(0,10000).SelectMany(x=>inputi).Select(x=>(byte)x).ToArray(); int offset=int.Parse(input.Substring(0,7)); return string.Join("",Apply2(allinput,100,offset).Skip(offset).Take(8)); } public static IEnumerable<byte> Apply(byte[] input, int phaseCount) { var ret=input; var output=new byte[input.Length]; for(int i=0;i<phaseCount;i++) { Array.Clear(output,0,output.Length); ApplyPhase(ret,output); var a=ret; ret=output; output=a; } return ret; } public static IEnumerable<byte> Apply2(byte[] input, int phaseCount, int offset) { var ret=input; var output=new byte[input.Length]; Array.Copy(input,output,input.Length); for(int i=0;i<phaseCount;i++) { ApplyPhase2(output,offset); } return output; } public static void ApplyPhase2(byte[] data, int offset) { int total=0; for(int i=data.Length-1;i>=offset;i--) { total+=data[i]; data[i]=(byte)(total%10); } } public static void ApplyPhase(byte[] input, byte[] output) { Parallel.For(0,input.Length,(i,state)=> { output[i]=ApplyPattern(input, i); } ); } public static IEnumerable<int> ApplyPhaseV1(IEnumerable<int> input, int[] pattern) { int i=0; foreach(var e in input) yield return ApplyPatternV1(input, CalcPattern(pattern,i++).Skip(1)); } public static IEnumerable<int> CalcPattern(int[] pattern, int index) { while (true) foreach(var e in pattern.SelectMany(x=>Enumerable.Range(0,index+1).Select(y=>x))) yield return e; } public static byte ApplyPattern(byte[] input, int idx) { int start=idx; // idx start at 0 int rcount=idx+1; // repeat count; int remain=rcount; int ret=0; int current=start; int state=1; while (current<input.Length) { if (remain>0) { if (state==1) ret+=input[current]; else ret-=input[current]; remain--; current++; } else { current+=rcount; // skip rcount '0' state=-state; remain=rcount; } } return (byte)(Math.Abs(ret)%10); } public static byte ApplyPatternV2(byte[] input, int idx) { int start=idx; // idx start at 0 int rcount=idx+1; // repeat count; int remain=rcount; int ret=0; int current=start; int state=1; while (current<input.Length) { if (remain>0) { if (state==1) ret+=input[current]; else ret-=input[current]; remain--; current++; } else { current+=rcount; // skip rcount '0' state=-state; remain=rcount; } } return (byte)(Math.Abs(ret)%10); } public static int ApplyPatternV1(IEnumerable<int> input, IEnumerable<int> pattern) { var ret1=input.Zip(pattern).Sum(x=>x.First*x.Second); var ret=Math.Abs(ret1)%10; //Log?.Invoke($"{string.Join(" + ",input.Zip(pattern).Select(x=>$"{x.First} * {x.Second}"))} = {ret1} => {ret}"); return ret; } } class Program { static void Main(string[] args) { var input="59718730609456731351293131043954182702121108074562978243742884161871544398977055503320958653307507508966449714414337735187580549358362555889812919496045724040642138706110661041990885362374435198119936583163910712480088609327792784217885605021161016819501165393890652993818130542242768441596060007838133531024988331598293657823801146846652173678159937295632636340994166521987674402071483406418370292035144241585262551324299766286455164775266890428904814988362921594953203336562273760946178800473700853809323954113201123479775212494228741821718730597221148998454224256326346654873824296052279974200167736410629219931381311353792034748731880630444730593"; var fft=new FFT(); var ret=fft.Apply(input,100); Console.WriteLine($"Result part 1= {ret}"); var ret2=fft.ApplyFull(input); Console.WriteLine($"Result part 2 = {ret2}"); } } }
ecd90a641e364eef2b791500c88dd49b874fbff2
C#
shendongnian/download4
/first_version_download2/332931-28405246-83362367-2.cs
2.765625
3
/// <summary> /// Updates the data. /// </summary> protected internal override void UpdateData() { if (this.ItemsSource == null) { return; } this.items.Clear(); // Use the mapping to generate the points if (this.Mapping != null) { foreach (var item in this.ItemsSource) { this.items.Add(this.Mapping(item)); } return; } var filler = new ListFiller<HighLowItem>(); filler.Add(this.DataFieldX, (p, v) => p.X = Axis.ToDouble(v)); filler.Add(this.DataFieldHigh, (p, v) => p.High = Axis.ToDouble(v)); filler.Add(this.DataFieldLow, (p, v) => p.Low = Axis.ToDouble(v)); filler.Add(this.DataFieldOpen, (p, v) => p.Open = Axis.ToDouble(v)); filler.Add(this.DataFieldClose, (p, v) => p.Close = Axis.ToDouble(v)); filler.FillT(this.items, this.ItemsSource); }
fc4bcf09f0036afb6581218f05f8e05d3a27241a
C#
1905-may06-dotnet/El_Fanneri_Sami_Project1
/PizzaBoxWebApp/PizzaBox.Domain/Users.cs
2.796875
3
using System; using System.Collections.Generic; using System.Text; namespace PizzaBox.Domain { public class Users { public int Id { get; set; } private string firstName; private string lastName; private string street; private string city; private string state; private string zipCode; private string phone; private string email; private string password; public string FirstName { get => firstName; set { if (String.IsNullOrEmpty(value)) throw new ArgumentException("First name cannot be empty"); firstName = value; } } public string LastName { get => lastName; set { if (String.IsNullOrEmpty(value)) throw new ArgumentException("Last name cannot be empty"); lastName = value; } } public string Street { get => street; set { if (String.IsNullOrEmpty(value)) throw new ArgumentException("Street address cannot be empty"); street = value; } } public string City { get => city; set { if (String.IsNullOrEmpty(value)) throw new ArgumentException("City field cannot be empty"); city = value; } } public string State { get => state; set { if (String.IsNullOrEmpty(value)) throw new ArgumentException("State field cannot be empty"); state = value; } } public string ZipCode { get => zipCode; set { if (String.IsNullOrEmpty(value)) throw new ArgumentException("ZipCode cannot be empty"); zipCode = value; } } public string Phone { get => phone; set { if (String.IsNullOrEmpty(value)) throw new ArgumentException("Phone number cannot be empty"); phone = value; } } public string Email { get => email; set { if (String.IsNullOrEmpty(value)) throw new ArgumentException("Email cannot be empty"); email = value; } } public string Password { get => password; set { if (String.IsNullOrEmpty(value)) throw new ArgumentException("Password field cannot be empty"); password = value; } } } }
a6a970921fe16fe31e46a535492b196a1f55c076
C#
edison9813123/DeberJuego
/PersistenciaTres/Persistencia3.cs
2.546875
3
using System; using System.Collections.Generic; using System.IO; using Entidades; using Interfaces; namespace PersistenciaTres { public class Persistencia3 : IPersistenciaTres { public new bool Grabar(Avatar avatar) { File.AppendAllLines("Avatar.txt", new List<string> { avatar.Nombre3 }); Console.WriteLine("Jugador: "); Console.WriteLine(avatar.Nombre3); return true; } public new bool Grabar(Acciones acciones) { File.AppendAllLines("Acciones.txt", new List<string> { acciones.Accion3 }); Console.WriteLine("Realiza la accion : "); Console.WriteLine(acciones.Accion3); return true; } public new bool Grabar(Nivel nivel) { File.AppendAllLines("Nivel.txt", new List<string> { nivel.Nivel3 }); Console.WriteLine("Usted esta en el nivel: "); Console.WriteLine(nivel.Nivel3); return true; } public new bool Grabar(AvatarPorAccion avatarPorAccion) { File.AppendAllLines("AvatarPorAccion.txt", new List<string> { avatarPorAccion.NivelId.ToString() }); return true; } } }
7ffad1086e8c16cda2e39089401b7df0b9dbb6b8
C#
BrandonGriffin/GameOfLifeKata
/GameOfLifeTests/GameOfLifeTests.cs
3.171875
3
using System; using NUnit.Framework; namespace GameOfLifeKata.Tests { [TestFixture] public class GameOfLifeTests { [Test] public void TopRightCellWithExactly3NeightborsComesToLife() { var grid = new Int32[,] { { 0, 1, 0 }, { 0, 1, 1 }, { 0, 0, 0 } }; var game = new GameOfLife(grid); var actual = game.CheckGrid(); var expected = new Int32[,] { { 0, 1, 1 }, { 0, 1, 1 }, { 0, 0, 0 } }; Assert.That(actual, Is.EqualTo(expected)); } [Test] public void TopLeftCellWithExactly3NeightborsComesToLife() { var grid = new Int32[,] { { 0, 1, 0 }, { 1, 1, 0 }, { 0, 0, 0 } }; var game = new GameOfLife(grid); var actual = game.CheckGrid(); var expected = new Int32[,] { { 1, 1, 0 }, { 1, 1, 0 }, { 0, 0, 0 } }; Assert.That(actual, Is.EqualTo(expected)); } [Test] public void BottomLeftCellWithExactly3NeightborsComesToLife() { var grid = new Int32[,] { { 0, 0, 0 }, { 1, 1, 0 }, { 0, 1, 0 } }; var game = new GameOfLife(grid); var actual = game.CheckGrid(); var expected = new Int32[,] { { 0, 0, 0 }, { 1, 1, 0 }, { 1, 1, 0 } }; Assert.That(actual, Is.EqualTo(expected)); } [Test] public void BottomRightCellWithExactly3NeightborsComesToLife() { var grid = new Int32[,] { { 0, 0, 0 }, { 0, 1, 1 }, { 0, 1, 0 } }; var game = new GameOfLife(grid); var actual = game.CheckGrid(); var expected = new Int32[,] { { 0, 0, 0 }, { 0, 1, 1 }, { 0, 1, 1 } }; Assert.That(actual, Is.EqualTo(expected)); } [Test] public void TopRowCellWithExactly3NeightborsComesToLife() { var grid = new Int32[,] { { 0, 0, 1 }, { 0, 1, 1 }, { 0, 0, 0 } }; var game = new GameOfLife(grid); var actual = game.CheckGrid(); var expected = new Int32[,] { { 0, 1, 1 }, { 0, 1, 1 }, { 0, 0, 0 } }; Assert.That(actual, Is.EqualTo(expected)); } [Test] public void LeftSideCellWithExactly3NeightborsComesToLife() { var grid = new Int32[,] { { 0, 1, 0 }, { 0, 1, 0 }, { 1, 0, 0 } }; var game = new GameOfLife(grid); var actual = game.CheckGrid(); var expected = new Int32[,] { { 0, 0, 0 }, { 1, 1, 0 }, { 0, 0, 0 } }; Assert.That(actual, Is.EqualTo(expected)); } [Test] public void RightSideCellWithExactly3NeightborsComesToLife() { var grid = new Int32[,] { { 0, 1, 0 }, { 0, 1, 0 }, { 0, 0, 1 } }; var game = new GameOfLife(grid); var actual = game.CheckGrid(); var expected = new Int32[,] { { 0, 0, 0 }, { 0, 1, 1 }, { 0, 0, 0 } }; Assert.That(actual, Is.EqualTo(expected)); } [Test] public void BottomRowCellWithExactly3NeightborsComesToLife() { var grid = new Int32[,] { { 0, 0, 0 }, { 1, 1, 0 }, { 0, 0, 1 } }; var game = new GameOfLife(grid); var actual = game.CheckGrid(); var expected = new Int32[,] { { 0, 0, 0 }, { 0, 1, 0 }, { 0, 1, 0 } }; Assert.That(actual, Is.EqualTo(expected)); } [Test] public void CellWithExactlyTwoOrLessNeighborsDies() { var grid = new Int32[,] { { 0, 0, 0 }, { 1, 1, 0 }, { 0, 0, 1 } }; var game = new GameOfLife(grid); var actual = game.CheckGrid(); var expected = new Int32[,] { { 0, 0, 0 }, { 0, 1, 0 }, { 0, 1, 0 } }; Assert.That(actual, Is.EqualTo(expected)); } [Test] public void BiggerGridReturnsTheCorrectResult() { var grid = new Int32[,] { { 0, 0, 0, 1, 0 }, { 1, 1, 0, 1, 1 }, { 0, 0, 1, 0, 0 }, { 1, 1, 0, 0, 0 }, { 0, 0, 1, 0, 0 } }; var game = new GameOfLife(grid); var actual = game.CheckGrid(); var expected = new Int32[,] { { 0, 0, 1, 1, 1 }, { 0, 1, 0, 1, 1 }, { 0, 0, 1, 1, 0 }, { 0, 1, 1, 0, 0 }, { 0, 1, 0, 0, 0 } }; Assert.That(actual, Is.EqualTo(expected)); } [Test] public void TwoIterationsOfAGridReturnsTheCorrectResult() { var grid = new Int32[,] { { 1, 1, 1 }, { 1, 0, 0 }, { 0, 1, 1 } }; var game = new GameOfLife(grid); var firstRun = game.CheckGrid(); var actual = game.CheckGrid(); var expected = new Int32[,] { { 1, 1, 0 }, { 1, 0, 0 }, { 0, 0, 0 } }; Assert.That(actual, Is.EqualTo(expected)); } } }
15bd28bfea297220e6c97e9e18f8bc6b05ccc2f8
C#
CaioPontalti/Curso-Asp.Net-Core-2.2-BaltaStore-WebAPI
/src/BaltaStore.Domain/StoreContext/Commands/OrderCommands/CreateOrderCommand.cs
2.515625
3
using BaltaStore.Domain.StoreContext.Entities; using BaltaStore.Shared.Commands; using FluentValidator; using FluentValidator.Validation; using System; using System.Collections.Generic; using System.Text; namespace BaltaStore.Domain.StoreContext.Commands.OrderCommands { public class CreateOrderCommand : Notifiable, ICommand { public CreateOrderCommand() { OrderItems = new List<CreateOrderItemCommand>(); } public Guid CustomerId { get; set; } public List<CreateOrderItemCommand> OrderItems { get; set; } public bool Valid() { AddNotifications(new ValidationContract() .HasLen(CustomerId.ToString(), 36, "Customer", "Identificador do Cliente inválido") .IsGreaterThan(OrderItems.Count, 0, "Items", "O pedido não possui itens.") ); return IsValid; } } }
04a2442c2321302e8dff503e7f90a168060b22e5
C#
ndrwrbgs/FastLinq
/src/Library/List/StayInList/Reverse.cs
3.21875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace System.Linq { using System.Collections; public static partial class FastLinq { /// <summary> /// May actually have some improvements due to avoiding double-copying of Buffer /// </summary> public static IReadOnlyList<T> Reverse<T>( this IReadOnlyList<T> source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } return new ReverseList<T>( source); } private sealed class ReverseList<T> : IReadOnlyList<T>, ICanCopyTo<T> { private readonly IReadOnlyList<T> list; public ReverseList(IReadOnlyList<T> list) { this.list = list; } public void CopyTo(long sourceIndex, T[] dest, long count) { CanCopyHelper.CopyTo(this.list, sourceIndex, dest, count); Array.Reverse(dest, 0, (int) count); } public IEnumerator<T> GetEnumerator() { return GetEnumerable().GetEnumerator(); } private IEnumerable<T> GetEnumerable() { // TODO: Is it faster to implement an enumerator? for (int i = this.list.Count - 1; i >= 0; i--) { yield return this.list[i]; } } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } public int Count => this.list.Count; public T this[int index] { get { var reversedIndex = this.list.Count - index - 1; return this.list[reversedIndex]; } set => throw new NotSupportedException(); } } } }
c0e1d158141a433236184f3d879c56ca894e5a60
C#
themeldingwars/Be.HexEditor
/Be.HexEditor/Util.cs
3.046875
3
using System.Collections.Generic; using System.Globalization; namespace Be.HexEditor { static class Util { /// <summary> /// Contains true, if we are in design mode of Visual Studio /// </summary> private static bool _designMode; /// <summary> /// Initializes an instance of Util class /// </summary> static Util() { // design mode is true if host process is: Visual Studio, Visual Studio Express Versions (C#, VB, C++) or SharpDevelop var designerHosts = new List<string>() { "devenv", "vcsexpress", "vbexpress", "vcexpress", "sharpdevelop" }; using (var process = System.Diagnostics.Process.GetCurrentProcess()) { var processName = process.ProcessName.ToLower(); _designMode = designerHosts.Contains(processName); } } /// <summary> /// Gets true, if we are in design mode of Visual Studio /// </summary> /// <remarks> /// In Visual Studio 2008 SP1 the designer is crashing sometimes on windows forms. /// The DesignMode property of Control class is buggy and cannot be used, so use our own implementation instead. /// </remarks> public static bool DesignMode { get { return _designMode; } } public static string GetDisplayBytes(long size) { const long multi = 1024; long kb = multi; long mb = kb*multi; long gb = mb*multi; long tb = gb*multi; const string BYTES = "Bytes"; const string KB = "KB"; const string MB = "MB"; const string GB = "GB"; const string TB = "TB"; string result; if (size < kb) result = string.Format("{0} {1}", size, BYTES); else if(size < mb) result = string.Format("{0} {1} ({2} Bytes)", ConvertToOneDigit(size, kb), KB, ConvertBytesDisplay(size)); else if(size < gb) result = string.Format("{0} {1} ({2} Bytes)", ConvertToOneDigit(size, mb), MB, ConvertBytesDisplay(size)); else if(size < tb) result = string.Format("{0} {1} ({2} Bytes)", ConvertToOneDigit(size, gb), GB, ConvertBytesDisplay(size)); else result = string.Format("{0} {1} ({2} Bytes)", ConvertToOneDigit(size, tb), TB, ConvertBytesDisplay(size)); return result; } static string ConvertBytesDisplay(long size) { return size.ToString("###,###,###,###,###", CultureInfo.CurrentCulture); } static string ConvertToOneDigit(long size, long quan) { double quotient = (double)size / (double)quan; string result = quotient.ToString("0.#", CultureInfo.CurrentCulture); return result; } } }
9fd9928df1b6bd38991c879e4adf2214c5afb570
C#
updateak47/accountSecure
/Biometric.Device/ImageConverter.cs
2.78125
3
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Windows.Forms; namespace Biometric.Tasks { public class ImageConverter { public static byte[] ToImageByte(string imagefile) { byte[] fileBytes = null; string fl = imagefile; using (FileStream fs = new FileStream(fl, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { fileBytes = new byte[fs.Length]; fs.Read(fileBytes, 0, fileBytes.Length); //fs.Flush(); fs.Close(); } GC.Collect(); return fileBytes; } public static string ToImageFile(object imagebyte, string filename) { byte[] _imByte = (byte[])imagebyte; string imagefile = Path.Combine(Application.StartupPath, "BioImages" , string.Format(@"{0}", filename)); if (!Directory.Exists(new FileInfo(imagefile).DirectoryName)) Directory.CreateDirectory(new FileInfo(imagefile).DirectoryName); string fl = imagefile; if (File.Exists(fl)) File.Delete(imagefile); using (FileStream fs = new FileStream(fl, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { fs.Write(_imByte, 0, _imByte.Length); fs.Flush(); fs.Close(); } return imagefile; } public static Image ToImage(byte[] imgByte, int offset, int len) { Image newImage; using (MemoryStream ms = new MemoryStream(imgByte, offset, len)) { ms.Write(imgByte, offset, len); newImage = Image.FromStream((Stream)ms, true); } return newImage; } } }
b78068f118aa3800fd60804dd6490511edc363ba
C#
lostm1nd/TelerikAcademy
/02CSharpAdvanced/StringTextProcessing/CountLetters/CountLetters.cs
4.15625
4
//Write a program that reads a string from //the console and prints all different letters //in the string along with information how many times each letter is found. using System; using System.Collections.Generic; using System.Linq; class CountLetters { static void Main() { Console.WriteLine("Counting letter occurrence in text"); Console.WriteLine("Enter text:"); string text = Console.ReadLine(); text = text.ToLower(); int[] letterCount = new int[26]; for (int i = 0; i < text.Length; i++) { if (char.IsLetter(text[i])) { int index = text[i] - 'a'; letterCount[index]++; } } for (int i = 0; i < letterCount.Length; i++) { if (letterCount[i] > 0) { Console.WriteLine("The letter \"{0}\" appears: {1} time/s", (char)(i + 'a'), letterCount[i]); } } } }
27e5ab4e8c2deee4b3c860adb6c95d759d4b5c68
C#
jonashammerschmidt/rAPI
/rAPICore/Models/DataTransferObjects/Comment.cs
2.609375
3
using rAPI.Answers; using System.Collections.Generic; namespace rAPI.DTO { public class Comment : DataAnswer { public Comment(int commentId, string text, string user, int upvotes, int downvotes) { this.commentId = commentId; this.text = text; this.user = user; this.upvotes = upvotes; this.downvotes = downvotes; this.comment = new List<Comment>(); } public Comment(int commentId, string text, string user, int upvotes, int downvotes, int yourvote) : this(commentId, text, user, upvotes, downvotes) { this.yourvote = yourvote; } public int commentId { get; set; } public string text { get; private set; } public string user { get; private set; } public int upvotes { get; private set; } public int downvotes { get; private set; } public int yourvote { get; private set; } public List<Comment> comment; } }
67616d5ae0881862b4870a0e79424766196527d0
C#
bonsai-rx/bonsai
/Bonsai.Vision/Crop.cs
2.921875
3
using System; using System.Linq; using System.Reactive.Linq; using OpenCV.Net; using System.ComponentModel; namespace Bonsai.Vision { /// <summary> /// Represents an operator that crops a rectangular subregion of each image /// in the sequence, without copying. /// </summary> [DefaultProperty(nameof(RegionOfInterest))] [Description("Crops a rectangular subregion of each image in the sequence, without copying.")] public class Crop : Transform<IplImage, IplImage> { /// <summary> /// Gets or sets a rectangle specifying the region of interest inside the image. /// </summary> [Description("Specifies the region of interest inside the image.")] [Editor("Bonsai.Vision.Design.IplImageRectangleEditor, Bonsai.Vision.Design", DesignTypes.UITypeEditor)] public Rect RegionOfInterest { get; set; } /// <summary> /// Crops a subregion of each image in an observable sequence. /// </summary> /// <param name="source">The sequence of images to crop.</param> /// <returns> /// A sequence of <see cref="IplImage"/> objects where each new image /// contains the extracted subregion of the original image. /// </returns> public override IObservable<IplImage> Process(IObservable<IplImage> source) { return source.Select(input => { var rect = RegionOfInterest; if (rect.Width > 0 && rect.Height > 0) { return input.GetSubRect(rect); } return input; }); } } }
1f1b4c41ac4d80126fc5dd876c9be83d7430c9e5
C#
BlazorHub/CS50G
/src/Games/BreakoutGame/ScoreData.cs
2.578125
3
namespace BreakoutGame { public class ScoreData { public string Name { get; } public int Score { get; } public ScoreData(string name, int score) { Name = name; Score = score; } } }
73a1676b620454524214f6678d1688bd4a48f0c9
C#
TheRealMichaelWang/MinimIDE
/MinimIDE/Syntax/Values.cs
2.921875
3
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MinimIDE.Syntax { public partial class NumericalNode : HighlightNode { public double Double { get;private set; } public NumericalNode(double @double, int pos) : base(pos, pos + @double.ToString().Length) { this.Double = @double; } public override bool Compare(INode node) { if (!typeof(NumericalNode).IsAssignableFrom(node.GetType())) return false; NumericalNode numerical = node as NumericalNode; return this.Double == numerical.Double; } public override void GetDifference(List<INode> differences, INode node) { if (!typeof(NumericalNode).IsAssignableFrom(node.GetType())) { differences.Add(node); return; } NumericalNode numerical = node as NumericalNode; if (this.Double != numerical.Double) differences.Add(node); } } public partial class StringLiteralNode : HighlightNode { public string String { get; private set; } public StringLiteralNode(string @string, int pos):base(pos, pos + @string.Length+2) { this.String = @string; } public override bool Compare(INode node) { if (!typeof(StringLiteralNode).IsAssignableFrom(node.GetType())) return false; StringLiteralNode stringLiteral = node as StringLiteralNode; return this.String == stringLiteral.String; } public override void GetDifference(List<INode> differences, INode node) { if (!typeof(StringLiteralNode).IsAssignableFrom(node.GetType())) { differences.Add(node); return; } StringLiteralNode stringLiteral = node as StringLiteralNode; if (this.String != stringLiteral.String) differences.Add(node); } } public partial class ArrayLiteralNode : HighlightNode { private List<INode> array; public int Size { get { return array.Count; } } public ArrayLiteralNode(List<INode> array, int start, int stop) :base(start, stop) { this.array = array; } public override bool Compare(INode node) { if (!typeof(ArrayLiteralNode).IsAssignableFrom(node.GetType())) return false; ArrayLiteralNode arrayLiteral = node as ArrayLiteralNode; if (arrayLiteral.Size != this.Size) return false; for(int i = 0; i < this.Size; i++) { if (!this.array.Equals(arrayLiteral.array[i])) return false; } return true; } public override void GetDifference(List<INode> differences, INode node) { if (!typeof(ArrayLiteralNode).IsAssignableFrom(node.GetType())) { differences.Add(node); return; } ArrayLiteralNode arrayLiteral = node as ArrayLiteralNode; if (this.Size != arrayLiteral.Size) { differences.Add(node); return; } for (int i = 0; i < this.Size && i < arrayLiteral.Size; i++) this.array[i].GetDifference(differences, arrayLiteral.array[i]); for (int i = this.Size; i < arrayLiteral.Size; i++) differences.Add(arrayLiteral.array[i]); } } public partial class CreateRecordNode : GotoNode { public string RecordType { get { return this.labelKeyword.Identifier; } } public CreateRecordNode(KeywordNode labelKeyword, List<INode> arguments, int pos) : base(new KeywordNode("new", pos, Color.DarkBlue), labelKeyword, arguments) { } public override bool Compare(INode node) { if (!typeof(CreateRecordNode).IsAssignableFrom(node.GetType())) return false; CreateRecordNode createRecord = node as CreateRecordNode; if (this.RecordType != createRecord.RecordType) return false; return base.Compare(createRecord); } public override void GetDifference(List<INode> differences, INode node) { if (!typeof(CreateRecordNode).IsAssignableFrom(node.GetType())) { differences.Add(node); return; } CreateRecordNode createRecord = node as CreateRecordNode; if (this.RecordType != createRecord.RecordType) { differences.Add(node); return; } base.GetDifference(differences, createRecord); } } public partial class CharacterLiteral : HighlightNode { public string Char { get; private set; } public CharacterLiteral(string @char, int pos) : base(pos , pos + @char.Length + 2) { this.Char = @char; } public override bool Compare(INode node) { if (!typeof(CharacterLiteral).IsAssignableFrom(node.GetType())) return false; CharacterLiteral character = node as CharacterLiteral; return (this.Char == character.Char); } public override void GetDifference(List<INode> differences, INode node) { if (!typeof(CharacterLiteral).IsAssignableFrom(node.GetType())) { differences.Add(node); return; } CharacterLiteral character = node as CharacterLiteral; if (this.Char != character.Char) { differences.Add(node); return; } } } }
ee6761bbc18026f3f9abf692b7341c9b8081a6ea
C#
SubinChitrakar/ExpenseManagement
/ExpenseManagement/Repository/RecurringTransactionRepository.cs
2.59375
3
using ExpenseManagement.Model; using ExpenseManagement.Utilities; using NLog; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExpenseManagement.Repository { class RecurringTransactionRepository : BaseRepository { private Logger _logger = LogManager.GetCurrentClassLogger(); //Constructor public RecurringTransactionRepository() : base() { } public List<RecurringTransaction> GetTransactions(int userId) { List<RecurringTransaction> recurringTransactionList = new List<RecurringTransaction>(); Query = "SELECT RecurringTransactions.*, Contacts.ContactName FROM RecurringTransactions LEFT JOIN Contacts ON RecurringTransactions.ContactId = Contacts.ContactId WHERE RecurringTransactions.UserId = @UserId ORDER BY RecurringTransactions.TransactionDate DESC"; try { SqlConnection.Open(); SqlCommand sqlCommand = new SqlCommand(Query, SqlConnection); sqlCommand.Parameters.Add("@UserId", SqlDbType.Int).Value = userId; SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); while (sqlDataReader.Read()) { RecurringTransaction recurringTransaction = new RecurringTransaction { Id = (int)sqlDataReader["Id"], Name = sqlDataReader["Name"].ToString(), Amount = Convert.ToDouble(sqlDataReader["Amount"]), Type = sqlDataReader["Type"].ToString(), Note = sqlDataReader["Note"].ToString(), TransactionDate = (DateTime)sqlDataReader["TransactionDate"], Status = sqlDataReader["Status"].ToString(), UserId = (int)sqlDataReader["UserId"] }; if (sqlDataReader["ContactId"] == DBNull.Value) recurringTransaction.ContactId = 0; else recurringTransaction.ContactId = (int)sqlDataReader["ContactId"]; if (sqlDataReader["ContactName"] == DBNull.Value) recurringTransaction.ContactName = ""; else recurringTransaction.ContactName = sqlDataReader["ContactName"].ToString(); if (sqlDataReader["TransactionEndDate"] == DBNull.Value) recurringTransaction.TransactionEndDate = DateTime.MinValue; else recurringTransaction.TransactionEndDate = (DateTime)sqlDataReader["TransactionEndDate"]; recurringTransactionList.Add(recurringTransaction); } } catch (Exception ex) { _logger.Error(ex); } finally { SqlConnection.Close(); } return recurringTransactionList; } public List<RecurringTransaction> GetExpenseTransactions(int userId) { List<RecurringTransaction> recurringTransactionList = new List<RecurringTransaction>(); Query = "SELECT * FROM RecurringTransactions WHERE UserId = @UserId AND Type = @Type ORDER BY TransactionDate DESC"; try { SqlConnection.Open(); SqlCommand sqlCommand = new SqlCommand(Query, SqlConnection); sqlCommand.Parameters.Add("@UserId", SqlDbType.Int).Value = userId; sqlCommand.Parameters.Add("@Type", SqlDbType.VarChar).Value = "Expense"; SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); while (sqlDataReader.Read()) { RecurringTransaction recurringTransaction = new RecurringTransaction { Id = (int)sqlDataReader["Id"], Name = sqlDataReader["Name"].ToString(), Amount = Convert.ToDouble(sqlDataReader["Amount"]), Type = sqlDataReader["Type"].ToString(), Note = sqlDataReader["Note"].ToString(), TransactionDate = (DateTime)sqlDataReader["TransactionDate"], Status = sqlDataReader["Status"].ToString(), UserId = (int)sqlDataReader["UserId"] }; if (sqlDataReader["TransactionEndDate"] == DBNull.Value) recurringTransaction.TransactionEndDate = DateTime.MinValue; else recurringTransaction.TransactionEndDate = (DateTime)sqlDataReader["TransactionEndDate"]; recurringTransactionList.Add(recurringTransaction); } } catch (Exception ex) { _logger.Error(ex); } finally { SqlConnection.Close(); } return recurringTransactionList; } public MessageStatus AddRecurringTransaction(RecurringTransaction recurringTransaction) { Query = "INSERT INTO RecurringTransactions([Name], [Amount], [Type], [Note], [TransactionDate], [ContactId], [Status], [TransactionEndDate], [UserId]) VALUES(@Name, @Amount, @Type, @Note, @TransactionDate, @ContactId, @Status, @TransactionEndDate, @UserId);"; try { SqlConnection.Open(); SqlCommand sqlCommand = new SqlCommand(Query, SqlConnection); sqlCommand.Parameters.Add("@Name", SqlDbType.VarChar).Value = recurringTransaction.Name; sqlCommand.Parameters.Add("@Amount", SqlDbType.Money).Value = recurringTransaction.Amount; sqlCommand.Parameters.Add("@Type", SqlDbType.VarChar).Value = recurringTransaction.Type; sqlCommand.Parameters.Add("@Note", SqlDbType.VarChar).Value = recurringTransaction.Note; sqlCommand.Parameters.Add("@Status", SqlDbType.VarChar).Value = recurringTransaction.Status; sqlCommand.Parameters.Add("@TransactionDate", SqlDbType.DateTime).Value = recurringTransaction.TransactionDate; sqlCommand.Parameters.Add("@UserId", SqlDbType.Int).Value = recurringTransaction.UserId; SqlParameter ContactId = new SqlParameter("@ContactId", SqlDbType.Int); if (recurringTransaction.ContactId == 0) ContactId.Value = DBNull.Value; else ContactId.Value = recurringTransaction.ContactId; sqlCommand.Parameters.Add(ContactId); SqlParameter transactionEndDate = new SqlParameter("@TransactionEndDate", SqlDbType.DateTime); if (recurringTransaction.TransactionEndDate == DateTime.MinValue) transactionEndDate.Value = DBNull.Value; else transactionEndDate.Value = recurringTransaction.TransactionEndDate; sqlCommand.Parameters.Add(transactionEndDate); var i = sqlCommand.ExecuteNonQuery(); if (i > 0) { MessageStatus.Message = "Transaction Added Successfully!!"; MessageStatus.ErrorStatus = false; } else throw new Exception("Error, Data Not Added!"); } catch (Exception ex) { _logger.Error(ex); MessageStatus.Message = ex.Message; MessageStatus.ErrorStatus = true; } finally { SqlConnection.Close(); } return MessageStatus; } //Update Contact public MessageStatus UpdateRecurringTransaction(RecurringTransaction recurringTransaction) { Query = "UPDATE RecurringTransactions SET [Name] = @Name, [Amount] = @Amount, [Type] = @Type, [Note] = @Note, [TransactionDate] = @TransactionDate, [ContactId] = @ContactId, [Status] = @Status, [TransactionEndDate] = @TransactionEndDate WHERE [Id] = @Id AND [UserId] = @UserId;"; try { SqlConnection.Open(); SqlCommand sqlCommand = new SqlCommand(Query, SqlConnection); sqlCommand.Parameters.Add("@Id", SqlDbType.Int).Value = recurringTransaction.Id; sqlCommand.Parameters.Add("@Name", SqlDbType.VarChar).Value = recurringTransaction.Name; sqlCommand.Parameters.Add("@Amount", SqlDbType.Money).Value = recurringTransaction.Amount; sqlCommand.Parameters.Add("@Type", SqlDbType.VarChar).Value = recurringTransaction.Type; sqlCommand.Parameters.Add("@Note", SqlDbType.VarChar).Value = recurringTransaction.Note; sqlCommand.Parameters.Add("@Status", SqlDbType.VarChar).Value = recurringTransaction.Status; sqlCommand.Parameters.AddWithValue("@TransactionDate", Convert.ToDateTime(recurringTransaction.TransactionDate)); sqlCommand.Parameters.Add("@UserId", SqlDbType.Int).Value = recurringTransaction.UserId; SqlParameter ContactId = new SqlParameter("@ContactId", SqlDbType.Int); if (recurringTransaction.ContactId == 0) ContactId.Value = DBNull.Value; else ContactId.Value = recurringTransaction.ContactId; sqlCommand.Parameters.Add(ContactId); SqlParameter transactionEndDate = new SqlParameter("@TransactionEndDate", SqlDbType.DateTime); if (recurringTransaction.TransactionEndDate == DateTime.MinValue) transactionEndDate.Value = DBNull.Value; else transactionEndDate.Value = recurringTransaction.TransactionEndDate; sqlCommand.Parameters.Add(transactionEndDate); var i = sqlCommand.ExecuteNonQuery(); if (i > 0) { MessageStatus.Message = "Transaction Updated Successfully!!"; MessageStatus.ErrorStatus = false; } else throw new Exception("Error, Data Not Updated!"); } catch (Exception ex) { _logger.Error(ex); MessageStatus.Message = ex.Message; MessageStatus.ErrorStatus = true; } finally { SqlConnection.Close(); } return MessageStatus; } public MessageStatus DeleteRecurringTransaction(RecurringTransaction recurringTransaction) { Query = "DELETE FROM RecurringTransactions WHERE [Id] = @Id AND [UserId] = @UserId;"; try { SqlConnection.Open(); SqlCommand sqlCommand = new SqlCommand(Query, SqlConnection); sqlCommand.Parameters.Add("@Id", SqlDbType.Int).Value = recurringTransaction.Id; sqlCommand.Parameters.Add("@UserId", SqlDbType.Int).Value = recurringTransaction.UserId; var i = sqlCommand.ExecuteNonQuery(); if (i > 0) { MessageStatus.Message = "Transaction Deleted Successfully!!"; MessageStatus.ErrorStatus = false; } else throw new Exception("Error, Data Not Deleted!"); } catch (Exception ex) { _logger.Error(ex); MessageStatus.Message = ex.Message; MessageStatus.ErrorStatus = true; } finally { SqlConnection.Close(); } return MessageStatus; } } }
e50d49dcabdf78bca10b683ef751261f3da35b1d
C#
kubapalasz/Challanger
/NancySelfHosting/Answers/SqueareCubeAnswer.cs
3.1875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json; namespace NancySelfHosting.Answers { public class SqueareQubeAnswer { private int[] _parameters; public SqueareQubeAnswer(string parameters) { _parameters = JsonConvert.DeserializeObject<int[]>(parameters); } public string GetAnswer() { var result = new List<int>(); foreach (var number in _parameters) { var sqrtResult = Math.Sqrt(number); if (Math.Round(sqrtResult) != sqrtResult) { continue; } var qubeResult = Math.Pow(number, 1/3); if (Math.Round(qubeResult) != qubeResult) { continue; } result.Add(number); } var response = result.Aggregate(string.Empty, (current, correct) => current + (correct + ',')); return response.TrimEnd(','); } } }
b4c3ee53c5db903f4aec52748acb15fb2411a421
C#
mbarzowska/UG-zajecia-uczelniane
/dotNET/XAMARIN.FORMS-app/FoodParty.Tests/CompareViewModelTests.cs
2.75
3
using System; using System.Collections.Generic; using System.Text; using FoodParty.Validators; using Xunit; namespace FoodParty.Tests { public class CompareViewModelTests { [Fact] public void PriceValidator_GivenValidPrice_ReturnsTrue() { // Arrange decimal validPrice = 10M; // Act var result = Validator.ValidatePrice(validPrice); // Assert Assert.True(result); } [Fact] public void PriceValidator_GivenInvalidPrice_Negative_ReturnsFalse() { // Arrange decimal invalidPrice = -10M; // Act var result = Validator.ValidatePrice(invalidPrice); // Assert Assert.False(result); } [Fact] public void PriceValidator_GivenInvalidPrice_MoreDigits_ReturnsFalse() { // Arrange decimal invalidPrice = 2.1234M; // Act var result = Validator.ValidatePrice(invalidPrice); // Assert Assert.False(result); } } }
c510433924d4900371d67387422b19c57d9b59ae
C#
angoudjou/lab4
/Program.cs
3.890625
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab4 { class Program { static void Main(string[] args) { Console.WriteLine("Program Factorial of a number"); bool run = true; while (run) { Console.WriteLine("Enter a number between 1-20:"); int x = int.Parse(Console.ReadLine()); if (x <= 20 && x >= 0) { Console.WriteLine("The factorial of "+x+" is " + factoRecursion(x)); } else Console.WriteLine("Number out of range"); run = continue_run(); }// end of while loop } public static bool continue_run() { Console.Write("Continue?(Y/N) : "); string response = Console.ReadLine(); response = response.ToLower(); if (response == "y") { return true; } else if (response == "n") { return false; } else { Console.WriteLine("You did not type a recognized caracter, type Y or N"); return continue_run(); } } public static long factoRecursion( int x) { if (x == 0 ||x == 1) return 1; return x * factoRecursion(x - 1); } public static long factoFor(int x) { long facto = 1; for (int i = 1; i <= x; i++) { facto *= i; } return facto; } } }
7cfc267b21d8cc8891972d4dd5aca118365062ba
C#
luismedel/sixthcircle
/SixthCircle/DataViewer.cs
2.8125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SixthCircle { public unsafe class DataViewer { byte[] _data; public DataViewer (byte[] data) { _data = data; } public Int16 AsInt16 (int offset) { fixed (void* ptr = &_data[offset]) return *(Int16*) ptr; } public Int32 AsInt32 (int offset) { fixed (void* ptr = &_data[offset]) return *(Int32*) ptr; } public Int64 AsInt64 (int offset) { fixed (void* ptr = &_data[offset]) return *(Int64*) ptr; } public Single AsSingle (int offset) { fixed (void* ptr = &_data[offset]) return *(Single*) ptr; } public Double AsDouble (int offset) { fixed (void* ptr = &_data[offset]) return *(Double*) ptr; } } }
418bb3c656a516cf291a76a72e1afeb2b8531a25
C#
radtek/Gradual
/Gradual.OMS-II/Gradual.OMS.STM/Gradual.OMS.ConectorSTM/ProcessadorMensagens.cs
2.59375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using com.espertech.esper.client; using Gradual.OMS.ConectorSTM.Eventos; using log4net; using System.Threading; namespace Gradual.OMS.ConectorSTM { public class ProcessadorMensagens: StatementAwareUpdateListener { private static readonly ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private Queue<EventoSTM> queue; private Semaphore queueSem; private bool _bKeepRunning = false; private ParserCBLCMessage parserCBLC = new ParserCBLCMessage(); private ParserMegaMessage parserMega = new ParserMegaMessage(); private Thread _me; public ProcessadorMensagens() { queue = new Queue<EventoSTM>(); queueSem = new Semaphore(1, short.MaxValue); } public void Start() { _bKeepRunning = true; _me = new Thread(new ThreadStart(Run)); _me.Start(); } public void Stop() { _bKeepRunning = false; while (_me != null && _me.IsAlive) { Thread.Sleep(250); } } /// <summary> /// Thread de processamento das mensagen /// </summary> public void Run() { logger.Info("Iniciando thread de tratamento das mensagens do STM"); prepareNesper(); int qtdeFila = 0; while (_bKeepRunning) { try { queueSem.WaitOne(250); lock (queue) { qtdeFila = queue.Count; } for (int i = 0; i < qtdeFila; i++) { EventoSTM evento; lock (queue) { evento = queue.Dequeue(); } switch (evento.Tipo) { case EventoSTM.TIPO_MSG_CBLC: parserCBLC.Parse(evento); break; case EventoSTM.TIPO_MSG_MEGA: parserMega.Parse(evento); break; default: logger.Error("Tipo de mensagem nao esperado [" + evento.Tipo + "]"); break; } } } catch (Exception ex) { logger.Error("Run() Error: " + ex.Message, ex); } } } /// <summary> /// Handler dos eventos do Nesper /// </summary> /// <param name="newEvents"></param> /// <param name="oldEvents"></param> /// <param name="statement"></param> /// <param name="epServiceProvider"></param> public void Update(EventBean[] newEvents, EventBean[] oldEvents, EPStatement statement, EPServiceProvider epServiceProvider) { foreach (EventBean evento in newEvents) { lock (queue) { queue.Enqueue((EventoSTM)evento.Underlying); } } queueSem.Release(); logger.Info("Update(): mensagens na fila: " + queue.Count); } /// <summary> /// prepara esta classe para receber os eventos do Nesper /// </summary> private void prepareNesper() { String consultaEsper = "select * from EventoSTM"; EPStatement comandoEsper = ServicoConectorSTM.epService.EPAdministrator.CreateEPL(consultaEsper); comandoEsper.AddListener(this); } } }
2e0cc5045248f5c45f3d820af8f767143414f75f
C#
matthewd673/FrogGame
/FrogGame/PhysicsEntity.cs
2.796875
3
using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace FrogGame { public class PhysicsEntity : Entity { public float mass = 1; public Acceleration a = new Acceleration(0, 0); public Velocity v = new Velocity(0, 0); public float frictionCoefficient = 0.15f; public PhysicsEntity(Texture2D sprite, float x, float y, int width, int height) : base(sprite, x, y, width, height) { } public void AddForce(float force, float angle) { float forceX = (float)Math.Sin(angle) * (force / mass); float forceY = (float)Math.Cos(angle) * (force / mass); a.aX += forceX; a.aY += forceY; } void ApplyFriction() { float aXMag = Math.Abs(a.aX); float aYMag = Math.Abs(a.aY); if (GetStrengthOfMotion() > 0.1f) AddForce(mass * frictionCoefficient, GetAngleOfMotion() + (float)(Math.PI)); } public float GetAngleOfMotion() { return GameMath.GetAngleBetweenPoints(x, y, x + v.vX, y + v.vY); } public float GetStrengthOfMotion() { return (float) Math.Sqrt(Math.Pow(v.vX, 2) + Math.Pow(v.vY, 2)); } public float GetAngleOfAcceleration() { return GameMath.GetAngleBetweenPoints(x, y, x + a.aX, y + a.aY); } public float GetStrengthOfAcceleration() { return (float)Math.Sqrt(Math.Pow(a.aX, 2) + Math.Pow(a.aY, 2)); } public override void Update() { if (!Game.velocityFrozen) { ApplyFriction(); v.vX += a.aX; v.vY += a.aY; Translate(new Vector2(x, y), new Vector2(x + v.vX, y + v.vY)); //reset acceleration a = new Acceleration(0, 0); //prevent drifting if (GetStrengthOfMotion() < 0.1f) v = new Velocity(0, 0); } base.Update(); } public void Translate(Vector2 currentPos, Vector2 newPos) { List<Entity> newPosCollides = CollisionSolver.GetAllPotentiallyColliding(newPos.X, newPos.Y, width, height, onlyWalls: true); if (newPosCollides.Count > 0) { //it has hit one wall (or more) Bounce(newPosCollides[0]); } else { x = newPos.X; y = newPos.Y; } } public void Bounce(Entity col) { float movementAngle = GameMath.GetAngleBetweenPoints(x, y, v.vX, v.vY); if (Math.Abs((x + 4) - (col.x + (col.width / 2))) >= Math.Abs((y + 4) - (col.y + (col.height / 2)))) //predominantly horizontal v.vX = -v.vX; else //predominantly vertical v.vY = -v.vY; } } }
98ecb119e54598171082b1c6a214df33f90f5265
C#
vladomelchenko/AngleSharp.Js
/src/AngleSharp.Js/Extensions/ReflectionExtensions.cs
2.546875
3
namespace AngleSharp.Js { using AngleSharp.Attributes; using AngleSharp.Text; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; static class ReflectionExtensions { public static String[] GetParameterNames(this MethodInfo method) => method?.GetParameters().Select(m => m.Name).ToArray(); public static Assembly GetAssembly(this Type type) => type.GetTypeInfo().Assembly; public static Object GetDefaultValue(this Type type) => type.GetTypeInfo().IsValueType ? Activator.CreateInstance(type) : null; public static IEnumerable<Type> GetExtensionTypes(this IEnumerable<Assembly> libs, String name) => libs .SelectMany(m => m.ExportedTypes) .Where(m => m.GetTypeInfo().GetCustomAttributes<DomExposedAttribute>().Any(n => n.Target.Is(name))) .ToArray(); public static IEnumerable<Type> GetTypeTree(this Type root) { var type = root; var types = new List<Type>(type.GetTypeInfo().ImplementedInterfaces); do { types.Add(type); type = type.GetTypeInfo().BaseType; } while (type != null); return types; } public static MethodInfo PrepareConvert(this Type fromType, Type toType) { try { // Throws an exception if there is no conversion from fromType to toType var exp = Expression.Convert(Expression.Parameter(fromType, null), toType); return exp.Method; } catch { return null; } } public static String GetOfficialName(this MemberInfo member) { var names = member.GetCustomAttributes<DomNameAttribute>(); var officalNameAttribute = names.FirstOrDefault(); return officalNameAttribute?.OfficialName ?? member.Name; } public static String GetOfficialName(this Type currentType, Type baseType) { var ti = currentType.GetTypeInfo(); var name = ti.GetCustomAttribute<DomNameAttribute>(true)?.OfficialName; if (name == null) { var interfaces = ti.ImplementedInterfaces; if (baseType != null) { var bi = baseType.GetTypeInfo(); var exclude = bi.ImplementedInterfaces; interfaces = interfaces.Except(exclude); } foreach (var impl in interfaces) { name = impl.GetTypeInfo().GetCustomAttribute<DomNameAttribute>(false)?.OfficialName; if (name != null) break; } } return name; } public static PropertyInfo GetInheritedProperty(this Type type, String propertyName, BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.Instance) { if (type.GetTypeInfo().IsInterface) { return type.GetInterfaces() .Union(new[] { type }) .Select(i => i.GetProperty(propertyName, bindingAttr)) .Where(propertyInfo => propertyInfo != null) .FirstOrDefault(); } return type.GetProperty(propertyName, bindingAttr); } public static IEnumerable<PropertyInfo> GetInheritedProperties(this Type type, BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.Instance) { if (type.GetTypeInfo().IsInterface) { return type.GetInterfaces() .Union(new[] { type }) .SelectMany(i => i.GetProperties(bindingAttr)) .Distinct(); } return type.GetProperties(bindingAttr); } } }
0175a51be48be8e9f1ceeaed64e1a460be9d7b6f
C#
pmdevers/iRacingOverlay
/src/iRacingSDK/DataFeed/Telementry/CarSectorIdx.cs
2.515625
3
using System; using System.Collections.Generic; using System.Text; namespace iRacingSDK { public partial class Telemetry : Dictionary<string, object> { LapSector[] carSectorIdx; public LapSector[] CarSectorIdx //0 -> Start/Finish, 1 -> 33%, 2-> 66% { get { if (carSectorIdx != null) return carSectorIdx; carSectorIdx = new LapSector[64]; for (int i = 0; i < 64; i++) carSectorIdx[i] = new LapSector(this.CarIdxLap[i], ToSectorFromPercentage(CarIdxLapDistPct[i])); return carSectorIdx; } } static int ToSectorFromPercentage(float percentage) { if (percentage > 0.66) return 2; else if (percentage > 0.33) return 1; return 0; } } }
7d52cbaa0886b04200fbd01ad101f3f61b9bc49d
C#
thundernova/niceshot888.github.com
/NiceShot/NiceShot.Core/Helper/JsonHelper.cs
2.84375
3
//using System.IO; //using System.Runtime.Serialization; //using System.Runtime.Serialization.Json; //using System.Text; //namespace NiceShot.Core.Helper //{ // public class JsonHelper // { // public static string JsonSerializer<T>(T t) // { // string jsonString; // using (var ms = new MemoryStream()) // { // var ser = new DataContractJsonSerializer(typeof(T)); // ser.WriteObject(ms, t); // jsonString = Encoding.UTF8.GetString(ms.ToArray()); // } // return jsonString; // } // public static T JsonDeserialize<T>(string jsonString) // { // try // { // var dser = new DataContractJsonSerializer(typeof(T)); // using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString))) // { // var obj = (T)dser.ReadObject(ms); // return obj; // } // } // catch (SerializationException ex) // { // return default(T); // } // } // } //}
6cabade8d79eca859deb97919876e787ce19e955
C#
macrobela/SP726
/ConsoleApplication29/ConsoleApplication29/Program.cs
2.828125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication29 { class Program { static void Main(string[] args) { int[] dizi2 = { 1, 2, 3, 4, 5, 6 }; foreach (int a in dizi2) { Console.WriteLine(a); } char[] cDizi = { 'a', 'f', 'a', 'd' }; Console.ReadLine(); } } }
d03138b08dbe01d2993c7e3f45216bfcaa8101bc
C#
mavrovski/SoftUni
/Programing Fundametals September2017/Arrays - Lab/04TripleSum.cs
4
4
using System; using System.Linq; namespace _04TripleSum { public class _04TripleSum { public static void Main(string[] args) { long[] numbers = Console.ReadLine().Split(' ') .Select(long.Parse) .ToArray(); bool match = false; for (int a = 0; a < numbers.Length; a++) { for (int b = a+1; b < numbers.Length; b++) { long sum = numbers[a] + numbers[b]; if (numbers.Contains(sum)) { Console.WriteLine($"{numbers[a]} + {numbers[b]} == {sum}"); match = true; } } } if (!match) { Console.WriteLine("No"); } } } }
2c279659127ad8f0ffd618f603421f107c13c31f
C#
Vitormdias/csharp-design-patterns
/Estudo/DesignPatterns/CalculadorDeImpostos.cs
2.65625
3
using System; namespace CursoDesignPatterns.StrategyPattern { public class CalculadorDeImpostos { public void RealizaCalculo(Orcamento orcamento, IImposto imposto) { double result = imposto.Calcula(orcamento); Console.WriteLine(result); } } }
27eab323380da4d3654059c1fb54a9e11655195f
C#
Magdalen36/RPG
/RPG/Equipements/Armure.cs
2.703125
3
using RPG.Interfaces; using System; using System.Collections.Generic; using System.Text; namespace RPG.Equipements { public class Armure : Equipement { public int ProtectionArmure { get; set; } public Armure() { } public Armure(string n, int cuir, int fer, int or, int protect, int rare) { Nom = n; Cuir = cuir; Fer = fer; Or = or; ProtectionArmure = protect; Rarete = rare; } public override string ToString() { return Nom + $" (P + {ProtectionArmure})"; } } }
d22659b588771229fb0a5de79a55d2771b56b0a9
C#
vchirilov/USM
/Documents/C09-ASP.NET MVC/C02-Controllers/C01.BaseController.cs
2.5625
3
/**************************************************************************** Every request that comes to your application is handled by a controller. Controllers are responsible for processing incoming requests, performing operations on the domain model, and selecting views to render to the user. *****************************************************************************/ //The simplest MVC controller would be a class that implements interface IController using System.Web.Mvc; using System.Web.Routing; namespace USM.Controllers { public class BasicController : IController { public void Execute(RequestContext requestContext) { string controller = (string)requestContext.RouteData.Values["controller"]; string action = (string)requestContext.RouteData.Values["action"]; requestContext.HttpContext.Response.Write(string.Format("Controller: {0}, Action: {1}", controller, action)); } } }
2f5ce3bb826950ea7cf105a9c57d1662815c00f8
C#
QuinntyneBrown/ngrx-getting-started
/NgrxGettingStarted/Services/DoctorService.cs
2.671875
3
using System; using System.Collections.Generic; using NgrxGettingStarted.Dtos; using NgrxGettingStarted.Data; using System.Linq; namespace NgrxGettingStarted.Services { public class DoctorService : IDoctorService { public DoctorService(IUow uow, ICacheProvider cacheProvider) { _uow = uow; _repository = uow.Doctors; _cache = cacheProvider.GetCache(); } public DoctorAddOrUpdateResponseDto AddOrUpdate(DoctorAddOrUpdateRequestDto request) { var entity = _repository.GetAll() .FirstOrDefault(x => x.Id == request.Id && x.IsDeleted == false); if (entity == null) _repository.Add(entity = new Models.Doctor()); entity.Name = request.Name; _uow.SaveChanges(); return new DoctorAddOrUpdateResponseDto(entity); } public ICollection<DoctorDto> Get() { ICollection<DoctorDto> response = new HashSet<DoctorDto>(); var entities = _repository.GetAll().Where(x => x.IsDeleted == false).ToList(); foreach (var entity in entities) { response.Add(new DoctorDto(entity)); } return response; } public DoctorDto GetById(int id) { return new DoctorDto(_repository.GetAll().Where(x => x.Id == id && x.IsDeleted == false).FirstOrDefault()); } public dynamic Remove(int id) { var entity = _repository.GetById(id); entity.IsDeleted = true; _uow.SaveChanges(); return id; } protected readonly IUow _uow; protected readonly IRepository<Models.Doctor> _repository; protected readonly ICache _cache; } }
2246034446b184d1f9f51a9489f86958734a1ba6
C#
garnhold/CrunchyBox
/CrunchyDough/Extensions/Float/FloatExtensions_Angle_CardinalOrdinalDirection.cs
2.84375
3
using System; namespace Crunchy.Dough { static public class FloatExtensions_Angle_CardinalOrdinalDirection { static public CardinalOrdinalDirection GetAngleClosestCardinalOrdinalDirection(this float item, float period) { float sixteenth = period / 16.0f; item = item.GetLooped(period); if (item < sixteenth) return CardinalOrdinalDirection.Right; if (item < sixteenth * 3.0f) return CardinalOrdinalDirection.RightUp; if (item < sixteenth * 5.0f) return CardinalOrdinalDirection.Up; if (item < sixteenth * 7.0f) return CardinalOrdinalDirection.LeftUp; if (item < sixteenth * 9.0f) return CardinalOrdinalDirection.Left; if (item < sixteenth * 11.0f) return CardinalOrdinalDirection.LeftDown; if (item < sixteenth * 13.0f) return CardinalOrdinalDirection.Down; if (item < sixteenth * 15.0f) return CardinalOrdinalDirection.RightDown; return CardinalOrdinalDirection.Right; } static public CardinalOrdinalDirection GetRadianAngleClosestCardinalOrdinalDirection(this float item) { return item.GetAngleClosestCardinalOrdinalDirection(Mathq.FULL_REVOLUTION_RADIANS); } static public CardinalOrdinalDirection GetDegreeAngleClosestCardinalOrdinalDirection(this float item) { return item.GetAngleClosestCardinalOrdinalDirection(Mathq.FULL_REVOLUTION_DEGREES); } static public CardinalOrdinalDirection GetPercentAngleClosestCardinalOrdinalDirection(this float item) { return item.GetAngleClosestCardinalOrdinalDirection(Mathq.FULL_REVOLUTION_PERCENT); } } }
cc76525fb80797e5f9003d59fa56f6d7cc998124
C#
raspbe2ry/Atomac
/Atomac/Atomac.EFDataLayer/DTO/DTOMove.cs
2.5625
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using AutoMapper; using Atomac.EFDataLayer.Models; namespace Atomac.EFDataLayer.DTO { [Serializable] public class DTOMove { private ApplicationDbContext db = new ApplicationDbContext(); public int Id { get; set; } public Board Board { get; set; } public string Color { get; set; } //koja boja je odigrala potez public string From { get; set; } public string To { get; set; } public string Piece { get; set; } public string Captured { get; set; } //ako je figura uzeta, koja je public string State { get; set; } //fen string sa stanjem public IEnumerable<string> White { get; set; } //koje figure beli ima u rezervi public IEnumerable<string> Black { get; set; } //koje figure crni ima u rezervi public int GameId { get; set; } public DTOMove GetById(int id) { var move = db.Moves.Find(id); return Mapper.Map<DTOMove>(move); } } }
cba38e88ba60ae1acc07c8e26d25b4a510be24cd
C#
disulfiram/CSharpPart1
/6. Loops mk2/6. N! ; X^N/Program.cs
3.671875
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Numerics; class Program { static void Main() { Console.Title = "N!/K^N"; int N; int K; while (true) { Console.Write("N = "); string Value = Console.ReadLine(); bool ResultN = int.TryParse(Value, out N); Console.Write("K = "); Value = Console.ReadLine(); bool ResultK = int.TryParse(Value, out K); if ((ResultN == true) && (ResultK == true)) { break; } else { Console.WriteLine("Invalid numbers. Try again:"); } } double S = 1; double Numerator = 1; double Denominator = 1; for (int i = 1; i <= N; i++) { Numerator *= i; Denominator = Math.Pow(K, i); S += Numerator / Denominator; } Console.WriteLine("N!/K^N = {0}", S); } }
4ca179a6aa252c1d6e2e1a5796afc136b730e0d0
C#
yapi-net/YandexDirect
/Yandex.Direct/Connectivity/JsonYandexApiClient.cs
2.5625
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using Yandex.Direct.Authentication; using Yandex.Direct.Configuration; using Yandex.Direct.Serialization; namespace Yandex.Direct.Connectivity { public class JsonYandexApiClient : IYandexApiClient { public IYandexApiConfiguration Configuration { get; private set; } private readonly JsonYandexApiSerializer _serializer; public JsonYandexApiClient(IYandexApiConfiguration configuration) { if (configuration == null) throw new ArgumentNullException("configuration"); _serializer = new JsonYandexApiSerializer(); Configuration = configuration; } public T Invoke<T>(string method, object param = null, bool financeTokenRequired = false) { if (string.IsNullOrEmpty(method)) throw new ArgumentNullException("method"); // Creating http-request var authProvider = Configuration.AuthProvider; var requestMessage = CreateRequestMessage(method, param, authProvider, financeTokenRequired); var request = CreateRequest(requestMessage, authProvider); // Invoking the request to server string responseMessage; try { using (WebResponse response = request.GetResponse()) { responseMessage = GetResponseMessage(response); } } catch (Exception ex) { throw new YandexConnectionException("Unable to perform http-request to Yandex API endpoint.", ex); } // Retrieving response var responseObject = _serializer.Deserialize<JsonResponseObject<T>>(responseMessage); if (responseObject == null) throw new YandexConnectionException("Not supported server response."); if (responseObject.ErrorCode != YandexApiErrorCode.None) throw new YandexDirectException(responseObject.ErrorCode, responseObject.ErrorMessage); return responseObject.Object; } private string CreateRequestMessage(string method, object param, IYandexApiAuthProvider authProvider, bool financeTokenRequired) { // Creating request message Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters["method"] = method; parameters["param"] = param; parameters["locale"] = Configuration.Language; // Adding authentication information into the request message if (authProvider != null) authProvider.OnRequestMessage(this, method, parameters, financeTokenRequired); return SerializeRequestMessage(parameters); } private HttpWebRequest CreateRequest(string requestMessage, IYandexApiAuthProvider authProvider) { var request = (HttpWebRequest)WebRequest.Create(Configuration.ServiceUrl); // Adding authentication information into the http-request if (authProvider != null) authProvider.OnHttpRequest(this, request); // Configuring request request.Method = "POST"; request.ContentType = "application/json; charset=utf-8"; var data = Encoding.UTF8.GetBytes(requestMessage); request.ContentLength = data.Length; using (var requestStream = request.GetRequestStream()) { requestStream.Write(data, 0, data.Length); } return request; } private static string GetResponseMessage(WebResponse response) { using (Stream stream = response.GetResponseStream()) { using (StreamReader responseStream = new StreamReader(stream)) { return responseStream.ReadToEnd(); } } } private string SerializeRequestMessage(Dictionary<string, object> messageParams) { var serializedParams = messageParams.Where(param => param.Value != null).Select(param => { string serializedValue = _serializer.Serialize(param.Value); return string.Format("\"{0}\": {1}", param.Key, serializedValue); }); return string.Format("{{{0}}}", string.Join(", ", serializedParams)); } } }
64dde7eba187d13ad4e50801055ad3550b717393
C#
tobbissimo/Klinik_WPF
/KlinikApp/ViewModel/VMPatientEdit.cs
2.6875
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KlinikApp.ViewModel { class VMPatientEdit : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public bool IstInEditMode { get; set; } public Patient P { get; set; } public int NrOfExams { get { return P.Examinations.Count(); } } public String HeaderText { get { if (IstInEditMode) { return "Edit Patient"; } return "New Patient"; } } public IEnumerable<Bundesland> AllBundeslands { get { using (KlinikDbEntities db = new KlinikDbEntities()) { var erg = from b in db.Bundeslands select b; return erg.ToList(); } } } public String NrOfOps() { return P.Examinations.Count().ToString(); } } }
a2e9e90267694e3874753e6b2b2f83ab9f8248f3
C#
Group-Pug/Loverwatch
/Assets/Scripts/BaseClasses/Hero.cs
2.765625
3
public class Hero : Character { private string fullName; private float relationship; //relationship meter towards player (0-9) public string GetFullName () { return fullName; } public void SetFullName (string val) { fullName = val; } public float GetRelationShipStatus () { return relationship; } public void ModRelationship (float val) { relationship += val; } }
50123f935de6fee2f13ce10097205bef330ed915
C#
szymonklo/Industry-WPF
/ModelLibrary1/Models/Facility.cs
3.25
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ModelLibrary.Models { public abstract class Facility { protected string _name; public string Name { get { return _name; } set { _name = value; } } public abstract int Id { get; set; } public List<Product> Products { get; set; } = new List<Product>(); public abstract int FacilityType { get; protected set; } public static List<Facility> Facilities = new List<Facility>(); public Facility() { //SetType(); } //DONE - zmienić i nie odwoływać się do klas dziedziczących z Facility //public void SetType() //{ // if (this is Factory) // FacilityType = 1; // else if (this is City) // FacilityType = 2; // else // FacilityType = 0; //} public static Facility GetFacility(int type, int id) { if (type == 1) return Factory.Factories.Where(x => x.Id == id).First(); else if (type == 2) return City.Cities.Where(x => x.Id == id).First(); else return null; } } }
3dc4e000a4cba7c625027a40c6bc5f28b66db346
C#
lithnet/ssh-managementagent
/src/Lithnet.SshMA/Rules/RuleKeyedCollection.cs
2.515625
3
// ----------------------------------------------------------------------- // <copyright file="RuleKeyedCollection.cs" company="Lithnet"> // The Microsoft Public License (Ms-PL) governs use of the accompanying software. // If you use the software, you accept this license. // If you do not accept the license, do not use the software. // http://go.microsoft.com/fwlink/?LinkID=131993 // </copyright> // ----------------------------------------------------------------------- namespace Lithnet.SshMA { using System.Collections.ObjectModel; /// <summary> /// A keyed collection of IEvaluableRuleObject objects /// </summary> public class RuleKeyedCollection : KeyedCollection<string, IEvaluableRuleObject> { /// <summary> /// Initializes a new instance of the RuleKeyedCollection class /// </summary> public RuleKeyedCollection() : base() { } /// <summary> /// Extracts the key from the specified element /// </summary> /// <param name="item">The element from which to extract the key</param> /// <returns>The key for the specified element</returns> protected override string GetKeyForItem(IEvaluableRuleObject item) { return item.Id; } } }
1bcb7edf4b1ad16c2139f8a0aa7e068981ceeeb9
C#
woodfor/IA-Project
/IAproject/Controllers/HomeController.cs
2.765625
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using IAproject.Models; namespace IAproject.Controllers { public class HomeController : Controller { public ActionResult Index([Bind(Include = "Age,PersonalGender,Height,Weight,Activity,CalResult")] Calculation cal) { IList<string> calorie = new List<string>(); double BMR=0; double rate = 1.2; double exercise = 0.17; if (!(cal.Age == 0) && !(cal.Height == 0) && !(cal.Height == 0)) { if (cal.PersonalGender == Gender.Male) { BMR = 10 * cal.Weight + 6.25 * cal.Height - 5 * cal.Age + 5; } else if (cal.PersonalGender == Gender.Female) { BMR = 10 * cal.Weight + 6.25 * cal.Height - 5 * cal.Age - 161; } if (cal.Activity == Activity.BMR) // Show the calculation result. { calorie.Add("you need" + BMR + "Calories/day to maintain your weight."); calorie.Add("you need" + (BMR - 500) + "Calories/day to lose 0.5 kg per week."); calorie.Add("you need" + (BMR - 1000) + "Calories/day to lose 1 kg per week."); calorie.Add("you need" + (BMR + 500) + "Calories/day to gain 0.5 kg per week."); calorie.Add("you need" + (BMR + 1000) + "Calories/day to gain 1 kg per week."); } if (cal.Activity == Activity.Sedentary) { double tmp = BMR * rate; calorie.Add("you need" + tmp + "Calories/day to maintain your weight."); calorie.Add("you need" + (tmp - 500) + "Calories/day to lose 0.5 kg per week."); calorie.Add("you need" + (tmp - 1000) + "Calories/day to lose 1 kg per week."); calorie.Add("you need" + (tmp + 500) + "Calories/day to gain 0.5 kg per week."); calorie.Add("you need" + (tmp + 1000) + "Calories/day to gain 1 kg per week."); } if (cal.Activity == Activity.Lightly) { double tmp = BMR * (rate + exercise); calorie.Add("you need" + tmp + "Calories/day to maintain your weight."); calorie.Add("you need" + (tmp - 500) + "Calories/day to lose 0.5 kg per week."); calorie.Add("you need" + (tmp - 1000) + "Calories/day to lose 1 kg per week."); calorie.Add("you need" + (tmp + 500) + "Calories/day to gain 0.5 kg per week."); calorie.Add("you need" + (tmp + 1000) + "Calories/day to gain 1 kg per week."); } if (cal.Activity == Activity.Moderately) { double tmp = BMR * (rate + exercise * 2); calorie.Add("you need" + tmp + "Calories/day to maintain your weight."); calorie.Add("you need" + (tmp - 500) + "Calories/day to lose 0.5 kg per week."); calorie.Add("you need" + (tmp - 1000) + "Calories/day to lose 1 kg per week."); calorie.Add("you need" + (tmp + 500) + "Calories/day to gain 0.5 kg per week."); calorie.Add("you need" + (tmp + 1000) + "Calories/day to gain 1 kg per week."); } if (cal.Activity == Activity.Very_Active) { double tmp = BMR * (rate + exercise * 3); calorie.Add("you need" + tmp + "Calories/day to maintain your weight."); calorie.Add("you need" + (tmp - 500) + "Calories/day to lose 0.5 kg per week."); calorie.Add("you need" + (tmp - 1000) + "Calories/day to lose 1 kg per week."); calorie.Add("you need" + (tmp + 500) + "Calories/day to gain 0.5 kg per week."); calorie.Add("you need" + (tmp + 1000) + "Calories/day to gain 1 kg per week."); } if (cal.Activity == Activity.Extra_Active) { double tmp = BMR * (rate + exercise * 4); calorie.Add("you need" + tmp + "Calories/day to maintain your weight."); calorie.Add("you need" + (tmp - 500) + "Calories/day to lose 0.5 kg per week."); calorie.Add("you need" + (tmp - 1000) + "Calories/day to lose 1 kg per week."); calorie.Add("you need" + (tmp + 500) + "Calories/day to gain 0.5 kg per week."); calorie.Add("you need" + (tmp + 1000) + "Calories/day to gain 1 kg per week."); } } else { } ViewData["Calculation"] = calorie; return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }
85e38ee43eb8bb693735c2815134cc32f4e61ad3
C#
LvJinliang1216/FolkLibrary
/trunk/FolkLibrary.Application/LeaveWordService.cs
2.546875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using AutoMapper; using FolkLibrary.Application.Interface; using FolkLibrary.DataTransferObject; using FolkLibrary.DataTransferObject.QueryModels; using FolkLibrary.Domain.Entities; using FolkLibrary.Infrastructure.Interface; using FolkLibrary.Repository.Interface.IRepository; namespace FolkLibrary.Application { public class LeaveWordService : ILeaveWordService { private readonly IUnitOfWork _unitOfWork; private readonly ILeaveWordRepository _leaveWordRepository; private readonly IMapper _mapper; public LeaveWordService(IUnitOfWork unitOfWork, ILeaveWordRepository leaveWordRepository, IMapper mapper) { this._unitOfWork = unitOfWork; this._leaveWordRepository = leaveWordRepository; this._mapper = mapper; } /// <summary> /// 添加留言 /// </summary> /// <param name="leaveWord"></param> /// <returns></returns> public async Task<bool> Save(LeaveWordView leaveWord) { var entity = _mapper.Map<LeaveWordEntity>(leaveWord); _unitOfWork.BeginTransaction(); await _unitOfWork.RegisterNew(entity); bool flag = await _unitOfWork.CommitAsync(); return flag; } /// <summary> /// 获取全部留言信息 /// </summary> /// <returns></returns> public async Task<IList<LeaveWordView>> GetAll() { var entityList = _leaveWordRepository.GetAll(); return _mapper.Map<IList<LeaveWordView>>(entityList).ToList(); } /// <summary> /// 分页获取留言信息 /// </summary> /// <param name="pageSize"></param> /// <param name="total"></param> /// <param name="leaveWordQueryView"></param> /// <param name="pageIndex"></param> /// <returns></returns> public IList<LeaveWordView> SearchLeaveWord(LeaveWordQueryView leaveWordQueryView, int pageIndex, int pageSize, out int total) { var tempData = _leaveWordRepository.GetAll(); if (leaveWordQueryView.StarTime.HasValue) { tempData = tempData.Where(x => x.CreateDateTime >= leaveWordQueryView.StarTime); } if (leaveWordQueryView.EndTime.HasValue) { tempData = tempData.Where(x => x.CreateDateTime <= leaveWordQueryView.EndTime); } total = tempData.Count(); var dataList = tempData.OrderBy(x => x.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize); return _mapper.Map<List<LeaveWordView>>(dataList); } /// <summary> /// 删除留言信息 /// </summary> /// <param name="leaveWordId"></param> /// <returns></returns> public async Task<bool> DeleteLeaveWord(string leaveWordId) { var entity = _leaveWordRepository.Get(Convert.ToInt32(leaveWordId)).FirstOrDefault(); if (entity != null) { _unitOfWork.BeginTransaction(); await _unitOfWork.RegisterDeleted(entity); bool flag = await _unitOfWork.CommitAsync(); return flag; } else { return false; } } } }
12426159d098eee1ab7ca002de7d21b852cbec2f
C#
shendongnian/download4
/code6/1142667-30114833-89976234-2.cs
3.4375
3
public static bool EmptyFolderTransactionaly(string folder) { var directoryInfo = new DirectoryInfo(folder); var tmpDir = Directory.CreateDirectory(Path.Combine(folder, Path.GetTempFileName())); try { foreach (var e in directoryInfo.EnumerateFiles(folder)) { e.MoveTo(tmpDir.FullName); } foreach (var e in directoryInfo.EnumerateDirectories(folder)) { e.MoveTo(tmpDir.FullName); } return true; } catch { foreach (var e in tmpDir.EnumerateDirectories()) { e.MoveTo(directoryInfo.FullName); } foreach (var e in tmpDir.EnumerateFiles()) { e.MoveTo(directoryInfo.FullName); } MessageBox.Show("Failed to remove files. Manually empty the folder and try again.", "Error"); return false; } finally { tmpDir.Delete(true); } }
34be5571732ee175746e3027065166d697e25c17
C#
zoe-nk/Terrain
/Test/Visualiser/Containers/SystemConfiguration.cs
2.546875
3
using System.Reflection; using System.Windows.Forms; namespace Visualiser.Containers { public class SystemConfiguration { public string Title { get; set; } public Dimension Size { get; set; } public static bool FullScreen { get; private set; } public static bool VerticalSyncEnabled { get; private set; } public static float ScreenDepth { get; private set; } public static float ScreenNear { get; private set; } public static FormBorderStyle BorderStyle { get; set; } public static string ShaderFilepath { get; private set; } public static string DataFilePath { get; private set; } public static string ObjectFilePath { get; private set; } public SystemConfiguration(WindowConfiguration windowConfiguration) { ScreenDepth = 1000.0f; ScreenNear = 0.1f; BorderStyle = FormBorderStyle.None; ShaderFilepath = @"C:\Code\Git\Database\dbCore\DB Structure\Visualiser\Shaders\"; DataFilePath = @"C:\Code\Git\Database\dbCore\DB Structure\Visualiser\Data\"; ObjectFilePath = @"C:\Code\Git\Database\dbCore\DB Structure\Visualiser\Models\"; FullScreen = windowConfiguration.FullScreen; Title = windowConfiguration.Title; VerticalSyncEnabled = windowConfiguration.VerticalSync; Size = new Dimension() { Width = FullScreen ? Screen.PrimaryScreen.Bounds.Width : windowConfiguration.Size.Width, Height = FullScreen ? Screen.PrimaryScreen.Bounds.Height : windowConfiguration.Size.Height }; } } }
10ec09b97d2a977a7dfa84368101dc4fb14fbbd1
C#
tfwcn/CnnDemo
/CnnDemo/CNN/Cnn.cs
2.859375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CnnDemo.CNN { [Serializable] public class Cnn { /// <summary> /// 卷积层+池化层 /// </summary> public List<CnnConvolutionLayer> CnnConvolutionLayerList { get; set; } /// <summary> /// 全链接层 /// </summary> public List<CnnFullLayer> CnnFullLayerList { get; set; } /// <summary> /// 卷积层间连接,参数:当前层,上一层 /// </summary> private List<bool[,]> convolutionLinkList; public Cnn() { CnnConvolutionLayerList = new List<CnnConvolutionLayer>(); CnnFullLayerList = new List<CnnFullLayer>(); convolutionLinkList = new List<bool[,]>(); } /// <summary> /// 增加首个卷积层 /// </summary> /// <param name="cnnConvolutionLayer"></param> public void AddCnnConvolutionLayer(int convolutionKernelCount, int inputWidth, int inputHeight, int receptiveFieldWidth, int receptiveFieldHeight, int offsetWidth, int offsetHeight, CnnNode.ActivationFunctionTypes activationFunctionType, int poolingReceptiveFieldWidth, int poolingReceptiveFieldHeight, CnnPooling.PoolingTypes poolingType, bool standardization) { CnnConvolutionLayer cnnConvolutionLayer = new CnnConvolutionLayer(); //创建卷积层 cnnConvolutionLayer.CreateCnnKernel(convolutionKernelCount, inputWidth, inputHeight, receptiveFieldWidth, receptiveFieldHeight, offsetWidth, offsetHeight, activationFunctionType, 1, standardization, null); if (poolingType != 0) { //创建池化层 cnnConvolutionLayer.CreateCnnPooling(poolingReceptiveFieldWidth, poolingReceptiveFieldHeight, activationFunctionType, poolingType); } CnnConvolutionLayerList.Add(cnnConvolutionLayer); } /// <summary> /// 增加后续卷积层 /// </summary> /// <param name="cnnConvolutionLayer"></param> public void AddCnnConvolutionLayer(int convolutionKernelCount, int receptiveFieldWidth, int receptiveFieldHeight, int offsetWidth, int offsetHeight, CnnNode.ActivationFunctionTypes activationFunctionType, int poolingReceptiveFieldWidth, int poolingReceptiveFieldHeight, CnnPooling.PoolingTypes poolingType, bool standardization, bool isFullLayerLinks) { var cnnConvolutionLayerLast = CnnConvolutionLayerList[CnnConvolutionLayerList.Count - 1];//最后的卷积层 bool[,] layerLinks = new bool[convolutionKernelCount, cnnConvolutionLayerLast.ConvolutionKernelCount]; if (!isFullLayerLinks) { //随机创建卷积层间连接 Random random = new Random(); for (int i = 0; i < convolutionKernelCount; i++) { int linkCount = 0;//每层链接数 while (linkCount < 2)//确保最低链接数 { for (int j = 0; j < cnnConvolutionLayerLast.ConvolutionKernelCount; j++) { if (random.NextDouble() < 0.5) layerLinks[i, j] = false; else { layerLinks[i, j] = true; linkCount++; } } } //排除相同链接 for (int j = 0; j < i; j++) { linkCount = 0;//相同链接数 for (int k = 0; k < cnnConvolutionLayerLast.ConvolutionKernelCount; k++) { if (layerLinks[i, k] == layerLinks[j, k]) linkCount++; } if (linkCount == cnnConvolutionLayerLast.ConvolutionKernelCount) { i--; break; } } } } else { //全链接 for (int i = 0; i < convolutionKernelCount; i++) { for (int j = 0; j < cnnConvolutionLayerLast.ConvolutionKernelCount; j++) { layerLinks[i, j] = true; } } } convolutionLinkList.Add(layerLinks); CnnConvolutionLayer cnnConvolutionLayer = new CnnConvolutionLayer(); //创建卷积层 cnnConvolutionLayer.CreateCnnKernel(convolutionKernelCount, cnnConvolutionLayerLast.OutputWidth, cnnConvolutionLayerLast.OutputHeight, receptiveFieldWidth, receptiveFieldHeight, offsetWidth, offsetHeight, activationFunctionType, cnnConvolutionLayerLast.ConvolutionKernelCount, standardization, layerLinks); if (poolingType != 0) { //创建池化层 cnnConvolutionLayer.CreateCnnPooling(poolingReceptiveFieldWidth, poolingReceptiveFieldHeight, activationFunctionType, poolingType); } CnnConvolutionLayerList.Add(cnnConvolutionLayer); } /// <summary> /// 增加全连接层,在卷积层后,要先创建完卷积层 /// </summary> /// <param name="cnnFullLayer"></param> public void AddCnnFullLayer(int outputCount, CnnNode.ActivationFunctionTypes activationFunctionType, bool standardization) { if (CnnFullLayerList.Count == 0) { //连接卷积层 var cnnConvolutionLayerLast = CnnConvolutionLayerList[CnnConvolutionLayerList.Count - 1];//最后的卷积层 CnnFullLayer cnnFullLayer = new CnnFullLayer(cnnConvolutionLayerLast.ConvolutionKernelCount * cnnConvolutionLayerLast.OutputWidth * cnnConvolutionLayerLast.OutputHeight, outputCount, activationFunctionType, standardization); CnnFullLayerList.Add(cnnFullLayer); } else { var cnnFullLayerLast = CnnFullLayerList[CnnFullLayerList.Count - 1];//最后的卷积层 CnnFullLayer cnnFullLayer = new CnnFullLayer(cnnFullLayerLast.OutputCount, outputCount, activationFunctionType, standardization); CnnFullLayerList.Add(cnnFullLayer); } } /// <summary> /// 增加全连接层,仅用于BP网络 /// </summary> /// <param name="cnnFullLayer"></param> public void AddCnnFullLayer(int inputCount, int outputCount, CnnNode.ActivationFunctionTypes activationFunctionType, bool standardization) { CnnFullLayer cnnFullLayer = new CnnFullLayer(inputCount, outputCount, activationFunctionType, standardization); CnnFullLayerList.Add(cnnFullLayer); } /// <summary> /// 训练 /// </summary> public List<List<double[,]>> Train(double[,] input, double[] output, double learningRate, ref double[] forwardOutputFull) { #region 正向传播 /* //计算卷积层输出 List<double[,]> forwardOutputConvolution = new List<double[,]>();//输出值 for (int i = 0; i < CnnConvolutionLayerList.Count; i++) { //List<List<double[,]>> inputTmp = new List<List<double[,]>>(); List<List<double[,]>> forwardInputConvolution = new List<List<double[,]>>();//输入值 if (i == 0)//第一层直接输入 { for (int j = 0; j < CnnConvolutionLayerList[i].ConvolutionKernelCount; j++) { forwardInputConvolution.Add(new List<double[,]> { input }); } //inputTmp = forwardInputConvolution; } else//随机链接 { for (int j = 0; j < CnnConvolutionLayerList[i].ConvolutionKernelCount; j++) { List<double[,]> forwardInputConvolutionOne = new List<double[,]>();//一个神经元的输入值 for (int k = 0; k < forwardOutputConvolution.Count; k++) { if (convolutionLinkList[i - 1][j, k]) { forwardInputConvolutionOne.Add(forwardOutputConvolution[k]); } //Console.Write((convolutionLinkList[i - 1][j, k] ? 1 : 0) + " "); } forwardInputConvolution.Add(forwardInputConvolutionOne); //Console.WriteLine(""); } } //Console.WriteLine(""); forwardOutputConvolution = CnnConvolutionLayerList[i].CalculatedResult(forwardInputConvolution); } //Console.WriteLine("end"); //计算卷积层转全连接层 var cnnConvolutionLayerLast = CnnConvolutionLayerList[CnnConvolutionLayerList.Count - 1];//最后的卷积层 double[] forwardOutputFull = new double[cnnConvolutionLayerLast.ConvolutionKernelCount * cnnConvolutionLayerLast.OutputWidth * cnnConvolutionLayerLast.OutputHeight]; for (int j = 0; j < cnnConvolutionLayerLast.OutputHeight; j++) { for (int i = 0; i < cnnConvolutionLayerLast.OutputWidth; i++) { for (int k = 0; k < cnnConvolutionLayerLast.ConvolutionKernelCount; k++) { forwardOutputFull[i * cnnConvolutionLayerLast.ConvolutionKernelCount + j * cnnConvolutionLayerLast.OutputWidth * cnnConvolutionLayerLast.ConvolutionKernelCount + k] = forwardOutputConvolution[k][i, j]; } } } //计算全连接层输出 foreach (var cnnFullLayer in CnnFullLayerList) { forwardOutputFull = cnnFullLayer.CalculatedResult(forwardOutputFull); } //double[] outputFullTmp = Predict(input); //*/ forwardOutputFull = Predict(input); #endregion #region 反向传播 double layerCount = 0; var cnnFullLayerLast = CnnFullLayerList[CnnFullLayerList.Count - 1];//最后的输出层 double[] backwardInputFull = new double[cnnFullLayerLast.OutputCount]; //计算输出误差 for (int i = 0; i < cnnFullLayerLast.OutputCount; i++) { backwardInputFull[i] = output[i] - forwardOutputFull[i]; } //计算全连接层 for (int i = CnnFullLayerList.Count - 1; i >= 0; i--) { backwardInputFull = CnnFullLayerList[i].BackPropagation(backwardInputFull, learningRate); LogHelper.Info(CnnFullLayerList[i].ToString()); layerCount++; } //计算全连接层转卷积层 var cnnConvolutionLayerLast = CnnConvolutionLayerList[CnnConvolutionLayerList.Count - 1];//最后的卷积层 List<double[,]> inputConvolutionTmp = new List<double[,]>(); for (int i = 0; i < cnnConvolutionLayerLast.ConvolutionKernelCount; i++) { inputConvolutionTmp.Add(new double[cnnConvolutionLayerLast.OutputWidth, cnnConvolutionLayerLast.OutputHeight]); } for (int j = 0; j < cnnConvolutionLayerLast.OutputHeight; j++) { for (int i = 0; i < cnnConvolutionLayerLast.OutputWidth; i++) { for (int k = 0; k < cnnConvolutionLayerLast.ConvolutionKernelCount; k++) { inputConvolutionTmp[k][i, j] = backwardInputFull[i * cnnConvolutionLayerLast.ConvolutionKernelCount + j * cnnConvolutionLayerLast.OutputWidth * cnnConvolutionLayerLast.ConvolutionKernelCount + k]; } } } //计算卷积层 List<List<double[,]>> backwardInputConvolution = new List<List<double[,]>>(); for (int i = CnnConvolutionLayerList.Count - 1; i >= 0; i--) { List<double[,]> backwardOutputConvolution = new List<double[,]>(); if (i == CnnConvolutionLayerList.Count - 1)//最后一层直接输入 { backwardOutputConvolution = inputConvolutionTmp; } else//随机链接 { int[] inputIndex = new int[backwardInputConvolution.Count];//记录当前神经元序号 for (int j = 0; j < CnnConvolutionLayerList[i].ConvolutionKernelCount; j++)//对应当前层的神经元 { double[,] backwardOutputConvolutionOne = new double[backwardInputConvolution[0][0].GetLength(0), backwardInputConvolution[0][0].GetLength(1)]; for (int k = 0; k < backwardInputConvolution.Count; k++)//对应下一层的神经元 { if (convolutionLinkList[i][k, j]) { for (int x = 0; x < backwardInputConvolution[0][0].GetLength(0); x++) { for (int y = 0; y < backwardInputConvolution[0][0].GetLength(1); y++) { backwardOutputConvolutionOne[x, y] += backwardInputConvolution[k][inputIndex[k]][x, y]; } } inputIndex[k]++; } //Console.Write((convolutionLinkList[i][k, j] ? 1 : 0) + " "); } backwardOutputConvolution.Add(backwardOutputConvolutionOne); //Console.WriteLine(""); } } //Console.WriteLine(""); backwardInputConvolution = CnnConvolutionLayerList[i].BackPropagation(backwardOutputConvolution, learningRate); LogHelper.Info(CnnConvolutionLayerList[i].ToString()); layerCount++; } //Console.WriteLine("end"); #endregion return backwardInputConvolution; } /// <summary> /// 训练,仅用于BP网络 /// </summary> public double[] TrainFullLayer(double[] input, double[] output, double learningRate) { #region 正向传播 //计算全连接层输出 double[] forwardOutputFull = input; foreach (var cnnFullLayer in CnnFullLayerList) { forwardOutputFull = cnnFullLayer.CalculatedResult(forwardOutputFull); } #endregion #region 反向传播 var cnnFullLayerLast = CnnFullLayerList[CnnFullLayerList.Count - 1];//最后的输出层 double[] backwardInputFull = new double[cnnFullLayerLast.OutputCount]; //计算输出误差 for (int i = 0; i < cnnFullLayerLast.OutputCount; i++) { backwardInputFull[i] = output[i] - forwardOutputFull[i]; } //计算全连接层 for (int i = CnnFullLayerList.Count - 1; i >= 0; i--) { backwardInputFull = CnnFullLayerList[i].BackPropagation(backwardInputFull, learningRate); } #endregion return backwardInputFull; } /// <summary> /// 识别 /// </summary> public double[] Predict(double[,] input) { #region 正向传播 //计算卷积层输出 List<double[,]> forwardOutputConvolution = new List<double[,]>();//输出值 for (int i = 0; i < CnnConvolutionLayerList.Count; i++) { List<List<double[,]>> forwardInputConvolution = new List<List<double[,]>>();//输入值 if (i == 0)//第一层直接输入 { for (int j = 0; j < CnnConvolutionLayerList[i].ConvolutionKernelCount; j++) { forwardInputConvolution.Add(new List<double[,]> { input }); } } else//随机链接 { for (int j = 0; j < CnnConvolutionLayerList[i].ConvolutionKernelCount; j++) { List<double[,]> forwardInputConvolutionOne = new List<double[,]>();//一个神经元的输入值 for (int k = 0; k < forwardOutputConvolution.Count; k++) { if (convolutionLinkList[i - 1][j, k]) { forwardInputConvolutionOne.Add(forwardOutputConvolution[k]); } } forwardInputConvolution.Add(forwardInputConvolutionOne); } } forwardOutputConvolution = CnnConvolutionLayerList[i].CalculatedResult(forwardInputConvolution); } //计算卷积层转全连接层 var cnnConvolutionLayerLast = CnnConvolutionLayerList[CnnConvolutionLayerList.Count - 1];//最后的卷积层 double[] forwardOutputFull = new double[cnnConvolutionLayerLast.ConvolutionKernelCount * cnnConvolutionLayerLast.OutputWidth * cnnConvolutionLayerLast.OutputHeight]; for (int j = 0; j < cnnConvolutionLayerLast.OutputHeight; j++) { for (int i = 0; i < cnnConvolutionLayerLast.OutputWidth; i++) { for (int k = 0; k < cnnConvolutionLayerLast.ConvolutionKernelCount; k++) { forwardOutputFull[i * cnnConvolutionLayerLast.ConvolutionKernelCount + j * cnnConvolutionLayerLast.OutputWidth * cnnConvolutionLayerLast.ConvolutionKernelCount + k] = forwardOutputConvolution[k][i, j]; } } } //计算全连接层输出 foreach (var cnnFullLayer in CnnFullLayerList) { forwardOutputFull = cnnFullLayer.CalculatedResult(forwardOutputFull); } #endregion return forwardOutputFull; } /// <summary> /// 识别,仅用于BP网络 /// </summary> public double[] PredictFullLayer(double[] input) { //计算全连接层输出 double[] forwardOutputFull = input; foreach (var cnnFullLayer in CnnFullLayerList) { forwardOutputFull = cnnFullLayer.CalculatedResult(forwardOutputFull); } return forwardOutputFull; } /// <summary> /// 分离ARGB /// </summary> /// <param name="input"></param> /// <param name="type"></param> /// <returns></returns> /*private double[,] GetARGB(double[,] input, int type) { double[,] result = new double[input.GetLength(0), input.GetLength(1)]; for (int i = 0; i < input.GetLength(0); i++) { for (int j = 0; j < input.GetLength(1); j++) { int point = Convert.ToInt32(input[i, j]); switch (type) { case 0://B result[i, j] = (point & 0xFF) / 255; break; case 1://G result[i, j] = ((point & 0xFF00) >> 8) / 255d; break; case 2://R result[i, j] = ((point & 0xFF0000) >> 16) / 255d; break; case 3://A result[i, j] = ((point & 0xFF000000) >> 24) / 255d; break; } } } return result; }*/ } }
9895bde1baf7b6b323c5956fa4bbe79f5fd186db
C#
niklinchuan/docker_test
/Program.cs
3.5625
4
using System; using System.Collections.Generic; namespace DOTNET { class Program { static void Main(string[] args) { foreach (var number in GenerateWithYield()) { Console.WriteLine(number); } } public static IEnumerable<int> GetNumbers() { yield return 1; yield return 2; yield return 3; } public static IEnumerable<int> GenerateWithoutYield() { var i = 0; var list = new List<int>(); while (i < 5) list.Add(++i); return list; } public static IEnumerable<int> GenerateWithYield() { var i = 0; while (i < 5) yield return ++i; } } }
101f01ad802cee41a9a2d3fb3d57d2ee0628eac7
C#
taylorchasewhite/TayFinitiv
/TayFinitiv/Shared/TellerMachine.cs
3.078125
3
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Text.Json.Serialization; using System.Threading.Tasks; namespace TayFinitiv.Shared { public class TellerMachine { #region Properties [NotMapped] [JsonIgnore] public Dictionary<Denomination,int> Bills { get { Dictionary<Denomination, int> bills = new Dictionary<Denomination, int>(); bills.Add(Denomination.One, Ones); bills.Add(Denomination.Five, Fives); bills.Add(Denomination.Ten, Tens); bills.Add(Denomination.Twenty, Twenties); bills.Add(Denomination.Fifty, Fifties); bills.Add(Denomination.Hundred, Hundreds); return bills; } } public string Id { get; set; } public string Name { get; set; } public int Ones { get; set; } public int Fives { get; set; } public int Tens { get; set; } public int Twenties { get; set; } public int Fifties { get; set; } public int Hundreds { get; set; } #endregion public TellerMachine() { } public bool RequestMoney(Denomination denomination, int amount) { if(!canDenominationServiceAmount(denomination,amount)) { return false; } int billsNeeded = amount / (int)denomination; if(billsNeeded<=Bills[denomination]) { switch(denomination) { case Denomination.One: Ones -= billsNeeded; break; case Denomination.Five: Fives -= billsNeeded; break; case Denomination.Ten: Tens -= billsNeeded; break; case Denomination.Twenty: Twenties -= billsNeeded; break; case Denomination.Fifty: Fifties -= billsNeeded; break; case Denomination.Hundred: Hundreds -= billsNeeded; break; } return true; } return false; } /// <summary> /// Replaces the bills in the ATM with the quantity of bills of each denomination in the RestockRequest object. /// </summary> /// <param name="bills">An object identifying the quantity of bills to stock in each denomination</param> public void Stock(RestockRequest bills) { Ones = bills.Ones; Fives = bills.Fives; Tens = bills.Tens; Twenties = bills.Twenties; Fifties = bills.Fifties; Hundreds = bills.Hundreds; } /// <summary> /// Adds the bills in the ATM with the quantity of bills of each denomination in the RestockRequest object. /// </summary> /// <param name="bills">An object identifying the quantity of bills to add to the stock of each denomination</param> public void Restock(RestockRequest bills) { Ones += bills.Ones; Fives += bills.Fives; Tens += bills.Tens; Twenties += bills.Twenties; Fifties += bills.Fifties; Hundreds += bills.Hundreds; } #region Helpers /// <summary> /// Determines whether or not the type of bill requested (Denomination) can be used to /// return back the amount of money requested. /// </summary> /// <param name="denomination">The Denomination bill type, ex. One, Fifty, etc.</param> /// <param name="amount">The integer amount of money requested</param> /// <returns>Whether the denomination requested can service the amount of money by itself</returns> private bool canDenominationServiceAmount(Denomination denomination, int amount) { if (amount % (int)denomination != 0) { return false; // Cannot get 101 dollars from hundos (hundreds) } return true; } #endregion } }
835befeceb5cdc257960076913b28ced1a5193fa
C#
plamen-parvanov/SoftUni
/02. Tech module/01. Programming Fundamentals/prere6avaneNaZada4i/03. A Miner Task/03. A Miner Task.cs
3.59375
4
namespace _03.A_Miner_Task { using System; using System.Collections.Generic; public class Dictionaries { public static void Main() { var colectedResourse = CollectAllResourcesInputed(); PrintColectedResourse(colectedResourse); } public static Dictionary<string, int> CollectAllResourcesInputed() { var colectedResourse = new Dictionary<string, int>(); var input = Console.ReadLine(); while (input != "stop") { var resource = input; var quantity = Console.ReadLine(); if (!colectedResourse.ContainsKey(resource)) { colectedResourse[resource] = 0; } colectedResourse[resource] += int.Parse(quantity); input = Console.ReadLine(); } return colectedResourse; } public static void PrintColectedResourse(Dictionary<string, int> dict) { foreach (var kvp in dict) { Console.WriteLine("{0} -> {1}", kvp.Key, kvp.Value); } } } }
375a464f9443654271428ba5308d7ba1dd825930
C#
fangulo29/snake-multiplayer-csharp
/Snake_v0.5/Snake_v2/AnalyzeDataServer.cs
3.046875
3
using System; using System.Collections.Generic; using System.Drawing; namespace Snake_v2 { class AnalyzeDataServer { List<Point> wallList = new List<Point>(); Point foodPoint; public void Matriz(string data) { } public List<Point> Wall(string data) { string removeBegin = data.Replace("Wall:", ""); string[] posicoes = removeBegin.Split(';'); string[] posWall = null; for (int i = 0; i < posicoes.Length - 1; i++) { posWall = posicoes[i].Split(','); int xWall = Convert.ToInt32(posWall[0]); int yWall = Convert.ToInt32(posWall[1]); wallList.Add(new Point(xWall, yWall)); } return wallList; } public Point Food(string data) { string removeBegin = data.Replace("Food:", ""); string[] posicoes = removeBegin.Split(','); foodPoint.X = Convert.ToInt32(posicoes[0]); foodPoint.Y = Convert.ToInt32(posicoes[1]); return foodPoint; } } }
e3d64f272fc173ac9dd46340e3b2f65994063d25
C#
matyasf/Perlin
/Src/Display/Stage.cs
2.765625
3
using System; using System.Numerics; using SixLabors.ImageSharp.PixelFormats; using Veldrid; using Point = Perlin.Geom.Point; namespace Perlin.Display { /// <summary> /// Stage is the root of the display tree. If you want to show something you have to add it to the Stage /// (via <code>AddChild()</code> or to one of its descendants.) /// </summary> public class Stage : DisplayObject { /// <summary> /// Stage cannot be rotated, this will throw an exception /// </summary> public override float Rotation { set => throw new ArgumentException("The Stage cannot be rotated."); } /// <summary> /// Background color of the Stage. /// </summary> public Rgb24 BackgroundColor = new Rgb24(255,255,255); /// <summary> /// Sets the X coordinate of the window. Does not do anything on Android/iOS. /// </summary> public override float X { set => PerlinApp.Window.X = (int)value; get => PerlinApp.Window.X; } /// <summary> /// Sets the Y coordinate of the window. Does not do anything on Android/iOS. /// </summary> public override float Y { set => PerlinApp.Window.Y = (int)value; get => PerlinApp.Window.Y; } /// <summary> /// Stage has no parent. Trying to set it will throw an exception. /// </summary> public override DisplayObject Parent { internal set => throw new ArgumentException(); } internal Stage(int width, int height) { _isOnStage = true; OriginalWidth = width; OriginalHeight = height; Name = "Stage"; } public override DisplayObject HitTest(Point p) { // if nothing else is hit, the stage returns itself as target DisplayObject target = base.HitTest(p); if (target == null) { target = this; } return target; } private DisplayObject _mouseDownTarget; private DisplayObject _mouseHoverTarget; internal void OnMouseMoveInternal(float x, float y) { var p = new Point(x, y); DisplayObject mouseDownTarget; DisplayObject currentObjectUnderMouse = HitTest(p); if (_mouseHoverTarget != currentObjectUnderMouse) // mouse hovered over a new object { _mouseHoverTarget?.DispatchMouseExit(p); currentObjectUnderMouse.DispatchMouseEnter(p); // Console.WriteLine("enter: " + currentObjectUnderMouse.Name + " exit: " + _mouseHoverTarget?.Name); _mouseHoverTarget = currentObjectUnderMouse; } currentObjectUnderMouse.DispatchMouseHover(p); if (_mouseDownTarget != null) { mouseDownTarget = _mouseDownTarget; } else { mouseDownTarget = currentObjectUnderMouse; } // Console.WriteLine("move x:" + x + " y:" + y + " " + currentObjectUnderMouse); mouseDownTarget.DispatchMouseMoved(p); // + send local coordinates too, but calculate on-demand } internal DisplayObject DispatchMouseDownInternal(MouseButton button, Vector2 mousePosition) { var p = new Point(mousePosition.X, mousePosition.Y); _mouseDownTarget = HitTest(p); _mouseDownTarget.DispatchMouseDown(button, p); // + send local coordinates too //Console.WriteLine("DOWN " + p + " " + target); return _mouseDownTarget; } internal DisplayObject DispatchMouseUpInternal(MouseButton button, Vector2 mousePosition) { var p = new Point(mousePosition.X, mousePosition.Y); var target = HitTest(p); target.DispatchMouseUp(button, p); // + send local coordinates too //Console.WriteLine("UP " + p + " " + target); _mouseDownTarget = null; return target; } /// <summary> /// Renders all its children recursively. /// </summary> public override void Render(float elapsedTimeSecs) { InvokeEnterFrameEvent(elapsedTimeSecs); foreach (var child in Children) { child.Render(elapsedTimeSecs); } } public override string ToString() { return "Stage"; } } }
1299d1d61ee9b79464c0e514791271a715b05885
C#
MrBacon/GroupedUserReport
/GroupedUserReport.ConsoleApp/Program.cs
2.5625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GroupedUserReport.ConsoleApp { class Program { static void Main(string[] args) { var tools = new Common.ReportTools( System.Web.Security.Membership.Providers["AspNetSqlMembershipProvider"] ); tools.InitUserAccounts(); OutputReport(tools); } /// <summary> /// Responsible for outputing a report of users accounts grouped by their associated company /// </summary> /// <param name="tools"></param> private static void OutputReport(Common.ReportTools tools) { throw new NotImplementedException(); } } }
8f3763aafe4be86f21633ceb79545f68702f2275
C#
won983212/UMPL
/Implementation/Renderer/IRenderContext.cs
3
3
using System; using System.Collections.Generic; using System.Text; namespace ExprCore.Renderer { public struct Size { public double Width; public double Height; public Size(double w, double h) { Width = w; Height = h; } } public interface IRenderContext { void DrawRectangle(int x, int y, int w, int h); void DrawString(string text, double x, double y); void DrawLine(int x1, int y1, int x2, int y2); void DrawBackground(Size size); Size MeasureString(string text); } }
8b843a02f21f997b7a07d8aae5796ac559be2931
C#
inaabadjieva/SoftUni-CSharp
/CSharpFundamentals/10 Middle_Exam_SoftUni/2/TransportPrice.cs
3.40625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _2 { class Program { static void Main(string[] args) { var distance = double.Parse(Console.ReadLine()); var dayOrNight = Console.ReadLine().ToLower(); var dayWithTaxi = 0.79 * distance + 0.70; var nightWithTaxi = 0.90 * distance +0.70; var busPrice = 0.09*distance; var trainPrice = 0.06*distance; if (distance < 20) { if (dayOrNight == "day") Console.WriteLine(dayWithTaxi); else if (dayOrNight == "night") Console.WriteLine(nightWithTaxi); } else if (distance<100) { Console.WriteLine(busPrice); } else if (distance >= 100) { Console.WriteLine(0.06*distance); } } } }
8bff63476880068c9e6c72c0d8b3e190404020d2
C#
IagoAntunes/C-sharp-_Learning
/BotcampDio/C#/Criando uma aplicação de transferências bancárias com .NET/Conta.cs
3.21875
3
using System; namespace Criandu { public class Conta { private TipoConta TipoConta {get; set;} private double Saldo {get; set;} private double Credito {get; set;} public string Nome {get; set;} public Conta(TipoConta tipoConta,double saldo,double credito,string nome){ //Construtor this.TipoConta = tipoConta; this.Saldo = Saldo; this.Credito = credito; this.Nome = nome; } public bool Sacar(double valorSaque){ //Saldo insuficiente if(this.Saldo - valorSaque < (this.Credito * -1)){ Console.WriteLine("Saldo Insuficiente!"); return false; } this.Saldo -= valorSaque; Console.WriteLine("Saldo atual da conte de {0} é {1}",this.Nome,this.Saldo); return true; } public void Depositar(double valorDeposito){ this.Saldo += valorDeposito; Console.WriteLine("Saldo atual da conte de {0} é {1}",this.Nome,this.Saldo); } public void Transferir(double valorTransferencia,Conta contaDestino){ //Verifica se tem dinheiro if(this.Sacar(valorTransferencia)){ contaDestino.Depositar(valorTransferencia); } } public override string ToString() { string retorno = ""; retorno += "TipoConta: " + this.TipoConta + " | "; retorno += "Nome: " + this.Nome + " | "; retorno += "Saldo: " + this.Saldo+ " | "; retorno += "Credito: " + this.Credito + " | "; return retorno; } } }
80088f7287c14cb96241b887f243f3be7a5c0b23
C#
nguyentanphu/CoolShopping
/CoolShopping.Application/Entities/Product.cs
2.953125
3
using System.Collections.Generic; using CoolShopping.Application.Exceptions; namespace CoolShopping.Application.Entities { public class Product { public Product() { } public Product(int productId, string productName, int unitsInStock, decimal buyPrice, decimal sellPrice, Category category, Supplier supplier) { ProductId = productId; ProductName = productName; Category = category; Supplier = supplier; if (buyPrice > sellPrice) throw new IncorrectPriceException(); } public int ProductId { get; set; } public string ProductName { get; set; } public IEnumerable<ProductVariant> ProductVariants = new List<ProductVariant>(); public int? UnitsInStock { get; set; } = 0; public decimal? BuyPrice { get; set; } public decimal? SellPrice { get; set; } public Category Category { get; set; } public Supplier Supplier { get; set; } } }
b8c55f13886eae0d68c3f6185063beb585b6c7e5
C#
antoops/track-task-time
/TrackTaskTime/TrackTaskTime/Program.cs
2.8125
3
using ClosedXML.Excel; using NLog; using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.Globalization; using System.IO; using System.Windows.Forms; using System.Linq; namespace TrackTaskTime { class Program { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); private static readonly string QueueFileName = Application.StartupPath +"\\"+ @"QueueData.txt"; private static void Main(string[] args) { try { var thisProcessName = Process.GetCurrentProcess().ProcessName; if (Process.GetProcesses().Count(p => p.ProcessName == thisProcessName) > 1) return; var fileName = ConfigurationManager.AppSettings.Get("FileName"); var sheetName = ConfigurationManager.AppSettings.Get("SheetName"); Logger.Info($"{sheetName} sheet in {fileName} file will be updated "); var newTaskName = string.Empty; var someDate = DateTime.Now; var time = someDate.ToString("hh:mm tt"); var date = someDate.ToString("dd/MMM/yyyy"); newTaskName = GetTaskName(args, newTaskName, time, date); XLWorkbook workbook = null; try { workbook = new XLWorkbook(fileName); } catch (Exception ex) { if (ex.Message.Contains("because it is being used by another process")) { Logger.Error($"File is already in use, so will queue this command"); WriteToQueue(newTaskName, date, time); } return; } //file is able to edit //read from queue and append file var queueData = File.ReadAllLines(QueueFileName); var ws = workbook.Worksheets.Worksheet(sheetName); var range = ws.RangeUsed(); var lr = range.LastRow(); int rowNumberToEdit = lr.RowNumber(); if (queueData.Length>0) { Logger.Info($"Queue have {queueData.Length} records"); foreach (var queueItem in queueData) { Logger.Info($"Writing queue item = {queueItem} at row number {rowNumberToEdit}"); var queueObject = ConvertToQueueObject(queueItem); var lastTime = ws.Cell(rowNumberToEdit, 4).Value.ToString(); if (string.IsNullOrWhiteSpace(lastTime)) { Logger.Info($"Last task's end time will be updated."); ws.Cell(rowNumberToEdit, 4).InsertData( new List<string> { queueObject.StartTime }); } rowNumberToEdit++; if (!string.IsNullOrWhiteSpace(queueObject.TaskName)) { lr.CopyTo(ws.Cell(rowNumberToEdit, 1)); var newTaskDetails = new List<string[]> { new[] { queueObject.Date, queueObject.TaskName, queueObject.StartTime, string.Empty } }; ws.Cell(rowNumberToEdit, 1).InsertData(newTaskDetails); } } ClearQueue(); } //Updating the completed date var taskToBeCompleted = new List<string> { time }; var lastRowTime = ws.Cell(rowNumberToEdit, 4).Value.ToString(); if (string.IsNullOrWhiteSpace(lastRowTime)) { Logger.Info($"Last task's end time will be updated."); ws.Cell(rowNumberToEdit, 4).InsertData(taskToBeCompleted); } else Logger.Info($"Last row time is <{lastRowTime}>, so will skip this windup command"); rowNumberToEdit++; //copying last row to new row if its a new task if (!string.IsNullOrWhiteSpace(newTaskName)) { Logger.Info($"{newTaskName} is going to start on {date} at {time}"); lr.CopyTo(ws.Cell(rowNumberToEdit, 1)); var newTaskDetails = new List<string[]> { new[] { date, newTaskName, time, string.Empty } }; ws.Cell(rowNumberToEdit, 1).InsertData(newTaskDetails); } workbook.Save(); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.ReadKey(); } } private static void ClearQueue() { Logger.Info($"Queue is cleared."); File.WriteAllText(QueueFileName, String.Empty); } private static QueueObject ConvertToQueueObject(string queueItem) { QueueObject queueObject = null; var dataItems = queueItem.Split(','); if(dataItems.Length==3) { queueObject = new QueueObject { TaskName = dataItems[0], Date = dataItems[1], StartTime = dataItems[2] }; } return queueObject; } private static string GetTaskName(string[] args, string taskName, string time, string date) { if (args.Length > 0 && args[0].ToLower() == "tasknamerequired") { Console.WriteLine("Time Initiated : " + DateTime.Now.ToString(CultureInfo.InvariantCulture)); Console.WriteLine("Initiated by : " + args[1] ?? "None"); Console.WriteLine("Please type the task you are going to do now: "); taskName = Console.ReadLine(); Logger.Info($"{taskName} is going to start on {date} at {time}"); } else if (args.Length > 0) taskName = args[0]; return taskName; } private static void WriteToQueue(string taskName, string date, string time) { Logger.Info($"{taskName} is going to queued on {date} at {time}"); var data = taskName + "," + date + "," + time; File.AppendAllText(QueueFileName, data + Environment.NewLine); } } public class QueueObject { public string TaskName; public string Date; public string StartTime; } }
b4d43968da5eff4a99182ef2682a9bee3dbddbe6
C#
pailinglo/HelloCoreApp
/HelloCoreApp/Models/Employee.cs
3.21875
3
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace HelloCoreApp.Models { public class Employee { public int Id { get; set; } [NotMapped] public string EncryptedId { get; set; } [Required,MaxLength(50,ErrorMessage ="max length is 50")] public string Name { get; set; } [Required] [RegularExpression(@"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$",ErrorMessage ="Invalid E-mail format")] [Display(Name="Office E-mail")] public string Email { get; set; } [Required] public Dept? Department { get; set; } //make Department type nullable such that, it won't display "invalid value" error when opetion "Select a value" is selected. public string PhotoPath { get; set; } } public interface IEmployeeRepository { Employee GetEmployee(int Id); IEnumerable<Employee> GetAllEmployee(); Employee Add(Employee employee); Employee Update(Employee employeeChanges); Employee Delete(int Id); } public class MockEmployeeRepository : IEmployeeRepository { private List<Employee> _employeeList; public MockEmployeeRepository() { _employeeList = new List<Employee>() { new Employee() { Id = 1, Name = "Mary", Department = Dept.HR, Email = "mary@pragimtech.com" }, new Employee() { Id = 2, Name = "John", Department = Dept.IT, Email = "john@pragimtech.com" }, new Employee() { Id = 3, Name = "Sam", Department = Dept.IT, Email = "sam@pragimtech.com" }, }; } public Employee GetEmployee(int Id) { return this._employeeList.FirstOrDefault(e => e.Id == Id); } public IEnumerable<Employee> GetAllEmployee() { return this._employeeList; } public Employee Add(Employee employee) { employee.Id = this._employeeList.Max(r => r.Id) + 1; this._employeeList.Add(employee); return employee; } public Employee Update(Employee employeeChanges) { Employee employee = _employeeList.FirstOrDefault(e => e.Id == employeeChanges.Id); if (employee != null) { employee.Name = employeeChanges.Name; employee.Email = employeeChanges.Email; employee.Department = employeeChanges.Department; } return employee; } public Employee Delete(int Id) { Employee employee = _employeeList.FirstOrDefault(e => e.Id == Id); if (employee != null) { _employeeList.Remove(employee); } return employee; } } }
fe4204939938054feeea705d298f76d06b8cfdfa
C#
Drawaes/dotnetXperiments
/Crusher2/Crusher2/Strike2/Compare/CompareMethod.cs
2.734375
3
using System; using System.Collections.Generic; using System.Text; using Mono.Cecil; namespace Crusher2.Strike2.Compare { public class CompareMethod : IEqualityComparer<MethodDefinition> { private ModuleRebuilder _builder; private CompareParameter _compareParameter; private CompareGenericParameter _compareGenericParameter; public CompareMethod(ModuleRebuilder builder) { _builder = builder; _compareParameter = new CompareParameter(builder); _compareGenericParameter = new CompareGenericParameter(builder); } public bool Equals(MethodDefinition x, MethodDefinition y) { if (x == null && y == null) return true; if (x == null) return false; if (x.GetStringKey() != y.GetStringKey()) { return false; } if (x.Parameters.Count != y.Parameters.Count) return false; if (x.GenericParameters.Count != y.GenericParameters.Count) return false; if (x.Attributes != y.Attributes) return false; for (var i = 0; i < x.Parameters.Count;i++) { if(!_compareParameter.Equals(x.Parameters[i], y.Parameters[i])) { return false; } } for(var i = 0; i< x.GenericParameters.Count;i++) { if(! _compareGenericParameter.Equals(x.GenericParameters[i], y.GenericParameters[i])) { return false; } } return true; } public int GetHashCode(MethodDefinition obj) { throw new NotImplementedException(); } } }
8ff5bc771c9a6f529ab3027b92e50bb2745de0d3
C#
matthew-r-richards/continuous-deployment
/apps/Server/WebApplication.tests/Repositories/TimesheetRepositoryFacts.cs
2.96875
3
using System; using System.Linq; using Microsoft.EntityFrameworkCore; using WebApplication.DatabaseContext; using WebApplication.Models; using WebApplication.Repositories; using Xunit; namespace Repositories { public class TimesheetRepositoryFacts { public class Constructor { /// <summary> /// Checks that the constructor throws an Exception if passed a null context. /// </summary> [Fact] public void Throws_Null_Exception_For_Null_Context() { var ex = Assert.Throws<ArgumentNullException>(() => new TimesheetRepository(null)); Assert.Contains("context", ex.Message); } } public class Find { [Fact] public void Returns_Timesheet_Entry_If_Found() { var options = BuildContextOptions(nameof(Returns_Timesheet_Entry_If_Found)); long idToFind; // Set up the test against one instance of the context using (var context = new TimesheetContext(options)) { context.Database.EnsureDeleted(); context.TimesheetEntries.Add(new TimesheetEntry { TaskName = "Task 1", TaskDescription = "Task 1 Description" }); context.TimesheetEntries.Add(new TimesheetEntry { TaskName = "Task 2", TaskDescription = "Task 2 Description" }); context.SaveChanges(); // Find out the ID of the last entry so that we can find it idToFind = context.TimesheetEntries.ToList().Last().Id; } // Run the test against another instance of the context using (var context = new TimesheetContext(options)) { var repository = new TimesheetRepository(context); var result = repository.Find(idToFind); Assert.Equal("Task 2", result.TaskName); Assert.Equal("Task 2 Description", result.TaskDescription); } } [Fact] public void Returns_Null_If_Entry_Is_Not_Found() { var options = BuildContextOptions(nameof(Returns_Timesheet_Entry_If_Found)); // Set up the test against one instance of the context using (var context = new TimesheetContext(options)) { context.Database.EnsureDeleted(); context.TimesheetEntries.Add(new TimesheetEntry { TaskName = "Task 1", TaskDescription = "Task 1 Description" }); context.TimesheetEntries.Add(new TimesheetEntry { TaskName = "Task 2", TaskDescription = "Task 2 Description" }); context.SaveChanges(); } // Run the test against another instance of the context using (var context = new TimesheetContext(options)) { var repository = new TimesheetRepository(context); var result = repository.Find(-1); Assert.Null(result); } } } public class GetAll { [Fact] public void Returns_All_Timesheet_Entries() { var options = BuildContextOptions(nameof(Returns_All_Timesheet_Entries)); // Insert seed data into the database using one instance of the context using (var context = new TimesheetContext(options)) { context.Database.EnsureDeleted(); context.TimesheetEntries.Add(new TimesheetEntry { TaskName = "Task 1", TaskDescription = "Task 1 Description" }); context.TimesheetEntries.Add(new TimesheetEntry { TaskName = "Task 2", TaskDescription = "Task 2 Description" }); context.SaveChanges(); } // Use a clean instance of the context to run the test using (var context = new TimesheetContext(options)) { var repository = new TimesheetRepository(context); var result = repository.GetAll(); Assert.Equal(2, result.Count()); var resultList = result.ToList(); // Check Entry 1 Assert.Equal("Task 1", resultList[0].TaskName); Assert.Equal("Task 1 Description", resultList[0].TaskDescription); // Check Entry 2 Assert.Equal("Task 2", resultList[1].TaskName); Assert.Equal("Task 2 Description", resultList[1].TaskDescription); } } [Fact] public void Returns_Empty_Collection_If_No_Timesheet_Entries_Exist() { var options = BuildContextOptions(nameof(Returns_All_Timesheet_Entries)); // Run the test with an empty db in the context using (var context = new TimesheetContext(options)) { context.Database.EnsureDeleted(); var repository = new TimesheetRepository(context); var result = repository.GetAll(); Assert.Empty(result); } } } public class Add { [Fact] public void Adds_Entry_To_Database() { var options = BuildContextOptions(nameof(Adds_Entry_To_Database)); // Run the test against one instance of the context using (var context = new TimesheetContext(options)) { context.Database.EnsureDeleted(); var repository = new TimesheetRepository(context); repository.Add(new TimesheetEntry { TaskName = "Test Task", TaskDescription = "Test Task Description" }); } // Use a separate instance of the context to verify correct data was added to the database using (var context = new TimesheetContext(options)) { Assert.Equal(1, context.TimesheetEntries.Count()); Assert.Equal("Test Task", context.TimesheetEntries.Single().TaskName); Assert.Equal("Test Task Description", context.TimesheetEntries.Single().TaskDescription); } } } public class Delete { [Fact] public void Removes_Entry_From_Database_If_It_Exists() { var options = BuildContextOptions(nameof(Removes_Entry_From_Database_If_It_Exists)); long idToDelete; // Set up the test against one instance of the context using (var context = new TimesheetContext(options)) { context.Database.EnsureDeleted(); context.TimesheetEntries.Add(new TimesheetEntry { TaskName = "Task 1", TaskDescription = "Task 1 Description" }); context.TimesheetEntries.Add(new TimesheetEntry { TaskName = "Task 2", TaskDescription = "Task 2 Description" }); context.SaveChanges(); // Find out the ID of the first entry so that we can delete it idToDelete = context.TimesheetEntries.ToList().First().Id; } // Run the test against another instance of the context using (var context = new TimesheetContext(options)) { var repository = new TimesheetRepository(context); repository.Delete(idToDelete); } // Use a separate instance of the context to verify correct data was deleted from the database using (var context = new TimesheetContext(options)) { Assert.Equal(1, context.TimesheetEntries.Count()); Assert.Equal("Task 2", context.TimesheetEntries.Single().TaskName); Assert.Equal("Task 2 Description", context.TimesheetEntries.Single().TaskDescription); } } [Fact] public void Throws_InvalidOperationException_If_Entry_Does_Not_Exist() { var options = BuildContextOptions(nameof(Throws_InvalidOperationException_If_Entry_Does_Not_Exist)); // Run the test with an empty db in the context using (var context = new TimesheetContext(options)) { context.Database.EnsureDeleted(); var repository = new TimesheetRepository(context); Assert.Throws<InvalidOperationException>(() => repository.Delete(1)); } } } public class Stop { [Fact] public void Updates_Entry_End_Time_If_Entry_Exists() { var options = BuildContextOptions(nameof(Updates_Entry_End_Time_If_Entry_Exists)); long idToStop; // Set up the test against one instance of the context using (var context = new TimesheetContext(options)) { context.Database.EnsureDeleted(); context.TimesheetEntries.Add(new TimesheetEntry { TaskName = "Task 1", TaskDescription = "Task 1 Description" }); context.TimesheetEntries.Add(new TimesheetEntry { TaskName = "Task 2", TaskDescription = "Task 2 Description" }); context.SaveChanges(); // Find out the ID of the first entry so that we can stop it idToStop = context.TimesheetEntries.ToList().First().Id; // make sure the end time is not already set Assert.Null(context.TimesheetEntries.ToList().First().TaskEnd); } // Run the test against another instance of the context using (var context = new TimesheetContext(options)) { var repository = new TimesheetRepository(context); repository.Stop(idToStop); } // Use a separate instance of the context to verify that the end time was updated using (var context = new TimesheetContext(options)) { Assert.True(AreDatesApproximatelyEqual((DateTime)context.TimesheetEntries.First().TaskEnd, DateTime.Now, 2)); } } [Fact] public void Throws_InvalidOperationException_If_Entry_Does_Not_Exist() { var options = BuildContextOptions(nameof(Throws_InvalidOperationException_If_Entry_Does_Not_Exist)); // Run the test with an empty db in the context using (var context = new TimesheetContext(options)) { context.Database.EnsureDeleted(); var repository = new TimesheetRepository(context); Assert.Throws<InvalidOperationException>(() => repository.Stop(1)); } } } /// <summary> /// Builds the database context options. /// </summary> /// <param name="dbName">The database name to use.</param> /// <returns>The context options.</returns> private static DbContextOptions<TimesheetContext> BuildContextOptions(string dbName) { return new DbContextOptionsBuilder<TimesheetContext>() .UseInMemoryDatabase(databaseName: dbName) .Options; } /// <summary> /// Determines if the specified <see cref="T:DateTime"/>s are equal within the given number of seconds. /// </summary> /// <returns><c>true</c>, if the DateTime objects are approximately equal within the specified tolerance, <c>false</c> otherwise.</returns> /// <param name="date1">The first DateTime object to compare.</param> /// <param name="date2">The second DateTime object to compare.</param> /// <param name="secondsTolerance">The number of seconds to use for the comparison tolerance.</param> private static bool AreDatesApproximatelyEqual(DateTime date1, DateTime date2, int secondsTolerance) { return date1.Ticks < (date2.Ticks + secondsTolerance * 1000); } } }
accb9365e5220a4c7974e05ec1429f4035c11a77
C#
ToanDao2612/Sholo.HomeAssistant
/Source/Sholo.HomeAssistant.Common/Utilities/IdentifierValidator.cs
2.90625
3
using System; using System.Linq; using JetBrains.Annotations; namespace Sholo.HomeAssistant.Utilities { [PublicAPI] public static class IdentifierValidator { private static readonly char[] CapitalLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray(); private static readonly char[] LowercaseLetters = "abcdefghijklmnopqrstuvwxyz".ToCharArray(); private static readonly char[] Digits = "0123456789".ToCharArray(); private static readonly char[] Hyphen = { '-' }; private static readonly char[] Underscore = { '_' }; private static readonly char[] ValidDiscoveryPrefixCharacters; private static readonly char[] ValidNodeIdCharacters; private static readonly char[] ValidObjectIdCharacters; static IdentifierValidator() { ValidDiscoveryPrefixCharacters // Guessing on this one. = ValidNodeIdCharacters = CapitalLetters.Concat(LowercaseLetters).Concat(Digits).Concat(Hyphen).Concat(Underscore).ToArray(); ValidObjectIdCharacters = CapitalLetters.Concat(LowercaseLetters).Concat(Digits).Concat(Hyphen).Concat(Underscore).Concat(new[] { '/' }).ToArray(); } public static bool IsValidDiscoveryPrefix(string discoveryPrefixId) => discoveryPrefixId.All(c => ValidDiscoveryPrefixCharacters.Contains(c)); public static bool IsValidNodeId(string nodeId) => nodeId.All(c => ValidNodeIdCharacters.Contains(c)); public static bool IsValidObjectId(string objectId) => objectId.All(c => ValidObjectIdCharacters.Contains(c)); public static void ValidateDiscoveryPrefix(string discoveryPrefix) => Validate(discoveryPrefix, nameof(discoveryPrefix), IsValidDiscoveryPrefix); public static void ValidateNodeId(string nodeId) => Validate(nodeId, nameof(nodeId), IsValidNodeId); public static void ValidateObjectId(string objectId) => Validate(objectId, nameof(objectId), IsValidObjectId); private static void Validate(string value, string parameterName, Func<string, bool> validator) { if (value == null) throw new ArgumentNullException(parameterName); if (value.Length == 0) throw new ArgumentException(parameterName); if (!validator(value)) throw new ArgumentException($"The {parameterName} is invalid", parameterName); } } }
3615c24a8138ff5ef6c8f68b89aa1b3621a641bc
C#
RaulPampliegaMayoral/coding-test-ranking-dotnet
/coding-test-ranking/infrastructure/persistence/repositories/AdsRepository.cs
2.734375
3
using coding_test_ranking.infrastructure.persistence.models; using System.Collections.Generic; using System.Linq; namespace coding_test_ranking.infrastructure.persistence.repositories { public class AdsRepository : IAdsRepository { IRepository<AdVO> _repository; public AdsRepository(IRepository<AdVO> repository) { _repository = repository; } public void Delete(AdVO value) { _repository.Delete(value); } public IList<AdVO> GetAll() { return _repository.GetAll().ToList(); } public IList<AdVO> GetBestByScore(int limit) { return _repository.GetAll().Where(c => c.Score >= limit).OrderByDescending(c => c.Score).ToList(); } public AdVO GetById(int id) { return _repository.GetById(id); } public IList<AdVO> GetWorstByScore(int limit) { return _repository.GetAll().Where(c => !c.Score.HasValue || c.Score < limit).OrderByDescending(c => c.Score).ToList(); } public void Save(AdVO ad) { _repository.SaveOrUpdate(ad); } } }
ba2738c3756fa6069ba1b82d8bd4eb6fb64d5823
C#
fizik26/football-manager-backend
/WebApi/ViewModels/PlayerViewModel.cs
2.578125
3
using DomainModels.Models.PlayerEntities; namespace WebApi.ViewModels { public class PlayerViewModel { public string FirstName { get; set; } public string LastName { get; set; } public string Country { get; set; } public int Age { get; set; } public int Talent { get; set; } public string Position { get; set; } public int Height { get; set; } public int Weight { get; set; } public PlayerStatsViewModel Stats { get; set; } public static PlayerViewModel Get(Player player) { return new PlayerViewModel { FirstName = player.FirstName, LastName = player.LastName, Country = player.Country.ToString(), Age = player.Age, Talent = player.Talent, Position = player.Position.ToString(), Height = player.Height, Weight = player.Weight, Stats = PlayerStatsViewModel.Get(player) }; } } }
4fb712fc6e1b5fb4359fc540092a9464523572d2
C#
CannonStealth/Notes
/Systems/C#/Input.cs
4.09375
4
using System; //Program to input a number and find sum of its digits namespace Learning { class InputAndSum { //start of class static void Main(string[] args) { //start of function Console.WriteLine("Enter a number"); int number = Convert.ToInt32(Console.ReadLine()); //Console.ReadLine() takes only string literals and Convert.ToInt32 helps convert it into an integer. int sum = 0; int remainder; while( number > 0 ) { remainder = number % 10; //last digit is stored inside remainder sum = sum + remainder; //the sum is added to remainder every time number = number / 10; //to reduce the size of the number by one digit which is the remainder so that a new remainder is chosen every next iteration } Console.WriteLine("Sum of digits is = " + sum); //How it works - //Note - this logic works only for int variables /* Suppose number = 123 * (123 > 0) is true * (123 % 10) i.e 3 will be stored in remainder * Therefore sum will be (0 + 3) i.e 3 * The number then becomes (123 / 10) i.e 12. Since both 123 and 10 are int, the result will be int. If numbers was of double data type and was divided by 10.0, the new value would have been 12.3and loop would not have worked * * For next iteration, (12 > 0) will be checked which is true * remainder will be (12 % 10) which is 2 * sum will be (3 + 2) = 5. (The value of sum was updated to 3 in previous iteration) * number will become (12 / 10) = 1 * * For next iteration, (1 > 0) will be checked which is true * remainder will be (1 % 10) which is 1 * sum will be (5 + 1) = 6. (The value of sum was updated to 5 in previous iteration) * number will become (1 / 10) = 0 * * For next iteration, (1 > 0) will be checked which is false and the loop ends */ Console.ReadKey(); // needed to close terminal window } } }
082f607189bf6cd759ec215f7aaa41484efeabfb
C#
GDCASU/ProjectAndroid
/Project Android/Assets/Scripts/CameraController.cs
2.890625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraController : MonoBehaviour { /* Programmer: Pablo Camacho Date: 06/05/17 Description: I had made this script to abstract rotating camera and translating camera for other scripts such as OrientationWatcher. */ private float cameraSpeed = 10; //how fast camera moves //variables for angle to turn main camera around x axis private float xRotationCameraAngle = 50; private bool rotateCameraXAxisBool = false;// bool to tell main camera to turn or not //variables for angle to turn main camera around x axis private float yRotationCameraAngle = 0; private bool rotateCameraYAxisBool = false;// bool to tell main camera to turn or not //variables for angle to turn main camera around x axis private float zRotationCameraAngle = 0; private bool rotateCameraZAxisBool = false;// bool to tell main camera to turn or not //variables to translate camera private bool moveCameraUpXAxisBool; private bool moveCameraUpYAxisBool; private bool moveCameraUpZAxisBool; private bool moveCameraDownXAxisBool; private bool moveCameraDownYAxisBool; private bool moveCameraDownZAxisBool; // Use this for initialization void Start () { //Initialize bools to false xRotationCameraAngle = 50; rotateCameraXAxisBool = false; yRotationCameraAngle = 0; rotateCameraYAxisBool = false; zRotationCameraAngle = 0; rotateCameraZAxisBool = false; moveCameraUpXAxisBool = false; moveCameraUpYAxisBool = false; moveCameraUpZAxisBool = false; moveCameraDownXAxisBool = false; moveCameraDownYAxisBool = false; moveCameraDownZAxisBool = false; } // Update is called once per frame void Update () { //if rotate camera around x axis bool is true, rotate camera and reset bool to false if(rotateCameraXAxisBool) { TiltCameraAroundXAxis(xRotationCameraAngle); rotateCameraXAxisBool = false; } //if rotate camera around y axis bool is true, rotate camera and reset bool to false if(rotateCameraYAxisBool) { TiltCameraAroundYAxis(yRotationCameraAngle); rotateCameraYAxisBool = false; } //if rotate camera up or down around z axis bool is true, rotate camera and reset bool to false if(rotateCameraZAxisBool) { TiltCameraAroundZAxis(zRotationCameraAngle); rotateCameraZAxisBool = false; } //if move camera up or down in x axis bool is true, move camera and reset bool if(moveCameraUpXAxisBool) { MoveCameraInXAxis(cameraSpeed); moveCameraUpXAxisBool = false; } else if(moveCameraDownXAxisBool) { MoveCameraInXAxis(-cameraSpeed); moveCameraDownXAxisBool = false; } //if move camera up or down in y axis bool is true, move camera and reset bool if(moveCameraUpYAxisBool) { MoveCameraInYAxis(cameraSpeed); moveCameraUpYAxisBool = false; } else if(moveCameraDownYAxisBool) { MoveCameraInYAxis(-cameraSpeed); moveCameraDownYAxisBool = false; } //if move camera up or down in z axis bool is true, move camera and reset bool if(moveCameraUpZAxisBool) { MoveCameraInZAxis(cameraSpeed); moveCameraUpZAxisBool = false; } else if(moveCameraDownZAxisBool) { MoveCameraInZAxis(-cameraSpeed); moveCameraDownZAxisBool = false; } } //public function to allow others to turn camera around x axis by certain angle public void RotateCameraAroundXAxis(float tiltAngle) { xRotationCameraAngle = tiltAngle; rotateCameraXAxisBool = true; } //public function to allow others to turn camera around y axis by certain angle public void RotateCameraAroundYAxis(float tiltAngle) { yRotationCameraAngle = tiltAngle; rotateCameraYAxisBool = true; } //public function to allow others to turn camera around z axis by certain angle public void RotateCameraAroundZAxis(float tiltAngle) { zRotationCameraAngle = tiltAngle; rotateCameraZAxisBool = true; } //function to only tilt main camera around x axis, other axes don't change private void TiltCameraAroundXAxis(float tiltAngle) { Camera.main.transform.localEulerAngles = new Vector3(tiltAngle,yRotationCameraAngle,zRotationCameraAngle); } //function to only tilt main camera around y axis, other axes don't change private void TiltCameraAroundYAxis(float tiltAngle) { Camera.main.transform.localEulerAngles = new Vector3(xRotationCameraAngle,tiltAngle,zRotationCameraAngle); } //function to only tilt main camera around z axis, other axes don't change private void TiltCameraAroundZAxis(float tiltAngle) { Camera.main.transform.localEulerAngles = new Vector3(xRotationCameraAngle,yRotationCameraAngle,tiltAngle); } //public function to allow others to move camera in x axis public void MoveCameraUpXAxis(){moveCameraUpXAxisBool = true;} public void MoveCameraDownXAxis(){moveCameraDownXAxisBool = true;} //public function to allow others to move camera in y axis public void MoveCameraUpYAxis(){moveCameraUpYAxisBool = true;} public void MoveCameraDownYAxis(){moveCameraDownYAxisBool = true;} //public function to allow others to move camera in z axis public void MoveCameraUpZAxis(){moveCameraUpZAxisBool = true;} public void MoveCameraDownZAxis(){moveCameraDownZAxisBool = true;} //private function to move camera in x axis private void MoveCameraInXAxis(float speed) { Camera.main.transform.Translate(new Vector3(speed,0,0) * Time.deltaTime); } //private function to move camera in y axis private void MoveCameraInYAxis(float speed) { Camera.main.transform.Translate(new Vector3(0,speed,0) * Time.deltaTime); } //private function to move camera in z axis private void MoveCameraInZAxis(float speed) { Camera.main.transform.Translate(new Vector3(0,0,speed) * Time.deltaTime); } }
913bda651fff882dcb537363ef1932359acf59ee
C#
lxysdtc1231/SurvivalDay
/Assets/Scripts/Item/CombineFormula.cs
2.515625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Assets.Scripts.Item { /// <summary> /// 合成配方 /// </summary> public class CombineFormula { //合成公式ID public int FormulaID; //合成类型 public enum MaterialNeed { // 1种合成材料-4种合成材料 例: 1种:木材合成木地板; 2种:木材+铁锭合成铁剑; OneMaterialsNeed=1, TwoMaterialsNeed=2, ThreeMaterialsNeed=3, FourMaterialsNeed=4, //装备+装备;装备升级(预留) EquipmentCombine=5, EquipmentUpdate=6 } //每种所需材料ID public int FirstMaterialID; public int SecondMaterialID; public int ThirdMaterialID; public int FourthMaterialID; //每种材料所需数量 public int FirstMaterialCounts; public int SecondMaterialCounts; public int ThirdMaterialCounts; public int FourthMaterialCounts; //获取合成公式 public void GetFormula() { //FirstMaterialID= //SecondMaterialID= //ThirdMaterialID= //FourthMaterialID= // FirstMaterialID= } } }
ebb833b7622a488be6e11cbee4ecf1a97ccf8def
C#
DoniaSheriff/IR-windowsForm
/Form3.cs
2.609375
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Text.RegularExpressions; namespace IR_milestone { public partial class Form3 : Form { static string connectionString = "Data Source=DONIA\\SQLEXPRESS;Initial Catalog=College;Integrated Security=True"; public Form3() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string searchQuery = textBox1.Text.TrimStart(); Module3 module3 = new Module3(); char[] delimiters = new char[] { '\r', '\n', ' ' , ',' }; //exact search if (searchQuery != null && searchQuery.StartsWith("\"") && searchQuery.EndsWith("\"")) { //Remove Punctuation and numbers string result = Regex.Replace(searchQuery, "[^a-zA-Z\\s]", ""); result = Regex.Replace(result, @"(?<!^)(?=[A-Z])", " "); module3.exactSearch(module3.StemWords(result)); } else if (radioButton1.Checked == true) { string[] words = searchQuery.Split(delimiters, StringSplitOptions.RemoveEmptyEntries).Where(x => x.Length > 1).ToArray(); module3.SpellCheck(words); } else if (radioButton2.Checked == true) { string[] words = searchQuery.Split(delimiters, StringSplitOptions.RemoveEmptyEntries).Where(x => x.Length > 1).ToArray(); module3.SoundexSearch(words); } } private void groupBox1_Enter(object sender, EventArgs e) { } } }
5a7c6d87e942f7bca0ccd42f67ca6afd17e4ca62
C#
ercananlama/JQDotNet
/source/JQDotNet/Extensions/Conversion.cs
3.28125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace JQDotNet.Extensions { public static class Conversion { private static double? ConvertToDouble(this object valueToConvert) { if (valueToConvert == null) return null; double cValue; if (double.TryParse(valueToConvert.ToString(), out cValue)) return cValue; return null; } private static DateTime? ConvertToDateTime(this object valueToConvert) { if (valueToConvert == null) return null; DateTime cValue; if (DateTime.TryParse(valueToConvert.ToString(), out cValue)) return cValue; return null; } private static bool? ConvertToBoolean(this object valueToConvert) { if (valueToConvert == null) return null; bool cValue; if (bool.TryParse(valueToConvert.ToString(), out cValue)) return cValue; return null; } private static int? ConvertToInt(this object valueToConvert) { if (valueToConvert == null) return null; int cValue; if (int.TryParse(valueToConvert.ToString(), out cValue)) return cValue; return null; } private static long? ConvertToLong(this object valueToConvert) { if (valueToConvert == null) return null; long cValue; if (long.TryParse(valueToConvert.ToString(), out cValue)) return cValue; return null; } public static Nullable<T> SafeCast<T>(this object valueToConvert) where T : struct { object val = null; if (typeof(T) == typeof(double)) { val = valueToConvert.ConvertToDouble(); } else if (typeof(T) == typeof(DateTime)) { val = valueToConvert.ConvertToDateTime(); } else if (typeof(T) == typeof(bool)) { val = valueToConvert.ConvertToBoolean(); } else if (typeof(T) == typeof(int)) { val = valueToConvert.ConvertToInt(); } else if (typeof(T) == typeof(long)) { val = valueToConvert.ConvertToLong(); } if (val != null) { return (T)Convert.ChangeType(val, typeof(T)); } return null; } internal static bool IsTypeof<T>(this object value) { return (value != null && value is T); } /// <summary> /// Check if given value is a primitive type such as int, string in the context /// </summary> /// <param name="value">Value to be checked</param> /// <returns>Primitive status</returns> public static bool IsPrimitive(this object value) { return !(value is SimpleJson.JsonArray || value is SimpleJson.JsonObject); } internal static bool IsNumeric(this string value) { return SafeCast<int>(value) == null; } internal static string ToValueString(this object value) { if (value == null) { return null; } if (value is DateTime) { return value.SafeCast<DateTime>().Value.ToString("yyyy-MM-dd hh:mm"); } return value.ToString(); } } }
d1db981cad1c8bcad93653b46343e7d421ace78f
C#
Ylambers/ITIL_practise_tool
/Exam/Exam2/Utilities/EmbeddedResourceUtility.cs
3.203125
3
using System.IO; using System.Reflection; namespace Exam2.Utilities { /// <summary> /// Defines a class that provides utilities for working with embedded resources /// </summary> public static class EmbeddedResourceUtility { /// <summary> /// Get a <see cref="Stream"/> containing a embedded resource /// </summary> /// <param name="resourceName">The name of the embedded resource to get</param> /// <returns>Returns <see cref="Stream"/> containing the resource or <see langword="null"/> if it doesn't exist</returns> public static Stream? GetEmbeddedResourceStream(string resourceName) { return Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName); } /// <summary> /// Get all the embedded resource names /// </summary> /// <returns><see cref="string[]"/> containing all embedded resource names</returns> public static string[] GetEmbeddedResourceNames() { return Assembly.GetExecutingAssembly().GetManifestResourceNames(); } } }
424c4fc888e2e5f45d1e03cfabeff02e85adcacc
C#
nirmal1031/daredevil
/PlayerCollectCoins.cs
2.671875
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class PlayerCollectCoins : MonoBehaviour // class is declared { // class opened public int points = 0; // a variable is decalred to store the score count private GUIStyle guiStyle = new GUIStyle(); // a new private object is created // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } private void OnGUI() // function declared { // function opened guiStyle.fontSize = 42; // font size is declared GUI.Label(new Rect(20, 20, 200, 100), "Score: " + points, guiStyle); // to display the score on the screen if (points == 100) // conditional statement to see if the player has scored 100 points { // open if statement SceneManager.UnloadSceneAsync("John The Explorer"); // to make the current scne inactive SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1); // to load the gamewinner scene } // close if statement } // close function } // close class
25ee003e88377b7f16e91c54ee9e480a61a1efee
C#
s-innovations/S-Innovations.ServiceFabric
/src/S-Innovations.ServiceFabric.CoreCLR.Tools.FabUtil/Program.cs
2.734375
3
using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; namespace SInnovations.ServiceFabric.CoreCLR.Tools.FabUtil { public class Program { [MTAThread] public static void Main(string[] args) { var basePath = string.Join("/", AppContext.BaseDirectory.Split(new[] { '/', '\\' }) .TakeWhile(s => !s.Equals(".nuget", StringComparison.OrdinalIgnoreCase))); //TODO nuget versioning from current dependencies. var fileName = Path.Combine(basePath, @".nuget\packages\Microsoft.ServiceFabric.Actors\2.6.210\build\FabActUtil.exe"); // Fires up a new process to run inside this one var process = Process.Start(new ProcessStartInfo { UseShellExecute = false, RedirectStandardError = true, RedirectStandardInput = true, RedirectStandardOutput = true, FileName = fileName, Arguments = string.Join(" ", args.Select(a=>$"\"{a}\"")) }); // Depending on your application you may either prioritize the IO or the exact opposite var outputThread = new Thread(outputReader) { Name = "ChildIO Output" }; var errorThread = new Thread(errorReader) { Name = "ChildIO Error" }; var inputThread = new Thread(inputReader) { Name = "ChildIO Input" }; // Set as background threads (will automatically stop when application ends) outputThread.IsBackground = errorThread.IsBackground = inputThread.IsBackground = true; // Start the IO threads outputThread.Start(process); errorThread.Start(process); inputThread.Start(process); // Demonstrate that the host app can be written to by the application process.StandardInput.WriteLine("Message from host"); // Signal to end the application ManualResetEvent stopApp = new ManualResetEvent(false); // Enables the exited event and set the stopApp signal on exited process.EnableRaisingEvents = true; process.Exited += (e, sender) => { stopApp.Set(); }; // Wait for the child app to stop stopApp.WaitOne(); // Write some nice output for now? Console.WriteLine(); Console.Write("Process ended... shutting down host"); Thread.Sleep(1000); } /// <summary> /// Continuously copies data from one stream to the other. /// </summary> /// <param name="instream">The input stream.</param> /// <param name="outstream">The output stream.</param> private static void passThrough(Stream instream, Stream outstream) { byte[] buffer = new byte[4096]; while (true) { int len; while ((len = instream.Read(buffer, 0, buffer.Length)) > 0) { outstream.Write(buffer, 0, len); outstream.Flush(); } } } private static void outputReader(object p) { var process = (Process)p; // Pass the standard output of the child to our standard output passThrough(process.StandardOutput.BaseStream, Console.OpenStandardOutput()); } private static void errorReader(object p) { var process = (Process)p; // Pass the standard error of the child to our standard error passThrough(process.StandardError.BaseStream, Console.OpenStandardError()); } private static void inputReader(object p) { var process = (Process)p; // Pass our standard input into the standard input of the child passThrough(Console.OpenStandardInput(), process.StandardInput.BaseStream); } } }
11f7fc807010c3347d5efc2a7c2bbcafada4a75c
C#
Iowa20/The-Tech-Academy-Basic-C-sharp-Projects
/BooleanLogicDrill/BooleanLogicDrill/Program.cs
3.34375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BooleanLogicDrill { class Program { static void Main(string[] args) { Console.WriteLine("What is your age?"); int x; x = int.Parse(Console.ReadLine()); bool trueOrFalse = x >= 15; string Dui = null; Console.WriteLine("Have you ever had a DUI?"); Dui = Console.ReadLine(); if (Dui == "no") { Console.WriteLine("False"); } else if (Dui == "yes") { Console.WriteLine(""); } Console.WriteLine("How many speeding tickets do you have?"); int y; y = int.Parse(Console.ReadLine()); bool yesOrNo = y <= 3; Console.ReadLine(); if (x >= 15) if (Dui == "no") if (y <= 3) { Console.WriteLine("Qualified!!!"); } else if (y >= 3) { Console.WriteLine("Unqualified!!!"); } else if (Dui == "yes") { Console.WriteLine("Unqualified!!!"); } if (x < 15) { Console.WriteLine("Unqualified!!!"); } Console.ReadLine(); } } }
bace66cb8aaae1e17a10268b9ae16a52ac5389fa
C#
JTOne123/JsonRpc.Standard
/JsonRpc.Streams/MessageReader.cs
2.90625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using JsonRpc.Messages; namespace JsonRpc.Streams { /// <summary> /// Represents a JSON RPC message reader. /// </summary> public abstract class MessageReader : IDisposable { /// <summary> /// Asynchronously reads the next message that matches the /// </summary> /// <param name="filter">The expected type of the message.</param> /// <param name="cancellationToken">A token that cancels the operation.</param> /// <returns> /// The next JSON RPC message, or <c>null</c> if no more messages exist. /// </returns> /// <remarks>This method should be thread-safe.</remarks> /// <exception cref="ArgumentNullException"><paramref name="filter"/> is <c>null</c>.</exception> /// <exception cref="OperationCanceledException">The operation has been canceled.</exception> public abstract Task<Message> ReadAsync(Predicate<Message> filter, CancellationToken cancellationToken); private readonly CancellationTokenSource disposalTokenSource = new CancellationTokenSource(); /// <summary> /// A <see cref="CancellationToken"/> that is cancelled when the current object has been disposed. /// </summary> protected CancellationToken DisposalToken => disposalTokenSource.Token; /// <inheritdoc /> protected virtual void Dispose(bool disposing) { // release unmanaged resources here if (disposing) { try { disposalTokenSource.Cancel(); } catch (AggregateException) { } } } /// <inheritdoc /> public void Dispose() { if (disposalTokenSource.IsCancellationRequested) return; Dispose(true); // GC.SuppressFinalize(this); } ///// <inheritdoc /> //~MessageReader() //{ // Dispose(false); //} } /// <summary> /// A JSON RPC message reader that implements selective read by buffering all the /// received messages into a queue (or list) first. /// </summary> public abstract class QueuedMessageReader : MessageReader { private readonly LinkedList<Message> messages = new LinkedList<Message>(); // used to lock `messages` private readonly SemaphoreSlim messagesLock = new SemaphoreSlim(1, 1); // used to ensure only 1 ReadDirectAsync is running at a time. private readonly SemaphoreSlim fetchMessagesLock = new SemaphoreSlim(1, 1); /// <inheritdoc /> public override async Task<Message> ReadAsync(Predicate<Message> filter, CancellationToken cancellationToken) { if (filter == null) throw new ArgumentNullException(nameof(filter)); cancellationToken.ThrowIfCancellationRequested(); if (DisposalToken.IsCancellationRequested) throw new ObjectDisposedException(nameof(PartwiseStreamMessageReader)); LinkedListNode<Message> lastNode = null; var linkedToken = DisposalToken; CancellationTokenSource linkedTokenSource = null; if (cancellationToken.CanBeCanceled) { linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, DisposalToken); linkedToken = linkedTokenSource.Token; } try { while (true) { await messagesLock.WaitAsync(linkedToken); try { // Check if there's a satisfying item in the queue. var node = lastNode?.Next == null ? messages.First : lastNode; while (node != null) { if (filter(node.Value)) { messages.Remove(node); return node.Value; } node = node.Next; } lastNode = messages.Last; } finally { messagesLock.Release(); } if (fetchMessagesLock.Wait(0)) { // Fetch the next message, and decide whether it can pass the filter. try { var next = await ReadDirectAsync(linkedToken); if (next == null) return null; // EOF reached. if (linkedToken.IsCancellationRequested) { // We don't want to lose any message because of cancellation… await messagesLock.WaitAsync(DisposalToken); try { messages.AddLast(next); } finally { messagesLock.Release(); } linkedToken.ThrowIfCancellationRequested(); } if (filter(next)) return next; // We're lucky. // We still need to put the next item into the queue await messagesLock.WaitAsync(DisposalToken); try { messages.AddLast(next); } finally { if (!DisposalToken.IsCancellationRequested) messagesLock.Release(); } // After that, we can check the cancellation linkedToken.ThrowIfCancellationRequested(); } finally { if (!DisposalToken.IsCancellationRequested) fetchMessagesLock.Release(); } } else { // Or wait for the next message to come. linkedToken.ThrowIfCancellationRequested(); await fetchMessagesLock.WaitAsync(linkedToken); fetchMessagesLock.Release(); } } } catch (ObjectDisposedException) { linkedToken.ThrowIfCancellationRequested(); throw; } finally { linkedTokenSource?.Dispose(); } } /// <summary> /// When overridden in the derived class, directly asynchronously reads the next message. /// </summary> /// <param name="cancellationToken">A token that cancels the operation OR indicates the current instance has just been disposed.</param> /// <returns>The message just read, or <c>null</c> if EOF has reached.</returns> /// <exception cref="OperationCanceledException">The operation has been canceled.</exception> /// <remarks>The caller has guaranteed there is at most 1 ongoing call of this method.</remarks> protected abstract Task<Message> ReadDirectAsync(CancellationToken cancellationToken); /// <inheritdoc /> protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { fetchMessagesLock.Dispose(); messagesLock.Dispose(); } } } }
b815d8f6cf928da17f1d7244814b694b5c77beaf
C#
maddemon/SparrowCMS
/SparrowCMS/Attributes/NameAttribute.cs
2.53125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SparrowCMS { [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class NameAttribute : Attribute { public string Name { get; private set; } public NameAttribute(string name) { Name = name; } } }
0291121bf66f26ef2ddc73028622f8fe7fdf2c2a
C#
samasder/unityProject_RogueTactics
/RogueTactics/Assets/Scripts/Exceptions/MultValueModifier.cs
2.6875
3
public class MultValueModifier : ValueModifier { private readonly float _toMultiply; public MultValueModifier (int sortOrder, float toMultiply) : base (sortOrder) { _toMultiply = toMultiply; } public override float Modify (float fromValue, float toValue) { return toValue * _toMultiply; } }
9483de26d0983e5ecc50938c5024a4a426607691
C#
ReVoLt112/ConsoleSnake
/ConsoleSnake/Program.cs
3.078125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Diagnostics; namespace ConsoleSnake { public static class GlobaleVariablen { public static bool eaten { get; set; } public static int player { get; set; } } class Program { static void Main(string[] args) { GlobaleVariablen.eaten = true; char[,] Spielfeld = new char[80, 25]; error: Console.Clear(); Console.Write("Wieviele Spieler? ([1] / 2): "); try { GlobaleVariablen.player = Convert.ToInt32(Console.ReadLine()); } catch (Exception) { GlobaleVariablen.player = 1; } switch (GlobaleVariablen.player) { default: Console.WriteLine("Ungültige Auswahl!"); Thread.Sleep(1000); goto error; case 1: GlobaleVariablen.player = 1; Snake mySnake = new Snake(Spielfeld, 2, 1, 2, ConsoleColor.DarkGreen); mySnake.stopremoving = 0; mySnake.Pause = 100; mySnake.Punkte = 0; mySnake.Richtung = 'E'; mySnake.Gezeichnet = false; SetNameAndKeys(mySnake); Console.CursorVisible = false; initSpielfeld(Spielfeld); drawSpielfeld(Spielfeld, GlobaleVariablen.player); drawSnake(Spielfeld, mySnake); bool Terminate = false; while (!Terminate) { setPoints(mySnake.Punkte, mySnake); spawnFood(Spielfeld); if (Console.KeyAvailable) { KeyBoardListener(Console.ReadKey(true).Key, mySnake); } Terminate = move(Spielfeld, mySnake); Thread.Sleep(mySnake.Pause); } //End of game / Game Over Console.SetCursorPosition(35, 12); Console.ForegroundColor = ConsoleColor.Red; Console.Write("GAME OVER..."); Console.SetCursorPosition(30, 13); Console.Write(String.Format("{0} reached: {1} points!", mySnake.name, mySnake.Punkte)); Console.ForegroundColor = ConsoleColor.Black; Console.ReadLine(); break; case 2: Snake myS1 = new Snake(Spielfeld, 2, 1, 2, ConsoleColor.DarkGreen); myS1.stopremoving = 0; myS1.Pause = 100; myS1.Punkte = 0; myS1.Richtung = 'E'; myS1.Gezeichnet = false; SetNameAndKeys(myS1); Snake myS2 = new Snake(Spielfeld, 2, 75, 20, ConsoleColor.Blue); myS2.stopremoving = 0; myS2.Pause = 100; myS2.Punkte = 0; myS2.Richtung = 'W'; myS2.Gezeichnet = false; SetNameAndKeys(myS2); Console.CursorVisible = false; initSpielfeld(Spielfeld); drawSpielfeld(Spielfeld, GlobaleVariablen.player); drawSnake(Spielfeld, myS1); bool Terminate1 = false; bool Terminate2 = false; while (!Terminate1 && !Terminate2) { //setPoints(myS1.Punkte, myS1); spawnFood(Spielfeld); if (Console.KeyAvailable) { ConsoleKey key = Console.ReadKey(true).Key; if (key == myS1.up || key == myS1.down || key == myS1.left || key == myS1.right) { KeyBoardListener(key, myS1); } if (key == myS2.up || key == myS2.down || key == myS2.left || key == myS2.right) { KeyBoardListener(key, myS2); } } Terminate1 = move(Spielfeld, myS1); if (!Terminate1) { Terminate2 = move(Spielfeld, myS2); } Thread.Sleep(100); } //End of game / Game Over if (Terminate1) { Console.SetCursorPosition(35, 12); Console.ForegroundColor = ConsoleColor.Red; Console.Write("GAME OVER..."); Console.SetCursorPosition(35, 13); Console.Write(String.Format("{0} died!", myS1.name)); Console.ForegroundColor = ConsoleColor.Black; } else { Console.SetCursorPosition(35, 12); Console.ForegroundColor = ConsoleColor.Red; Console.Write("GAME OVER..."); Console.SetCursorPosition(35, 13); Console.Write(String.Format("{0} died!", myS2.name)); Console.ForegroundColor = ConsoleColor.Black; } Console.ReadLine(); break; } } private static void SetNameAndKeys(Snake mySnake) { Console.Clear(); Console.Write("Bitte geben Sie ihren Namen ein: "); mySnake.name = Console.ReadLine(); Console.Write("Bitte drücken Sie die Taste für hoch: "); mySnake.up = Console.ReadKey(true).Key; Console.WriteLine(mySnake.up.ToString()); Console.Write("Bitte drücken Sie die Taste für runter: "); mySnake.down = Console.ReadKey(true).Key; Console.WriteLine(mySnake.down.ToString()); Console.Write("Bitte drücken Sie die Taste für links: "); mySnake.left = Console.ReadKey(true).Key; Console.WriteLine(mySnake.left.ToString()); Console.Write("Bitte drücken Sie die Taste für rechts: "); mySnake.right = Console.ReadKey(true).Key; Console.WriteLine(mySnake.right.ToString()); Thread.Sleep(1000); } private static bool move(char[,] Spielfeld, Snake snake) { bool returnvalue = false; string[] pos = snake.snakequeue[0].Split('|'); switch (snake.Richtung) { case 'N': if (Spielfeld[Convert.ToInt32(pos[0]), Convert.ToInt32(pos[1]) - 1] != '*' && Spielfeld[Convert.ToInt32(pos[0]), Convert.ToInt32(pos[1]) - 1] != 'O' && Spielfeld[Convert.ToInt32(pos[0]), Convert.ToInt32(pos[1]) - 1] != 'X') { if (Spielfeld[Convert.ToInt32(pos[0]), Convert.ToInt32(pos[1]) - 1] == '#') { GlobaleVariablen.eaten = true; snake.stopremoving = 1; snake.Punkte++; snake.Pause = Convert.ToInt32(Math.Round(Convert.ToDouble(snake.Pause) * 0.98, 0)); } if (Spielfeld[Convert.ToInt32(pos[0]), Convert.ToInt32(pos[1]) - 1] == '+') { GlobaleVariablen.eaten = true; snake.stopremoving = 5; snake.Punkte += 5; snake.Pause = Convert.ToInt32(Math.Round(Convert.ToDouble(snake.Pause) * 0.98, 0)); } snake.snakequeue.Insert(0, String.Format("{0}|{1}", Convert.ToInt32(pos[0]), Convert.ToInt32(pos[1]) - 1)); Debug.WriteLine(String.Format("Snake insert @ {0}|{1}", Convert.ToInt32(pos[0]), Convert.ToInt32(pos[1]) - 1)); if (snake.stopremoving == 0) { string[] pos2 = snake.snakequeue[snake.snakequeue.Count - 1].Split('|'); Spielfeld[Convert.ToInt32(pos2[0]), Convert.ToInt32(pos2[1])] = '\0'; Console.SetCursorPosition(Convert.ToInt32(pos2[0]), Convert.ToInt32(pos2[1])); Console.Write(" "); snake.snakequeue.RemoveAt(snake.snakequeue.Count - 1); } else { snake.stopremoving--; } } else { returnvalue = true; } break; case 'E': if (Spielfeld[Convert.ToInt32(pos[0]) + 1, Convert.ToInt32(pos[1])] != '*' && Spielfeld[Convert.ToInt32(pos[0]) + 1, Convert.ToInt32(pos[1])] != 'O' && Spielfeld[Convert.ToInt32(pos[0]) + 1, Convert.ToInt32(pos[1])] != 'X') { if (Spielfeld[Convert.ToInt32(pos[0]) + 1, Convert.ToInt32(pos[1])] == '#') { GlobaleVariablen.eaten = true; snake.stopremoving = 1; snake.Punkte++; snake.Pause = Convert.ToInt32(Math.Round(Convert.ToDouble(snake.Pause) * 0.98, 0)); } if (Spielfeld[Convert.ToInt32(pos[0]) + 1, Convert.ToInt32(pos[1])] == '+') { GlobaleVariablen.eaten = true; snake.stopremoving = 5; snake.Punkte += 5; snake.Pause = Convert.ToInt32(Math.Round(Convert.ToDouble(snake.Pause) * 0.98, 0)); } snake.snakequeue.Insert(0, String.Format("{0}|{1}", Convert.ToInt32(pos[0]) + 1, Convert.ToInt32(pos[1]))); Debug.WriteLine(String.Format("Snake insert @ {0}|{1}", Convert.ToInt32(pos[0]) + 1, Convert.ToInt32(pos[1]))); if (snake.stopremoving == 0) { string[] pos2 = snake.snakequeue[snake.snakequeue.Count - 1].Split('|'); Spielfeld[Convert.ToInt32(pos2[0]), Convert.ToInt32(pos2[1])] = '\0'; Console.SetCursorPosition(Convert.ToInt32(pos2[0]), Convert.ToInt32(pos2[1])); Console.Write(" "); snake.snakequeue.RemoveAt(snake.snakequeue.Count - 1); } else { snake.stopremoving--; } } else { returnvalue = true; } break; case 'S': if (Spielfeld[Convert.ToInt32(pos[0]), Convert.ToInt32(pos[1]) + 1] != '*' && Spielfeld[Convert.ToInt32(pos[0]), Convert.ToInt32(pos[1]) + 1] != 'O' && Spielfeld[Convert.ToInt32(pos[0]), Convert.ToInt32(pos[1]) + 1] != 'X') { if (Spielfeld[Convert.ToInt32(pos[0]), Convert.ToInt32(pos[1]) + 1] == '#') { GlobaleVariablen.eaten = true; snake.stopremoving = 1; snake.Punkte++; snake.Pause = Convert.ToInt32(Math.Round(Convert.ToDouble(snake.Pause) * 0.98, 0)); } if (Spielfeld[Convert.ToInt32(pos[0]), Convert.ToInt32(pos[1]) + 1] == '+') { GlobaleVariablen.eaten = true; snake.stopremoving = 5; snake.Punkte += 5; snake.Pause = Convert.ToInt32(Math.Round(Convert.ToDouble(snake.Pause) * 0.98, 0)); } snake.snakequeue.Insert(0, String.Format("{0}|{1}", Convert.ToInt32(pos[0]), Convert.ToInt32(pos[1]) + 1)); Debug.WriteLine(String.Format("Snake insert @ {0}|{1}", Convert.ToInt32(pos[0]), Convert.ToInt32(pos[1]) + 1)); if (snake.stopremoving == 0) { string[] pos2 = snake.snakequeue[snake.snakequeue.Count - 1].Split('|'); Spielfeld[Convert.ToInt32(pos2[0]), Convert.ToInt32(pos2[1])] = '\0'; Console.SetCursorPosition(Convert.ToInt32(pos2[0]), Convert.ToInt32(pos2[1])); Console.Write(" "); snake.snakequeue.RemoveAt(snake.snakequeue.Count - 1); } else { snake.stopremoving--; } } else { returnvalue = true; } break; case 'W': if (Spielfeld[Convert.ToInt32(pos[0]) - 1, Convert.ToInt32(pos[1])] != '*' && Spielfeld[Convert.ToInt32(pos[0]) - 1, Convert.ToInt32(pos[1])] != 'O' && Spielfeld[Convert.ToInt32(pos[0]) - 1, Convert.ToInt32(pos[1])] != 'X') { if (Spielfeld[Convert.ToInt32(pos[0]) - 1, Convert.ToInt32(pos[1])] == '#') { GlobaleVariablen.eaten = true; snake.stopremoving = 1; snake.Punkte++; snake.Pause = Convert.ToInt32(Math.Round(Convert.ToDouble(snake.Pause) * 0.98, 0)); } if (Spielfeld[Convert.ToInt32(pos[0]) - 1, Convert.ToInt32(pos[1])] == '+') { GlobaleVariablen.eaten = true; snake.stopremoving = 5; snake.Punkte += 5; snake.Pause = Convert.ToInt32(Math.Round(Convert.ToDouble(snake.Pause) * 0.98, 0)); } snake.snakequeue.Insert(0, String.Format("{0}|{1}", Convert.ToInt32(pos[0]) - 1, Convert.ToInt32(pos[1]))); Debug.WriteLine(String.Format("Snake insert @ {0}|{1}", Convert.ToInt32(pos[0]) - 1, Convert.ToInt32(pos[1]))); if (snake.stopremoving == 0) { string[] pos2 = snake.snakequeue[snake.snakequeue.Count - 1].Split('|'); Spielfeld[Convert.ToInt32(pos2[0]), Convert.ToInt32(pos2[1])] = '\0'; Console.SetCursorPosition(Convert.ToInt32(pos2[0]), Convert.ToInt32(pos2[1])); Console.Write(" "); snake.snakequeue.RemoveAt(snake.snakequeue.Count - 1); } else { snake.stopremoving--; } } else { returnvalue = true; } break; } if (!returnvalue) drawSnake(Spielfeld, snake); return returnvalue; } private static void setPoints(int punkte, Snake snake) { Console.SetCursorPosition(9, 0); Console.Write(punkte.ToString()); Console.SetCursorPosition(26, 0); Console.Write(snake.Richtung); Console.SetCursorPosition(36, 0); Console.Write(100 - snake.Pause); Console.SetCursorPosition(0, 0); } private static void drawSnake(char[,] Spielfeld, Snake snake) { Console.ForegroundColor = snake.color; for (int i = snake.snakequeue.Count - 1; i >= 0; i--) { string[] pos = snake.snakequeue[i].Split('|'); Console.SetCursorPosition(Convert.ToInt32(pos[0]), Convert.ToInt32(pos[1])); if (i == 0) { Spielfeld[Convert.ToInt32(pos[0]), Convert.ToInt32(pos[1])] = 'X'; Console.Write("X"); } else if (i == snake.snakequeue.Count - 1) { Spielfeld[Convert.ToInt32(pos[0]), Convert.ToInt32(pos[1])] = 'O'; Console.Write("o"); } else { Spielfeld[Convert.ToInt32(pos[0]), Convert.ToInt32(pos[1])] = 'O'; Console.Write("O"); } } Console.ForegroundColor = ConsoleColor.Gray; Console.SetCursorPosition(0, 0); snake.Gezeichnet = true; Debug.WriteLine(String.Format("Drawn: {0}", snake.Gezeichnet)); } private static void drawSpielfeld(char[,] Spielfeld, int player) { Console.Clear(); for (int y = 0; y <= Spielfeld.GetLength(1) - 1; y++) { for (int x = 0; x <= Spielfeld.GetLength(0) - 1; x++) { Console.SetCursorPosition(x, y); Console.Write(Spielfeld[x, y]); } } switch (player) { case 1: Console.SetCursorPosition(1, 0); Console.Write("Points:"); Console.SetCursorPosition(15, 0); Console.Write("Direction:"); Console.SetCursorPosition(29, 0); Console.Write("Speed:"); Console.SetCursorPosition(0, 0); break; case 2: Console.SetCursorPosition(1, 0); Console.Write("MULTIPLAYER GAME"); break; default: break; } } private static void initSpielfeld(char[,] Spielfeld) { for (int y = 0; y <= Spielfeld.GetLength(1) - 1; y++) { for (int x = 0; x <= Spielfeld.GetLength(0) - 1; x++) { if (y == 1 || y == Spielfeld.GetLength(1) - 1) { Spielfeld[x, y] = '*'; } else if (y > 0 && y < Spielfeld.GetLength(1) && (x == 0 || x == Spielfeld.GetLength(0) - 1)) { Spielfeld[x, y] = '*'; } } } } private static void KeyBoardListener(ConsoleKey keypressed, Snake snake) { int i = 0; if (!snake.Gezeichnet) goto hit; if (keypressed == snake.up && snake.Richtung != 'S') { north: if (snake.Gezeichnet) { snake.Gezeichnet = false; snake.Richtung = 'N'; Debug.WriteLine(snake.Richtung); goto hit; } else { i = 0; goto north; } } else if (keypressed == snake.right && snake.Richtung != 'W') { east: if (snake.Gezeichnet) { snake.Gezeichnet = false; snake.Richtung = 'E'; Debug.WriteLine(snake.Richtung); goto hit; } else { i = 0; goto east; } } else if (keypressed == snake.down && snake.Richtung != 'N') { south: if (snake.Gezeichnet) { snake.Gezeichnet = false; snake.Richtung = 'S'; Debug.WriteLine(snake.Richtung); goto hit; } else { i = 0; goto south; } } else if (keypressed == snake.left && snake.Richtung != 'E') { west: if (snake.Gezeichnet) { snake.Gezeichnet = false; snake.Richtung = 'W'; Debug.WriteLine(snake.Richtung); goto hit; } else { i = 0; goto west; } } hit: i++; } private static void spawnFood(char[,] Spielfeld) { Random myRNDNumber = new Random(); if (GlobaleVariablen.eaten) { int x = myRNDNumber.Next(1, Spielfeld.GetLength(0) - 1); int y = myRNDNumber.Next(2, Spielfeld.GetLength(1) - 1); if (Spielfeld[x, y] == '\0') { Random myRNDItem = new Random(); int i = myRNDItem.Next(0, 11); switch (i) { case 1: Spielfeld[x, y] = '+'; Console.ForegroundColor = ConsoleColor.Magenta; Console.SetCursorPosition(x, y); Console.Write("+"); Console.ForegroundColor = ConsoleColor.Gray; break; default: Spielfeld[x, y] = '#'; Console.ForegroundColor = ConsoleColor.Yellow; Console.SetCursorPosition(x, y); Console.Write("#"); Console.ForegroundColor = ConsoleColor.Gray; break; } Console.SetCursorPosition(0, 0); GlobaleVariablen.eaten = false; } } } } }
5a3d110aa943e5cebc8283d6d355cb208661f02e
C#
bright-sparks/MyToolkit
/src/Shared/Converters/TruncateConverter.cs
2.796875
3
using System; using MyToolkit.Utilities; #if !WINRT using System.Windows.Data; #else using Windows.UI.Xaml.Data; #endif namespace MyToolkit.Converters { public class TruncateConverter : IValueConverter { #if !WINRT public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) #else public object Convert(object value, Type typeName, object parameter, string language) #endif { var maxLength = int.Parse((string)parameter); if (value != null) return value.ToString().TruncateWithoutChopping(maxLength); return null; } #if !WINRT public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) #else public object ConvertBack(object value, Type typeName, object parameter, string language) #endif { throw new NotSupportedException(); } } }
4619f63ee63a7989b8cc1ae6bd93bfbf68e5a644
C#
vararucristian/.Net-Project
/microservices/Messages-MS/Messages-MS/Controllers/MessagesController.cs
2.59375
3
using System; using System.Text.Json; using System.Threading.Tasks; using MediatR; using Messages_MS.DTO; using Microsoft.AspNetCore.Mvc; namespace Messages_MS.Controllers { [Route("api/[controller]")] [ApiController] public class MessagesController : ControllerBase { private readonly IMediator _mediator; public MessagesController(IMediator mediator) { _mediator = mediator; } // GET: api/Messages [HttpGet] public async Task<ActionResult<string>> GetAllMessagesAsync() { var messages = await _mediator.Send(new GetMessagesQuery()); var json = JsonSerializer.Serialize(messages); return json; } // GET: api/Messages/receiverId/... [HttpGet("receiverId/{receiverId}")] public async Task<ActionResult<string>> GetMessagesByReceiverIdAsync(Guid receiverId) { var messages = await _mediator.Send(new GetMessagesByReceiverIdQuery(receiverId)); var json = JsonSerializer.Serialize(messages); return json; } // GET: api/Messages/senderId/... [HttpGet("senderId/{senderId}")] public async Task<ActionResult<string>> GetMessagesBySenderIdAsync(Guid senderId) { var messages = await _mediator.Send(new GetMessagesBySenderIdQuery(senderId)); var json = JsonSerializer.Serialize(messages); return json; } [HttpGet("{receiverId}/{senderId}")] public async Task<ActionResult<string>> GetMessagesBySenderandReceiverIdAsync(Guid receiverId,Guid senderId) { var messages = await _mediator.Send(new GetMessagesBySenderandReceiverIdQuery(receiverId,senderId)); var json = JsonSerializer.Serialize(messages); return json; } // GET: api/Messages/5 //[HttpGet("{id}", Name = "Get")] //public string Get(int id) //{ // return "value"; //} // POST: api/Messages [HttpPost] public async Task<ActionResult<string>> Create([FromBody]CreateMessage jsonRequest) { var response = await _mediator.Send(jsonRequest); var json = JsonSerializer.Serialize(response); return json; } // PUT: api/Messages/5 [HttpPut("{id}")] public void Put(int id, [FromBody] string value) { } // DELETE: api/ApiWithActions/5 [HttpDelete("{id}")] public async Task<ActionResult<string>> Delete(Guid id) { var message = await _mediator.Send(new DeleteMessage(id)); var json = JsonSerializer.Serialize(message); return json; } } }
a880ee774e5ee206c381a3911eb6282562abecd3
C#
xeon2007/WSProf
/Components/Sourcecode/NewSynergy/WSOfficeAddin/OfficeAddinRegistrar/RegistrarApp.cs
2.859375
3
using System; namespace Workshare.Registrar { /// <summary> /// Summary description for Class1. /// </summary> class RegistrarApp { /// <summary> /// The main entry point for the application. /// /// @params - 1st string = register/unregister, 2nd string = path /// </summary> private static void PrintHelp() { Console.WriteLine("Workshare .NET Registration Assistant"); Console.WriteLine(" Workshare.Registrar [options] <component install path>"); Console.WriteLine(" Options:"); Console.WriteLine(" /u - unregister (default is register)"); Console.WriteLine(" /s - silent"); Console.WriteLine(" /h - this help page"); Console.WriteLine(" /p - Register Protect Assembies Only"); } enum ReturnValue { Success = 0, Failure = 1 } [STAThread] static int Main(string[] args) { CommandLineParser parser = new CommandLineParser( args ); if (parser.RegistrationPath.Length == 0) parser.RegistrationPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(typeof(RegistrarApp)).Location); try { AssemblyRegistrar registrar = new AssemblyRegistrar( parser ); if( parser.RegisterMode == CommandLineParser.InstallMode.Register ) registrar.Register(); else { try { registrar.UnRegister(); } catch { // ignore the exception } } return (int) ReturnValue.Success; } catch( Exception ex ) { System.Diagnostics.Debug.Assert(false, ex.Message); ErrorReporter reporter = new ErrorReporter(parser.RegistrationPath, parser.SilentMode); reporter.Report(ex.Message); return (int) ReturnValue.Failure; } } } }
5b8b4468785a7bea9497241f40b94a0d7bd99d50
C#
Avatarchik/TypeTreeGenerator
/TypeTreeGenerator/Type/BaseType.cs
2.734375
3
using System; namespace TypeTreeGenerator { public enum BaseType { @bool, UInt8, SInt16, UInt16, @int, unsignedint, SInt64, UInt64, @float, } public static class BaseTypeExtensions { public static string ToExportType(this BaseType _this) { switch(_this) { case BaseType.@bool: return "bool"; case BaseType.UInt8: return "byte"; case BaseType.SInt16: return "short"; case BaseType.UInt16: return "ushort"; case BaseType.@int: return "int"; case BaseType.unsignedint: return "uint"; case BaseType.SInt64: return "long"; case BaseType.UInt64: return "ulong"; case BaseType.@float: return "float"; default: throw new NotSupportedException(_this.ToString()); } } public static string ToExportNETType(this BaseType _this) { switch (_this) { case BaseType.@bool: return "Boolean"; case BaseType.UInt8: return "Byte"; case BaseType.SInt16: return "Int16"; case BaseType.UInt16: return "UInt16"; case BaseType.@int: return "Int32"; case BaseType.unsignedint: return "UInt32"; case BaseType.SInt64: return "Int64"; case BaseType.UInt64: return "UInt64"; case BaseType.@float: return "Single"; default: throw new NotSupportedException(_this.ToString()); } } } }
b10a52d614e2e79dbdeab00a23f632e3e30be0a9
C#
Fransmohsen/BroadcastChat.cs
/BroadcastChat.cs/Program.cs
3.296875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using System.Net.Sockets; using System.Net; namespace BroadcastChat.cs { class Program { private const int ListenPort = 11000; static void Main(string[] args) { //skapar en tråd som körs parallelt 0emed huvudprogrammet var listenThread = new Thread(Listener); listenThread.Start(); Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket.EnableBroadcast = true; IPEndPoint ep = new IPEndPoint(IPAddress.Broadcast, ListenPort); while(true) { //Använderen skriver medelande Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Skriv meddelandet:"); string msg = Console.ReadLine(); byte[] sendbuf = Encoding.UTF8.GetBytes(msg); socket.SendTo(sendbuf, ep); Thread.Sleep(200); } } static void Listener() { UdpClient listener = new UdpClient(ListenPort); try { while(true) { DateTime time = DateTime.Now; string format = "MMM ddd d HH:mm yyyy"; //skapa objekt som lyssnar efter traik från valfri ip-adress men via port IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, ListenPort); byte[] bytes = listener.Receive(ref groupEP); Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine("\n Mottaget meddelande från {0} : {1}\n", groupEP.ToString(), Encoding.UTF8.GetString(bytes,0,bytes.Length)); Console.WriteLine("Meddelandet mottogs: " + time.ToString(format)); } } catch (Exception e) { Console.WriteLine(e.ToString()); } finally { listener.Close(); } } } }
73041a499d91c41f834ecfd09f962f75e48c1280
C#
WestsideBG/Software-University
/C# FUNDAMENTALS/02. C# OOP BASIC/04. Inheritance/Inheritance-LAB/LAB/RandomListProject/RandomList.cs
3.4375
3
using System; using System.Collections.Generic; namespace CustomRandomList { public class RandomList : List<string> { public Random Random { get; set; } public RandomList() { Random = new Random(); } public string GetRandomString() { var index = Random.Next(0, this.Count - 1); string result = this[index]; RemoveAt(index); return result; } } }
ad7edd1933ac5ebb1b3af051b801be7b3fa368ec
C#
Bronz57/bronzetti.christian.4h.saverecord
/Program.cs
3.078125
3
using System; using bronzetti.christian._4h.SaveRecord.Models; namespace bronzetti.christian._4h.SaveRecord { class Program { static void Main(string[] args) { Console.WriteLine("SaveRecord - 2021 - christian bronzetti"); //leggere file cvs voi comuni e trasformarlo in una list <comune> Comuni c = new Comuni("CodiciComuni.csv"); // scrivere la list in file.bin c.Save(); Console.WriteLine($"Ecco la riga 1000 dopo il dave\n{c[5]}\n"); //rileggere il file binario in una list<Comune> c.Load(); Console.WriteLine($"Ecco la riga 1000 dopo load \n{c[5]}\n"); Console.WriteLine(c.RicercaComune(Convert.ToInt32(100))); } } }
e13100b9e6287e03729876866097a935656b7981
C#
nss-copper-dragonflies/BangazonAPI
/BangazonAPI/Controllers/DepartmentController.cs
2.734375
3
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; using BangazonAPI.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; //JORDAN ROSAS: Controller for the Get, Get single, put and post working with query strings and q='s namespace BangazonAPI.Controllers { [Route("api/[controller]")] [ApiController] public class DepartmentController : ControllerBase { private readonly IConfiguration _config; public DepartmentController(IConfiguration configuration) { _config = configuration; } public SqlConnection Connection { get { return new SqlConnection(_config.GetConnectionString("DefaultConnection")); } } // GET: api/Department [HttpGet] public IEnumerable<Department> Get(string include, string q) { using (SqlConnection conn = Connection) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { if (include == "employees") { cmd.CommandText = @"select department.id as Departmentid, department.[Name] as departmentName, department.budget, employee.Id as employeeId, employee.FirstName, employee.LastName, employee.isSupervisor, employee.DepartmentId from Department left join employee on Department.Id = employee.DepartmentId Where 1=1"; } else { cmd.CommandText = @"select department.id as Departmentid, department.[name] as departmentName, department.budget From department Where 1=1"; } if (!string.IsNullOrWhiteSpace(q)) { cmd.CommandText += @" AND (department.[name] LIKE @q)"; cmd.Parameters.Add(new SqlParameter("@q", $"%{q}%")); } SqlDataReader reader = cmd.ExecuteReader(); Dictionary<int, Department> departmentDictionary = new Dictionary<int, Department>(); while (reader.Read()) { int Departmentid = reader.GetInt32(reader.GetOrdinal("Departmentid")); if (!departmentDictionary.ContainsKey(Departmentid)) { Department newDepartment = new Department { id = Departmentid, Name = reader.GetString(reader.GetOrdinal("departmentName")), Budget = reader.GetInt32(reader.GetOrdinal("Budget")) }; departmentDictionary.Add(Departmentid, newDepartment); } if (include == "employees") { if (!reader.IsDBNull(reader.GetOrdinal("employeeId"))) { Department currentDepartment = departmentDictionary[Departmentid]; currentDepartment.employeeList.Add( new Employee { Id = reader.GetInt32(reader.GetOrdinal("employeeId")), FirstName = reader.GetString(reader.GetOrdinal("FirstName")), LastName = reader.GetString(reader.GetOrdinal("LastName")), IsSupervisor = reader.GetBoolean(reader.GetOrdinal("isSupervisor")), DepartmentId = reader.GetInt32(reader.GetOrdinal("departmentId")) } ); } } } reader.Close(); return departmentDictionary.Values.ToList(); } } } //GET by Id with query strings! [HttpGet("{id}", Name = "GetSpecific")] public IActionResult Get(int id, string include) { using (SqlConnection conn = Connection) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { //this if statement catches the search parameters for the words "product" and "payment" if (include == "employees") { cmd.CommandText = @"select department.id as Departmentid, department.[Name] as departmentName, department.budget, employee.Id as employeeId, employee.FirstName, employee.LastName, employee.isSupervisor, employee.DepartmentId from Department left join employee on Department.Id = employee.DepartmentId Where department.id = @id"; } else { cmd.CommandText = @"select department.id as Departmentid, department.[name] as departmentName, department.budget From department Where department.id = @id"; } cmd.Parameters.Add(new SqlParameter("@id", id)); SqlDataReader reader = cmd.ExecuteReader(); Department department = null; while (reader.Read()) { if (department == null) { department = new Department { id = reader.GetInt32(reader.GetOrdinal("departmentId")), Name = reader.GetString(reader.GetOrdinal("departmentName")), Budget = reader.GetInt32(reader.GetOrdinal("budget")) }; } //this "if" statement includes the details of a product with its corresponding customer in the case that product is included as a search parameter if (include == "employees") { if (!reader.IsDBNull(reader.GetOrdinal("employeeId"))) { department.employeeList.Add( new Employee { Id = reader.GetInt32(reader.GetOrdinal("employeeId")), FirstName = reader.GetString(reader.GetOrdinal("FirstName")), LastName = reader.GetString(reader.GetOrdinal("LastName")), IsSupervisor = reader.GetBoolean(reader.GetOrdinal("isSupervisor")), DepartmentId = reader.GetInt32(reader.GetOrdinal("departmentId")) } ); } } } reader.Close(); return Ok(department); } } } // Posts a new customer to the database [HttpPost] public IActionResult Post([FromBody] Department newDepartment) { using (SqlConnection conn = Connection) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = @"INSERT INTO Department ([name], budget) OUTPUT INSERTED.Id VALUES (@name, @budget)"; cmd.Parameters.Add(new SqlParameter("@name", newDepartment.Name)); cmd.Parameters.Add(new SqlParameter("@budget", newDepartment.Budget)); int newId = (int)cmd.ExecuteScalar(); newDepartment.id = newId; return CreatedAtRoute( new { id = newId }, newDepartment); } } } // Put an existing customer based on customer Id [HttpPut("{id}")] public IActionResult Put(int id, [FromBody] Department updatedDepartment) { using (SqlConnection conn = Connection) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = @"UPDATE Department SET [Name] = @name, Budget = @budget WHERE id = @id"; cmd.Parameters.Add(new SqlParameter("@name", updatedDepartment.Name)); cmd.Parameters.Add(new SqlParameter("@budget", updatedDepartment.Budget)); cmd.Parameters.Add(new SqlParameter("@id", id)); cmd.ExecuteNonQuery(); return NoContent(); } } } } }
a0a0a73fa6291fba30a9cbf6b4ef98d27d3f8d44
C#
shendongnian/download4
/first_version_download2/9781-522245-868151-1.cs
2.859375
3
// In Your Program.cs Convert This static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } // To This static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Form1 TheForm = new Form1(); Application.Run(); } // Call Application.Exit() From Anywhere To Stop Application.Run() Message Pump and Exit Application
a2c6feade955bdc292f40e7b03f87c22d4d83048
C#
oshustov/tg-periodical-jobs-bot
/TelegramReminder/Model/CommandArgs.cs
2.828125
3
using System.Collections.Generic; using Telegram.Bot.Types; namespace TelegramReminder.Model { public class Context { public Update Update { get; } public string Tag { get; set; } public Context(string tag, Update update) { Tag = tag; Update = update; } public LocalContext UseLocal(object with) => new LocalContext(Tag, Update, with); public ExternalContext UseExternal(IReadOnlyDictionary<string, string> with) => new ExternalContext(Tag, Update, with); public LocalContext AsLocal() => this as LocalContext; public ExternalContext AsExternal() => this as ExternalContext; } public class LocalContext : Context { public object Args { get; set; } public LocalContext(string tag, Update update, object args) : base(tag, update) => Args = args ?? new object(); public virtual T UseArgument<T>() where T : class => Args as T; } public class ExternalContext : Context { public IReadOnlyDictionary<string, string> Args { get; set; } public ExternalContext(string tag, Update update, IReadOnlyDictionary<string, string> args) : base(tag, update) { Args = args ?? new Dictionary<string, string>(); } public virtual T UseArgument<T>() where T : class => Arguments.Using<T>(Args); } }
9a312303ea40d42abe62e4c43a65d1741149fc39
C#
Woldelig/Vurderingssystem
/VMS/VMS/fagside.aspx.cs
2.6875
3
using System; using System.Data; using System.Linq; using MySql.Data.MySqlClient; using System.Web.UI.DataVisualization.Charting; using System.Drawing; namespace VMS { public partial class Fagside : System.Web.UI.Page { private Database db = new Database(); private String sidensFagkode = "obj2100"; /* * Dette er bare en statisk variabel så fagsiden alltid viser et resultat */ protected void Page_Load(object sender, EventArgs e) { /* * Under henter vi ut en string query. Denne inneholder * fagkoden siden skal vise. Denne kommer enten fra søk eller en lenke. * Denne blir formatert ved hjelp av formaterQueryString metoden deretter * brukes den i en SQL spørring mot databasen. */ String uformatertQueryString = Request.Url.Query; String formatertQueryString = FormaterQueryString.FormaterString(uformatertQueryString); if (formatertQueryString != "" || formatertQueryString == null) { sidensFagkode = formatertQueryString; } int foreleserId; //Denne trenger vi for å få informasjon om foreleser String query = "SELECT f.*, s.fakultet FROM fag as f, studier as s WHERE f.fagkode = @SidensFagkode AND f.studieretning = s.studieretning"; var cmd = db.SqlCommand(query); cmd.Parameters.AddWithValue("@SidensFagkode", sidensFagkode); db.OpenConnection(); MySqlDataReader leser = cmd.ExecuteReader(); if (!leser.HasRows) { //Hvis fagkoden ikke inneholder informasjon eller er feil sender serveren deg til default.aspx Server.Transfer("Default.aspx"); } leser.Read(); /* * Her blir databaseresultatet skrevet rett inn i labels, * noen av labels inneholder htmlformatering, dette er for å gjøre de * til linker så man lettere kan navigere siden. * ForeleserId blir castet til int fordi den brukes til en sql * spørring lenger nede */ foreleserId = (int)leser[2]; fagkodeLbl.Text = "Fagkode: " + leser[0].ToString(); fagnavnLbl.Text = "Fagnavn: " + leser[1].ToString(); studieretningLbl.Text = "Studieretning: <a href = 'linjeside.aspx?" + leser[3].ToString() + "'>" + leser[3].ToString() + "</a>"; String forkurs = leser[4].ToString(); fakultetLbl.Text = "Fakultet: <a href = 'fakultet.aspx?" + leser[5].ToString() + "'>" + leser[5].ToString() + "</a>"; //Her sjekkes det om forkurs finnes, og skriver ut et forkurs label hvis det eksisterer if (forkurs != "") { forkursLbl.Text = "Forkurs: <a href = 'fagside.aspx?" + forkurs + "'>" + forkurs + "</a>"; } else { forkursLbl.Text = ""; } leser.Close(); db.CloseConnection(); query = "SELECT fornavn, etternavn FROM foreleser WHERE foreleserid = @ForeleserId"; cmd = db.SqlCommand(query); cmd.Parameters.AddWithValue("@ForeleserId", foreleserId); db.OpenConnection(); leser = cmd.ExecuteReader(); leser.Read(); //Setter sammen fornavn og etternavn fra databasen String foreleserNavn = leser[0].ToString() + " " + leser[1].ToString(); leser.Close(); db.CloseConnection(); foreleserLbl.Text = "Foreleser: <a href = 'foreleserside.aspx?" + foreleserNavn + "'>" + foreleserNavn + "</a>"; /* * Under bruker vi en metode for å kalle på database prosedyrene våre * de blir deretter lagt inn i et int array */ int[] prosedyreSvarSpm1 = ProsedyreKaller("hent_spm1_verdier", sidensFagkode, 1); int[] prosedyreSvarSpm2 = ProsedyreKaller("hent_spm2_verdier", sidensFagkode, 2); int[] prosedyreSvarSpm3 = ProsedyreKaller("hent_spm3_verdier", sidensFagkode, 3); int[] prosedyreSvarSpm4 = ProsedyreKaller("hent_spm4_verdier", sidensFagkode, 4); int[] prosedyreSvarSpm5 = ProsedyreKaller("hent_spm5_verdier", sidensFagkode, 5); /* * Under sjekker vi om et eller flere av spørsmålene ikke har data * de uten data blir deretter skjult fra nettsiden, da de mest sannsynlig * ikke er valide. */ int sumSpm1 = prosedyreSvarSpm1.Sum(); int sumSpm2 = prosedyreSvarSpm2.Sum(); int sumSpm3 = prosedyreSvarSpm3.Sum(); int sumSpm4 = prosedyreSvarSpm4.Sum(); int sumSpm5 = prosedyreSvarSpm5.Sum(); /* * if (sumSpm1 != 0 || sumSpm2 != 0 || sumSpm3 != 0 ) * if Setningen under fungerer på samme måte som denne. * istendenfor at vi sjekker en og en variabel, legger vi * de inn i et anonymt array som og brukes Contains metoden til array * klassen */ if (!new int[] { sumSpm1, sumSpm2, sumSpm3, sumSpm4, sumSpm5 }.Contains(0)) { /* * Her kaller vi på en metode som gir oss gjennomsnittet * til spørsmålene, tallene blir lagt til å spm1RatingLbl. * Og for å få det vist som stjerner blir det lagt inn i * spm1RatingStjerne.Value, men her må vi først bytte ut * komma med punktum. Fordi i noen land bruker de punktum * til å vise tall med desimaler */ String gjennomsnittSpm1 = BeregnGjennomsnittsRating(prosedyreSvarSpm1); String gjennomsnittSpm2 = BeregnGjennomsnittsRating(prosedyreSvarSpm2); String gjennomsnittSpm3 = BeregnGjennomsnittsRating(prosedyreSvarSpm3); String gjennomsnittSpm4 = BeregnGjennomsnittsRating(prosedyreSvarSpm4); String gjennomsnittSpm5 = BeregnGjennomsnittsRating(prosedyreSvarSpm5); spm1RatingLbl.Text = gjennomsnittSpm1; spm2RatingLbl.Text = gjennomsnittSpm2; spm3RatingLbl.Text = gjennomsnittSpm3; spm4RatingLbl.Text = gjennomsnittSpm4; spm5RatingLbl.Text = gjennomsnittSpm5; spm1RatingStjerne.Value = gjennomsnittSpm1.Replace(",", "."); spm2RatingStjerne.Value = gjennomsnittSpm2.Replace(",", "."); spm3RatingStjerne.Value = gjennomsnittSpm3.Replace(",", "."); spm4RatingStjerne.Value = gjennomsnittSpm4.Replace(",", "."); spm5RatingStjerne.Value = gjennomsnittSpm5.Replace(",", "."); //Koden under lager kakediagramet String diagramTittel = "Var faget vanskelig?"; String seriesname = "seriesName"; diagram.Series.Clear(); diagram.Legends.Clear(); diagram.Series.Add(seriesname); diagram.Series[seriesname].ChartType = SeriesChartType.Pie; Title tittel = diagram.Titles.Add(diagramTittel); //Her forandreres skrifttypen til diagramtittelen tittel.Font = new System.Drawing.Font("Verdana", 16, System.Drawing.FontStyle.Bold); diagram.Legends.Add("Legende"); diagram.Legends[0].Alignment = StringAlignment.Center; diagram.Legends[0].BorderColor = Color.Black; /* * #PERCENT{P0} Gjør at man får prosenter på diagramet. * og points vil tilsvarer verdiene. De første parameterne * som går fra 1-5 er for å gi punktene en Id så vi kan sette vår egen * forklaring til dem i Legend. Under vil du se at vi vi setter vår egen * tekst i legende ved å gjøre slik: * diagram.Series[seriesname].Points[0].LegendText = "Svært misfornøyd"; */ diagram.Series[seriesname].Label = "#PERCENT{P0}"; diagram.Series[seriesname].Points.AddXY(0, prosedyreSvarSpm1[1]); diagram.Series[seriesname].Points.AddXY(1, prosedyreSvarSpm1[2]); diagram.Series[seriesname].Points.AddXY(2, prosedyreSvarSpm1[3]); diagram.Series[seriesname].Points.AddXY(3, prosedyreSvarSpm1[4]); diagram.Series[seriesname].Points.AddXY(4, prosedyreSvarSpm1[5]); //Teksten under er den som kommer opp i legend. diagram.Series[seriesname].Points[0].LegendText = "Svært misfornøyd"; diagram.Series[seriesname].Points[1].LegendText = "Litt misfornøyd"; diagram.Series[seriesname].Points[2].LegendText = "Hverken/eller"; diagram.Series[seriesname].Points[3].LegendText = "Litt fornøyd"; diagram.Series[seriesname].Points[4].LegendText = "Meget fornøyd"; } else { /* * Hvis if setningen feiler fordi en av verdiene inneholder 0, * vil det si at det ikke er foretatt en fagvurdering i faget * og siden vil kun vise foreleser, fagkode osv. */ pensumLbl.ForeColor = System.Drawing.Color.Red; pensumLbl.Text = "Det er ikke foretatt en fagvurdering i dette faget. Prøv igjen senere."; //Kodesnutten under trenger vi for å skjule rateit. Uten den vil stjernene vises spm1Div.InnerHtml = ""; spm2Div.InnerHtml = ""; spm3Div.InnerHtml = ""; spm4Div.InnerHtml = ""; spm5Div.InnerHtml = ""; kvalitetLbl.Text = ""; vanskelighetsgradLbl.Text = ""; pensumFormidlingLbl.Text = ""; fagRelevantLbl.Text = ""; } } private String BeregnGjennomsnittsRating(int[] prosedyreSvar) { double spmGjennomsnittsRating = 0; //Arrayet som sendes inn her må tilhøre det spørsmålet du ønsker å gjøre en gjennomsnittsberegning på int totalSpmRating = prosedyreSvar[1] * 1 + prosedyreSvar[2] * 2 + prosedyreSvar[3] * 3 + prosedyreSvar[4] * 4 + prosedyreSvar[5] * 5; /* * Grunnen til at prosedyre svar må ganges opp er fordi den kun teller antall forekomster, så for å få den korrekte gjennomsnittsverdien * må vi gange opp verdiene så vi for den riktige totalsummen så vi kan få gjennomsnittet * * Under må det brukes en try catch fordi det er en mulighet for DivideByZeroException */ try { spmGjennomsnittsRating = (double)totalSpmRating / (double)prosedyreSvar[0]; } catch (DivideByZeroException) { //Response.Write(e); //Denne ble brukt til debugging } //Runder av gjennomsnittet til å vise en desimal og returner verdien som en string return Math.Round(spmGjennomsnittsRating, 1).ToString(); } private int[] ProsedyreKaller(String prosedyreNavn, String fagkode, int spmnr) { /* * Denne metoden kaller på prosedyrer så vi får telling over alle verdier * derfor trenger vi fagkoden, prosedyrenr og spmnr som inn parameter, man * vil få tilbake et int array som resultat etter å ha kalt på metoden * Posisjon 0 i arrayet vil innehold antall svar per spm */ var cmd = db.SqlCommand(""); //prosedyrenavn må være helt likt som i db cmd.CommandText = prosedyreNavn; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@in_fagkode", fagkode).Direction = ParameterDirection.Input; cmd.Parameters.AddWithValue("@out_verdi1", MySqlDbType.Int32).Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@out_verdi2", MySqlDbType.Int32).Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@out_verdi3", MySqlDbType.Int32).Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@out_verdi4", MySqlDbType.Int32).Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@out_verdi5", MySqlDbType.Int32).Direction = ParameterDirection.Output; db.OpenConnection(); cmd.ExecuteNonQuery(); int stjerne1 = (int)cmd.Parameters["@out_verdi1"].Value; int stjerne2 = (int)cmd.Parameters["@out_verdi2"].Value; int stjerne3 = (int)cmd.Parameters["@out_verdi3"].Value; int stjerne4 = (int)cmd.Parameters["@out_verdi4"].Value; int stjerne5 = (int)cmd.Parameters["@out_verdi5"].Value; db.CloseConnection(); String telleProsedyreNavn = "telle_svar_skjemaer"; /* * Denne prosedyren teller opp antall svar som har kommet per fagkode og spm * dette tallet kan vi dele på den totale summen vi får senere for å finne ut * gjennomsnittsverdien til vært enkelt spm */ cmd = db.SqlCommand(telleProsedyreNavn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@in_fagkode", fagkode).Direction = ParameterDirection.Input; cmd.Parameters.AddWithValue("@out_verdi1", MySqlDbType.Int32).Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@in_spmnr", spmnr).Direction = ParameterDirection.Input; db.OpenConnection(); cmd.ExecuteNonQuery(); int totaltAntallSvar = (int)cmd.Parameters["@out_verdi1"].Value; db.CloseConnection(); int[] rating = new int[] { totaltAntallSvar, stjerne1, stjerne2, stjerne3, stjerne4, stjerne5 }; return rating; } } }
3f135481055b2d0eab7af9ec41555333cbdbd284
C#
cesar9401/PracticaCorta
/Practica/MainWindow.cs
2.53125
3
using System; using System.Collections.Generic; using Gtk; using Practica; public partial class MainWindow : Gtk.Window { public MainWindow() : base(Gtk.WindowType.Toplevel) { Build(); } protected void OnDeleteEvent(object sender, DeleteEventArgs a) { Application.Quit(); a.RetVal = true; } protected void OnAnalizarButtonClicked(object sender, EventArgs e) { String oracion = entradaText.Text; if (oracion.Equals("")) { MessageDialog md = new MessageDialog(null, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, "Ingresa una oracion para analizar"); md.Run(); md.Destroy(); } else { Logica logic = new Logica(); logic.setOracion(oracion); labelPalabras.Text = logic.Palabras(); labelNumeros.Text = logic.Numeros(); labelDecimales.Text = logic.Decimales(); labelMonedas.Text = logic.Monedas(); labelErrores.Text = logic.Errores(); } } }
434749d5937f06b4b32cf732b98ebb6cc1940752
C#
JDR-Ninja/CIV
/CIV/Mail/MailTagFormater.cs
2.921875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Videotron; using CIV.Common; using System.Collections; namespace CIV.Mail { /// <summary> /// Parcours du texte pour convertir les tags rencontrés avec les valeurs du compte associé /// </summary> public class MailTagFormater { private const string MAIL_TAG = @"\[(?<tag>{0})(\((?<param>[^\)]*)?\))?\]"; private const string METHOD_PARAM = @"(?<method>[a-z]{3,})=(?<param>[^,]+)"; private VideotronAccount _account; private MailTagFactory _factory; private List<string> _tags; /// <summary> /// Initialise le constructeur /// </summary> /// <param name="account">Le compte vidéotron à utiliser pour la conversion</param> public MailTagFormater(VideotronAccount account) { _account = account; _factory = new MailTagFactory(_account); _tags = new List<string>(); _tags.Add("NAME"); _tags.Add("USERNAME"); _tags.Add("PERIOD_START"); _tags.Add("PERIOD_END"); _tags.Add("DAY_REMAINING"); _tags.Add("UPLOAD_PERCENT"); _tags.Add("UPLOAD"); _tags.Add("DOWNLOAD_PERCENT"); _tags.Add("DOWNLOAD"); _tags.Add("TOTAL_COMBINED_PERCENT"); _tags.Add("TOTAL_COMBINED_REMAINING"); _tags.Add("TOTAL_COMBINED_MAX"); _tags.Add("TOTAL_COMBINED"); _tags.Add("SUGGEST_DAILY_USAGE"); _tags.Add("OVERCHARGE"); _tags.Add("NOW"); _tags.Add("LAST_UPDATE"); _tags.Add("AVERAGE_COMBINED"); _tags.Add("SUGGEST_COMBINED"); _tags.Add("ESTIMATE_COMBINED"); //_tags.Add("ESTIMATE_TOTAL_COMBINED"); _tags.Add("SUGGEST_COMBINED_PERCENT"); _tags.Add("THEORY_DAILY_COMBINED"); _tags.Add("THEORY_COMBINED"); _tags.Add("THEORY_COMBINED_DIFFERENCE"); } /// <summary> /// Format une valeur en fonction des paramètres défini /// </summary> /// <param name="tag">Le tag trouvé dans le texte</param> /// <param name="param">Chaine de caractère représentant les fonctions à appliquer</param> /// <returns>Le nouvelle valeur</returns> private string Format(string tag, string param) { MailTagTypes type = _factory.GetType(tag); if (type != MailTagTypes.None) { try { // Si c'est une date if (_factory.IsDateTime(type)) { return FormatDateTime(type, param); } // Si c'est un double else if (_factory.IsDouble(type)) { return FormatDouble(type, param); } // Si c'est un pourcentage else if (_factory.IsPercent(type)) { return FormatPercent(type, param); } // Si c'est un integer else if (_factory.IsInt(type)) { return _factory.GetIntValue(type).ToString(); } // Si c'est de la monnaie else if (_factory.IsCurrency(type)) { return FormatCurrency(type, param); } // Si c'est du texte else { return _factory.GetStringValue(type); } } catch (Exception formatExcep) { return String.Format("({0})", formatExcep.Message); } } return string.Empty; } /// <summary> /// Converti un tag de format DateTime en une valeur string /// </summary> /// <param name="type">Le nom du tag</param> /// <param name="param">Les méthodes</param> /// <returns>La valeur à insérer dans le texte</returns> private string FormatDateTime(MailTagTypes type, string param) { Match paramMatch = Regex.Match(param, METHOD_PARAM, RegexOptions.IgnoreCase); while (paramMatch.Success) { if (paramMatch.Groups["method"].Value.ToUpper() == "FORMAT") { return _factory.GetDateTimeValue(type).ToString(paramMatch.Groups["param"].Value); } paramMatch = paramMatch.NextMatch(); } return _factory.GetDateTimeValue(type).ToShortDateString(); } private string FormatDouble(MailTagTypes type, string param) { double value = _factory.GetDoubleValue(type); SIUnitTypes unit = ProgramSettings.Instance.ShowUnitType; Match paramMatch = Regex.Match(param, METHOD_PARAM, RegexOptions.IgnoreCase); while (paramMatch.Success) { if (paramMatch.Groups["method"].Value.ToUpper() == "ROUND") value = System.Math.Round(value, Int32.Parse(paramMatch.Groups["param"].Value)); else if (paramMatch.Groups["method"].Value.ToUpper() == "UNIT") { switch (paramMatch.Groups["param"].Value.ToUpper()) { case "G": unit = SIUnitTypes.Go; break; case "M": unit = SIUnitTypes.Mo; break; case "K": unit = SIUnitTypes.ko; break; } } paramMatch = paramMatch.NextMatch(); } return UnitsConverter.SIUnitToString(value, unit); } private string FormatPercent(MailTagTypes type, string param) { double value = _factory.GetPercentValue(type) * 100; int round = 2; Match paramMatch = Regex.Match(param, METHOD_PARAM, RegexOptions.IgnoreCase); while (paramMatch.Success) { if (paramMatch.Groups["method"].Value.ToUpper() == "ROUND") round = Int32.Parse(paramMatch.Groups["param"].Value); paramMatch = paramMatch.NextMatch(); } value = System.Math.Round(value, round); return value.ToString(); } private string FormatCurrency(MailTagTypes type, string param) { double value = _factory.GetCurrencyValue(type); return value.ToString("C"); } /// <summary> /// Parcours un texte et transforme les tags rencontrés /// </summary> /// <param name="text">Le texte à analyser</param> /// <returns>Le texte avec les tags convertis en valeur</returns> public string Convert(string text) { StringBuilder result = new StringBuilder(text); Match tagMatch; foreach (string key in _tags) { int delta = 0; // %DOWNLOAD_PERCENT[format:ff gg,round:2]% tagMatch = Regex.Match(result.ToString(), String.Format(MAIL_TAG, key)); // Le tag est présent dans le modèle while (tagMatch.Success) { result.Remove(tagMatch.Index + delta, tagMatch.Length); string newValue = Format(tagMatch.Groups["tag"].Value, tagMatch.Groups["param"].Value); result.Insert(tagMatch.Index + delta, newValue); if (tagMatch.Length > newValue.Length) delta -= tagMatch.Length - newValue.Length; else if (tagMatch.Length < newValue.Length) delta += newValue.Length - tagMatch.Length; tagMatch = tagMatch.NextMatch(); } } return result.ToString(); } } }
7ab8d43fe586ef1429f0b95d55787ecb24198b06
C#
MaevaValls/ProyectoM13
/Assets/Scripts/Models/Cards/Abilities/Target Selectors/RandomTarget.cs
2.8125
3
using System.Collections.Generic; using Atonement.AspectContainer; using Atonement.Extensions; //Selector que aplicará la habilidad a uno o más objetivos aleatorios public class RandomTarget : Aspect, ITargetSelector { public Mark mark; public int count = 1; public List<Card> SelectTargets (IContainer game) { var result = new List<Card> (); var system = game.GetAspect<TargetSystem> (); var card = (container as Ability).card; var marks = system.GetMarks (card, mark); if (marks.Count == 0) return result; for (int i = 0; i < count; ++i) { result.Add (marks.Random ()); } return result; } public void Load(Dictionary<string, object> data) { var markData = (Dictionary<string, object>)data["mark"]; mark = new Mark (markData); count = System.Convert.ToInt32(data ["count"]); } }
4b46d93d6f1e92c8fc9a9fc6255ec9586ff6eadf
C#
dant02/snippets
/dotnet/app.console/PalallelTest.cs
3.296875
3
using System; namespace app.console { internal class PalallelTest { private void Calculate() { var r5 = SimulateCalculation.Calculate(5); var r6 = SimulateCalculation.Calculate(6); var r7 = SimulateCalculation.Calculate(7); Console.WriteLine(r5 + r6 + r7); } } internal class SimulateCalculation { public static double Calculate(double x) { var ticks = Environment.TickCount; for (int i = 0; i < 100_000_000; i++) { x = 1 + Math.Log10(x); } Console.WriteLine(Environment.TickCount - ticks + " calculated: " + x); return x; } } }
5ac05a43375293312023e7c1b0bbd8eb80e582ff
C#
FeFi7/CarrierTracking
/Software/CarrierTracking/Assets/Scripts/VisualStations/LinkedStationList.cs
3.25
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LinkedStationList { private readonly List<Station> stations; private int number = 1; private Station start = null; private Station end = null; private Station selected = null; public LinkedStationList() { stations = new List<Station>(); } //registers a station in the list public void Add(Station Station) { if(GetStationByID(Station.GetID()) != null) { Debug.Log("[PROBLEM] Station ID bereits existent!..."); return; } if (stations.Count < 1) { start = Station; end = Station; Station.LinkNextStation(Station); Station.LinkPreviousStation(Station); } else { end.LinkNextStation(Station); Station.LinkPreviousStation(end); Station.LinkNextStation(start); start.LinkPreviousStation(Station); end = Station; } stations.Add(Station); number++; } public List<Station> GetAllStation() { return stations; } public void SelectNext() { selected = selected.GetNextStation(); } public void SelectPrevious() { selected = selected.GetPreviousStation(); } public void SelectNewest() { selected = end; } public void Select(Station station) { selected = station; } public Station GetSelected() { return selected; } public void DeleteSelected() { Station bridge = selected; bridge.GetPreviousStation().LinkNextStation(bridge.GetNextStation()); bridge.GetNextStation().LinkPreviousStation(bridge.GetPreviousStation()); stations.Remove(bridge); SelectPrevious(); } public int GetSize() { return stations.Count; } public int GetNextStationNumber() { return number; } public List<GameObject> GetAllAreas() { List<GameObject> areas = new List<GameObject>(); Station next = start; for (int i = 0; i < stations.Count; i++) { foreach (GameObject area in next.GetAreaObjects()) { areas.Add(area); } next = next.GetNextStation(); } return areas; } public List<string> GetAllNames() { List<string> stationNames = new List<string>(); Station next = start; for (int i = 0; i < stations.Count; i++) { stationNames.Add(next.GetName()); next = next.GetNextStation(); } return stationNames; } public Station GetStationByID(string id) { Station current = start; for (int i = 0; i < stations.Count; i++) { if (current.GetID().Equals(id)) return current; current = current.GetNextStation(); } return null; } public Station GetStationByName(string name) { Station current = start; for (int i = 0; i < stations.Count; i++) { if (current.GetName().Equals(name)) return current; current = current.GetNextStation(); } return null; } }
9ce49c75b0d210e85272191618fa324b3371ba8e
C#
kritsadadechawantana/hackathon01-url-mapper
/UrlMapper.Tests/UnitTest1.cs
2.6875
3
using System; using System.Collections.Generic; using Xunit; namespace UrlMapper.Tests { public class UnitTest1 { //[Fact] //public void Test_Matching() //{ // var strBuilder = new SimpleStringParameterBuilder(); // var strParam = strBuilder.Parse("http://google.com/{user}/aa"); // var isMatched = strParam.IsMatched("http://google.com//aa"); // Assert.Equal(true, isMatched); //} //[Theory] //[InlineData("https://mana.com/linkto/{link-id}", new string[] { "https://mana.com/linkto/", "{link-id}" })] //[InlineData("http://google.com/?s={keyword}&a={hgyyh}", new string[] { "http://google.com/?s=", "{keyword}", "&a=", "{hgyyh}" })] //[InlineData("https://mana.com/app/{app-id}/services/{service-id}", new string[] { "https://mana.com/app/", "{app-id}", "/services/", "{service-id}" })] //[InlineData("https://mana.com/app/{app/-id}/services/{service-id}", new string[] { "https://mana.com/app/", "{app/-id}", "/services/", "{service-id}" })] //public void Test_GetPatterns(string pattern, string[] expected) //{ // var strParam = new SimpleStringParameter(pattern); // var result = strParam.GetPatterns(pattern); // Assert.Equal(expected, result); //} //[Theory] //[InlineData("https://mana.com/linkto/A2348", new string[] { "https://mana.com/linkto/", "{link-id}" }, true)] //[InlineData("http://google.com/?s=value1&a=value2", new string[] { "http://google.com/?s=", "{keyword}", "&a=", "{hgyyh}" }, true)] //[InlineData("http://google.com/?s=value1&a=", new string[] { "http://google.com/?s=", "{keyword}", "&a=" }, true)] //[InlineData("https://mana.com/linkto/A2348/services", new string[] { "https://mana.com/linkto/", "{link-id}" ,"services"}, true)] //public void Test_IsRoutMatch(string url, string[] patternParams, bool expected) //{ // var strParam = new SimpleStringParameter(string.Empty); // var result = strParam.IsRoutMatch(url, patternParams); // Assert.Equal(expected, result); //} //[Fact] //public void Test_GetValueFromUrl() //{ // var url = "https://mana.com/linkto/A2348"; // var patternParams = new string[] { "https://mana.com/linkto/", "{link-id}" }; // var expected = new Dictionary<string, string>{{"{link-id}", "A2348"}}; // var strParam = new SimpleStringParameter(string.Empty); // var result = strParam.GetValueFromUrl(url, patternParams); // Assert.Equal(expected, result); //} //[Fact] //public void Test_GetValueFromUrl2() //{ // var url = "http://hackathon.com/test 123/none"; // var patternParams = new string[] { "http://hackathon.com/", "{username}" ,"/none"}; // var expected = new Dictionary<string, string> { { "{username}", "test 123" } }; // var strParam = new SimpleStringParameter(string.Empty); // var result = strParam.GetValueFromUrl(url, patternParams); // Assert.Equal(expected, result); //} //[Fact] //public void Test_GetValueFromUrl3() //{ // var url = "http://hackathon.com/test/123/none"; // var patternParams = new string[] { "http://hackathon.com/", "{username}", "/none" }; // var expected = new Dictionary<string, string> { { "{username}", "test/123" } }; // var strParam = new SimpleStringParameter(string.Empty); // var result = strParam.GetValueFromUrl(url, patternParams); // Assert.Equal(expected, result); //} [Fact] public void Test_GetValueFromUrl4() { var url = "http://google.com/"; var patternParams = new string[] { "http://google.com/","{user}" }; var expected = new Dictionary<string, string> { { "{user}", "" } }; var strParam = new SimpleStringParameter(string.Empty); var result = strParam.GetValueFromUrl(url, patternParams); Assert.Equal(expected, result); } } }
a28c12c487bb9abb8bb02f502fca1fa25d59e227
C#
pavelangelov/CSharp-OOP-Homework
/02.DefiningClasses-Part2/5-7.GenericClass/Models/GenericList.cs
3.875
4
namespace _5_7.GenericClass.Models { using System; using System.Text; public class GenericList<T> where T : IComparable { private T[] list; private uint index; public GenericList(uint capacity) { if (capacity < 1) { throw new ArgumentException("The capacity must be greater than 0!"); } this.list = new T[capacity]; this.index = 0; } public T[] List { get { return this.list; } private set { this.list = value; } } public T this[int i] { get { if (i >= index) { throw new IndexOutOfRangeException(); } return this.List[i]; } set { if (i > index) { throw new IndexOutOfRangeException(); } this.List[i] = value; } } public void Add(T element) { if (index == list.Length) { list = IncreaseArrayLength(list); } this.List[index] = element; index++; } public void Insert(int possition, T element) { if (possition >= index) { throw new IndexOutOfRangeException(); } var tempArr = new T[list.Length]; var tempArrIndex = 0; for (int i = 0; i < list.Length; i++) { if (tempArrIndex == tempArr.Length) { tempArr = IncreaseArrayLength(tempArr); } if (tempArrIndex == possition) { tempArr[tempArrIndex] = element; i--; } else { tempArr[tempArrIndex] = list[i]; } tempArrIndex++; } list = tempArr; index++; } /// <summary> /// Return the index of the first occurrence /// </summary> /// <param name="element"></param> /// <returns></returns> public int IsContain(T element) { return Array.IndexOf(list, element); } /// <summary> /// Remove element on given possition /// </summary> /// <param name="possition"></param> public void Remove(int possition) { if (possition >= index) { throw new IndexOutOfRangeException(); } var tempArr = new T[list.Length]; var tempArrIndex = 0; for (int i = 0; i < list.Length; i++) { if (possition == i) { continue; } else { tempArr[tempArrIndex] = list[i]; } tempArrIndex++; } list = tempArr; index--; } public override string ToString() { var sb = new StringBuilder(); for (int i = 0; i < index; i++) { if (i == index) { sb.Append(list[i]); } else { sb.Append(list[i] + ", "); } } return sb.ToString(); } /// <summary> /// Remove all elemnts from the list, but keep the capacity /// </summary> public void Clear() { var newArr = new T[list.Length]; index = 0; list = newArr; } public T Min() { T min = list[0]; for (int i = 1; i < index; i++) { if (min.CompareTo(list[i]) > 0) { min = list[i]; } } return min; } public T Max() { T max = list[0]; for (int i = 1; i < index; i++) { if (max.CompareTo(list[i]) < 0) { max = list[i]; } } return max; } private T[] IncreaseArrayLength(T[] array) { T[] newArr = new T[array.Length * 2]; for (int i = 0; i < array.Length; i++) { newArr[i] = array[i]; } return newArr; } } }
48571a7a48875687e493cbe15139f14ff61210d3
C#
Franciscoscp/zft
/Zip.cs
2.75
3
using Microsoft.AspNetCore.SignalR; using System; using System.Collections.Generic; using System.IO.Compression; using System.Linq; using System.Threading.Tasks; namespace zft { public class Zip { public int id { get; set; } public string name { get; set; } public Uri zipUri { get; set; } public LinkedList<zip.ZipInfo> data { get; set; } public override string ToString() { return base.ToString()+ " - "+zipUri.ToString(); } } } namespace zip { public class ZipInfo { public string name { get; set; } long _compressedSize; public double compressedSize { get { return ConvertBytesToKbytes(_compressedSize); } set { _compressedSize = (long)value; } } long _fullSize; public double fullSize { get { return ConvertBytesToKbytes(_fullSize); } set { _fullSize = (long)value; } } static double ConvertBytesToKbytes(long bytes) { return (bytes / 1024f); } } }
1862dd59e42ab475c43220650957dc588a86e6fe
C#
AndreasBieber/TypedRest-DotNet
/TypedRest.Wpf/ViewModels/PollingViewModel.cs
2.65625
3
using System; using System.Threading.Tasks; using Caliburn.Micro; namespace TypedRest.Wpf.ViewModels { /// <summary> /// View model for tracking the state of an entity represented by a <see cref="IPollingEndpoint{TEntity}"/>. /// </summary> /// <typeparam name="TEntity">The type of entity to represent.</typeparam> public class PollingViewModel<TEntity> : ElementViewModelBase<TEntity, IPollingEndpoint<TEntity>> { public PollingViewModel(IPollingEndpoint<TEntity> endpoint, IEventAggregator eventAggregator) : base(endpoint, eventAggregator) { } protected override async Task OnLoadAsync() { Entity = await Endpoint.ReadAsync(CancellationToken); DisplayName = Entity.ToString(); NotifyOfPropertyChange(() => Entity); } /// <summary> /// Controls whether a save button is shown and fields are editable. /// </summary> public bool CanSave => false; protected override Task OnSaveAsync() { throw new NotImplementedException(); } } }