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
1620088cb384b9c8e9e1f5c812cf8cd48981174b
C#
mei-rune/jingxian-project
/jingxian-mailer/jingxian.ui.controls/FastListView/FastObjectListView.cs
2.625
3
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Drawing.Design; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Windows.Forms; using System.Runtime.Serialization.Formatters.Binary; namespace jingxian.ui.controls.fastlistview { /// <summary> /// A FastObjectListView trades function for speed. /// </summary> /// <remarks> /// <para>On my mid-range laptop, this view builds a list of 10,000 objects in 0.1 seconds, /// as opposed to a normal ObjectListView which takes 10-15 seconds. Lists of up to 50,000 items should be /// able to be handled with sub-second response times even on low end machines.</para> /// <para> /// A FastObjectListView is implemented as a virtual list with some of the virtual modes limits (e.g. no sorting) /// fixed through coding. There are some functions that simply cannot be provided. Specifically, a FastObjectListView cannot: /// <list> /// <item>shows groups</item> /// <item>use Tile view</item> /// <item>display images on subitems</item> /// </list> /// </para> /// <para>You can circumvent the limit on subitem images by making the list owner drawn, and giving the column /// a Renderer of BaseRenderer, e.g. <code>myColumnWithImage.Renderer = new BaseRenderer();</code> </para> /// </remarks> public class FastObjectListView : VirtualObjectListView { public FastObjectListView() { this.SearchForVirtualItem += new SearchForVirtualItemEventHandler(FastObjectListView_SearchForVirtualItem); this.CustomSorter = delegate(OLVColumn column, SortOrder sortOrder) { this.lastRetrieveVirtualItemIndex = -1; if (sortOrder != SortOrder.None) this.objectList.Sort(new ModelObjectComparer(column, sortOrder, this.SecondarySortColumn, this.SecondarySortOrder)); this.objectsToIndexMap.Clear(); for (int i = 0; i < this.objectList.Count; i++) this.objectsToIndexMap[this.objectList[i]] = i; }; } Hashtable objectsToIndexMap = new Hashtable(); #region Public properties /// <summary> /// Get/set the list of objects that are shown by the control. /// </summary> /// <remarks> /// <para>This method preserves selection, if possible. Use SetObjects() if /// you do not want to preserve the selection. Preserving selection is the slowest part of this /// code and performance is O(n) where n is the number of selected rows.</para> /// <para>This method is not thread safe.</para> /// </remarks> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] new public ArrayList Objects { get { return this.objectList; } set { ArrayList previousSelection = this.SelectedObjects; this.SetObjects(value); this.SelectedObjects = previousSelection; } } private ArrayList objectList = new ArrayList(); /// <summary> /// When the user types into a list, should the values in the current sort column be searched to find a match? /// If this is false, the primary column will always be used regardless of the sort column. /// </summary> /// <remarks>When this is true, the behavior is like that of ITunes.</remarks> [Category("Behavior"), Description("When the user types into a list, should the values in the current sort column be searched to find a match?"), DefaultValue(false)] public bool IsSearchOnSortColumn { get { return isSearchOnSortColumn; } set { isSearchOnSortColumn = value; } } private bool isSearchOnSortColumn = false; #endregion #region Commands /// <summary> /// Set the collection of objects that this control will show. /// </summary> /// <param name="collection"></param> override public void SetObjects(IEnumerable collection) { if (this.InvokeRequired) { this.Invoke(new SetObjectsInvoker(this.SetObjects), new object[] { collection }); return; } if (collection == null) this.objectList = new ArrayList(); else if (collection is ICollection) this.objectList = new ArrayList((ICollection)collection); else { this.objectList = new ArrayList(); foreach (object x in collection) this.objectList.Add(x); } this.VirtualListSize = this.objectList.Count; this.Sort(); } #endregion #region Event Handlers /// <summary> /// Event handler for the column click event /// </summary> /// <remarks> /// This differs from its base version by trying to preserve selection. The base class, /// being a pure virtual list, cannot maintain selection since it cannot map a /// model objects to the row that is responsible for displaying it. This class can do that. /// </remarks> override protected void HandleColumnClick(object sender, ColumnClickEventArgs e) { // Toggle the sorting direction on successive clicks on the same column if (this.lastSortColumn != null && e.Column == this.lastSortColumn.Index) this.lastSortOrder = (this.lastSortOrder == SortOrder.Descending ? SortOrder.Ascending : SortOrder.Descending); else this.lastSortOrder = SortOrder.Ascending; this.BeginUpdate(); ArrayList previousSelection = this.SelectedObjects; this.Sort(e.Column); this.SelectedObjects = previousSelection; this.EndUpdate(); } void FastObjectListView_SearchForVirtualItem(object sender, SearchForVirtualItemEventArgs e) { // The event has e.IsPrefixSearch, but as far as I can tell, this is always false (maybe that's different under Vista) // So we ignore IsPrefixSearch and IsTextSearch and always to a case insensitve prefix match int increment = (e.Direction == SearchDirectionHint.Up ? -1 : 1); OLVColumn column = this.GetColumn(0); if (this.IsSearchOnSortColumn && this.View == View.Details && this.lastSortColumn != null) column = this.lastSortColumn; int i; for (i = e.StartIndex; i >= 0 && i < this.objectList.Count; i += increment) { string data = column.GetStringValue(this.objectList[i]); if (data.StartsWith(e.Text, StringComparison.CurrentCultureIgnoreCase)) { e.Index = i; return; } } // Also the LVFINDINFO has a LV_WRAP flag, but the SearchForVirtualItemEventArgs does not. Why? // We always wrap i = (increment < 0 ? this.objectList.Count : 0); while ((increment < 0 && i > e.StartIndex) || (increment > 0 && i < e.StartIndex)) { string data = column.GetStringValue(this.objectList[i]); if (data.StartsWith(e.Text, StringComparison.CurrentCultureIgnoreCase)) { e.Index = i; return; } i += increment; } } #endregion #region Object manipulation /// <summary> /// Select the row that is displaying the given model object. /// </summary> /// <param name="modelObject">The object that gave data</param> override public void SelectObject(object modelObject) { if (!this.objectsToIndexMap.ContainsKey(modelObject)) return; int index = (int)this.objectsToIndexMap[modelObject]; // If this object is already selected, we don't need to do anything if (this.SelectedIndices.Count == 1 && this.SelectedIndices[0] == index) return; this.SelectedIndices.Clear(); if (index >= 0) this.SelectedIndices.Add(index); } /// <summary> /// Select the rows that is displaying any of the given model object. /// </summary> /// <param name="modelObjects">A collection of model objects</param> override public void SelectObjects(IList modelObjects) { this.SelectedIndices.Clear(); foreach (object model in modelObjects) { if (this.objectsToIndexMap.ContainsKey(model)) { int index = (int)this.objectsToIndexMap[model]; if (index >= 0) this.SelectedIndices.Add(index); } } } /// <summary> /// Update the rows that are showing the given objects /// </summary> override public void RefreshObjects(IList modelObjects) { this.Invalidate(); } #endregion #region Implementation /// <summary> /// Return the row object for the given row index /// </summary> /// <param name="index">index of the row whose object is to be fetched</param> /// <returns>A model object or null if no delegate is installed</returns> override protected object GetRowObjectAt(int index) { return this.objectList[index]; } internal class ModelObjectComparer : IComparer { public ModelObjectComparer(OLVColumn col, SortOrder order) { this.column = col; this.sortOrder = order; this.secondComparer = null; } public ModelObjectComparer(OLVColumn col, SortOrder order, OLVColumn col2, SortOrder order2) : this(col, order) { // There is no point in secondary sorting on the same column if (col != col2) this.secondComparer = new ModelObjectComparer(col2, order2); } public int Compare(object x, object y) { int result = 0; object x1 = this.column.GetValue(x); object y1 = this.column.GetValue(y); if (this.sortOrder == SortOrder.None) return 0; // Handle nulls. Null values come last bool xIsNull = (x1 == null || x1 == System.DBNull.Value); bool yIsNull = (y1 == null || y1 == System.DBNull.Value); if (xIsNull || yIsNull) { if (xIsNull && yIsNull) result = 0; else result = (xIsNull ? -1 : 1); } else { result = this.CompareValues(x1, y1); } if (this.sortOrder == SortOrder.Descending) result = 0 - result; // If the result was equality, use the secondary comparer to resolve it if (result == 0 && this.secondComparer != null) result = this.secondComparer.Compare(x, y); return result; } public int CompareValues(object x, object y) { // Force case insensitive compares on strings if (x is String) return String.Compare((String)x, (String)y, true); else { IComparable comparable = x as IComparable; if (comparable != null) return comparable.CompareTo(y); else return 0; } } private OLVColumn column; private SortOrder sortOrder; private ModelObjectComparer secondComparer; } #endregion } }
fabaeeffbd99cca7e81066d65c3284ff3446ac61
C#
Zgencheva/Advanced
/MultidimensionalArrays/7.KnightGame/Program.cs
3.28125
3
using System; using System.Diagnostics.Tracing; using System.Linq; namespace _7.KnightGame { class Program { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); char[,] matrix = ReadMatrix(n, n); int maxStrikes = int.MinValue; int rowPossition = 0; int colPossition = 0; bool AreThereKnightsLeft = true; int counter = 0; while (AreThereKnightsLeft) { int totalStrikesForTheMatrix = 0; for (int rows = 0; rows < matrix.GetLength(0); rows++) { for (int cols = 0; cols < matrix.GetLength(1); cols++) { if (matrix[rows, cols] == '0') { continue; } int strikes = 0; bool possition1 = false; //two left, one up if (cols - 2 >= 0 && rows - 1 >= 0) { possition1 = true; if (matrix[rows - 1, cols - 2] == 'K') { strikes++; totalStrikesForTheMatrix++; } } bool possition2 = false; //two up, one left if (rows - 2 >= 0 && cols - 1 >= 0) { possition2 = true; if (matrix[rows - 2, cols - 1] == 'K') { strikes++; totalStrikesForTheMatrix++; } } bool possition3 = false; //two up, one right if (rows - 2 >= 0 && cols + 1 < n) { possition3 = true; if (matrix[rows - 2, cols + 1] == 'K') { strikes++; totalStrikesForTheMatrix++; } } bool possition4 = false; //two right, one up if (rows - 1 >= 0 && cols + 2 < n) { possition4 = true; if (matrix[rows - 1, cols + 2] == 'K') { strikes++; totalStrikesForTheMatrix++; } } bool possition5 = false; //two right, one down if (rows + 1 < n && cols + 2 < n) { possition5 = true; if (matrix[rows + 1, cols + 2] == 'K') { strikes++; totalStrikesForTheMatrix++; } } bool possition6 = false; //one right, two down if (rows + 2 < n && cols + 1 < n) { possition6 = true; if (matrix[rows + 2, cols + 1] == 'K') { strikes++; totalStrikesForTheMatrix++; } } bool possition7 = false; //two down, one left if (rows + 2 < n && cols - 1 >= 0) { possition7 = true; if (matrix[rows + 2, cols - 1] == 'K') { strikes++; totalStrikesForTheMatrix++; } } bool possition8 = false; //one down, two left if (rows + 1 < n && cols - 2 >= 0) { possition8 = true; if (matrix[rows + 1, cols - 2] == 'K') { strikes++; totalStrikesForTheMatrix++; } } if (strikes > maxStrikes) { maxStrikes = strikes; rowPossition = rows; colPossition = cols; } } } if (totalStrikesForTheMatrix == 0) { AreThereKnightsLeft = false; } else { matrix[rowPossition, colPossition] = '0'; counter++; maxStrikes = 0; rowPossition = 0; colPossition = 0; } } Console.WriteLine(counter); } static char[,] ReadMatrix(int rows, int cols) { char[,] matrix = new char[rows, cols]; for (int row = 0; row < matrix.GetLength(0); row++) { string rowData = Console.ReadLine(); for (int col = 0; col < matrix.GetLength(1); col++) { matrix[row, col] = rowData[col]; } } return matrix; } static void GetMatrix(char[,] matrix) { for (int row = 0; row < matrix.GetLength(0); row++) { for (int col = 0; col < matrix.GetLength(1); col++) { Console.Write(matrix[row, col] + " "); } Console.WriteLine(); } } } }
1d6e8d222ebed097747223e8f9c66a96793841d5
C#
Glaerd/Formation-projects
/2017/C#-huffman_compression/HuffmanBibli/HuffmanBibli/HuffmanBibli/Noeud.cs
2.9375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HuffmanBibli { class Noeud { public List<byte> clef; public int poids; public Noeud droite; public Noeud gauche; public Noeud(List<byte> k, int p) { clef = k; poids = p; droite = null; gauche = null; } public Noeud(List<byte> k, int p, Noeud g, Noeud d) { clef = k; poids = p; droite = d; gauche = g; } public Noeud() { clef = null; poids = 0; droite = null; gauche = null; } override public string ToString() { string str = ""; if (this.gauche != null) { str += this.gauche.ToString(); str += this.droite.ToString(); } char[] key = new char[this.clef.Count()]; int i = 0; foreach (byte b in this.clef) { key[i] = Convert.ToChar(b); i++; } string k = new string(key); str += k + ":" + this.poids + " "; return str; } } }
a8dc311da62ab08b09774c7ff287b13c55eba0b5
C#
Earthmark/Libnoise
/Noiselib/NoiseGen.cs
3.125
3
namespace Noiselib { /// <summary> /// Enumerates the noise quality. /// </summary> public enum NoiseQuality { /// <summary> /// Generates coherent noise quickly. When a coherent-noise function with /// this quality setting is used to generate a bump-map image, there are /// noticeable "creasing" artifacts in the resulting image. This is /// because the derivative of that function is discontinuous at integer /// boundaries. /// </summary> Fast = 0, /// <summary> /// Generates standard-quality coherent noise. When a coherent-noise /// function with this quality setting is used to generate a bump-map /// image, there are some minor "creasing" artifacts in the resulting /// image. This is because the second derivative of that function is /// discontinuous at integer boundaries. /// </summary> Standard = 1, /// <summary> /// Generates the best-quality coherent noise. When a coherent-noise /// function with this quality setting is used to generate a bump-map /// image, there are no "creasing" artifacts in the resulting image. This /// is because the first and second derivatives of that function are /// continuous at integer boundaries. /// </summary> Best = 2 } /// <summary> /// The container for noise generation methods. /// </summary> public static class NoiseGen { // These constants control certain parameters that all coherent-noise // functions require. // Constants used by the original version of libnoise. // Because XNoiseGen is not relatively prime to the other values, and // ZNoiseGen is close to 256 (the number of random gradient vectors), // patterns show up in high-frequency coherent noise. #if NOISE_VERSION1 const int XNoiseGen = 1; const int YNoiseGen = 31337; const int ZNoiseGen = 263; const int SeedNoiseGen = 1013; const int ShiftNoiseGen = 13; #else // Constants used by the current version of libnoise. private const int XNoiseGen = 1619; private const int YNoiseGen = 31337; private const int ZNoiseGen = 6971; private const int SeedNoiseGen = 1013; private const int ShiftNoiseGen = 8; #endif /// <summary> /// Generates a gradient-coherent-noise value from the coordinates of a /// three-dimensional input value. /// </summary> /// <remarks> /// <para> /// The return value ranges from -1.0 to +1.0. /// </para> /// <para> /// For an explanation of the difference between gradient noise and /// value noise, see the comments for the <see cref="GradientNoise3D" /> function. /// </para> /// </remarks> /// <param name="x">The x coordinate of the input value.</param> /// <param name="y">The y coordinate of the input value.</param> /// <param name="z">The z coordinate of the input value.</param> /// <param name="seed">The random number seed.</param> /// <param name="noiseQuality">The quality of the coherent-noise.</param> /// <returns>The generated gradient-coherent-noise value.</returns> public static double GradientCoherentNoise3D(double x, double y, double z, int seed = 0, NoiseQuality noiseQuality = NoiseQuality.Standard) { // Create a unit-length cube aligned along an integer boundary. This cube // surrounds the input point. int x0 = (x > 0.0 ? (int)x : (int)x - 1); int x1 = x0 + 1; int y0 = (y > 0.0 ? (int)y : (int)y - 1); int y1 = y0 + 1; int z0 = (z > 0.0 ? (int)z : (int)z - 1); int z1 = z0 + 1; // Map the difference between the coordinates of the input value and the // coordinates of the cube's outer-lower-left vertex onto an S-curve. double xs = 0, ys = 0, zs = 0; switch(noiseQuality) { case NoiseQuality.Fast: xs = (x - x0); ys = (y - y0); zs = (z - z0); break; case NoiseQuality.Standard: xs = Interp.SCurve3(x - x0); ys = Interp.SCurve3(y - y0); zs = Interp.SCurve3(z - z0); break; case NoiseQuality.Best: xs = Interp.SCurve5(x - x0); ys = Interp.SCurve5(y - y0); zs = Interp.SCurve5(z - z0); break; } // Now calculate the noise values at each vertex of the cube. To generate // the coherent-noise value at the input point, interpolate these eight // noise values using the S-curve value as the interpolant (trilinear // interpolation.) double n0 = GradientNoise3D(x, y, z, x0, y0, z0, seed); double n1 = GradientNoise3D(x, y, z, x1, y0, z0, seed); double ix0 = Interp.LinearInterp(n0, n1, xs); n0 = GradientNoise3D(x, y, z, x0, y1, z0, seed); n1 = GradientNoise3D(x, y, z, x1, y1, z0, seed); double ix1 = Interp.LinearInterp(n0, n1, xs); double iy0 = Interp.LinearInterp(ix0, ix1, ys); n0 = GradientNoise3D(x, y, z, x0, y0, z1, seed); n1 = GradientNoise3D(x, y, z, x1, y0, z1, seed); ix0 = Interp.LinearInterp(n0, n1, xs); n0 = GradientNoise3D(x, y, z, x0, y1, z1, seed); n1 = GradientNoise3D(x, y, z, x1, y1, z1, seed); ix1 = Interp.LinearInterp(n0, n1, xs); double iy1 = Interp.LinearInterp(ix0, ix1, ys); return Interp.LinearInterp(iy0, iy1, zs); } /// <summary> /// Generates a gradient-coherent-noise value from the coordinates of a /// three-dimensional input value. /// </summary> /// <remarks> /// <para> /// The return value ranges from -1.0 to +1.0. /// </para> /// <para> /// For an explanation of the difference between gradient noise and /// value noise, see the comments for the <see cref="GradientNoise3D" /> function. /// </para> /// </remarks> /// <param name="x">The x coordinate of the input value.</param> /// <param name="y">The y coordinate of the input value.</param> /// <param name="z">The z coordinate of the input value.</param> /// <param name="seed">The random number seed.</param> /// <param name="noiseQuality">The quality of the coherent-noise.</param> /// <returns>The generated gradient-coherent-noise value.</returns> public static double GradientCoherentNoise2D(double x, double y, int seed = 0, NoiseQuality noiseQuality = NoiseQuality.Standard) { // Create a unit-length cube aligned along an integer boundary. This cube // surrounds the input point. int x0 = (x > 0.0 ? (int)x : (int)x - 1); int x1 = x0 + 1; int y0 = (y > 0.0 ? (int)y : (int)y - 1); int y1 = y0 + 1; // Map the difference between the coordinates of the input value and the // coordinates of the cube's outer-lower-left vertex onto an S-curve. double xs = 0, ys = 0; switch(noiseQuality) { case NoiseQuality.Fast: xs = (x - x0); ys = (y - y0); break; case NoiseQuality.Standard: xs = Interp.SCurve3(x - x0); ys = Interp.SCurve3(y - y0); break; case NoiseQuality.Best: xs = Interp.SCurve5(x - x0); ys = Interp.SCurve5(y - y0); break; } // Now calculate the noise values at each vertex of the cube. To generate // the coherent-noise value at the input point, interpolate these eight // noise values using the S-curve value as the interpolant (trilinear // interpolation.) double n0 = GradientNoise2D(x, y, x0, y0, seed); double n1 = GradientNoise2D(x, y, x1, y0, seed); double ix0 = Interp.LinearInterp(n0, n1, xs); n0 = GradientNoise2D(x, y, x0, y1, seed); n1 = GradientNoise2D(x, y, x1, y1, seed); double ix1 = Interp.LinearInterp(n0, n1, xs); return Interp.LinearInterp(ix0, ix1, ys); } /// <summary> /// Generates a gradient-coherent-noise value from the coordinates of a /// three-dimensional input value. /// </summary> /// <remarks> /// <para> /// The return value ranges from -1.0 to +1.0. /// </para> /// <para> /// For an explanation of the difference between gradient noise and /// value noise, see the comments for the <see cref="GradientNoise3D" /> function. /// </para> /// </remarks> /// <param name="x">The x coordinate of the input value.</param> /// <param name="y">The y coordinate of the input value.</param> /// <param name="z">The z coordinate of the input value.</param> /// <param name="seed">The random number seed.</param> /// <param name="noiseQuality">The quality of the coherent-noise.</param> /// <returns>The generated gradient-coherent-noise value.</returns> public static double GradientCoherentNoise1D(double x, int seed = 0, NoiseQuality noiseQuality = NoiseQuality.Standard) { // Create a unit-length cube aligned along an integer boundary. This cube // surrounds the input point. int x0 = (x > 0.0 ? (int)x : (int)x - 1); int x1 = x0 + 1; // Map the difference between the coordinates of the input value and the // coordinates of the cube's outer-lower-left vertex onto an S-curve. double xs = 0, ys = 0; switch(noiseQuality) { case NoiseQuality.Fast: xs = (x - x0); break; case NoiseQuality.Standard: xs = Interp.SCurve3(x - x0); break; case NoiseQuality.Best: xs = Interp.SCurve5(x - x0); break; } // Now calculate the noise values at each vertex of the cube. To generate // the coherent-noise value at the input point, interpolate these eight // noise values using the S-curve value as the interpolant (trilinear // interpolation.) double n0 = GradientNoise1D(x, x0, seed); double n1 = GradientNoise1D(x, x1, seed); return Interp.LinearInterp(n0, n1, xs); } /// <summary> /// Generates a gradient-noise value from the coordinates of a /// three-dimensional input value and the integer coordinates of a /// nearby three-dimensional value. /// </summary> /// <remarks> /// <para> /// The difference between <paramref name="fx" /> and <paramref name="ix" /> must be less than or equal to one. /// </para> /// <para> /// The difference between <paramref name="fy" /> and <paramref name="iy" /> must be less than or equal to one. /// </para> /// <para> /// The difference between <paramref name="fz" /> and <paramref name="iz" /> must be less than or equal to one. /// </para> /// <para> /// A gradient-noise function generates better-quality noise than a /// value-noise function. Most noise modules use gradient noise for /// this reason, although it takes much longer to calculate. /// </para> /// <para> /// The return value ranges from -1.0 to +1.0. /// </para> /// <para> /// This function generates a gradient-noise value by performing the /// following steps: /// </para> /// <para> /// - It first calculates a random normalized vector based on the /// nearby integer value passed to this function. /// </para> /// <para> /// - It then calculates a new value by adding this vector to the /// nearby integer value passed to this function. /// </para> /// <para> /// - It then calculates the dot product of the above-generated value /// and the floating-point input value passed to this function. /// </para> /// <para> /// A noise function differs from a random-number generator because it /// always returns the same output value if the same input value is passed /// to it. /// </para> /// </remarks> /// <param name="fx">The floating-point x coordinate of the input value.</param> /// <param name="fy">The floating-point y coordinate of the input value.</param> /// <param name="fz">The floating-point z coordinate of the input value.</param> /// <param name="ix">The integer x coordinate of a nearby value.</param> /// <param name="iy">The integer y coordinate of a nearby value.</param> /// <param name="iz">The integer z coordinate of a nearby value.</param> /// <param name="seed">The random number seed.</param> /// <returns>The generated gradient-noise value.</returns> public static double GradientNoise3D(double fx, double fy, double fz, int ix, int iy, int iz, int seed = 0) { // Randomly generate a gradient vector given the integer coordinates of the // input value. This implementation generates a random number and uses it // as an index into a normalized-vector lookup table. long vectorIndex = (XNoiseGen * ix + YNoiseGen * iy + ZNoiseGen * iz + SeedNoiseGen * seed) & 0xffffffff; vectorIndex ^= (vectorIndex >> ShiftNoiseGen); vectorIndex &= 0xff; double xvGradient = Misc.RandomVectors[(vectorIndex << 2)]; double yvGradient = Misc.RandomVectors[(vectorIndex << 2) + 1]; double zvGradient = Misc.RandomVectors[(vectorIndex << 2) + 2]; // Set up us another vector equal to the distance between the two vectors // passed to this function. double xvPoint = (fx - ix); double yvPoint = (fy - iy); double zvPoint = (fz - iz); // Now compute the dot product of the gradient vector with the distance // vector. The resulting value is gradient noise. Apply a scaling value // so that this noise value ranges from -1.0 to 1.0. return ((xvGradient * xvPoint) + (yvGradient * yvPoint) + (zvGradient * zvPoint)) * 2.12; } /// <summary> /// Generates a gradient-noise value from the coordinates of a /// three-dimensional input value and the integer coordinates of a /// nearby three-dimensional value. /// </summary> /// <remarks> /// <para> /// The difference between <paramref name="fx" /> and <paramref name="ix" /> must be less than or equal to one. /// </para> /// <para> /// The difference between <paramref name="fy" /> and <paramref name="iy" /> must be less than or equal to one. /// </para> /// <para> /// The difference between <paramref name="fz" /> and <paramref name="iz" /> must be less than or equal to one. /// </para> /// <para> /// A gradient-noise function generates better-quality noise than a /// value-noise function. Most noise modules use gradient noise for /// this reason, although it takes much longer to calculate. /// </para> /// <para> /// The return value ranges from -1.0 to +1.0. /// </para> /// <para> /// This function generates a gradient-noise value by performing the /// following steps: /// </para> /// <para> /// - It first calculates a random normalized vector based on the /// nearby integer value passed to this function. /// </para> /// <para> /// - It then calculates a new value by adding this vector to the /// nearby integer value passed to this function. /// </para> /// <para> /// - It then calculates the dot product of the above-generated value /// and the floating-point input value passed to this function. /// </para> /// <para> /// A noise function differs from a random-number generator because it /// always returns the same output value if the same input value is passed /// to it. /// </para> /// </remarks> /// <param name="fx">The floating-point x coordinate of the input value.</param> /// <param name="fy">The floating-point y coordinate of the input value.</param> /// <param name="fz">The floating-point z coordinate of the input value.</param> /// <param name="ix">The integer x coordinate of a nearby value.</param> /// <param name="iy">The integer y coordinate of a nearby value.</param> /// <param name="iz">The integer z coordinate of a nearby value.</param> /// <param name="seed">The random number seed.</param> /// <returns>The generated gradient-noise value.</returns> public static double GradientNoise2D(double fx, double fy, int ix, int iy, int seed = 0) { // Randomly generate a gradient vector given the integer coordinates of the // input value. This implementation generates a random number and uses it // as an index into a normalized-vector lookup table. long vectorIndex = (XNoiseGen * ix + YNoiseGen * iy + SeedNoiseGen * seed) & 0xffffffff; vectorIndex ^= (vectorIndex >> ShiftNoiseGen); vectorIndex &= 0xff; double xvGradient = Misc.RandomVectors[(vectorIndex << 2)]; double yvGradient = Misc.RandomVectors[(vectorIndex << 2) + 1]; // Set up us another vector equal to the distance between the two vectors // passed to this function. double xvPoint = (fx - ix); double yvPoint = (fy - iy); // Now compute the dot product of the gradient vector with the distance // vector. The resulting value is gradient noise. Apply a scaling value // so that this noise value ranges from -1.0 to 1.0. //TODO: Verify bounds return ((xvGradient * xvPoint) + (yvGradient * yvPoint)) * 2.12; } /// <summary> /// Generates a gradient-noise value from the coordinates of a /// three-dimensional input value and the integer coordinates of a /// nearby three-dimensional value. /// </summary> /// <remarks> /// <para> /// The difference between <paramref name="fx" /> and <paramref name="ix" /> must be less than or equal to one. /// </para> /// <para> /// The difference between <paramref name="fy" /> and <paramref name="iy" /> must be less than or equal to one. /// </para> /// <para> /// The difference between <paramref name="fz" /> and <paramref name="iz" /> must be less than or equal to one. /// </para> /// <para> /// A gradient-noise function generates better-quality noise than a /// value-noise function. Most noise modules use gradient noise for /// this reason, although it takes much longer to calculate. /// </para> /// <para> /// The return value ranges from -1.0 to +1.0. /// </para> /// <para> /// This function generates a gradient-noise value by performing the /// following steps: /// </para> /// <para> /// - It first calculates a random normalized vector based on the /// nearby integer value passed to this function. /// </para> /// <para> /// - It then calculates a new value by adding this vector to the /// nearby integer value passed to this function. /// </para> /// <para> /// - It then calculates the dot product of the above-generated value /// and the floating-point input value passed to this function. /// </para> /// <para> /// A noise function differs from a random-number generator because it /// always returns the same output value if the same input value is passed /// to it. /// </para> /// </remarks> /// <param name="fx">The floating-point x coordinate of the input value.</param> /// <param name="fy">The floating-point y coordinate of the input value.</param> /// <param name="fz">The floating-point z coordinate of the input value.</param> /// <param name="ix">The integer x coordinate of a nearby value.</param> /// <param name="iy">The integer y coordinate of a nearby value.</param> /// <param name="iz">The integer z coordinate of a nearby value.</param> /// <param name="seed">The random number seed.</param> /// <returns>The generated gradient-noise value.</returns> public static double GradientNoise1D(double fx, int ix, int seed = 0) { // Randomly generate a gradient vector given the integer coordinates of the // input value. This implementation generates a random number and uses it // as an index into a normalized-vector lookup table. long vectorIndex = (XNoiseGen * ix + SeedNoiseGen * seed) & 0xffffffff; vectorIndex ^= (vectorIndex >> ShiftNoiseGen); vectorIndex &= 0xff; double xvGradient = Misc.RandomVectors[(vectorIndex << 2)]; // Set up us another vector equal to the distance between the two vectors // passed to this function. double xvPoint = (fx - ix); // Now compute the dot product of the gradient vector with the distance // vector. The resulting value is gradient noise. Apply a scaling value // so that this noise value ranges from -1.0 to 1.0. //TODO: Verify bounds return (xvGradient * xvPoint) * 2.12; } /// <summary> /// Generates an integer-noise value from the coordinates of a /// three-dimensional input value. /// </summary> /// <remarks> /// <para> /// The return value ranges from 0 to 2147483647. /// </para> /// <para> /// A noise function differs from a random-number generator because it /// always returns the same output value if the same input value is passed /// to it. /// </para> /// </remarks> /// <param name="x">The integer x coordinate of the input value.</param> /// <param name="y">The integer y coordinate of the input value.</param> /// <param name="z">The integer z coordinate of the input value.</param> /// <param name="seed">A random number seed.</param> /// <returns>The generated integer-noise value.</returns> public static int IntValueNoise3D(int x, int y, int z, int seed = 0) { // All constants are primes and must remain prime in order for this noise // function to work correctly. int n = (XNoiseGen * x + YNoiseGen * y + ZNoiseGen * z + SeedNoiseGen * seed) & 0x7fffffff; n = (n >> 13) ^ n; return (n * (n * n * 60493 + 19990303) + 1376312589) & 0x7fffffff; } /// <summary> /// Generates an integer-noise value from the coordinates of a /// three-dimensional input value. /// </summary> /// <remarks> /// <para> /// The return value ranges from 0 to 2147483647. /// </para> /// <para> /// A noise function differs from a random-number generator because it /// always returns the same output value if the same input value is passed /// to it. /// </para> /// </remarks> /// <param name="x">The integer x coordinate of the input value.</param> /// <param name="y">The integer y coordinate of the input value.</param> /// <param name="seed">A random number seed.</param> /// <returns>The generated integer-noise value.</returns> public static int IntValueNoise2D(int x, int y, int seed = 0) { // All constants are primes and must remain prime in order for this noise // function to work correctly. int n = (XNoiseGen * x + YNoiseGen * y + SeedNoiseGen * seed) & 0x7fffffff; n = (n >> 13) ^ n; return (n * (n * n * 60493 + 19990303) + 1376312589) & 0x7fffffff; } /// <summary> /// Modifies a floating-point value so that it can be stored in a /// int32 variable. /// </summary> /// <remarks> /// This function does not modify n. /// In libnoise, the noise-generating algorithms are all integer-based; /// they use variables of type int32. Before calling a noise /// function, pass the x, y, and z coordinates to this function to /// ensure that these coordinates can be cast to a int32 value. /// Although you could do a straight cast from double to int32, the /// resulting value may differ between platforms. By using this function, /// you ensure that the resulting value is identical between platforms. /// </remarks> /// <param name="n">A floating-point number.</param> /// <returns>The modified floating-point number.</returns> public static double MakeInt32Range(double n) { if(n >= 1073741824.0) { return (2.0 * (n % 1073741824.0)) - 1073741824.0; } if(n <= -1073741824.0) { return (2.0 * (n % 1073741824.0)) + 1073741824.0; } return n; } /// <summary> /// Generates a value-coherent-noise value from the coordinates of a /// three-dimensional input value. /// </summary> /// <remarks> /// The return value ranges from -1.0 to +1.0. /// For an explanation of the difference between gradient noise and /// value noise, see the comments for the <see cref="GradientNoise3D" /> function. /// </remarks> /// <param name="x">The x coordinate of the input value.</param> /// <param name="y">The y coordinate of the input value.</param> /// <param name="z">The z coordinate of the input value.</param> /// <param name="seed">The random number seed.</param> /// <param name="noiseQuality">The quality of the coherent-noise.</param> /// <returns>The generated value-coherent-noise value.</returns> public static double ValueCoherentNoise3D(double x, double y, double z, int seed = 0, NoiseQuality noiseQuality = NoiseQuality.Standard) { // Create a unit-length cube aligned along an integer boundary. This cube // surrounds the input point. int x0 = (x > 0.0 ? (int)x : (int)x - 1); int x1 = x0 + 1; int y0 = (y > 0.0 ? (int)y : (int)y - 1); int y1 = y0 + 1; int z0 = (z > 0.0 ? (int)z : (int)z - 1); int z1 = z0 + 1; // Map the difference between the coordinates of the input value and the // coordinates of the cube's outer-lower-left vertex onto an S-curve. double xs = 0, ys = 0, zs = 0; switch(noiseQuality) { case NoiseQuality.Fast: xs = (x - x0); ys = (y - y0); zs = (z - z0); break; case NoiseQuality.Standard: xs = Interp.SCurve3(x - x0); ys = Interp.SCurve3(y - y0); zs = Interp.SCurve3(z - z0); break; case NoiseQuality.Best: xs = Interp.SCurve5(x - x0); ys = Interp.SCurve5(y - y0); zs = Interp.SCurve5(z - z0); break; } // Now calculate the noise values at each vertex of the cube. To generate // the coherent-noise value at the input point, interpolate these eight // noise values using the S-curve value as the interpolant (trilinear // interpolation.) double n0 = ValueNoise3D(x0, y0, z0, seed); double n1 = ValueNoise3D(x1, y0, z0, seed); double ix0 = Interp.LinearInterp(n0, n1, xs); n0 = ValueNoise3D(x0, y1, z0, seed); n1 = ValueNoise3D(x1, y1, z0, seed); double ix1 = Interp.LinearInterp(n0, n1, xs); double iy0 = Interp.LinearInterp(ix0, ix1, ys); n0 = ValueNoise3D(x0, y0, z1, seed); n1 = ValueNoise3D(x1, y0, z1, seed); ix0 = Interp.LinearInterp(n0, n1, xs); n0 = ValueNoise3D(x0, y1, z1, seed); n1 = ValueNoise3D(x1, y1, z1, seed); ix1 = Interp.LinearInterp(n0, n1, xs); double iy1 = Interp.LinearInterp(ix0, ix1, ys); return Interp.LinearInterp(iy0, iy1, zs); } /// <summary> /// Generates a value-noise value from the coordinates of a /// three-dimensional input value. /// </summary> /// <remarks> /// The return value ranges from -1.0 to +1.0. /// A noise function differs from a random-number generator because it /// always returns the same output value if the same input value is passed /// to it. /// </remarks> /// <param name="x">The x coordinate of the input value.</param> /// <param name="y">The y coordinate of the input value.</param> /// <param name="z">The z coordinate of the input value.</param> /// <param name="seed">A random number seed.</param> /// <returns>The generated value-noise value.</returns> public static double ValueNoise3D(int x, int y, int z, int seed = 0) { return 1.0 - (IntValueNoise3D(x, y, z, seed) / 1073741824.0); } /// <summary> /// Generates a value-noise value from the coordinates of a /// three-dimensional input value. /// </summary> /// <remarks> /// The return value ranges from -1.0 to +1.0. /// A noise function differs from a random-number generator because it /// always returns the same output value if the same input value is passed /// to it. /// </remarks> /// <param name="x">The x coordinate of the input value.</param> /// <param name="y">The y coordinate of the input value.</param> /// <param name="z">The z coordinate of the input value.</param> /// <param name="seed">A random number seed.</param> /// <returns>The generated value-noise value.</returns> public static double ValueNoise2D(int x, int y, int seed = 0) { return 1.0 - (IntValueNoise2D(x, y, seed) / 1073741824.0); } /// <summary> /// Generates a value-noise value from the coordinates of a /// three-dimensional input value. /// </summary> /// <remarks> /// The return value ranges from -1.0 to +1.0. /// A noise function differs from a random-number generator because it /// always returns the same output value if the same input value is passed /// to it. /// </remarks> /// <param name="x">The x coordinate of the input value.</param> /// <param name="y">The y coordinate of the input value.</param> /// <param name="z">The z coordinate of the input value.</param> /// <param name="seed">A random number seed.</param> /// <returns>The generated value-noise value.</returns> public static double ValueNoise1D(int x, int seed = 0) { return 1.0 - (IntValueNoise2D(x, seed) / 1073741824.0); } } }
76e9ba6936c52289e0f446c81afb5e98c00813dc
C#
nFoooo/TicTacToe
/WindowsFormsApplication1/WelcomeScreenController.cs
2.796875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TicTacToe.Model; using TicTacToe.View; namespace TicTacToe.Controller { public class WelcomeScreenController { //Constructors public WelcomeScreenController( WelcomeScreen wS ) { _view = wS; _model = new GameEngine(); _view.SetController(this); } //Attributes WelcomeScreen _view; GameEngine _model; //Methods public void StartGame(bool multiplayer) { //Launch the game GameView gV = new GameView(); GameController gC = new GameController(gV, _model); //Set game to 1 or 2 players _model.SetMultiplayer(multiplayer); //In the case of a multiplayer game where the AI goes first, they play their first move right away if (!multiplayer && (_model.GetXFirst() == false)) gC.AiMove(); gV.ShowDialog(); } public void StartSettings() { //Launch the settings form Settings settingsView = new Settings(); SettingsController sC = new SettingsController(settingsView, _model); settingsView.ShowDialog(); } } }
5b39ed212d8fe7a7533e25cf0109a21ad47899e3
C#
snel13/NoMushyBrains
/Assets/Scripts/Controller2D.cs
2.65625
3
using UnityEngine; using System.Collections; public class Controller2D : RaycastController { float maxClimbAngle = 80; float maxDescendAngle = 75; public CollisionInfo collisions; //public reference to our collision info [HideInInspector] public Vector2 playerInput; //store our player input public override void Start(){ base.Start(); collisions.faceDir = 1; } public void Move(Vector3 velocity, bool standingOnPlatform){ Move(velocity, Vector2.zero, standingOnPlatform); } // use Move function to keep track of the ray casts public void Move(Vector3 velocity, Vector2 input, bool standingOnPlatform = false){ UpdateRaycastOrigins(); collisions.Reset(); //blank slate each time collisions.velocityOld = velocity; playerInput = input; if (velocity.x != 0){ collisions.faceDir = (int)Mathf.Sign(velocity.x); } if (velocity.y < 0){ DescendSlope(ref velocity); } HorizontalCollisions(ref velocity); if (velocity.y != 0){ VerticalCollisions(ref velocity); } transform.Translate(velocity); if(standingOnPlatform){ collisions.below = true; } } // HorizontalCollisions function uses the RaycastHit2D struct to detect objects in the raycast area (right to left) void HorizontalCollisions(ref Vector3 velocity) { float directionX = collisions.faceDir; // make sure length is a positive number float rayLength = Mathf.Abs(velocity.x) + skinWidth; if (Mathf.Abs(velocity.x) < skinWidth){ rayLength = 2 * skinWidth; } for (int i = 0; i < horizontalRayCount; i++){ // see what direction we are moving in Vector2 rayOrigin = (directionX == -1) ? raycastOrigins.bottomLeft : raycastOrigins.bottomRight; rayOrigin += Vector2.up * (horizontalRaySpacing * i); RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.right * directionX, rayLength, collisionMask); // used for debugging, draws the rays in red Debug.DrawRay(rayOrigin, Vector2.right * directionX * rayLength, Color.red); if (hit){ if(hit.distance == 0){ continue; } //angled movement float slopeAngle = Vector2.Angle(hit.normal, Vector2.up); if(i == 0 && slopeAngle <= maxClimbAngle){ if(collisions.descendingSlope){ collisions.descendingSlope = false; velocity = collisions.velocityOld; } float distanceToSlopeStart = 0; //starting to climb a new slope if(slopeAngle != collisions.slopeAngleOld){ distanceToSlopeStart = hit.distance-skinWidth; velocity.x -= distanceToSlopeStart * directionX; //only uses velocity x that it has once it reaches the slope } ClimbSlope(ref velocity, slopeAngle);//print(slopeAngle); velocity.x += distanceToSlopeStart * directionX; //add back on } //check other rays if we're not climbing slope if(!collisions.climbingSlope || slopeAngle > maxClimbAngle){ velocity.x = (hit.distance - skinWidth) * directionX; rayLength = hit.distance; //update velocity on y axis if(collisions.climbingSlope){ velocity.y = Mathf.Tan(collisions.slopeAngle * Mathf.Deg2Rad) * Mathf.Abs(velocity.x); } //set depending on the direction collisions.left = directionX == -1; //if we've hit something and we're going left then this will be true collisions.right = directionX == 1; } } } } // VerticalCollisions function uses the RaycastHit2D struct to detect objects in the raycast area (bottom to top) void VerticalCollisions(ref Vector3 velocity){ float directionY = Mathf.Sign(velocity.y); // make sure length is a positive number float rayLength = Mathf.Abs(velocity.y) + skinWidth; for (int i = 0; i < verticalRayCount; i++){ // see what direction we are moving in Vector2 rayOrigin = (directionY == -1)?raycastOrigins.bottomLeft:raycastOrigins.topLeft; rayOrigin += Vector2.right * (verticalRaySpacing * i + velocity.x); RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.up * directionY, rayLength, collisionMask); // used for debugging, draws the rays in red Debug.DrawRay(rayOrigin, Vector2.up * directionY * rayLength, Color.red); if (hit){ //test through tag's...if collided with through tag objects let it pass through if(hit.collider.tag == "Through"){ //working code - temp comment if(directionY == 1 || hit.distance == 0){ continue; } /***************************************************************************** * * * --This comment applies to 11 lines below,void resetPlatform() * * --And Player.cs if (cntrlr.colsions.abv || cntrlr.colsions.blw){ * * * * Falling through works appropriately for narrow (short width) * * platforms but once the length of the platform exceeds a certain * * width (that is currently unknown), the player falls through mistakenly * * code below does work but needs an unknown amount of modifications either * * here or in player class * * * *****************************************************************************/ if(collisions.fallingThroughPlatform){ continue; } //working code temp comment if(playerInput.y == -1){ collisions.fallingThroughPlatform = true; //calls reset function for falling through platform after half a second. //invoke is a unity only function. Invoke("ResetFallingThroughPlatform", .5f); continue; } } velocity.y = (hit.distance - skinWidth) * directionY; rayLength = hit.distance; if(collisions.climbingSlope){ velocity.x = velocity.y / Mathf.Tan(collisions.slopeAngle * Mathf.Deg2Rad) * Mathf.Sign(velocity.x); } collisions.below = directionY == -1; collisions.above = directionY == 1; } } if(collisions.climbingSlope) { float directionX = Mathf.Sign(velocity.x); rayLength = Mathf.Abs(velocity.x) + skinWidth; Vector2 rayOrigin = ((directionX == -1)?raycastOrigins.bottomLeft:raycastOrigins.bottomRight) + Vector2.up * velocity.y; RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.right * directionX, rayLength, collisionMask); if(hit){ float slopeAngle = Vector2.Angle(hit.normal, Vector2.up); if(slopeAngle != collisions.slopeAngle){ velocity.x = (hit.distance - skinWidth) * directionX; collisions.slopeAngle = slopeAngle; } } } } void ClimbSlope(ref Vector3 velocity, float slopeAngle){ //figure out new velocity x and y for slopes float moveDistance = Mathf.Abs(velocity.x); float climbVelocityY = Mathf.Sin(slopeAngle * Mathf.Deg2Rad) * moveDistance; if(velocity.y <= climbVelocityY){ velocity.y = climbVelocityY; velocity.x = Mathf.Cos(slopeAngle * Mathf.Deg2Rad) * moveDistance * Mathf.Sign(velocity.x); collisions.below = true; //fix jumping collisions.climbingSlope = true; //set to true collisions.slopeAngle = slopeAngle; } } void DescendSlope(ref Vector3 velocity){ float directionX = Mathf.Sign(velocity.x); Vector2 rayOrigin = (directionX == -1)?raycastOrigins.bottomRight:raycastOrigins.bottomLeft; RaycastHit2D hit = Physics2D.Raycast(rayOrigin, -Vector2.up, Mathf.Infinity, collisionMask); if(hit){ float slopeAngle = Vector2.Angle(hit.normal, Vector2.up); if(slopeAngle != 0 && slopeAngle <= maxDescendAngle){ if(Mathf.Sign(hit.normal.x) == directionX){ if(hit.distance - skinWidth <= Mathf.Tan(slopeAngle * Mathf.Deg2Rad)*Mathf.Abs(velocity.x)){ float moveDistance = Mathf.Abs(velocity.x); float descendVecolityY = Mathf.Sin(slopeAngle * Mathf.Deg2Rad) * moveDistance; velocity.x = Mathf.Cos(slopeAngle * Mathf.Deg2Rad) * moveDistance * Mathf.Sign(velocity.x); velocity.y -= descendVecolityY; collisions.slopeAngle = slopeAngle; collisions.descendingSlope = true; collisions.below = true; } } } } } //method to reset boolean for tracking whether or not we are falling through platform, timing occurs on line 129ish void ResetFallingThroughPlatform(){ collisions.fallingThroughPlatform = false; } public struct CollisionInfo{ public bool above, below; public bool left, right; public bool climbingSlope; public bool descendingSlope; public float slopeAngle, slopeAngleOld; public Vector3 velocityOld; // 1 means faing left, -1 means facing right public int faceDir; //keeping track of if we fall through platform or not...used for timing. public bool fallingThroughPlatform; //reset bools to false public void Reset(){ above = below = false; left = right = false; climbingSlope = false; descendingSlope = false; slopeAngleOld = slopeAngle; slopeAngle = 0; } } }
66728fe81f054e9f62ca9c5b09b7e23cbfde1ff4
C#
squall-tech/akmapeditor
/AKMapEditor/OtMapEditor/OtBrush/CarpetBrush.cs
2.53125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; using System.Windows.Forms; using System.Diagnostics; namespace AKMapEditor.OtMapEditor.OtBrush { public class CarpetBrush : Brush { protected UInt16 look_id; protected CarpetNode[] carpet_items; protected String name; private static Random random = new Random(); public class CarpetType { public ushort id; public int chance; } public class CarpetNode { public CarpetNode() { this.total_chance = 0; } public int total_chance; public List<CarpetType> items = new List<CarpetType>(); } public CarpetBrush() : base() { carpet_items = new CarpetNode[14]; for (int x = 0; x < 14; x++) { carpet_items[x] = new CarpetNode(); } } public override string getName() { return this.name; } public override void setName(string name) { this.name = name; } public override int getLookID() { return look_id; } public override bool needBorders() { return true; } public override bool canDraw(GameMap map, Position pos) { return true; } public override void undraw(GameMap map, Tile tile) { List<Item> itemToRemove = new List<Item>(); foreach (Item it in tile.Items) { if (it.Type.IsCarpet) { CarpetBrush cb = it.getCarpetBrush(); if (cb == this) { itemToRemove.Add(it); } } } foreach (Item it in itemToRemove) { tile.Items.Remove(it); } } public override void draw(GameMap map, Tile tile, object param = null) { undraw(map, tile); // Remove old tile.addItem(Item.Create(getRandomCarpet(BorderType.CARPET_CENTER))); } public static void doCarpets(GameMap map, Tile tile) { if (tile.hasCarpet() == false) { return; } int x = tile.getPosition().x; int y = tile.getPosition().y; int z = tile.getPosition().z; foreach(Item item in tile.Items) { CarpetBrush carpet_brush = item.getCarpetBrush(); if (carpet_brush == null) { continue; } bool[] neighbours = new bool[8]; if (x == 0) { if (y == 0) { neighbours[0] = false; neighbours[1] = false; neighbours[2] = false; neighbours[3] = false; neighbours[4] = hasMatchingCarpetBrushAtTile(map, carpet_brush, x + 1, y, z); neighbours[5] = false; neighbours[6] = hasMatchingCarpetBrushAtTile(map, carpet_brush, x, y + 1, z); neighbours[7] = hasMatchingCarpetBrushAtTile(map, carpet_brush, x + 1, y + 1, z); } else { neighbours[0] = false; neighbours[1] = hasMatchingCarpetBrushAtTile(map, carpet_brush, x, y - 1, z); neighbours[2] = hasMatchingCarpetBrushAtTile(map, carpet_brush, x + 1, y - 1, z); neighbours[3] = false; neighbours[4] = hasMatchingCarpetBrushAtTile(map, carpet_brush, x + 1, y, z); neighbours[5] = false; neighbours[6] = hasMatchingCarpetBrushAtTile(map, carpet_brush, x, y + 1, z); neighbours[7] = hasMatchingCarpetBrushAtTile(map, carpet_brush, x + 1, y + 1, z); } } else if (y == 0) { neighbours[0] = false; neighbours[1] = false; neighbours[2] = false; neighbours[3] = hasMatchingCarpetBrushAtTile(map, carpet_brush, x - 1, y, z); neighbours[4] = hasMatchingCarpetBrushAtTile(map, carpet_brush, x + 1, y, z); neighbours[5] = hasMatchingCarpetBrushAtTile(map, carpet_brush, x - 1, y + 1, z); neighbours[6] = hasMatchingCarpetBrushAtTile(map, carpet_brush, x, y + 1, z); neighbours[7] = hasMatchingCarpetBrushAtTile(map, carpet_brush, x + 1, y + 1, z); } else { neighbours[0] = hasMatchingCarpetBrushAtTile(map, carpet_brush, x - 1, y - 1, z); neighbours[1] = hasMatchingCarpetBrushAtTile(map, carpet_brush, x, y - 1, z); neighbours[2] = hasMatchingCarpetBrushAtTile(map, carpet_brush, x + 1, y - 1, z); neighbours[3] = hasMatchingCarpetBrushAtTile(map, carpet_brush, x - 1, y, z); neighbours[4] = hasMatchingCarpetBrushAtTile(map, carpet_brush, x + 1, y, z); neighbours[5] = hasMatchingCarpetBrushAtTile(map, carpet_brush, x - 1, y + 1, z); neighbours[6] = hasMatchingCarpetBrushAtTile(map, carpet_brush, x, y + 1, z); neighbours[7] = hasMatchingCarpetBrushAtTile(map, carpet_brush, x + 1, y + 1, z); } uint tiledata = 0; for (int i = 0; i < 8; i++) { if (neighbours[i]) { // Same table as this one, calculate what border tiledata |= Convert.ToUInt32(1) << i; } } // bt is always valid. int id = carpet_brush.getRandomCarpet(Border_Types.carpet_types[tiledata]); if (id != 0) { item.setID((ushort)id); } } } private static bool hasMatchingCarpetBrushAtTile(GameMap map, CarpetBrush carpet_brush, int x, int y, int z) { Tile t = map.getTile(x, y, z); if (t == null) { return false; } foreach(Item item in t.Items) { CarpetBrush cb = item.getCarpetBrush(); if (cb == carpet_brush) { return true; } } return false; } public ushort getRandomCarpet(int alignment) { if (carpet_items[alignment].total_chance > 0) { int chance = random.Next(1, carpet_items[alignment].total_chance + 1); foreach (CarpetType carpet_iter in carpet_items[alignment].items) { if (chance <= carpet_iter.chance) { return carpet_iter.id; } chance -= carpet_iter.chance; } } else { if (alignment != BorderType.CARPET_CENTER && carpet_items[BorderType.CARPET_CENTER].total_chance > 0) { int chance = random.Next(1, carpet_items[BorderType.CARPET_CENTER].total_chance + 1); foreach (CarpetType carpet_iter in carpet_items[alignment].items) { if (chance <= carpet_iter.chance) { return carpet_iter.id; } chance -= carpet_iter.chance; } } // Find an item to place on the tile, first center, then the rest. for (int i = 0; i < 12; ++i) { if (carpet_items[i].total_chance > 0) { int chance = random.Next(1, carpet_items[i].total_chance + 1); foreach (CarpetType carpet_iter in carpet_items[alignment].items) { if (chance <= carpet_iter.chance) { return carpet_iter.id; } chance -= carpet_iter.chance; } } } } return 0; } public override void load(XElement node) { string strVal = ""; look_id = node.Attribute("lookid").GetUInt16(); if (node.Attribute("server_lookid").GetUInt16() != 0) { look_id = node.Attribute("server_lookid").GetUInt16(); } foreach (XElement child_node in node.Elements()) { if ("carpet".Equals(child_node.Name.LocalName)) { int alignment; strVal = child_node.Attribute("align").GetString(); if (!"".Equals(strVal)) { alignment = AutoBorder.EdgeNameToEdge(strVal); if (alignment == BorderType.BORDER_NONE) { if ("center".Equals(strVal)) { alignment = BorderType.CARPET_CENTER; } else { Messages.AddWarning("Invalid alignment of carpet node"); continue; } } } else { Messages.AddWarning("Could not read alignment tag of carpet node"); continue; } bool use_local_id = true; foreach (XElement subchild_node in child_node.Elements()) { if ("item".Equals(subchild_node.Name.LocalName)) { use_local_id = false; int id = subchild_node.Attribute("id").GetInt32(); int chance = subchild_node.Attribute("chance").GetInt32(); if (id == 0) { Messages.AddWarning("Could not read id tag of item node"); continue; } if (chance == 0) { Messages.AddWarning("Could not read chance tag of item node"); continue; } ItemType it = Global.items.items[id]; if (it == null) { Messages.AddWarning("There is no itemtype with id " + id); continue; } if ((it.brush != null) && (it.brush != this)) { Messages.AddWarning("itemId " + id + "already has a brush"); continue; } it.IsCarpet = true; it.brush = this; carpet_items[alignment].total_chance += chance; CarpetType t = new CarpetType(); t.chance = chance; t.id = (ushort) id; carpet_items[alignment].items.Add(t); } } if (use_local_id) { int id = child_node.Attribute("id").GetInt32(); if (id == 0) { Messages.AddWarning("Could not read id tag of item node"); continue; } ItemType it = Global.items.items[id]; if (it == null) { Messages.AddWarning("There is no itemtype with id " + id); continue; } if ((it.brush != null) && (it.brush != this)) { Messages.AddWarning("itemId " + id + "already has a brush"); continue; } it.IsCarpet = true; it.brush = this; carpet_items[alignment].total_chance += 1; CarpetType t = new CarpetType(); t.chance = 1; t.id = (ushort)id; carpet_items[alignment].items.Add(t); } } } } } }
2465a3433aec9dc9c6b2e57561ce593f2750955b
C#
apatbizen/AnagramAnalyzer
/AnagramAnalyzer/CharRanker/CharacterRanker.cs
3.546875
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AnagramAnalyzer.CharRanker { public class CharacterRanker : ICharRanker{ Dictionary<char, int> appearance = new Dictionary<char, int>(); public void CheckIn(string v) { foreach(var p in v.ToCharArray().GroupBy(x => x)) { if (!this.appearance.ContainsKey(p.Key)) this.appearance.Add(p.Key, 1); else this.appearance[p.Key]++; } } public int PopularityOf(char c) => this.appearance.ContainsKey(c) ? this.appearance[c] : 0; public int Compare(char x, char y) { var diff = this.PopularityOf(x) - this.PopularityOf(y); //if (diff != 0) return diff; return y - x; } public IEnumerable<char> ListOfPopularityOrder => this.appearance.OrderBy(x=>x.Key).OrderByDescending(x => x.Value).Select(x => x.Key); public IEnumerable<char> ListOfRarityOrder => this.appearance.OrderBy(x => x.Key).OrderBy(x => x.Value).Select(x => x.Key); } }
e1a364a9375f0651f241a92ac9fa0100c702d580
C#
GalacticChimp/ShadowsBehindTheThrone
/Assets/Code/VoteIssue_DeclareWar.cs
2.5625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Assets.Code { public class VoteIssue_DeclareWar : VoteIssue { public SocialGroup target; public VoteIssue_DeclareWar(Society soc,SocialGroup target,Person proposer) : base(soc,proposer) { this.target = target; } public override string ToString() { if (society.offensiveTarget.getName() != null) { return "Declare War on " + society.offensiveTarget.getName(); } else { return "Declare War"; } } public override string getLargeDesc() { string reply = "Vote to declare war on " + target.getName() +"."; return reply; } public override string getIndexInfo(int index) { if (index == 0) { return "Maintain Peace"; } else { return "Declare War"; } } public override double computeUtility(Person voter, VoteOption option,List<ReasonMsg> msgs) { double u = option.getBaseUtility(voter); //double parityMult = 1; //if (option.index == 0) { parityMult = -1; } //return 100 * parityMult; //Option 0 is "Don't declare war" //1 if we're 100% of the balance, -1 if they are double ourStrength = society.currentMilitary; double theirStrength = target.currentMilitary; if (ourStrength + theirStrength == 0) { ourStrength += 0.001; } double relativeStrength = (ourStrength - theirStrength) / (ourStrength + theirStrength + 1); double localU = 0; double relMilU = society.map.param.utility_militaryTargetRelStrengthOffensive * relativeStrength; bool shouldExpand = true; int nDukes = 0; foreach (Title t in society.titles) { if (t is Title_ProvinceRuler) { nDukes += 1; } } if (nDukes >= society.map.param.society_maxDukes) { shouldExpand = false; } bool hasOurTerritory = false; foreach (Location loc in target.lastTurnLocs) { foreach (Location l2 in society.lastTurnLocs) { if (loc.province == l2.province) { hasOurTerritory = true; } } } //Peace if (option.index == 0) { if (ourStrength < 1) { localU = 1000; msgs.Add(new ReasonMsg("We are too weak", localU)); u += localU; return u; } if (ourStrength*2 < theirStrength) { localU = 1000; msgs.Add(new ReasonMsg("We stand no chance", localU)); u += localU; return u; } if (relMilU < 0) { msgs.Add(new ReasonMsg("Relative strength of current militaries", -relMilU)); u += relMilU; } bool tinyComplete = target.lastTurnLocs.Count <= 3 && hasOurTerritory;//You can take over tiny nations to complete your provinces if (!tinyComplete && society.isDarkEmpire == false && shouldExpand == false && target is Society) { localU = society.map.param.utility_militaryOverexpansionHalt; msgs.Add(new ReasonMsg("We have as much as we can control", localU)); u += localU; } localU = voter.politics_militarism * -100; msgs.Add(new ReasonMsg("Militarism of " + voter.getFullName(), localU)); u += localU; } else //Pro-war { //We want to expand into territory we already partially own bool hasMyTerritory = false; foreach (Location loc in target.lastTurnLocs) { if (loc.province == voter.getLocation().province) { hasMyTerritory = true; break; } } if (hasMyTerritory) { localU = society.map.param.utility_militaryTargetCompleteProvince; msgs.Add(new ReasonMsg("Has territory from my province", localU)); u += localU; } //We want to own more land. Invade weak neighbours if (shouldExpand && target is Society && target.currentMilitary * 1.5 < this.society.currentMilitary && target.getNeighbours().Contains(this.society)) { //Society soc = (Society)target; //if (this.society.getCapital() != null && soc.getCapital() != null) //{ // if (soc.getCapital().hex.getHabilitability() > 0.5) // { localU = society.map.param.utility_militaryTargetExpansion * Math.Max(0, voter.politics_militarism); msgs.Add(new ReasonMsg("Expand our holdings", localU)); u += localU; // } //} } localU = voter.politics_militarism * 100; msgs.Add(new ReasonMsg("Militarism of " + voter.getFullName(), localU)); u += localU; foreach (ThreatItem threat in voter.threatEvaluations) { if (threat.group == target) { localU = threat.threat*society.map.param.utility_fromThreat; msgs.Add(new ReasonMsg("Perceived Threat", localU)); u += localU; break; } } } /* if (relMilU > 0 && target is Society) { //0 if stability is full, getting more negative as stability decreases double stabilityU = (this.society.data_societalStability-1); stabilityU = relMilU * stabilityU;//More negative the worse stability is, reaches the complement of relMilU when civil war is imminent msgs.Add(new ReasonMsg("Our societal stability concerns", stabilityU)); u += stabilityU; } */ /* if (this.society.defensiveTarget != null && this.society.defensiveTarget != this.society.offensiveTarget) { theirStrength = society.defensiveTarget.currentMilitary; //0 if we're 100% of the balance, -1 if they are relativeStrength = (((ourStrength - theirStrength) / (ourStrength + theirStrength))-1)/2; localU = society.map.param.utility_militaryTargetRelStrength * relativeStrength * parityMult; msgs.Add(new ReasonMsg("Defensive Target's Capabilities (risk of sneak attack)", localU)); u += localU; } */ return u; } public override void implement(VoteOption option) { base.implement(option); if (option.index == 1 && society.posture == Society.militaryPosture.offensive) { society.map.declareWar(society, target); } } public override bool stillValid(Map map) { if (society.posture != Society.militaryPosture.offensive) { return false; } if (society.offensiveTarget == null) { return false; } if (society.offensiveTarget != target) { return false; } if (society.map.socialGroups.Contains(target) == false) { return false; } return true; } } }
9ca1283f1385e0d7cb9bc2de4d6f1d5f5fb79f7b
C#
YoshikawaOnion/ProcedualLevels
/Assets/Scripts/Views/Adventure/Enemy/EnemyController.cs
2.515625
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using UniRx.Triggers; using UniRx; using System; using ProcedualLevels.Common; namespace ProcedualLevels.Views { /// <summary> /// 敵キャラクターの振る舞いを提供するクラス。 /// </summary> public abstract class EnemyController : BattlerController { public Models.Enemy Enemy { get; private set; } protected EnemyAnimationController Animation { get; set; } protected AdventureViewContext Context { get; set; } public virtual void Initialize(Models.Enemy enemy, AdventureViewContext context) { base.Initialize(enemy); Enemy = enemy; Context = context; Animation = GetComponent<EnemyAnimationController>(); Animation.Initialize(context.EventReceiver); } /// <summary> /// 毎フレーム行う処理を実行します。 /// </summary> public override abstract void Control(); /// <summary> /// キャラクターが死亡した際の処理を行います。 /// </summary> public override void Die() { Animation.AnimateDie() .Subscribe(x => { Destroy(gameObject); }); } } }
d516f39cf6a7ead297b2e67a57c8e105e9d7cb3a
C#
brandon-julio-t/TPA-Desktop
/TPA Desktop/Core/Models/TransactionType.cs
2.921875
3
using System; using System.Windows; using TPA_Desktop.Core.Builders; namespace TPA_Desktop.Core.Models { public class TransactionType { public TransactionType() { } public TransactionType(Guid id) { using (var reader = QueryBuilder .Table("TransactionType") .Select("ID", "Name") .Where("ID", id.ToString()) .Get()) { if (!reader.Read() || !reader.HasRows) { MessageBox.Show("Transaction Type doesn't exist"); Id = Guid.Empty; return; } Id = reader.GetGuid(0); Name = reader.GetString(1); } } public TransactionType(string name) { using (var reader = QueryBuilder .Table("TransactionType") .Select("ID", "Name") .Where("Name", name) .Get()) { if (!reader.Read() || !reader.HasRows) { MessageBox.Show("Transaction Type doesn't exist"); Id = Guid.Empty; return; } Id = reader.GetGuid(0); Name = reader.GetString(1); } } public Guid Id { get; set; } public string Name { get; set; } public override string ToString() { return Name; } } }
d5c5f686567e680e3b4532ab430b1af7feac141b
C#
grantwang96/Dating-Sim-Action-Hero-Combo
/Dating Sim Action Hero Combo/Assets/Scripts/Game State Machine/SceneController.cs
2.546875
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public delegate void SceneUpdateDelegate(string sceneName); public class SceneController : MonoBehaviour { private const string LoadingScreenScene = "LoadingScreen"; public static SceneController Instance { get; private set; } public string CurrentSceneName => SceneManager.GetActiveScene().name; public event SceneUpdateDelegate OnSceneLoaded; private string _nextSceneName; private bool _isLoadingScene; private void Awake() { Instance = this; } public bool TransitionToScene(string sceneName, bool requiresLoadingScreen) { Debug.Log($"Loading scene {sceneName}..."); if (_isLoadingScene) { CustomLogger.Warn(nameof(SceneController), $"Already loading scene {_nextSceneName}!"); return false; } if(CurrentSceneName == sceneName) { CustomLogger.Log(nameof(SceneController), $"Already in scene {CurrentSceneName}!"); return true; } _isLoadingScene = true; _nextSceneName = sceneName; if (requiresLoadingScreen) { LoadingScreenController.Instance.OnLoadingScreenShowComplete += OnEndSceneTransition; LoadingScreenController.Instance.ShowLoadingScreen(); } else { StartCoroutine(LoadSceneOneFrame()); } return true; } // when transition animation ends -> should be in loading screen private void OnEndSceneTransition() { LoadingScreenController.Instance.OnLoadingScreenShowComplete -= OnEndSceneTransition; StartCoroutine(LoadSceneAsync()); } private IEnumerator LoadSceneAsync() { AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(_nextSceneName); while (!asyncLoad.isDone) { yield return new WaitForEndOfFrame(); } FinishLoadingScene(); } private void FinishLoadingScene() { LoadingScreenController.Instance.OnLoadingScreenHideComplete += OnLoadingScreenHideComplete; LoadingScreenController.Instance.HideLoadingScreen(); } private void OnLoadingScreenHideComplete() { LoadingScreenController.Instance.OnLoadingScreenHideComplete -= OnLoadingScreenHideComplete; _isLoadingScene = false; // Debug.Log("Scene load complete!"); OnSceneLoaded?.Invoke(_nextSceneName); } private void LoadSceneInstant(string sceneName) { _isLoadingScene = false; SceneManager.LoadScene(sceneName); // Debug.Log("Scene load complete!"); OnSceneLoaded?.Invoke(_nextSceneName); } private IEnumerator LoadSceneOneFrame() { _isLoadingScene = true; yield return new WaitForEndOfFrame(); LoadSceneInstant(_nextSceneName); } }
ef5d16ef42d96719e611a4519fd1353ed67ea0d5
C#
marc68128/Nutrition
/Nutrition.Api.ViewModels/MealPartViewModel.cs
2.5625
3
namespace Nutrition.Api.ViewModels { public class MealPartViewModel { private AlimentViewModel _aliment; private double _quantity; public AlimentViewModel Aliment { get => _aliment; set { _aliment = value; UpdateTotal(); } } public double Quantity { get => _quantity; set { _quantity = value; UpdateTotal(); } } public double TotalQuantity { get; private set; } public double TotalCalories { get; private set; } public double TotalProtides { get; private set; } public double TotalLipides { get; private set; } public double TotalGlucides { get; private set; } private void UpdateTotal() { TotalQuantity = Quantity * Aliment.Quantity; TotalCalories = Quantity * Aliment.Calories; TotalProtides = Quantity * Aliment.Protides; TotalLipides = Quantity * Aliment.Lipides; TotalGlucides = Quantity * Aliment.Glucides; } } }
f24c7640cd6cb33863e676431dfbb1dadd57d4b9
C#
JeffLeBert/RubiksCubeTrainer
/Puzzle/Puzzle3x3/Scrambler.cs
3.21875
3
using System; using System.Collections.Generic; using System.Linq; namespace RubiksCubeTrainer.Puzzle3x3 { public static class Scrambler { public static string Scamble(int depth = 10) => string.Join(" ", EnumerateMoveNames().Take(depth)); private static IEnumerable<string> EnumerateMoveNames() => from move in EnumerateMoves() select NotationParser.FormatMove(move); internal static IEnumerable<NotationMoveType> EnumerateMoves() { var randomGenerator = new Random(); var lastRotation = NotationRotationNames.None; while (true) { var nextMove = new NotationMoveType( GetRandomRotationName(randomGenerator, lastRotation), GetRandomRotationType(randomGenerator)); lastRotation = nextMove.Name; yield return nextMove; } } private static NotationRotationNames GetRandomRotationName(Random randomGenerator, NotationRotationNames lastRotation) { while (true) { var rotationName = randomGenerator.Next(12) + NotationRotationNames.Right; if (rotationName != lastRotation) { return rotationName; } } } private static NotationRotationType GetRandomRotationType(Random randomGenerator) { switch (randomGenerator.Next(3)) { case 0: return NotationRotationType.Clockwise; case 1: return NotationRotationType.CounterClockwise; case 2: return NotationRotationType.Double; default: throw new InvalidOperationException(); } } } }
063ce280aef3ddfb2fa1374b9b621b2fa7be44a5
C#
xiaobaxiang/QrCode_Csharp
/Qrsource/Gma/QrCodeNet/Encoding/Versions/ErrorCorrectionBlocks.cs
2.53125
3
namespace Gma.QrCodeNet.Encoding.Versions { using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] internal struct ErrorCorrectionBlocks { private ErrorCorrectionBlock[] m_ECBlock; internal int NumErrorCorrectionCodewards { get; private set; } internal int NumBlocks { get; private set; } internal int ErrorCorrectionCodewordsPerBlock { get; private set; } internal ErrorCorrectionBlocks(int numErrorCorrectionCodewords, ErrorCorrectionBlock ecBlock) { this = new ErrorCorrectionBlocks(); this.NumErrorCorrectionCodewards = numErrorCorrectionCodewords; this.m_ECBlock = new ErrorCorrectionBlock[] { ecBlock }; this.initialize(); } internal ErrorCorrectionBlocks(int numErrorCorrectionCodewords, ErrorCorrectionBlock ecBlock1, ErrorCorrectionBlock ecBlock2) { this = new ErrorCorrectionBlocks(); this.NumErrorCorrectionCodewards = numErrorCorrectionCodewords; this.m_ECBlock = new ErrorCorrectionBlock[] { ecBlock1, ecBlock2 }; this.initialize(); } internal ErrorCorrectionBlock[] GetECBlocks() { return this.m_ECBlock; } private void initialize() { if (this.m_ECBlock == null) { throw new ArgumentNullException("ErrorCorrectionBlocks array doesn't contain any value"); } this.NumBlocks = 0; int length = this.m_ECBlock.Length; for (int i = 0; i < length; i++) { this.NumBlocks += this.m_ECBlock[i].NumErrorCorrectionBlock; } this.ErrorCorrectionCodewordsPerBlock = this.NumErrorCorrectionCodewards / this.NumBlocks; } } }
d575c2657cd0b35f7416f4c10affb9440bf81447
C#
olegtarasov/Retia
/Retia/Interop/MatrixPointersBag.cs
2.59375
3
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Storage; namespace Retia.Interop { /// <summary> /// A collection of pinned matrix pointers. /// Pointers are unpinned when an object is disposed. /// </summary> /// <typeparam name="T">Data type.</typeparam> public struct MatrixPointersBag<T> : IDisposable where T : struct, IEquatable<T>, IFormattable { private readonly GCHandle[] _handles; private readonly IntPtr[] _pointers; private readonly MatrixDefinition[] _defs; private readonly bool _rowMajor; private readonly List<Tuple<Matrix<T>, T[]>> _arrayMap; private bool _disposed; /// <summary> /// Pins pointers to underlying matrix arrays and stores them for later use. /// The order of matrices is preserved. /// </summary> /// <param name="matrices">Matrices to pin pointers to.</param> public MatrixPointersBag(params Matrix<T>[] matrices) : this(false, matrices) { } /// <summary> /// Pins pointers to underlying matrix arrays and stores them for later use. /// The order of matrices is preserved. /// </summary> /// <param name="generateDefinitions">Whether to generate matrix definitions for GPU transfer.</param> /// <param name="matrices">Matrices to pin pointers to.</param> public MatrixPointersBag(bool generateDefinitions, params Matrix<T>[] matrices) : this(false, generateDefinitions, matrices) { } /// <summary> /// Pins pointers to underlying matrix arrays and stores them for later use. /// The order of matrices is preserved. /// </summary> /// <remarks> /// When <see cref="rowMajor"/> is set, arrays are decoupled from original matrices. /// Changes made to arrays will be synchronized only upon <see cref="Dispose"/>. /// </remarks> /// <param name="rowMajor"> /// Indicates whether matrices should be converted to row-major format. /// </param> /// <param name="generateDefinitions">Whether to generate matrix definitions for GPU transfer.</param> /// <param name="matrices">Matrices to pin pointers to.</param> public MatrixPointersBag(bool rowMajor, bool generateDefinitions, params Matrix<T>[] matrices) { _rowMajor = rowMajor; _arrayMap = rowMajor ? new List<Tuple<Matrix<T>, T[]>>() : null; _defs = generateDefinitions ? new MatrixDefinition[matrices.Length] : null; _disposed = false; _handles = new GCHandle[matrices.Length]; _pointers = new IntPtr[matrices.Length]; for (int i = 0; i < matrices.Length; i++) { var matrix = matrices[i]; T[] array; if (rowMajor) { array = matrix.ToRowMajorArray(); _arrayMap.Add(new Tuple<Matrix<T>, T[]>(matrix, array)); } else { array = matrix.AsColumnMajorArray(); } _handles[i] = GCHandle.Alloc(array, GCHandleType.Pinned); var ptr = _handles[i].AddrOfPinnedObject(); _pointers[i] = ptr; if (generateDefinitions) { _defs[i] = new MatrixDefinition(matrix.RowCount, matrix.ColumnCount, 1, ptr); } } } /// <summary> /// Get a pointer to the matrix. /// </summary> /// <param name="idx">Matrix index.</param> /// <returns>Pointer to an underlying matrix array.</returns> public IntPtr this[int idx] { get { if (_disposed) throw new ObjectDisposedException(nameof(MatrixPointersBag<T>)); return _pointers[idx]; } } public MatrixDefinition[] Definitions { get { if (_defs == null) throw new InvalidOperationException("Matrix definitions has not been generated!"); return _defs; } } public void Dispose() { if (_disposed) return; _disposed = true; if (_rowMajor) { foreach (var pair in _arrayMap) { var matrix = pair.Item1; var storage = DenseColumnMajorMatrixStorage<T>.OfRowMajorArray(matrix.RowCount, matrix.ColumnCount, pair.Item2); storage.CopyTo(matrix.Storage); } _arrayMap.Clear(); } for (int i = 0; i < _handles.Length; i++) { _handles[i].Free(); } } } }
104efc7ee4cad1349ad024376df4f09d41a0929d
C#
NazirAhmd/Algorithms
/Algorithms/Tree/HeightOfBinaryTree.cs
3.625
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Algorithms.Tree { public class HeightOfBinaryTree { //Time - O(n) //AS - O(h) where h=height of binary tree //Recursive approach public int Height(Node root) { if (root == null) return 0; return 1 + Math.Max(Height(root.left), Height(root.right)); } } //class Program //{ // static void Main(string[] args) // { // var obj = new HeightOfBinaryTree(); // var root = new Node(1); // root.left = new Node(2); // root.right = new Node(3); // root.left.left = new Node(4); // root.left.right = new Node(5); // Console.WriteLine(obj.Height(root)); // } //} }
87e2c27ad71450c260fc9670bbc418c196edcc0d
C#
endjin/SilverlightWalkthrough
/SilverlightWalkthrough/Commands/CommandManager.cs
2.640625
3
namespace SilverlightWalkthrough.Commands { #region using System; using System.Collections.Generic; using SilverlightWalkthrough.Async; #endregion /// <summary> /// The command manager. /// </summary> public class CommandManager { /// <summary> /// Commands we know about /// </summary> private readonly List<WeakReference> eventHandlers = new List<WeakReference>(); /// <summary> /// The current command manager /// </summary> private static CommandManager current; /// <summary> /// Determines if we have already queued a request /// </summary> private bool hasCanExecuteQueued; public static event EventHandler RequerySuggested { add { AddWeakReferenceHandler(Current.eventHandlers, value); } remove { RemoveWeakReferenceHandler(Current.eventHandlers, value); } } /// <summary> /// Gets Current. /// </summary> public static CommandManager Current { get { return current ?? (current = new CommandManager()); } } /// <summary> /// The invalidate requery suggested. /// </summary> public static void InvalidateRequerySuggested() { Current.RaiseCanExecuteChanged(); } private static void RemoveWeakReferenceHandler(List<WeakReference> weakReferences, EventHandler handler) { for (int i = weakReferences.Count - 1; i >= 0; i--) { WeakReference reference = weakReferences[i]; EventHandler target = reference.Target as EventHandler; if ((target == null) || (target == handler)) { weakReferences.RemoveAt(i); } } } private static void AddWeakReferenceHandler(List<WeakReference> weakReferences, EventHandler handler) { weakReferences.Add(new WeakReference(handler)); } private static void CallWeakReferenceHandlers(List<WeakReference> handlers) { if (handlers != null) { EventHandler[] handlerArray = new EventHandler[handlers.Count]; int index = 0; for (int i = handlers.Count - 1; i >= 0; i--) { WeakReference reference = handlers[i]; EventHandler target = reference.Target as EventHandler; if (target == null) { handlers.RemoveAt(i); } else { handlerArray[index] = target; index++; } } for (int j = 0; j < index; j++) { EventHandler handler2 = handlerArray[j]; handler2(null, EventArgs.Empty); } } } /// <summary> /// Raises requery changes for registered commands /// </summary> private void RaiseCanExecuteChanged() { if (this.hasCanExecuteQueued) { return; } this.hasCanExecuteQueued = true; DispatcherHelper.UIDispatcher.BeginInvoke( () => { CallWeakReferenceHandlers(eventHandlers); this.hasCanExecuteQueued = false; }); } } } // -------------------------------------------------------------------------------------------------------------------- // <copyright file="CommandManager.cs" company="Endjin Ltd"> // Copyright © 2010 Endjin Ltd // </copyright> // <summary> // The command manager. // </summary> // --------------------------------------------------------------------------------------------------------------------
fe088e24483711c48609362bb642c964ba394f62
C#
Csharp2020/csharp2020
/dvukasovic/Moj projekt/Neparni_do_20/Program.cs
3.265625
3
using System; namespace Neparni_do_20 { class Program { static void Main(string[] args) { Console.WriteLine("Neparni do 20!"); for (int i = 2; i < 20; i++) { if (i % 2 == 0) { Console.WriteLine("To su parni " + i); } else { Console.WriteLine("Neparni brojevi od 2 do 20 su: " + i); } } } } }
6c3e1dd17d2433535987a55cc6e8ff4a6d3c9507
C#
JacquesLucke/Collage
/Collage/Gui/ProgressBarWindow.cs
3.109375
3
using Gtk; using System.Threading; namespace Collage { public class ProgressBarWindow { Window window; ProgressBar progressBar; int totalSteps; int currentStep; string name = ""; public ProgressBarWindow() { } public void Start() { currentStep = 0; window = new Window(WindowType.Toplevel); window.Move(10, 10); window.KeepAbove = true; window.Resize(400, 30); window.AcceptFocus = false; window.Title = "Progress Bar"; progressBar = new ProgressBar(); progressBar.Fraction = 0; window.Add(progressBar); window.ShowAll(); } public void Start(int totalSteps) { Start(); this.totalSteps = totalSteps; } public void Destroy() { if(progressBar == null) { for(int i = 0; i < 30; i++) { if (progressBar != null) break; Thread.Sleep(1); } } if(progressBar != null) progressBar.Destroy(); if(progressBar != null) window.Destroy(); } public void StepUp(string text) { StepUp(); progressBar.Text = text; } public void StepUp() { currentStep++; if (progressBar != null) { // change the progress fraction progressBar.Fraction = (double)currentStep / (double)totalSteps; // update the text if (name != "") progressBar.Text = name + " : " + currentStep + " of " + totalSteps; else progressBar.Text = currentStep + " of " + totalSteps; } } public string Name { get { return name; } set { name = value; } } public float Fraction { get { return (float)progressBar.Fraction; } set { progressBar.Fraction = (float)value; } } public int TotalSteps { get { return totalSteps; } set { totalSteps = value; } } public int CurrentStep { get { return currentStep; } set { currentStep = value; } } } }
05f061a004f20548e2669e534347ce5050e85424
C#
zfybs/SDSS
/Projects/SDSS/Definitions/Definition.cs
2.71875
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Text; using System.Xml.Serialization; using SDSS.Constants; using SDSS.Project; namespace SDSS.Definitions { /// <summary> 水中桩段或者嵌岩桩段的截面参数 </summary> [Serializable()] [XmlInclude(typeof(Material))] [XmlInclude(typeof(Profile))] public class Definition : ICloneable { #region --- XmlAttribute [XmlAttribute()] [Category(Categories.Tag), Description("定义对象的名称")] public string Name { get; set; } [XmlIgnore] private Guid _id; [XmlElement] [Browsable(true), ReadOnly(true), Category(Categories.Tag), Description("定义对象的唯一标识符")] public Guid ID { get { return _id; } set { _id = value; } } #endregion [XmlIgnore()] [Category(Categories.Tag)] public Definition Self { get { return this; } } /// <summary> 构造函数 </summary> public Definition() { _id = Guid.NewGuid(); Name = _id.ToString(); } public override bool Equals(object obj) { Definition def = obj as Definition; if (def == null) { return false; } return (this.ID == def.ID); } /// <summary> 返回一个<seealso cref="Definition"/>对象 </summary> public object Clone() { return this.MemberwiseClone(); } public override string ToString() { return Name; } } }
0bf30b09d453a85d173bb8f507e990f718d77704
C#
rolywhateva/Lab-Algoritmi
/Lab7/MergeSort/Program.cs
3.421875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MergeSort { class Program { static int[] Merge(int[] st, int[] dr) { int i1, i2, i3; int[] v = new int[st.Length + dr.Length]; i1 = i2 = i3 = 0; while(i1<st.Length&&i2<dr.Length) { if (st[i1] < dr[i2]) v[i3++] = st[i1++]; else v[i3++] = dr[i2++]; } while(i1<st.Length) v[i3++] = st[i1++]; while (i2 < dr.Length) v[i3++] = dr[i2++]; return v; } static int[] MergeSort(int[] a) { if (a.Length == 1) return a; else { int m = a.Length / 2; int[] left = new int[m]; int[] right; if (a.Length % 2 != 0) right = new int[m + 1]; else right = new int[m]; for (int i = 0; i < m; i++) left[i] = a[i]; int k = 0; for (int i = m; i < a.Length; i++) right[k++] = a[i]; left = MergeSort(left); right = MergeSort(right); int[] r = new int[a.Length]; r = Merge(left, right); return r; } } static void Main(string[] args) { int[] r = MergeSort(new int[] { -2, -3, 0, 0, 0, 0, 1, -5, 6, 7, -3, 4, 0, -10, 2, 3, 4, -3 }); Console.WriteLine(string.Join(" ",r)); } } }
db7a217cf5b9aba42e4ed7d65ce0afd69e9b8301
C#
FajarPriam/OOP
/Bootcamp.OOP/Bootcamp.OOP/Program.cs
3.171875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bootcamp.OOP { class Program { static void Main(string[] args) { Bangun2D panggil; Console.WriteLine("Perhitungan Luas Lingkaran"); Console.WriteLine("============================"); Console.WriteLine("1. Lingkaran"); Console.WriteLine("2. Segitiga"); Console.WriteLine("3. Persegi"); Console.WriteLine("4. Persegi Panjang"); Console.WriteLine("============================"); Console.Write("Masukkan pilihan anda (1-4): "); string pilihan = Console.ReadLine(); int i = Convert.ToInt16(pilihan); switch (i) { case 1: Console.Write("Masukkan Nilai Jari-jari:"); double jari = Convert.ToDouble(Console.ReadLine()); panggil = new Lingkaran(jari); panggil.CetakLuas("Lingkaran;"); Console.Read(); break; case 2: Console.WriteLine("Masukkan Nilai Alas:"); double alas = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Masukkan Nilai Tinggi"); double tinggis = Convert.ToDouble(Console.ReadLine()); panggil = new Segitiga(alas, tinggis); panggil.CetakLuas("Segitiga;"); Console.Read(); break; case 3: Console.Write("Masukkan Nilai Sisi:"); double sisi = Convert.ToDouble(Console.ReadLine()); panggil = new Persegi(sisi); panggil.CetakLuas("Persegi;"); Console.Read(); break; case 4: Console.WriteLine("Masukkan Nilai Alas:"); double panjang = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Masukkan Nilai Tinggi"); double tinggip = Convert.ToDouble(Console.ReadLine()); panggil = new Persegipanjang(panjang, tinggip); panggil.CetakLuas("Persegipanjang;"); Console.Read(); break; default: Console.WriteLine("Pilihan tidak ada -GOOD BYE-"); break; } Console.ReadLine(); } } }
9a40123ddef259012eadf38aae91e3e6426e197b
C#
JoseMarkos/EL-1-Ejercicios-1
/src/12.cs
3.703125
4
using System; public class Program { public static void Main() { string[,] array = new string[4, 4]; Console.WriteLine("Ingrese el numero: "); string num = Console.ReadLine(); Console.WriteLine ("------------------"); for (int i = 0; i < 4; i++ ) { for (int h = 0; h < 4; h++ ) { if (i % 2 == 0) { if (h == 0) { array [i, h] = num; } else { array[i, h] = " " + num; } } else { array[i, h] = num; } Console.Write(array[i, h]); } Console.WriteLine (); } } }
f524a3d5534fa1be1d6b0b55ba50ccbbd09b888f
C#
KristopherGBaker/Stravan
/Stravan/Json/RideService.cs
2.625
3
#region MIT License /* * Copyright (c) 2012 Kristopher Baker (kris@empyrealnight.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion using System; using System.Collections.Generic; using System.Collections.Specialized; using EmpyrealNight.Core; using EmpyrealNight.Core.Json; namespace Stravan.Json { /// <summary> /// Service implementation for rides in the Strava API /// </summary> public class RideService : BaseService, IRideService { /// <summary> /// Date format for start/end dates /// </summary> private const string DateFormat = "yyyy-MM-dd"; /// <summary> /// Initializes a RideService with the specified client /// </summary> /// <param name="client">IStravaWebClient to use with the service</param> public RideService(IStravaWebClient client) : base(client) { } /// <summary> /// Searches for Rides by Athlete, Club, date, or Id range. Returns a list of Rides. The response includes the Id and Name of each matching Ride. Rides are ordered by their start date. /// </summary> /// <param name="clubId">Optional. Id of the Club for which to search for member's Rides.</param> /// <param name="athleteId">Optional. Id of the Athlete for which to search for Rides.</param> /// <param name="athleteName">Optional. Username of the Athlete for which to search for Rides.</param> /// <param name="startDate">Optional. Day on which to start search for Rides. The date is the local time of when the ride started.</param> /// <param name="endDate">Optional. Day on which to end search for Rides. The date is the local time of when the ride started.</param> /// <param name="startId">Optional. Only return Rides with an Id greater than or equal to the startId.</param> /// <param name="offset">Optional. Any search will return at most 50 rows. To retrieve results after the 50th row use the offset parameter. For example, to retrieve rows 51-100 use an offset of 50.</param> /// <returns>List of matching rides</returns> public List<Ride> Index(int? clubId = null, int? athleteId = null, string athleteName = null, DateTime? startDate = null, DateTime? endDate = null, int? startId = null, int? offset = null) { var parameters = new NameValueCollection(); if (clubId.HasValue && clubId.Value > 0) { parameters.Add("clubId", clubId.Value.ToString()); } if (athleteId.HasValue && athleteId.Value > 0) { parameters.Add("athleteId", athleteId.Value.ToString()); } if (!string.IsNullOrWhiteSpace(athleteName)) { parameters.Add("athleteName", athleteName); } if (startDate.HasValue) { parameters.Add("startDate", startDate.Value.ToString(DateFormat)); } if (endDate.HasValue) { parameters.Add("endDate", endDate.Value.ToString(DateFormat)); } if (startId.HasValue && startId.Value > 0) { parameters.Add("startId", startId.Value.ToString()); } if (offset.HasValue && offset.Value > 0) { parameters.Add("offset", offset.Value.ToString()); } var response = Client.Download("rides", parameters); return JsonDeserializer.Deserialize<RidesWrapper>(response).Rides; } /// <summary> /// Returns extended information for a Ride. /// </summary> /// <param name="id">Required. The Id of the Ride.</param> /// <returns>Ride for the specified id with extended information.</returns> public Ride Show(int id) { var response = Client.Download(string.Format("rides/{0}", id)); return JsonDeserializer.Deserialize<RideWrapper>(response).Ride; } /// <summary> /// Shows details about a specific ride. /// </summary> /// <param name="id">Required. The Id of the Ride.</param> /// <returns>Ride for the specified id with extended information.</returns> public RideV2 ShowV2(int id) { var response = Client.Download(string.Format("rides/{0}", id), versionType: ApiVersionType.VersionTwo); var rideWrapper = JsonDeserializer.Deserialize<RideV2Wrapper>(response); var ride = rideWrapper.Ride.ToRideV2(); ride.Version = rideWrapper.Version; return ride; } /// <summary> /// Determines if a ride is synced. /// </summary> /// <param name="id">Required. The Id of the Ride.</param> /// <param name="version">Required. A 'synced' boolean is returned, which indicates whether or not the device has the current version of the ride.</param> /// <returns>true iff the ride is synced, false otherwise</returns> public bool IsSyncedV2(int id, string version) { if (version == null) throw new ArgumentNullException("version"); if (version.Length == 0) throw new ArgumentException("version", "version cannot be empty"); var parameters = new NameValueCollection { { "version", version } }; var response = Client.Download(string.Format("rides/{0}", id), parameters, versionType: ApiVersionType.VersionTwo); var rideWrapper = JsonDeserializer.Deserialize<RideV2Wrapper>(response); return rideWrapper.IsSynced; } /// <summary> /// Returns the list of lat/lng points to be used to generate a map of the ride. /// </summary> /// <param name="rideId">Required. The Id of the Ride.</param> /// <param name="token">Required. Authentication token.</param> /// <param name="threshold">Optional. If provided, the array of lat/lng points will be reduced to exclude "uninteresting" points within a tolerance of threshold meters.</param> /// <returns>The list of lat/lng points to be used to generate a map of the ride</returns> public MapDetailV2 MapDetailsV2(int rideId, string token, int? threshold = null) { if (token == null) throw new ArgumentNullException("token"); if (token.Length == 0) throw new ArgumentException("token", "token cannot be empty"); var parameters = new NameValueCollection { { "token", token } }; if (threshold.HasValue) { parameters.Add("threshold", threshold.Value.ToString()); } var response = Client.Download(string.Format("rides/{0}/map_details", rideId), parameters, versionType: ApiVersionType.VersionTwo); var mapWrapper = JsonDeserializer.Deserialize<MapDetailsWrapper>(response); return mapWrapper.ToMapDetail(); } /// <summary> /// Returns a list of Efforts on a Ride. The response includes the Id of the Effort, the elapsed time of the Effort, and the Id and Name of the Segment associated with the Effort. /// </summary> /// <param name="id">Required. The Id of the Ride.</param> /// <returns>List of Efforts on the specified Ride</returns> public RideEfforts Efforts(int id) { var response = Client.Download(string.Format("rides/{0}/efforts", id)); return JsonDeserializer.Deserialize<RideEfforts>(response); } /// <summary> /// Shows details the segment efforts on a specific ride. /// The elapsed_time and moving_time properties are returned as seconds. The average_speed property is returned as meters/sec. The elevation_gain and distance properties are returned in meters. /// </summary> /// <param name="id">Required. The id of the ride.</param> /// <returns>List of Efforts and Segments on the specified Ride</returns> public RideEffortsV2 EffortsV2(int id) { var response = Client.Download(string.Format("rides/{0}/efforts", id), versionType: ApiVersionType.VersionTwo); var rideEffortWrapper = JsonDeserializer.Deserialize<RideEffortsV2Wrapper>(response); return rideEffortWrapper.ToRideEfforts(); } /// <summary> /// Returns information about a specific segment effort on a specific ride. /// There are 3 sections to the JSON response: /// effort - Summary information about the effort (you already have this from /api/v2/rides/98715/efforts) /// segment - Information about the segment /// leaderboard - Information to populate the leaderboard. More on the leaderboard below... /// /// The leadboard payload will have between 2 and 4 sections: /// rank - Rank of this effort compared to the best efforts of all other athletes on this segment. This property will always exist. If this isn't the athletes best effort (case #3) this rank will be "virtual" (e.g. you'll see it in parenthesis). /// best - This section will only exist in case #3. Best will contain information on the athlete's best effort (since this effort isn't their best). "best" will have 2 properties: /// rank - The rank of their best effort on the leaderboard. /// effort - Properties of this best effort /// prev_best - This section will only exist in case #2. Prev_best will contain information on the athlete's best effort before this effort beat it. It will contain the same properties as best above, except in this case "rank" refers to their old rank on the leaderboard. NOTE: it's possible for their time to be better but for the rank to remain the same, e.g. if they improved their time by 10 seconds, but there was no one on the leaderboard between their old time and new time, so their rank remains unchanged. /// context - Information on the "nearby" efforts on the leaderboard. This property will always exist. It's will be an array of items. Each item will have 3 properties: /// rank - The rank of this effort on the leaderboard. /// effort - Properties of this effort. /// athlete - Summary information about the athlete, e.g. name. /// /// The context section contains the information you need to build out the leaderboard. There are a few corner cases with context. As mentioned it's possible for there to be fewer than 4 items in it (2 above, 2 below) if fewer than 4 other athletes have ridden the segment. It's possible for context to actually be empty if this effort is the first effort on this segment (no one has ridden it before). Finally, if this effort is within the top 5, I'll return the top 4, instead of 2 below and 2 above, e.g. if they are 5th I'll return efforts 1 thru 4. This is just to be able to show the top of the leaderboard if they're close. Since all the context efforts are ranked, you'll always put the current effort in it's spot within those rankings (it's possible for the current effort to be ranked the same as a context effort, see case #3). /// /// There are 3 possible cases when viewing an effort. These different cases will determine what information is sent back in the leaderboard payload (and of course determines what is displayed). /// /// This effort is the athlete's first on this segment. In this case both the best and prev_best sections won't exist. /// This effort is a new best (or it ties their current best). In this case there will be no best section in the leaderboard. The rank will be an actual rank on the leaderboard. Context will contain the 2 efforts above it and below it on the leaderboard. If this isn't my first effort (not case #3) then prev_best will be populated. /// This effort is slower than their current best. In this case their will always be a best section. therefore the rank will be a "virtual" rank on the leaderboard. Context will still contain the 2 efforts above it and below it, but the first one below it will have the same rank. When ordering the leaderboard you'll always put the new effort above the effort in context with the same rank. /// </summary> /// <param name="rideId">Required. The given segment effort's ride.</param> /// <param name="effortId">Required. The segment effort's id.</param> /// <returns>Returns information about a specific segment effort on a specific ride.</returns> public EffortDetailsV2 ShowEffortsV2(int rideId, int effortId) { var response = Client.Download(string.Format("rides/{0}/efforts/{1}", rideId, effortId), versionType: ApiVersionType.VersionTwo); var effortDetailsWrapper = JsonDeserializer.Deserialize<EffortDetailsV2Wrapper>(response); return effortDetailsWrapper.ToEffortDetails(); } #region wrapper classes /// <summary> /// Wrapper class for EffortDetailsV2 /// </summary> protected class EffortDetailsV2Wrapper { /// <summary> /// Gets or sets the effort /// </summary> [JsonName("effort")] public EffortV2 Effort { get; set; } /// <summary> /// Gets or sets the segment /// </summary> [JsonName("segment")] public SegmentDetailsV2Wrapper Segment { get; set; } /// <summary> /// Gets or sets the leaderboard /// </summary> [JsonName("leaderboard")] public LeaderboardV2 Leaderboard { get; set; } public EffortDetailsV2 ToEffortDetails() { var effort = new EffortDetailsV2 { Effort = Effort, Leaderboard = Leaderboard }; if (Segment != null) { effort.Segment = Segment.ToSegmentDetails(); } return effort; } } /// <summary> /// Wrapper class for SegmentDetailsV2 /// </summary> protected class SegmentDetailsV2Wrapper { /// <summary> /// Gets or sets the start coordinate /// </summary> [JsonName("start_latlng")] public double[] StartCoordinate { get; set; } /// <summary> /// Gets or sets the end coordinate /// </summary> [JsonName("end_latlng")] public double[] EndCoordinate { get; set; } /// <summary> /// Gets or sets the climb category /// </summary> [JsonName("climb_category")] public int ClimbCategory { get; set; } /// <summary> /// Gets or sets the number of times ridden /// </summary> [JsonName("num_times_ridden")] public int TimeRidden { get; set; } /// <summary> /// Gets or sets the number of riders ridden /// </summary> [JsonName("num_riders_ridden")] public int RidersRidden { get; set; } /// <summary> /// Gets or sets the name /// </summary> [JsonName("name")] public string Name { get; set; } /// <summary> /// Gets or sets the id /// </summary> [JsonName("id")] public int Id { get; set; } /// <summary> /// Gets or sets the elevation difference /// </summary> [JsonName("elev_difference")] public double ElevationDifference { get; set; } /// <summary> /// Gets or sets the kom /// </summary> [JsonName("kom")] public LeaderV2 KingOfMountain { get; set; } public SegmentDetailsV2 ToSegmentDetails() { var seg = new SegmentDetailsV2 { KingOfMountain = KingOfMountain, ClimbCategory = ClimbCategory, TimeRidden = TimeRidden, RidersRidden = RidersRidden, Name = Name, Id = Id, ElevationDifference = ElevationDifference }; if (StartCoordinate != null && StartCoordinate.Length == 2) { seg.StartCoordinate = new Coordinate { Latitude = StartCoordinate[0], Longitude = StartCoordinate[1] }; } if (EndCoordinate != null && EndCoordinate.Length == 2) { seg.EndCoordinate = new Coordinate { Latitude = EndCoordinate[0], Longitude = EndCoordinate[1] }; } return seg; } } /// <summary> /// Wrapper class for a list of rides /// </summary> protected class RidesWrapper { /// <summary> /// Gets or sets the list of rides /// </summary> [JsonName("rides")] public List<Ride> Rides { get; set; } } /// <summary> /// Wrapper class for a ride /// </summary> protected class RideWrapper { /// <summary> /// Gets or sets the ride /// </summary> [JsonName("ride")] public Ride Ride { get; set; } } /// <summary> /// Wrapper class for a V2 ride /// </summary> protected class RideV2Wrapper { /// <summary> /// Gets or sets the id /// </summary> [JsonName("id")] public string Id { get; set; } /// <summary> /// Gets or sets the ride /// </summary> [JsonName("ride")] public RideV2Temp Ride { get; set; } /// <summary> /// Gets or sets the version /// </summary> [JsonName("version")] public string Version { get; set; } /// <summary> /// Gets or sets the synced boolean /// </summary> [JsonName("synced")] public bool IsSynced { get; set; } } /// <summary> /// Wrapper class for a V2 ride /// </summary> protected class RideV2Temp { /// <summary> /// Gets or sets the id /// </summary> [JsonName("id")] public int Id { get; set; } /// <summary> /// Gets or sets the name /// </summary> [JsonName("name")] public string Name { get; set; } /// <summary> /// Gets or sets the start date local /// </summary> [JsonName("start_date_local")] public string StartDateLocal { get; set; } /// <summary> /// Gets or sets the elapsed time /// </summary> [JsonName("elapsed_time")] public int ElapsedTime { get; set; } /// <summary> /// Gets or sets the moving time /// </summary> [JsonName("moving_time")] public int MovingTime { get; set; } /// <summary> /// Gets or sets the distance /// </summary> [JsonName("distance")] public double Distance { get; set; } /// <summary> /// Gets or sets the average speed /// </summary> [JsonName("average_speed")] public double AverageSpeed { get; set; } /// <summary> /// Gets or sets the elevation gain /// </summary> [JsonName("elevation_gain")] public double ElevationGain { get; set; } /// <summary> /// Gets or sets the location /// </summary> [JsonName("location")] public string Location { get; set; } /// <summary> /// Gets or sets the start coordinate /// </summary> [JsonName("start_latlng")] public double[] StartCoordinate { get; set; } /// <summary> /// Gets or sets the end coordinate /// </summary> [JsonName("end_latlng")] public double[] EndCoordinate { get; set; } /// <summary> /// Gets or sets the version /// </summary> [JsonName("version")] public string Version { get; set; } public RideV2 ToRideV2() { var ride = new RideV2 { Id = Id, Name = Name, StartDateLocal = StartDateLocal, ElapsedTime = ElapsedTime, MovingTime = MovingTime, Distance = Distance, AverageSpeed = AverageSpeed, ElevationGain = ElevationGain, Location = Location, Version = Version }; if (StartCoordinate != null && StartCoordinate.Length == 2) { ride.StartCoordinate = new Coordinate { Latitude = StartCoordinate[0], Longitude = StartCoordinate[1] }; } if (EndCoordinate != null && EndCoordinate.Length == 2) { ride.EndCoordinate = new Coordinate { Latitude = EndCoordinate[0], Longitude = EndCoordinate[1] }; } return ride; } } /// <summary> /// Wrapper class for a list of coordinates (latitude/longitude pairs) /// </summary> protected class CoordinatesWrapper { [JsonName("latlng")] public List<Coordinate> Coordinates { get; set; } } /// <summary> /// Wrapper class for map details v2 /// </summary> protected class MapDetailsWrapper { /// <summary> /// Gets or sets the id /// </summary> [JsonName("id")] public string Id { get; set; } /// <summary> /// Gets or sets the coordinates /// </summary> [JsonName("latlng")] public List<List<double>> Coordinates { get; set; } /// <summary> /// Gets or sets the version /// </summary> [JsonName("version")] public string Version { get; set; } public MapDetailV2 ToMapDetail() { var map = new MapDetailV2 { RideId = ConvertWrapper.ToInt32(Id), Version = Version, Coordinates = new List<Coordinate>() }; if (Coordinates != null) { Coordinates.Each(pair => { if (pair.Count == 2) { map.Coordinates.Add(new Coordinate { Latitude = pair[0], Longitude = pair[1] }); } }); } return map; } } /// <summary> /// Wrapper class for RideEffortsV2 /// </summary> protected class RideEffortsV2Wrapper { /// <summary> /// Gets or sets the ride id /// </summary> [JsonName("id")] public string Id { get; set; } /// <summary> /// Gets or sets the effort-segment list /// </summary> [JsonName("efforts")] public List<EffortSegmentV2Wrapper> Efforts { get; set; } /// <summary> /// Gets or sets the version /// </summary> [JsonName("version")] public string Version { get; set; } public RideEffortsV2 ToRideEfforts() { var rideEffort = new RideEffortsV2 { RideId = ConvertWrapper.ToInt32(Id), Version = Version, Efforts = new List<EffortSegmentV2>() }; if (Efforts != null) { Efforts.Each(effort => rideEffort.Efforts.Add(effort.ToEffortSegment())); } return rideEffort; } } /// <summary> /// Wrapper class for EffortSegmentV2 /// </summary> protected class EffortSegmentV2Wrapper { /// <summary> /// Gets or sets the effort /// </summary> [JsonName("effort")] public EffortV2 Effort { get; set; } /// <summary> /// Gets or sets the segment /// </summary> [JsonName("segment")] public SegmentV2Wrapper Segment { get; set; } public EffortSegmentV2 ToEffortSegment() { var effortSeg = new EffortSegmentV2 { Effort = Effort }; if (Segment != null) { effortSeg.Segment = Segment.ToSegment(); } return effortSeg; } } /// <summary> /// Wrapper class for SegmentV2 /// </summary> protected class SegmentV2Wrapper { /// <summary> /// Gets or sets the id /// </summary> [JsonName("id")] public int Id { get; set; } /// <summary> /// Gets or sets the name /// </summary> [JsonName("name")] public string Name { get; set; } /// <summary> /// Gets or sets the climb category /// </summary> [JsonName("climb_category")] public int ClimbCategory { get; set; } /// <summary> /// Gets or sets the average grade /// </summary> [JsonName("avg_grade")] public double AverageGrade { get; set; } /// <summary> /// Gets or sets the start coordinate /// </summary> [JsonName("start_latlng")] public double[] StartCoordinate { get; set; } /// <summary> /// Gets or sets the end coordinate /// </summary> [JsonName("end_latlng")] public double[] EndCoordinate { get; set; } /// <summary> /// Gets or sets the elevation difference /// </summary> [JsonName("elev_difference")] public double ElevationDifference { get; set; } public SegmentV2 ToSegment() { var seg = new SegmentV2 { Id = Id, Name = Name, ClimbCategory = ClimbCategory, AverageGrade = AverageGrade, ElevationDifference = ElevationDifference }; if (StartCoordinate != null && StartCoordinate.Length == 2) { seg.StartCoordinate = new Coordinate { Latitude = StartCoordinate[0], Longitude = StartCoordinate[1] }; } if (EndCoordinate != null && EndCoordinate.Length == 2) { seg.EndCoordinate = new Coordinate { Latitude = EndCoordinate[0], Longitude = EndCoordinate[1] }; } return seg; } } #endregion } }
a3ad43e60381e421427119c4ed60d078f626fd6e
C#
SONJAYA80026/Meadow.CLI
/Meadow.CLI.Core/Internals/MeadowComms/RecvClasses/RecvSimpleText.cs
2.828125
3
using System; using System.Text; namespace Meadow.CLI.Internals.MeadowComms.RecvClasses { // Factory class public class RecvSimpleTextFactory : RecvMessageFactory { public override IReceivedMessage Create(byte[] recvdMsg, int recvdMsgLength) => new RecvSimpleText(recvdMsg, recvdMsgLength); } // Concrete class internal class RecvSimpleText : RecvHeader { public RecvSimpleText(byte[] recvdMsg, int recvdMsgLength) : base(recvdMsg, recvdMsgLength) { } public override bool Execute(byte[] recvdMsg, int recvdMsgLen) { try { if (recvdMsg.Length == HeaderLength) { throw new ArgumentException("Received RecvSimpleText with no text data"); } return true; } catch (Exception ex) { Console.WriteLine($"Exception:{ex.Message}"); return false; } } public override string ToString() { return (MessageDataLength > 0) ? ASCIIEncoding.ASCII.GetString(MessageData) : string.Empty; } } }
7ba2e38cfae69c15dcd76749cf43e1891afe117d
C#
zendorx/testapp
/Assets/Plugins/GameOfWhales/Examples/Example2/GowExample2.cs
2.578125
3
using System.Collections; using UnityEngine; using UnityEngine.UI; using UnityEngine.Purchasing; namespace GameOfWhales { public class GowExample2 : GowExampleBase { [SerializeField] GowExampleStoreListener _storeController; private static GowExample2 _instance; public static GowExample2 instance { get { return _instance; } } private void Awake() { _instance = this; } private void OnEnable() { _storeController.PurchaseCompleted += OnPurchaseComplete; } private void OnDisable() { _storeController.PurchaseCompleted -= OnPurchaseComplete; } protected override void InitStore() { //Init Unity Purchasing and subscribe to events _storeController.Initialized += UnityPurchasingInitialized; Gow.Initialized += Initialized; _storeController.Init(infos.Select(i => i.name).ToArray()); } private void OnPurchaseComplete(PurchaseEventArgs e) { //Add "coins" when purchase is completed; infos.Where(i => i.name == e.purchasedProduct.definition.id) .ForEach(i => { AddCoins(i.coins); Debug.Log("Add coins:" + i.coins); }); } private void UnityPurchasingInitialized() { //Init Gow Gow.Init(); } public void Buy(string product) { //Buy product; _storeController.Buy(product); } } }
948d9f9dac4a938e824e6bbd56255e0c6c63d574
C#
ryomutk/Bingo
/Assets/Scripts/Roulette.cs
2.53125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Roulette : MonoBehaviour { public static Roulette instance = null; List<int> drawedCards; ExitGames.Client.Photon.Hashtable roomHash; void Singleton(){ if(instance == null){ instance = this; } else if(instance != this){ Destroy(this.gameObject); } } void Awake(){ roomHash.Add("NextNum",0); roomHash.Add("Drawed",new List<int>()); } public void UpdateList(int number){ List<int> drawedNumbers = roomHash["Drawed"] as List<int>; drawedNumbers.Add(number); roomHash["NextNum"] = number; } }
6f3494ba3eb203e828d8ddf51bb89fe848b2ceb9
C#
KarmaScripter/BudgetExecution
/extensions/DataGridExtensions.cs
2.6875
3
// <copyright file = "DataGridExtensions.cs" company = "Terry D. Eppler"> // Copyright (c) Terry D. Eppler. All rights reserved. // </copyright> namespace BudgetExecution { using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Windows.Forms; /// <summary> /// /// </summary> public static class DataGridExtensions { /// <summary> /// The GetCurrentDataRow /// </summary> /// <param name="bindingSource">The bindingSource /// <see cref="BindingSource" /></param> /// <returns> /// The /// <see cref="System.Data.DataRow" /> /// </returns> public static DataRow GetCurrentDataRow( this BindingSource bindingSource ) { try { return ( (DataRowView)bindingSource?.Current )?.Row; } catch( Exception ex ) { Fail( ex ); return default( DataRow ); } } /// <summary> /// The GetDataTable /// </summary> /// <param name="dataGridView">The dataGridView /// <see cref="DataGridView" /></param> /// <returns> /// The /// <see cref="System.Data.DataTable" /> /// </returns> public static DataTable GetDataTable( this DataGridView dataGridView ) { try { var _table = new DataTable(); foreach( DataGridViewColumn _column in dataGridView.Columns ) { _table.Columns.Add( new DataColumn { ColumnName = _column.Name, DataType = _column.ValueType } ); } foreach( DataGridViewRow row in dataGridView.Rows ) { var cellvalues = new object[ row.Cells.Count ]; for( var i = 0; i < cellvalues.Length; i++ ) { cellvalues[ i ] = row.Cells[ i ].Value; } _table.Rows.Add( cellvalues ); } return _table; } catch( Exception ex ) { Fail( ex ); return default( DataTable ); } } /// <summary> /// The SetColumns /// </summary> /// <param name="dataGridView">The dataGridView</param> /// <param name="columns">The fields /// <see><cref> string[] </cref></see></param> /// <returns> /// The /// <see cref="System.Data.DataTable" /> /// </returns> public static DataTable SetColumns( this DataGridView dataGridView, string[ ] columns ) { if( dataGridView?.DataSource != null && columns?.Length > 0 ) { try { using var _grid = dataGridView.GetDataTable(); using var _view = new DataView( _grid ); if( _grid?.Columns.Count > 0 ) { var _table = _view.ToTable( true, columns ); return _table?.Columns?.Count > 0 ? _table : default( DataTable ); } } catch( Exception ex ) { Fail( ex ); return default( DataTable ); } } return default( DataTable ); } /// <summary> /// The SetColumns /// </summary> /// <param name="dataGridView">The dataGridView /// <see cref="DataGridView" /></param> /// <param name="fields">The fields /// <see /></param> /// <returns> /// The /// <see cref="System.Data.DataTable" /> /// </returns> public static DataTable SetColumns( this DataGridView dataGridView, Field[ ] fields ) { if( dataGridView?.DataSource != null && fields?.Length > 0 ) { try { using var _dataTable = dataGridView.GetDataTable(); using var _view = new DataView( _dataTable ); using var _grid = dataGridView.GetDataTable(); if( _grid?.Columns?.Count > 0 ) { var _columns = fields?.Select( f => f.ToString() )?.ToArray(); var _table = _view?.ToTable( true, _columns ); return _table?.Columns?.Count > 0 ? _table : default( DataTable ); } } catch( Exception ex ) { Fail( ex ); return default( DataTable ); } } return default( DataTable ); } /// <summary> /// The SetColumns /// </summary> /// <param name="dataGridView">The dataGridView /// <see cref="DataGridView" /></param> /// <param name="index">The index /// <see /></param> /// <returns> /// The /// <see cref="System.Data.DataTable" /> /// </returns> public static DataTable SetColumns( this DataGridView dataGridView, int[ ] index ) { try { using var _dataTable = dataGridView?.GetDataTable(); if( _dataTable?.Columns?.Count > 0 && index?.Length > 0 ) { var _columns = _dataTable.Columns; var _names = new string[ index.Length ]; if( _columns?.Count > 0 && _names?.Length > 0 ) { for( var i = 0; i < index.Length; i++ ) { _names[ i ] = _columns[ index[ i ] ].ColumnName; } } using var _view = new DataView( _dataTable ); var _table = _view?.ToTable( true, _names ); return _table.Columns.Count > 0 ? _table : default( DataTable ); } } catch( Exception ex ) { Fail( ex ); return default( DataTable ); } return default( DataTable ); } /// <summary> /// The CommaDelimitedRows /// </summary> /// <param name="datagridview">The dataGridView /// <see cref="DataGridView" /></param> /// <returns> /// The /// <see /> /// </returns> public static string[ ] CommaDelimitedRows( this DataGridView datagridview ) { if( datagridview?.RowCount > 0 ) { try { var _list = new List<string>(); foreach( var _row in datagridview.Rows ) { if( !( (DataGridViewRow)_row )?.IsNewRow == true ) { var _cells = ( (DataGridViewRow)_row ) ?.Cells?.Cast<DataGridViewCell>() ?.ToArray(); var _array = ( (DataGridViewRow)_row ) ?.Cells ?.Cast<DataGridViewCell>() ?.ToArray(); if( _cells?.Any() == true ) { var _item = string.Join( ",", Array.ConvertAll( _array, c => c.Value?.ToString() ) ); if( !string.IsNullOrEmpty( _item ) ) { _list?.Add( _item ); } } } } return _list?.Any() == true ? _list.ToArray() : default( string[ ] ); } catch( Exception ex ) { Fail( ex ); return default( string[ ] ); } } return default( string[ ] ); } /// <summary> /// The ExportToCommaDelimitedFile /// </summary> /// <param name="dataGridView">The dataGridView /// <see cref="DataGridView" /></param> /// <param name="fileName">The fileName /// <see cref="string" /></param> public static void ExportToCommaDelimitedFile( this DataGridView dataGridView, string fileName ) { if( !string.IsNullOrEmpty( fileName ) && dataGridView != null ) { try { var _path = Path.Combine( AppDomain.CurrentDomain.BaseDirectory, fileName ); if( !string.IsNullOrEmpty( _path ) ) { File.WriteAllLines( _path, dataGridView.CommaDelimitedRows() ); } } catch( Exception ex ) { Fail( ex ); } } } /// <summary> /// The ExpandColumns /// </summary> /// <param name="dataGridView">The dataGridView /// <see cref="DataGridView" /></param> public static void ExpandColumns( this DataGridView dataGridView ) { try { foreach( DataGridViewColumn _column in dataGridView.Columns ) { _column.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells; } } catch( Exception ex ) { Fail( ex ); } } /// <summary> /// The PascalizeHeaders /// </summary> /// <param name="dataGridView">The dataGridView /// <see cref="DataGridView" /></param> /// <param name="dataTable">The dataTable /// <see cref="System.Data.DataTable" /></param> public static void PascalizeHeaders( this DataGridView dataGridView, DataTable dataTable ) { if( dataGridView != null && dataTable?.Columns?.Count > 0 ) { try { foreach( DataGridViewColumn _column in dataGridView.Columns ) { if( !string.IsNullOrEmpty( dataTable.Columns[ _column.Name ].Caption ) ) { _column.HeaderText = dataTable.Columns[ _column.Name ].Caption; } } } catch( Exception ex ) { Fail( ex ); } } } /// <summary> /// The PascalizeHeaders /// </summary> /// <param name="dataGridView">The dataGridView /// <see cref="DataGridView" /></param> public static void PascalizeHeaders( this DataGridView dataGridView ) { if( dataGridView?.DataSource != null ) { try { using var _table = dataGridView.GetDataTable(); if( _table?.Columns?.Count > 0 ) { foreach( DataGridViewColumn _column in dataGridView.Columns ) { if( !string.IsNullOrEmpty( _table.Columns[ _column.Name ].Caption ) ) { _column.HeaderText = _table.Columns[ _column.Name ].Caption; } } } } catch( Exception ex ) { Fail( ex ); } } } /// <summary> /// Get Error Dialog. /// </summary> /// <param name="ex">The ex.</param> private static void Fail( Exception ex ) { using var _error = new Error( ex ); _error?.SetText(); _error?.ShowDialog(); } } }
4d5717f5861084140c22bcbef5470888d6fe98b3
C#
blfortier/TDD
/TDD_Smallestint-master/SmallestService/Finder.cs
3.59375
4
using System; using System.Linq; namespace SmallestService { public class Finder { public int FindSmallestInt(int[] arr) { if (arr.Length == 1) return arr[0]; else if (arr.Length == 2) return (arr[0] < arr[1]) ? arr[0] : arr[1]; else if (arr.Length >= 3) { int max = arr[0]; for (int i = 1; i < arr.Length; i++) { if (arr[i] < max) max = arr[i]; } return max; } else throw new ArgumentException(); } public int FindClosestIntToZero(int[] arr) { if (arr.Length == 0) throw new ArgumentException(); else if (arr.Length == 1) return 1; else if (arr.Length == 2) return (arr[0] < arr[1]) ? arr[0] : arr[1]; else { int closestToZero = arr[0]; for (int i = 1; i < arr.Length; i ++) { if (Math.Abs(arr[i]) < Math.Abs(closestToZero)) closestToZero = arr[i]; if ((Math.Abs(arr[i]) == Math.Abs(closestToZero)) && (arr[i] < closestToZero)) closestToZero = arr[i]; } return closestToZero; } } } }
a3de8029e9dd2f03dddbc71df6954a936b8db045
C#
lucastomazrm/pwbe-dotnet-webapi
/Services/Service[TModel].cs
2.84375
3
using System.Collections.Generic; using PWBE.TeamAthlete.DataAccess; using Microsoft.EntityFrameworkCore; using System.Linq; namespace PWBE.TeamAthlete.Services { public abstract class Services<T> : Service where T : class { public Services(MainContext context) : base(context) { } public Services() : base() { } public IEnumerable<T> All() { var query = this.context.Set<T>().AsQueryable(); foreach (var property in this.context.Model.FindEntityType(typeof(T)).GetNavigations()) { query = query.Include(property.Name); } return query; } public void Save(T item) { this.context.Set<T>().Add(item); base.Save(); } public void Save(IEnumerable<T> items) { this.context.Set<T>().AddRange(items); base.Save(); } public void Update(T item) { this.context.Set<T>().Attach(item); this.context.Entry(item).State = Microsoft.EntityFrameworkCore.EntityState.Modified; base.Save(); } public void Delete(int id) { var item = this.Get(id); this.context.Set<T>().Remove(item); base.Save(); } public T Get(object id) { return base.context.Set<T>().Find(id); } } }
6a98e5f1eaac70cfac8d60c95ba88648e3bf1402
C#
MagpieLaboratories/tpp-core
/tests/TPP.Persistence.MongoDB.Tests/Repos/MessagequeueRepoTest.cs
2.53125
3
using System.Collections.Generic; using System.Threading.Tasks; using MongoDB.Driver; using NUnit.Framework; using TPP.Model; using TPP.Persistence.MongoDB.Repos; namespace TPP.Persistence.MongoDB.Tests.Repos { public class MessagequeueRepoTest : MongoTestBase { [Test] public async Task persists_successfully() { MessagequeueRepo repo = new(CreateTemporaryDatabase()); const string ircLine = "some text"; // persist to db MessagequeueItem written = await repo.EnqueueMessage(ircLine); Assert.That(written.IrcLine, Is.EqualTo(ircLine)); Assert.NotNull(written.Id); // read from db List<MessagequeueItem> allItems = await repo.Collection .Find(FilterDefinition<MessagequeueItem>.Empty).ToListAsync(); Assert.That(allItems.Count, Is.EqualTo(1)); MessagequeueItem read = allItems[0]; Assert.That(read, Is.EqualTo(written)); Assert.That(read.IrcLine, Is.EqualTo(ircLine)); } } }
101c231857e6440c2218861cd3fa3376de4c0cdf
C#
KevinWeiHadExtra/CSC631HW4Infection
/ClientTicTacToe/Assets/Scripts/Network/Response/ResponseEnterName.cs
2.546875
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ResponseEnterNameEventArgs : ExtendedEventArgs { public int user_id { get; set; } // The user_id of whom who sent the request public string name { get; set; } // Their new name public ResponseEnterNameEventArgs() { event_id = Constants.SMSG_ENTERNAME; } } public class ResponseEnterName : NetworkResponse { private int user_id; private string name; public ResponseEnterName() { } public override void parse() { user_id = DataReader.ReadInt(dataStream); name = DataReader.ReadString(dataStream); } public override ExtendedEventArgs process() { ResponseEnterNameEventArgs args = new ResponseEnterNameEventArgs { user_id = user_id, name = name }; return args; } }
fdfe7ba4678a3f022553a986c170c5f4cc70b382
C#
CBIIT/CEC-Harmonization
/CECMapper/CECHarmonization/DATA/MapperRepository.cs
2.609375
3
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; using CECHarmonization.Models; using Ninject; namespace CECHarmonization.DATA { public class MapperRepository : IMapperRepository { /// <summary> /// We pass in the context so that we do not create it over and over (dependency injection) /// To use this we bind this context in the NinjectWebCommon.sc file /// </summary> private MapContext _ctx; public MapperRepository(MapContext ctx) { _ctx = ctx; } public IQueryable<Mapper> GetMappers() { return _ctx.Mappers; } public Mapper GetMapperByVariables(string targetId, string svaId) { try { //return _ctx.Mappers.Where(o => o.TargetVariableId == targetId && o.StudyVariableAttributeId == svaId).First(); var m = _ctx.Mappers.Where(o => o.TargetFieldId == targetId && o.StudyVariableAttributeId == svaId).First(); return m; } catch (Exception ex) { return null; } } public bool Save() { try { // return how many row changes were made (as long as it is greater than 0 return _ctx.SaveChanges() > 0; } catch (Exception ex) { // to do - log error return false; } } public bool AddMapper(Mapper m) { try { m.CreatedDate = DateTime.Now; _ctx.Mappers.Add(m); return true; } catch (Exception) { //to do - log error return false; } } public bool UpdateMapper(Mapper m) { try { m.ModifiedDate = DateTime.Now; _ctx.Entry(m).State = EntityState.Modified; // Do some more work... _ctx.SaveChanges(); foreach (MapRecord mr in m.MapRecs) UpdateMapRecord(mr); return true; } catch { return false; } } public bool UpdateMapRecord(MapRecord mr) { try { mr.ModifiedDate = DateTime.Now; _ctx.Entry(mr).State = EntityState.Modified; // Do some more work... _ctx.SaveChanges(); return true; } catch { return false; } } public bool DeleteMapper(Mapper m) { throw new NotImplementedException(); } } }
b2f0a206e60097e0d18094e6b0c9e312a9605c61
C#
sanmuru/aegisub-automations
/ChatroomEffect/tools/cre-tools/cre-dialogs/IncludePluginDialog.cs
2.546875
3
using System; using System.Data; using System.IO; using System.Linq; using System.Windows.Forms; namespace SamLu.Cre.Dialogs { public partial class IncludePluginDialog : Form { public IncludePluginDialog() { InitializeComponent(); } private void addSource(string path) { this.lvPlugins.Items.Add(new ListViewItem(new[] { "*", path }) { Checked = true }); } private void removeSource(string path) { var items = this.lvPlugins.Items.OfType<ListViewItem>().Where(item => item.SubItems[2].Text == path).ToList(); items.ForEach(item => this.lvPlugins.Items.Remove(item)); } private void btnAddFile_Click(object sender, EventArgs e) { if (this.openFileDialog1.ShowDialog() == DialogResult.OK) { foreach (var path in this.openFileDialog1.FileNames) { if (this.lbSource.Items.OfType<string>().All(item => !string.Equals(item, path, StringComparison.OrdinalIgnoreCase))) { this.lbSource.Items.Add(path); this.addSource(path); } } } } private void btnAddFolder_Click(object sender, EventArgs e) { if (this.folderBrowserDialog1.ShowDialog() == DialogResult.OK) { foreach (string path in Directory.GetFiles(this.folderBrowserDialog1.SelectedPath).Where(f => { string extension = Path.GetExtension(f); return string.Equals(extension, ".lua", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".xml", StringComparison.OrdinalIgnoreCase); } )) { if (this.lbSource.Items.OfType<string>().All(item => !string.Equals(item, path, StringComparison.OrdinalIgnoreCase))) { this.lbSource.Items.Add(path); this.addSource(path); } } } } private void btnRemove_Click(object sender, EventArgs e) { this.removeSource(this.lbSource.SelectedItem as string); this.lbSource.Items.Remove(this.lbSource.SelectedItem); } } }
5045cb25eda7de531cd858d89096faa6d83c3840
C#
MrProctor/cofoundry-flower
/src/Cofoundry.Core/Mail/Dispatch/DebugMailDispatchService.cs
2.8125
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Cofoundry.Core.Mail { /// <summary> /// This is a simple debug implementation that writes out mail /// to a text file to make debugging templates easier. This is /// also the default Cofoundry mail dispatch service and needs /// to be overidden by a plugin in order to actually dispatch /// email. /// </summary> public class DebugMailDispatchService : IMailDispatchService { #region constructor private readonly MailSettings _mailSettings; private readonly IPathResolver _pathResolver; public DebugMailDispatchService( IPathResolver pathResolver, MailSettings mailSettings ) { _mailSettings = mailSettings; _pathResolver = pathResolver; } #endregion #region public methods /// <summary> /// Sends a mail message. /// </summary> /// <param name="message">The MailMessage to send</param> public async Task DispatchAsync(MailMessage message) { using (var session = CreateSession()) { session.Add(message); await session.FlushAsync(); } } /// <summary> /// Creates a new mail session that can be used to send batches of mail. /// </summary> /// <returns>New instance of an IMailDispatchSession</returns> public IMailDispatchSession CreateSession() { return new DebugMailDispatchSession(_mailSettings, _pathResolver); } #endregion } }
0126308eb6ccb9d2555ae9fe4317f7dc664a851d
C#
olli1/tankkkipeli
/Assets/Skripti2/MAPPIGEN.cs
2.609375
3
using UnityEngine; using System.Collections; using System; public class MAPPIGEN : MonoBehaviour { public int height; public int width; public string seed; public bool useRandomSeed; [Range(0,100)] public int randomFillPercent; int[,] map; void Start(){ GenerateMap (); RandomFillMap (); } void GenerateMap(){ map = new int[width,height]; for (int i =0; i<5; i++) { smoothMap(); } } void RandomFillMap(){ if (useRandomSeed) { seed = Time.time.ToString(); } System.Random pseudoRandom = new System.Random (seed.GetHashCode ()); for (int x =0; x <width; x++) { for (int y =0; y <height; y++) { if(x==0||x==width-1||y==0||y==height-1){ map[x,y] =1; } else{ map[x,y] = (pseudoRandom.Next(0,100) <randomFillPercent)? 1: 0; } } } } void smoothMap(){ for (int x =0; x <width; x++) { for (int y =0; y <height; y++) { int neighbourWallTiles = GetSurroundingWallCount(x,y); if(neighbourWallTiles>4) map[x,y]=1; else if(neighbourWallTiles<4) map[x,y]=0; } } } int GetSurroundingWallCount (int gridx, int gridy){ int wallCount = 0; for (int neighbourx = gridx-1; neighbourx <= gridx+1; neighbourx++) { for (int neighboury = gridy-1; neighboury <= gridy+1; neighboury++) { if(neighbourx>=0 && neighbourx < width && neighboury>=0 && neighboury<height){ if(neighbourx!=gridx || neighboury!=gridy){ wallCount+=map[neighbourx,neighboury]; } } else{ wallCount++; } } } return wallCount; } void OnDrawGizmos(){ if (map != null) { for (int x =0; x <width; x++) { for (int y =0; y <height; y++) { Gizmos.color = (map[x,y] ==1)? Color.black: Color.white; Vector3 pos = new Vector3(-width/2+x+0.5f, -height/2+y+0.5f,0); Gizmos.DrawCube(pos,Vector3.one); } } } } }
809c15ca9df96fc8f02cc609e55b9b7815f5bd81
C#
officesyncpersonal/wget
/NB.Core.Web.Command/wget/CommandArgument.cs
2.859375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace wget { public enum JobType { None, EarningCalendar, FairValue } public class CommandArgument { // -e earning // -f file download // -a analysis private readonly CommandLineArgumentsParser _parser; private const string JobTypeSetting = "j"; private const string TargetFileSetting = "t"; private readonly string _targetFile; private readonly string _jobTypeStr; public CommandArgument(CommandLineArgumentsParser parser) { _parser = parser; _targetFile = GetValueOrDefault(_parser[TargetFileSetting], "tickerInfo.txt"); _jobTypeStr = _parser[JobTypeSetting]; } private string GetValueOrDefault (string field, string defaultVal) { return _parser[field] ?? defaultVal; } public JobType[] JobTypes { get { var jobs = new List<JobType>(); var jobsStr = _jobTypeStr.Split(new[] {',', ';'}, StringSplitOptions.RemoveEmptyEntries); foreach (var job in jobsStr) { JobType test; var isJob = Enum.TryParse(job, true, out test); if (isJob) { jobs.Add(test); } } return jobs.ToArray(); } } public string TargetFile { get { return _targetFile; } } } }
21d86e71a6e447314b7dfb456595597ca0e59df7
C#
Vladyslav-Kuznetsov/Chat
/ChatLib/ChatClient.cs
3.328125
3
using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading.Tasks; namespace ChatLib { public class ChatClient : IDisposable { private readonly TcpClient _client; private readonly IPEndPoint _endPoint; private StreamReader _reader; private StreamWriter _writer; public ChatClient(IPEndPoint endPoint) : this(new TcpClient()) { _endPoint = endPoint; _client.Connect(endPoint); } public ChatClient(TcpClient client) { _client = client; } public Task Start() { var stream = _client.GetStream(); _reader = new StreamReader(stream); _writer = new StreamWriter(stream); return Task.Run(() => Read()); } private void Read() { while (true) { var answer = _reader.ReadLine(); Console.WriteLine("Answer: " + answer); MessageRecivedEvent?.Invoke(this, new ChatMessageEventArgs(answer)); } } public void Write() { while (true) { //Console.Write("Enter the message: "); var msg = Console.ReadLine(); _writer.WriteLine(msg); _writer.Flush(); } } public void Send(string message) { _writer.WriteLine(message); _writer.Flush(); } public void Dispose() { _client.Dispose(); } public event EventHandler<ChatMessageEventArgs> MessageRecivedEvent; } }
9c6e1f70645be95081149ca290773f46d8bb16f3
C#
nguyentriencf/LTCSDL
/Lab5_Standard/Lab5_Standard/StudentManager.cs
3.34375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab5_Standard { public interface IDataSource { string FilePath { get; } List<Student> GetStudents(); void Save(List<Student> studentlist); } public class StudentManager { private readonly IDataSource _dataSource; private readonly List<Student> _studentList; public StudentManager(IDataSource dataSource) { _dataSource = dataSource; _studentList = _dataSource.GetStudents(); } // lấy DS sinh viên public List<Student> GetALLStudents() { return _studentList; } public void AddStudent(Student student) { if (student is null) throw new ArgumentException($"sinh viên không hợp lệ"); var isExist = _studentList.Exists(SV => SV.MSSV == student.MSSV); if (isExist) throw new ArgumentException($"Sinh viên có mã số {student.MSSV} đã tồn tại"); _studentList.Add(student); _dataSource.Save(_studentList); } public void DelByID(string MSSV) { if (string.IsNullOrWhiteSpace(MSSV)) throw new ArgumentException($"Mã số sinh viên không hợp lệ"); var student = _studentList.Find(st => st.MSSV == MSSV); if (student is null) throw new ArgumentException($"{MSSV} không hợp lệ!"); _studentList.Remove(student); _dataSource.Save(_studentList); } public void UpdateByID(string mssv, Student studentUpdate) { if (string.IsNullOrWhiteSpace(mssv)) throw new ArgumentException($"MÃ sinh viên không hợp lệ"); var isExist = _studentList.Exists(SV=> SV.MSSV == mssv); if (!isExist) throw new ArgumentException($"không tồn tại SV có {mssv}"); var index = _studentList.FindIndex(SV=> SV.MSSV == mssv); _studentList[index] = studentUpdate; _dataSource.Save(_studentList); } } }
d8fd4b21d1ee47b4c3075cbfed50d10944551c01
C#
shreyasmurthy24/HackerRank-CSharp
/GradingStudents/Program.cs
3.75
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GradingStudents { class Program { static void Main(string[] args) { int gradecount = Convert.ToInt32(Console.ReadLine()); List<int> grades = new List<int>(); for (int i = 0; i < gradecount; i++) { int gradesItem = Convert.ToInt32(Console.ReadLine().Trim()); grades.Add(gradesItem); } List<int> result = gradingStudents(grades); foreach (var item in result) { Console.WriteLine(item); } } private static List<int> gradingStudents(List<int> grades) { int addNum, addNum1, num = 0; List<int> lst = new List<int>(); foreach (var items in grades) { num = items; addNum = num + 2; addNum1 = num + 1; if (addNum % 5 == 0 && num >= 38) { num += 2; lst.Add(num); } else if (addNum1 % 5 == 0 && num >= 38) { num += 1; lst.Add(num); } else if (num < 38) { lst.Add(num); } else if (num % 5 != 0 && num >= 38) { lst.Add(num); } else { lst.Add(num); } } return lst; } } }
6078af61b62996412b8e7f49988cb64272aa4393
C#
lev1rand/EnvelopesTask
/Classes/Objects/Square.cs
3.640625
4
using System; namespace EnvelopesTask.Classes.Objects { class Square : Parallelogram //square (similiar sides), rectangle(different sides) { #region private const int DEFAULT_SIDE_LENGTH = 4; private const int DEFAULT_ANGLE_VALUE = 90; #endregion public Square() : base() { for (int index = 0; index < MAX_QUANTITY; index++) { sides[index] = DEFAULT_SIDE_LENGTH; angles[index] = DEFAULT_ANGLE_VALUE; } } public Square(double firstSide, double secondSide, int firstAngle, int secondAngle) : base(firstSide, secondSide, firstAngle, secondAngle) { } new public double CalculateHeight() { return sides[0] < sides[1] ? sides[0] : sides[1]; } new public double CalculateDiagonal() { return Math.Sqrt(sides[0] * sides[0] + sides[1] * sides[1]); } } }
a56cd785e9725e4eace60a595e24542c8a27709d
C#
gavogt/VogtPayroll5
/VogtPayroll5/PayrollConsoleReader.cs
3.671875
4
using System; using System.Collections.Generic; using System.Text; namespace VogtPayroll5 { class PayrollConsoleReader { #region GetEmployeeInfo /// <summary> /// Gets employee info /// </summary> /// <returns>An employee</returns> public Employee GetEmployeeInfo() { Console.WriteLine("What is employee's ID?"); var empID = int.Parse(Console.ReadLine()); Console.WriteLine("What is employee's name?"); var empName = Console.ReadLine(); Console.WriteLine("What is the number of hours the employee worked?"); var hoursWorked = int.Parse(Console.ReadLine()); Console.WriteLine("What is the payrate of the employee?"); var hourlyPayRate = decimal.Parse(Console.ReadLine()); return new Employee(empID, empName, hoursWorked, hourlyPayRate); } #endregion #region ReadTrueOrFalseFromConsole /// <summary> /// Read true or false from console for input loop /// </summary> /// <returns>True or False</returns> public bool ReadTrueOrFalseFromConsole() { Console.WriteLine("Would you like to add another employee? y/n"); var temp = Console.ReadLine().ToLower(); do { if (temp == "y") { return true; } else if (temp == "n") { return false; } Console.WriteLine("Please enter 'y' or 'n'!"); temp = Console.ReadLine().ToLower(); } while (temp != "y" || temp == "n"); return true; } #endregion } }
665b4e1fb909deb08c97279c0398d613251af7b3
C#
Moksiy/ComputerShop
/ComputerShop/Products/ShipmentProductsList.cs
2.78125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ComputerShop { public static class ShipmentProductsList { public static List<Product> ProductList = new List<Product>(); /// <summary> /// Добавление продукта в список /// </summary> /// <param name="item"></param> public static void Add(Product item) { ProductList.Add(item); } /// <summary> /// Очистка списка /// </summary> public static void Clear() { ProductList.Clear(); } } }
8437f8fd0463cb75d51cf9f2c3f26f58082ca121
C#
dusanrasic/Diamonds_ASP_Website
/WebProgramiranjeASP/BusinessLayer/OperationUser.cs
2.625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WebProgramiranjeASP.DataLayer; namespace WebProgramiranjeASP.BusinessLayer { public class UserDb : DbItem { #region Podaci private int idUser; private int idFunction; private string userName; private string password; private string mail; #endregion #region Svojstva public int IdUser { get { return this.idUser; } set { this.idUser = value; } } public int IdFunction { get { return this.idFunction; } set { this.idFunction = value; } } public string UserName { get { return this.userName; } set { this.userName = value; } } public string Password { get { return this.password; } set { this.password = value; } } public string Mail { get { return this.mail; } set { this.mail = value; } } #endregion } public class CriteriaUser : CriteriaForSelection { public string UserName { get; set; } public string Password { get; set; } } public abstract class OpUserBase : Operation { public CriteriaUser Criteria { get; set; } public override OperationResult execute(BaseEntities entities) { IEnumerable<UserDb> ieUsers; if ((this.Criteria == null) || (this.Criteria.UserName == null)&& (this.Criteria.Password == null)) ieUsers = from user in entities.users join userFunction in entities.userFunctions on user.userId equals userFunction.id_user select new UserDb { IdUser = user.userId, IdFunction = userFunction.id_function, UserName = user.user_name, Password = user.password, Mail = user.mail }; else ieUsers = from user in entities.users join userFunction in entities.userFunctions on user.userId equals userFunction.id_user where ((this.Criteria.UserName == null) ? true : this.Criteria.UserName == user.user_name) && ((this.Criteria.Password == null) ? true : this.Criteria.Password == user.password) select new UserDb { IdUser = user.userId, IdFunction = userFunction.id_function, UserName = user.user_name, Password = user.password, Mail = user.mail }; UserDb[] array = ieUsers.ToArray(); OperationResult obj = new OperationResult(); obj.DbItems = array; obj.Status = true; return obj; } } public class OpUserSelect : OpUserBase { } public class OpUserInsert : OpUserBase { private UserDb user; public UserDb User { get { return user; } set { user = value; } } public override OperationResult execute(BaseEntities entities) { if ((this.user != null) && !string.IsNullOrEmpty(this.user.UserName) && !string.IsNullOrEmpty(this.user.Password) && !string.IsNullOrEmpty(this.user.Mail) && (this.user.IdFunction) > 0) entities.UserInsert(this.user.UserName, this.user.Password,this.user.Mail,this.user.IdFunction); return base.execute(entities); } } public class OpUserUpdate : OpUserBase { private UserDb user; public UserDb User { get { return user; } set { user = value; } } public override OperationResult execute(BaseEntities entities) { if ((this.user != null) && (this.user.IdUser) > 0 && !string.IsNullOrEmpty(this.user.UserName) && !string.IsNullOrEmpty(this.user.Password) && !string.IsNullOrEmpty(this.user.Mail) && (this.user.IdFunction) > 0) entities.UserUpdate(this.user.IdUser, this.user.UserName, this.user.Password, this.user.Mail,this.user.IdFunction); return base.execute(entities); } } public class OpUserDelete : OpUserBase { private int idUser; public int IdUser { get { return idUser; } set { idUser = value; } } public override OperationResult execute(BaseEntities entities) { if (this.IdUser > 0) entities.UserDelete(this.idUser); return base.execute(entities); } } }
d76b424ad6122603ebc791d5bcb83eb996bbe585
C#
kurtfurbush/docs
/samples/snippets/csharp/new-in-6/Newcode.cs
3.34375
3
// <UsingStaticMath> using static System.Math; // </UsingStaticMath> // <UsingStatic> using static System.String; // </UsingStatic> using System; using System.Collections.Generic; // <usingStaticLinq> using static System.Linq.Enumerable; // </usingStaticLinq> namespace NewStyle { public class Student { // <ReadOnlyAutoPropertyConstructor> public Student(string firstName, string lastName) { // <UsingStaticString> if (IsNullOrWhiteSpace(lastName)) throw new ArgumentException(message: "Cannot be blank", paramName: nameof(lastName)); // </UsingStaticString> FirstName = firstName; LastName = lastName; } // </ReadOnlyAutoPropertyConstructor> // <ReadOnlyAutoProperty> public string FirstName { get; } public string LastName { get; } // </ReadOnlyAutoProperty> // <Initialization> public ICollection<double> Grades { get; } = new List<double>(); // </Initialization> // <FullNameExpressionMember> public string FullName => $"{FirstName} {LastName}"; // </FullNameExpressionMember> // <ToStringExpressionMember> public override string ToString() => $"{LastName}, {FirstName}"; // </ToStringExpressionMember> // <stringInterpolationFormat> public string GetGradePointPercentage() => $"Name: {LastName}, {FirstName}. G.P.A: {Grades.Average():F2}"; // </stringInterpolationFormat> } }
8dbb7899fd26fcce659b04b165592e420a1897b7
C#
RebeccaSantos/apilive
/Bussines/filmebussines.cs
2.59375
3
using System; using System.Linq; using System.Collections.Generic; namespace apilive.Bussines { public class filmebussines { Database.filmedatabase db = new Database.filmedatabase(); public Models.TbFilme ValidarInserir(Models.TbFilme tabela) { if(tabela.NmFilme==string.Empty) throw new ArgumentException("Nome é obrigatorio"); if(tabela.DsGenero==string.Empty) throw new ArgumentException("Genero é obrigatorio"); if(tabela.DtLancamento==new DateTime()) throw new ArgumentException("Data invalida"); if(tabela.NrDuracao<=0) throw new ArgumentException("Duração invalida"); if(tabela.VlAvaliacao<=0) throw new ArgumentException("Avaliação invalida"); db.Inserir(tabela); return tabela; } public List<Models.TbFilme> ConsultarPorNomeGenero (string nome, string genero) { if (string.IsNullOrEmpty(nome)) throw new ArgumentException("Nome é obrigatório."); if (string.IsNullOrEmpty(genero)) throw new ArgumentException("Gênero é obrigatório."); return db.ConsultarPorNomeGenero(nome, genero); } } }
7934c66ff82a24860ca6429beac899b489dc1e3d
C#
MaksymRybak/RobotWars
/RobotWars.Core/System/Logging/LogWriter.cs
2.6875
3
using System; using log4net; namespace RobotWars.Core.System.Logging { public class LogWriter : ILogWriter { private static readonly ILog _log = LogManager.GetLogger("RobotWars"); public void LogError(object msg, Exception exception) { _log.Error(msg, exception); } public void LogErrorFormat(string msg, params object[] args) { _log.ErrorFormat(msg, args); } public void LogDebug(object msg, Exception exception) { _log.Debug(msg, exception); } public void LogDebugFormat(string msg, params object[] args) { _log.DebugFormat(msg, args); } public void LogInfo(object msg, Exception exception) { _log.Info(msg, exception); } public void LogInfoFormat(string msg, params object[] args) { _log.InfoFormat(msg, args); } } }
bfb62d24b09d7edf23d837b37337b4c104a8261b
C#
softwareliberationarmy/DesktopWallpaper
/RandomWallpaperService/Program.cs
3.078125
3
using System; using System.Collections.Generic; using WallpaperManager; namespace RandomWallpaperService { static class Program { private static string _imageDirectory = "C:\\Images\\"; static void Main() { string imageFile = GetRandomWallpaperImage(); if (!string.IsNullOrEmpty(imageFile)) { Wallpaper.Set(imageFile); } } private static string GetRandomWallpaperImage() { List<string> images = Wallpaper.GetImages(_imageDirectory); if (images.Count > 0) { Random rnd = new Random(); int wallpaperIndex = rnd.Next(0, images.Count - 1); return images[wallpaperIndex]; } return null; } } }
a3e34d5573bf19a7f9b16c4c9d3b9b34b0862320
C#
StanislavStefanovPetrov/Software-University-SoftUni
/Databases Advanced - Entity Framework 6/DB Apps Introduction/3. Get Minion Names/Startup.cs
3.21875
3
namespace _3.Get_Minion_Names { using System; using System.Data.SqlClient; using System.IO; public class Startup { private const string ConnectionString = @" Server=DESKTOP-5FMQC2G\SQLEXPRESS; Database=MinionsDB; Integrated Security=true;"; private const string SelectionQueryPath = @"..\..\Selection query.sql"; public static void Main() { Console.Write("Enter a Villain ID: "); int villainId = int.Parse(Console.ReadLine()); using (SqlConnection connection = new SqlConnection(ConnectionString)) { connection.Open(); string cmdText = string.Format(File.ReadAllText(SelectionQueryPath), villainId); using (SqlCommand command = new SqlCommand(cmdText, connection)) { command.Parameters.AddWithValue("@villainId", villainId); using (SqlDataReader reader = command.ExecuteReader()) { ProcessSelection(reader, villainId); } } } } private static void ProcessSelection(SqlDataReader reader, int villainId) { if (reader.HasRows) { reader.Read(); Console.WriteLine($"Villain: {reader["VillainName"]}"); if (reader.IsDBNull(1)) { Console.WriteLine("(no minions)"); } else { int minionNumber = 1; while (true) { Console.WriteLine($"{minionNumber++}. {reader["MinionName"]} {reader["MinionAge"]}"); if (!reader.Read()) { break; } } } } else { Console.WriteLine($"No villain with ID {villainId} exists in the database."); } } } }
f56a4e8009904ad193c4b6ffab66b614c42beabf
C#
PavelDobranov/TelerikAcademy
/03-CSharp-Object-Oriented-Programming/03-ExtensionMethodsDelegatesLambdaLinq/11.ExtractStudentsByEmail/StudentsByEmailQuery.cs
3.78125
4
// Problem 11. Extract students by email // Extract all students that have email in abv.bg. // Use string methods and LINQ. namespace ExtractStudentsByEmail { using System; using System.Collections.Generic; using System.Linq; using DataRepository; using IEnumerableExtensions; public static class StudentsByEmailQuery { public static void Main() { var students = StudentsData.GetStudents(); Console.WriteLine("------------"); Console.WriteLine("All students"); Console.WriteLine("------------"); students.ForEach(Console.WriteLine); string domain = "abv.bg"; // Linq query var result = from student in students where student.Email.Contains(domain) select student; // Lambda //var result = students.Where(st => st.Email.Contains(domain)); Console.WriteLine("----------------------------------"); Console.WriteLine("Students that have email in {0}", domain); Console.WriteLine("----------------------------------"); result.ForEach(Console.WriteLine); } } }
dd333d48d31ef520188644942b11592134df10c4
C#
BackupTheBerlios/pwmds
/pwmds/MDS/Tests/DataGenerator.cs
3.109375
3
using System; using System.Collections.Generic; using System.Text; using System.IO; namespace MDS.Tests { class DataGenerator { public void Generate( int size) { double[] tab; //StreamWriter wr = (StreamWriter)File.OpenText("data.txt"); //= new StreamWriter(); for( int i = 0; i < size; ++i) { tab = new double[5]; SetVal(tab); //String str = Data.ProcessData.GetStringList(tab); //wr.WriteLine( str ); for(int j=0;j<4;j++) System.Console.Write(tab[j]+"* "); System.Console.WriteLine(tab[4]); // System.Console.WriteLine(str); } // wr.Close(); } public void SetVal( double[] t) { Random r = new Random(); double x = r.NextDouble(), y = r.NextDouble(); t[0] = x; t[1] = y; t[2] = (x + y)/2; t[3] = x / 2; t[4] = x * y; } } }
0388d687c1f2772aeb1da9eeb4bf3dd2d7a853f7
C#
syatin003/Wpf
/EventManagementSystem/Converters/PriceConverter.cs
2.703125
3
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Windows.Data; using EventManagementSystem.Data.Model; namespace EventManagementSystem.Converters { public class PriceConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { double retailPrice = 0; var product = (TillProduct)values[0]; if (product.Price1L1 == null && product.Price1L2 == null && product.Price1L3 == null && product.Price1L4 == null && product.Price2L1 == null && product.Price2L2 == null && product.Price2L3 == null && product.Price2L4 == null && product.Price3L1 == null && product.Price3L2 == null && product.Price3L3 == null && product.Price3L4 == null) return string.Empty; var details = (IEnumerable<TillTransactionDetail>)values[1]; var detail = details.FirstOrDefault(det => det.File == 1 & det.ItemRecord == product.Record); if (values.Any(v => v == null)) return string.Empty; if (Math.Abs(detail.Quantity) == product.Quantity1) { switch (detail.PriceLevel) { case 1: retailPrice = (double)product.Price1L1; break; case 2: retailPrice = (double)product.Price1L2; break; case 3: retailPrice = (double)product.Price1L3; break; case 4: retailPrice = (double)product.Price1L4; break; } } else if (Math.Abs(detail.Quantity) == product.Quantity2) { switch (detail.PriceLevel) { case 1: retailPrice = (double)product.Price2L1; break; case 2: retailPrice = (double)product.Price2L2; break; case 3: retailPrice = (double)product.Price2L3; break; case 4: retailPrice = (double)product.Price2L4; break; } } else { switch (detail.PriceLevel) { case 1: retailPrice = (double)product.Price3L1; break; case 2: retailPrice = (double)product.Price3L2; break; case 3: retailPrice = (double)product.Price3L3; break; case 4: retailPrice = (double)product.Price3L4; break; } } if (detail.Quantity < 0) retailPrice *= -1; return retailPrice.ToString("C"); } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
b6153e9ff25dff0f4e76dbf7d0b6b3488f7c0529
C#
fdieulle/RelayBoard
/RelayBoard/Tools.cs
3.046875
3
using System.Collections; using System.Linq; using System.Text; namespace RelayBoard { public static unsafe class Tools { public const int NB_BITS_PER_BYTE = 8; public static string SerializeBits(byte* p, int length) { var sb = new StringBuilder(); for (var i = 0; i < length; i++) { sb.Append((*p & 0x01) == 0x01 ? '1' : '0'); sb.Append((*p & 0x02) == 0x02 ? '1' : '0'); sb.Append((*p & 0x04) == 0x04 ? '1' : '0'); sb.Append((*p & 0x08) == 0x08 ? '1' : '0'); sb.Append((*p & 0x10) == 0x10 ? '1' : '0'); sb.Append((*p & 0x20) == 0x20 ? '1' : '0'); sb.Append((*p & 0x80) == 0x80 ? '1' : '0'); p++; } return new string(sb.ToString().Reverse().ToArray()); } public static string SerializeBits(BitArray a) { var sb = new StringBuilder(); for (var i = 0; i < a.Count; i++) sb.Append(a[i] ? '1' : '0'); return sb.ToString(); } } }
c827d8f13e9af9325d641b3450adbee092ffe0ce
C#
ARaie/Programmeerimine
/src/Blackjack/Blackjack.Core/Deck.cs
3.546875
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Blackjack.Core { public class Deck { private readonly List<Card> _cards; // Gives back right list according to user choice public static List<Card> List(string userInput) { if (userInput == "52") { return D52.Shuffle(); } else { return D36.Shuffle(); } } public Deck(List<Card> cards) { _cards = cards; } // Populates list with cards public static List<Card> d52() { var result = new List<Card>(); for (var suit = Suite.Club; suit <= Suite.Diamond; suit++) { for (var rank = Rank.two; rank <= Rank.ace; rank++) { var card = new Card(rank, suit, (int) rank, true); result.Add(card); } } return result; } // Populates list with cards public static List<Card> d36() { var result = new List<Card>(); for (var suit = Suite.Club; suit <= Suite.Diamond; suit++) { for (var rank = Rank.six; rank <= Rank.ace; rank++) { var card = new Card(rank, suit, (int)rank, true); result.Add(card); } } return result; } //Makes Deck from populated list public static Deck D36 = new Deck(d36()); //Makes Deck from populated list public static Deck D52 = new Deck(d52()); public List<Card> Shuffle() { // Insert cards at random order into the shuffled list var shuffled = new List<Card>(); var random = new Random(); // As long as there are any cards left to insert randomly while (_cards.Count != 0) { // Get the index of the random card to insert var i = random.Next(_cards.Count); // Insert it shuffled.Add(_cards[i]); // Remove from non-shuffled list _cards.RemoveAt(i); } return shuffled; } // Method for get next card from deck public Card Next() { Card card = null; for( int i = 0; i < _cards.Count; i++) { card = _cards[i]; _cards.RemoveAt(i); i++; return card; } return card; } } }
0e0c2d1b1c8406be7f5616132495a25e71b5926e
C#
erdemcobanoglu/aspdotnet-core-api
/CityInfo/CitiesDataStore.cs
2.703125
3
using CityInfo.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CityInfo { public class CitiesDataStore { public static CitiesDataStore Current { get; } = new CitiesDataStore(); public List<CityDto> Cities { get; set; } public CitiesDataStore() { Cities = new List<CityDto>() { new CityDto() { Id = 1, Name = "New York Cit", Description = "The one with that big park.", PointOfInterests = new List<PointOfInterestDto>() { new PointOfInterestDto() { Id = 1, Name = "Central Park", Description = "The Most visited urban in the United States." }, new PointOfInterestDto() { Id = 2, Name = "Empires State Building", Description = "A 102- story skycrapper located in Midtown Manhattan." }, } }, new CityDto() { Id = 2, Name = "Antwerp", Description = "The one with the cathedral that was never really finished.", PointOfInterests = new List<PointOfInterestDto>() { new PointOfInterestDto() { Id = 1, Name = "France Park", Description = "The Most visited urban in the France." }, new PointOfInterestDto() { Id = 2, Name = "Empires State Building", Description = "A 102- story skycrapper located in Midtown paris." }, } }, new CityDto() { Id =3 , Name = "Houston", Description ="The one with new data sience centre.", PointOfInterests = new List<PointOfInterestDto>() { new PointOfInterestDto() { Id = 1, Name = "Houston Park", Description = "The Most visited urban in the United States." }, new PointOfInterestDto() { Id = 2, Name = "Houston State Building", Description = "A 102- story skycrapper located in Midtown Housteon." }, } } }; } } }
eb06203d101cc15fc0133032e18f5d9983427b79
C#
gro-ove/actools
/AcManager/Pages/Selected/NumberToColumnsConverter.cs
2.703125
3
using System; using System.Globalization; using System.Linq; using System.Windows.Data; using AcTools.Utils.Helpers; using FirstFloor.ModernUI.Serialization; namespace AcManager.Pages.Selected { public class NumberToColumnsConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var v = value.As<int>(); var max = parameter.As<int>(); if (max < 1 || v <= max) return v; var from = max / 2; return Enumerable.Range(from, max - from + 1).Select(x => new { Colums = x, Rows = (int)Math.Ceiling((double)v / x) }).MinEntry(x => (x.Colums * x.Rows - v) * from - x.Colums).Colums; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(); } } }
76e8ecb11cabbb606cc1c84eb5b6e78f0bf0d911
C#
sheryllan/TFS
/Systematica/Matrix/MatrixHelper.cs
3.46875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Matrix { public class MatrixHelper { public bool hasRowOrColumnOfZeros(int[,] A) { int rows = A.GetLength(0); int cols = A.GetLength(1); bool found = false; for (int i = 0; i < rows; i++) { bool frow = true; bool fcol = true; for (int j = 0; j < cols; j++) { frow = (A[i, j] == 0) && frow; fcol = (A[j, i] == 0) && fcol; } found = frow || fcol; if (found) break; } return found; } public bool hasDiagonalOfZeros(int[,] A) { int rows = A.GetLength(0); int cols = A.GetLength(1); bool found = false; for (int i = 0; i < rows; i++) { int i1 = i; int j1 = 0; int i2 = 0; int j2 = i; int i3 = i; int j3 = rows - 1; int i4 = 0; int j4 = rows - 1 - i; bool f1 = true; bool f2 = true; bool f3 = true; bool f4 = true; while (i1 < rows && j2 < cols && i3 < rows && j4 >= 0) { f1 = (A[i1++, j1++] == 0) && f1; f2 = (A[i2++, j2++] == 0) && f2; f3 = (A[i3++, j3--] == 0) && f3; f4 = (A[i4++, j4--] == 0) && f4; } found = f1 || f2 || f3 || f4; if (found) break; } return found; } } }
7dbc4aaf67963f985392c1b0821047abe8eabd01
C#
Rekkuujin/bigfoot-home-ggj
/bigfoot-home-ggj/Assets/Scripts/Player/Attack.cs
2.640625
3
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Attack : MonoBehaviour { public float damage = 10f; Ray ray; RaycastHit hit; int layerMask = 1 << 9; float range = 1f; Collider[] enemies; Animator m_Animator; public Action OnAttack; void Start() { m_Animator = GetComponent<Animator>(); } void Update () { if (Input.GetKeyDown(KeyCode.E)) { StartCoroutine("AnimateAttack"); } } void ProcessAttack(){ enemies = Physics.OverlapSphere(transform.position, range, layerMask); foreach (var enemy in enemies) { House house = enemy.GetComponentInParent<House>(); if(house) { //Debug.Log("Damaging " + enemy.name); house.TakeDamage(damage); } } if(OnAttack != null) { OnAttack.Invoke(); } } IEnumerator AnimateAttack() { m_Animator.SetBool("Kicking", true); yield return new WaitForSeconds(0.15f); ProcessAttack(); yield return new WaitForSeconds(0.18f); m_Animator.SetBool("Kicking", false); } }
dbb436872043da9e10f2507c982742a343a98af6
C#
guidebee/guidebeemapdotnet
/DotNetMapDigitLib/Mapdigit.Util/Log.cs
2.84375
3
//------------------------------------------------------------------------------ // COPYRIGHT 2010 GUIDEBEE // ALL RIGHTS RESERVED. // GUIDEBEE CONFIDENTIAL PROPRIETARY ///////////////////////////////////// REVISIONS //////////////////////////////// // Date Name Tracking # Description // --------- ------------------- ---------- -------------------------- // 24SEP2010 James Shen Code review //////////////////////////////////////////////////////////////////////////////// //--------------------------------- IMPORTS ------------------------------------ using System; using System.Threading; //--------------------------------- PACKAGE ------------------------------------ namespace Mapdigit.Util { //[-------------------------- MAIN CLASS ----------------------------------] //////////////////////////////////////////////////////////////////////////// //----------------------------- REVISIONS ---------------------------------- // Date Name Tracking # Description // -------- ------------------- ------------- ---------------------- // 24SEP2010 James Shen Code review //////////////////////////////////////////////////////////////////////////// /// <summary> /// Pluggable logging framework that allows a developer to log into storage /// using the file connector API. It is highly recommended to use this /// class coupled with Netbeans preprocessing tags to reduce its overhead /// completely in runtime. /// </summary> public class Log { ///<summary> /// Constant indicating the logging level Debug is the default and the ///lowest level followed by info, warning and error ///</summary> public const int Debug = 1; /// <summary> /// Constant indicating the logging level Debug is the default and the /// lowest level followed by info, warning and error /// </summary> public const int Info = 2; ///<summary> /// Constant indicating the logging level Debug is the default and the ///lowest level followed by info, warning and error ///</summary> public const int Warning = 3; ///<summary> /// Constant indicating the logging level Debug is the default and the ///lowest level followed by info, warning and error ///</summary> public const int Error = 4; //////////////////////////////////////////////////////////////////////////// //--------------------------------- REVISIONS ------------------------------ // Date Name Tracking # Description // --------- ------------------- ------------- ---------------------- // 24SEP2010 James Shen Code review //////////////////////////////////////////////////////////////////////////// /// <summary> /// Installs a log subclass that can replace the logging destination/behavior /// </summary> /// <param name="newInstance">The new instance.</param> public static void Install(Log newInstance) { _instance = newInstance; } //////////////////////////////////////////////////////////////////////////// //--------------------------------- REVISIONS ------------------------------ // Date Name Tracking # Description // --------- ------------------- ------------- ---------------------- // 24SEP2010 James Shen Code review //////////////////////////////////////////////////////////////////////////// /// <summary> /// Default println method invokes the print instance method, uses DEBUG level /// </summary> /// <param name="text"> text to print</param> public static void P(string text) { P(text, Debug); } //////////////////////////////////////////////////////////////////////////// //--------------------------------- REVISIONS ------------------------------ // Date Name Tracking # Description // --------- ------------------- ------------- ---------------------- // 24SEP2010 James Shen Code review //////////////////////////////////////////////////////////////////////////// /// <summary> ///Default println method invokes the print instance method, uses given level /// </summary> /// <param name="text">The text.</param> /// <param name="level">The level,one of DEBUG, INFO, WARNING, ERROR</param> public static void P(string text, int level) { _instance.Print(text, level); } //////////////////////////////////////////////////////////////////////////// //--------------------------------- REVISIONS ------------------------------ // Date Name Tracking # Description // --------- ------------------- ------------- ---------------------- // 24SEP2010 James Shen Code review //////////////////////////////////////////////////////////////////////////// /// <summary> /// Sets the logging level for printing log details, the lower the value /// the more verbose would the printouts be /// </summary> /// <param name="level">The level,one of DEBUG, INFO, WARNING, ERROR</param> public static void SetLevel(int level) { _instance.level = level; } //////////////////////////////////////////////////////////////////////////// //--------------------------------- REVISIONS ------------------------------ // Date Name Tracking # Description // --------- ------------------- ------------- ---------------------- // 24SEP2010 James Shen Code review //////////////////////////////////////////////////////////////////////////// /// <summary> /// Returns the logging level for printing log details, the lower the value /// the more verbose would the printouts be /// </summary> /// <returns>one of DEBUG, INFO, WARNING, ERROR</returns> public static int GetLevel() { return _instance.level; } /// <summary> /// the level of logging. /// </summary> /// protected int level = Debug; private static Log _instance = new Log(); private readonly DateTime _zeroTime = DateTime.Now; //////////////////////////////////////////////////////////////////////////// //--------------------------------- REVISIONS ------------------------------ // Date Name Tracking # Description // --------- ------------------- ------------- ---------------------- // 24SEP2010 James Shen Code review //////////////////////////////////////////////////////////////////////////// /// <summary> /// Prints the specified text. /// </summary> /// <param name="text">The text.</param> /// <param name="debugLevel">The level.</param> protected void Print(string text, int debugLevel) { if (level > debugLevel) { return; } text = GetThreadAndTimeStamp() + " - " + text; Console.WriteLine(text); } //////////////////////////////////////////////////////////////////////////// //--------------------------------- REVISIONS ------------------------------ // Date Name Tracking # Description // --------- ------------------- ------------- ---------------------- // 24SEP2010 James Shen Code review //////////////////////////////////////////////////////////////////////////// /// <summary> /// Returns a simple string containing a timestamp and thread name.. /// </summary> /// <returns></returns> protected string GetThreadAndTimeStamp() { TimeSpan time = DateTime.Now - _zeroTime; return "[" + Thread.CurrentThread.Name + "] " + time.Hours + ":" + time.Minutes + ":" + time.Seconds + "," + time.Milliseconds; } } }
19306852227cd775d75cac58e709ba920a967355
C#
VladislavKondratenko/UniversityWeb
/University.Infractructure.Data/EntityTypeConfiguration/CourseConfiguration.cs
2.640625
3
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using University.Domain.Core; namespace University.Infrastructure.Data.EntityTypeConfiguration { internal class CourseConfiguration : IEntityTypeConfiguration<Course> { public void Configure(EntityTypeBuilder<Course> builder) { builder.ToTable("COURSES"); builder.HasKey(e => e.Id); builder.HasIndex(e => e.Name, "COURSES__INDEX") .IsUnique(); builder.Property(e => e.Id) .IsRequired() .HasColumnName("COURSE_ID"); builder.Property(e => e.Description) .IsRequired() .HasMaxLength(50) .HasColumnName("DESCRIPTION"); builder.Property(e => e.Name) .IsRequired() .HasMaxLength(30) .HasColumnName("NAME"); } } }
f46e951449449b64ede6f3e21d9b5638f7914cd9
C#
wk-j/il-syntax
/scripts/Uint/Min.csx
2.609375
3
Console.WriteLine(int.MaxValue); var range = Enumerable.Range(1, 10); foreach (var item in range) { Console.WriteLine((uint)-item); }
b170b8b99370ce8c0f65b79110de2d16a8bab6b3
C#
YexpZIS/QsFlai
/QsFlai/Preferences/Settings.cs
2.6875
3
using Microsoft.Win32; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Windows; using Newtonsoft.Json; using Sys = System.IO.File; using System.Windows.Controls; using System.Windows.Media; namespace QsFlai.Preferences { public class Settings { private readonly string name = "QsFlai.settings"; private readonly string path; private readonly string fullname; public List<Gap> gaps; public Settings() { path = Directory.GetCurrentDirectory(); fullname = String.Format("{0}/{1}", path, name); Load(); } public void Save() { string json = JsonConvert.SerializeObject(gaps); Sys.WriteAllText(fullname, json); } public void Load() { if (Sys.Exists(fullname)) { string json = Sys.ReadAllText(fullname); gaps = JsonConvert.DeserializeObject<List<Gap>>(json); if (gaps == null || gaps.Count == 0) { gaps = new List<Gap>(); gaps.Add(new Gap(0)); } } else { gaps = new List<Gap>(); gaps.Add(new Gap(0)); Save(); } } } [Serializable] public class Gap { public int id { get; set; } public Gap(int id) { this.id = id; } public TopBorder border = new TopBorder(); public string BackgroundImage { get; set; } // Путь к изображению типа постер //(при увеличении/уменьшении окна //не должно меняться в размерах) public bool isImgStaticSize = true; // Position public Point Position { get; set; } = new Point(0, 0); // Положение окна по оси X и Y // Size public Scale Scale { get; set; } = new Scale(); // Отвечает за размер окна // Animation public Animation Animation { get; set; } = new Animation();// Отвечает за настройки анимации // Files public FilesSettings filesSettings { get; set; } = new FilesSettings(); public List<File> Files { get; set; } = new List<File>(); // Список файлов, добавленных в окно // Цвета editMode public Colors editMode { get; set; } = new Colors(Color.FromArgb(100, 0, 0, 0), new Color[] { Color.FromArgb(90, 255, 0, 0), Color.FromArgb(100, 0, 0, 0)}); public Gap DeepCopy() { var gap = (Gap)this.MemberwiseClone(); gap.Scale = this.Scale.DeepCopy(); return gap; } } public class TopBorder { public string Name { get; set; } = "Window"; // Название окна public Color BorderColor { get; set; } = Color.FromArgb(128, 0, 0, 0); // Цвет верхней полоски public Color TextColor { get; set; } = Color.FromArgb(255, 255, 255, 255); public FontFamily FontFamily { get; set; } = new FontFamily("Segoe UI"); public double FontSize { get; set; } = 20; public int TextHeight { get; set; } = 40; public int BorderHeight { get; set; } = 30; } public class Scale { // Статическую шириру/высоту можно получить при указании одинаковых значений в Initial и Final public Size Initial { get; set; } = new Size(120, 30); // Начальный размер (min) public Size Final { get; set; } = new Size(800, 450); // Конечный размер (max) public Scale DeepCopy() { return (Scale)this.MemberwiseClone(); } } public class Colors { public Color originalColor { get; set; } = Color.FromArgb(100, 0, 0, 0); public Color[] colors { get; set; } public Colors() { } public Colors(Color originalColor, Color[] colors) { this.originalColor = originalColor; this.colors = colors; } } public class Animation { public int Speed { get; set; } = 1000; // Скорость всех анимаций в милисекундах } public class File { public int id { get; set; } public string Name { get; set; } // Название файла public string Image { get; set; } //Изображение в формате Base64 public string Link { get; set; } // Ссылка на файл } public class FilesSettings { public Size Size { get; set; } = new Size(80, 110); public double blockHeight { get; set; } = 40; public Thickness Margin { get; set; } = new Thickness(1); // Text public Color TextColor { get; set; } = Color.FromArgb(255, 255, 255, 255); public FontFamily FontFamily { get; set; } = new FontFamily("Agency FB"); public double FontSize { get; set; } = 20; // Border public Color BackgroundColor { get; set; } = Color.FromArgb(128, 0, 0, 0); public Color BorderColor { get; set; } = Color.FromArgb(255, 0, 0, 0); public Thickness BorderSize { get; set; } = new Thickness(1); } }
729374fae48526ec9c898ba532958cc425817cdf
C#
injekt666/InMemoryLoaderCommon
/Obsolete.PowerUpUtils/PowerUpDateTimeUtils/DateTimeUtils.CalendarWeekStartDate.cs
2.578125
3
// // DateTimeUtils.CalendarWeekStartDate.cs // // Author: responsive kaysta // // Copyright (c) 2017 responsive kaysta // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using InMemoryLoaderBase; using System.Globalization; namespace PowerUpDateTimeUtils { public partial class DateTimeUtils : AbstractComponent { /// <summary> /// Berechnet das Startdatum einer deutschen Kalenderwoche /// </summary> /// <param name="calendarWeek">Die Kalenderwoche</param> /// <param name="year">Das Jahr</param> /// <returns>Gibt das Datum zurück, an dem die Kalenderwoche beginnt</returns> public DateTime GetGermanCalendarWeekStartDate (int calendarWeek, int year) { // Datum für den 4.1. des Jahres ermitteln var baseDate = new DateTime (year, 1, 4); // Den Montag dieser Woche ermitteln int dayOfWeek = (int)baseDate.DayOfWeek; baseDate = dayOfWeek > 0 ? baseDate.AddDays ((dayOfWeek - 1) * -1) : baseDate.AddDays (-6); // Das Ergebnisdatum ermitteln return baseDate.AddDays ((calendarWeek - 1) * 7); } /// <summary> /// Berechnet das Startdatum einer internationalen Kalenderwoche /// </summary> /// <param name="calendarWeek">Die Kalenderwoche</param> /// <param name="year">Das Jahr</param> /// <returns>Gibt das Datum zurück, an dem die Kalenderwoche beginnt</returns> public DateTime GetCalendarWeekStartDate (int calendarWeek, int year) { // Basisdatum (1.1. des angegebenen Jahres) ermitteln var startDate = new DateTime (year, 1, 1); // Das Datum des ersten Wochentags dieser Woche ermitteln while (startDate.DayOfWeek != CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek) { startDate = startDate.AddDays (-1); } // Die Kalenderwoche ermitteln: Wenn es sich um die Woche 1 handelt, // ist dies das Basisdatum für die Berechnung, wenn nicht, müssen // sieben Tage aufaddiert werden var cw = GetCalendarWeek (startDate); if (cw.Week != 1) { startDate = startDate.AddDays (7); } // Das Ergebnisdatum ermitteln return startDate.AddDays ((calendarWeek - 1) * 7); } } }
1db6f4285633698a9ee86ce5ea2909ea670968db
C#
ajwhitehead88/tridion-couchbase-delivery
/src/net/CouchbaseDelivery.Data.ContentModel/Serializers/ContentSerializer.cs
2.9375
3
using CouchbaseDelivery.Data.ContentModel.Contract.Model; using CouchbaseDelivery.Data.ContentModel.Contract.Serializers; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace CouchbaseDelivery.Data.ContentModel.Serializers { /// <summary> /// Helper serialiser class to convert published data to JSON and back /// </summary> public class ContentSerializer<T> : IContentSerializer<T> where T : IPublishedDataModel { private readonly JsonSerializerSettings _settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), DateFormatHandling = DateFormatHandling.IsoDateFormat, Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore, TypeNameHandling = TypeNameHandling.None }; /// <summary> /// Serialise published data to JSON /// </summary> /// <param name="model"></param> /// <returns></returns> public string Serialize(T model) { return JsonConvert.SerializeObject(model, _settings); } /// <summary> /// Deserialise published data to from JSON /// </summary> /// <param name="json"></param> /// <returns></returns> public T Deserialize(string json) { return JsonConvert.DeserializeObject<T>(json, _settings); } } }
1458e0d96486736a4c5213f2bc8d8faf54390e31
C#
sevdalin/Software-University-SoftUni
/Db Advanced - EF Core/03. EntityFramework Code-First/01. Define class Person/Models/Student.cs
3.046875
3
namespace _01.Define_class_Person.Models { public class Student { private static int count = 0; public Student(string name) { this.Name = name; Count++; } public string Name { get; set; } public static int Count { get { return count; } private set { count = value; } } } }
0647b3a923570cb20862b03a274460dedff2fec1
C#
ShazJ/AzureCSharp
/Azure/sas-storage/Program.cs
3.203125
3
using Microsoft.Azure.Storage; using Microsoft.Azure.Storage.Blob; using System; namespace sas_storage { class Program { string storageConnect; string policyName; static void Main(string[] args) { sas(); } static void sas() { // Prompt a user for information on the storage account, policy name, and container name Console.WriteLine("Enter policy name"); string policyName = Console.ReadLine(); Console.WriteLine("Enter the storage account connection string"); string storageConnectionString = Console.ReadLine(); Console.WriteLine("Enter the container name"); string name = Console.ReadLine(); //Connect to the storage account with the appropriate storage connection string var storageConnect = CloudStorageAccount.Parse(storageConnectionString); //Create the blob client to reference the container name CloudBlobClient blob = storageConnect.CreateCloudBlobClient(); CloudBlobContainer containerName = blob.GetContainerReference(name); //Create a new shared access policy that allows for reading and listing container contents SharedAccessBlobPolicy sharedPolicy = new SharedAccessBlobPolicy() { Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.List }; //Retrieve existing permissions BlobContainerPermissions perms = containerName.GetPermissions(); perms.SharedAccessPolicies.Add(policyName, sharedPolicy); //Set new permissions from the shared access policy that was created. containerName.SetPermissions(perms); } } }
3cc29b1df28948678dd9efc97a237dafb44f4f4c
C#
ralumbaugh/C-Sharp-Hackathon
/Characters/samurai.cs
3.484375
3
using System; namespace Really_Fun_Game { class Samurai : Character { // Constructors public Samurai(string name) : base(name) { this.IsAlive = true; this.Strength = 3; this.Health = 200; this.MaxHealth = 200; } // public Samurai(string name, int strength, int intelligence, int dexterity, int health) : base(name, strength, intelligence, dexterity, health) // { // this.MaxHealth=health; // } // Methods public override void Attack(Character target) { if(this.IsAlive == false) { Console.WriteLine($"{this.Name} dramatically starts to get back onto their knee. Nope! {this.Name}'s foot slips out beneath themself. {this.Name} is dead!"); } else if(this == target) { Console.Write($"{this.Name} draws their sword out for a moment, then resheathes it. Perhaps attacking yourself isn't a good plan."); } else if(target.IsAlive == false) { Console.WriteLine($"Show some mercy {this.Name}! You can only cut {target.Name} into so many pieces!"); } else { Console.WriteLine($"{this.Name} slashes into {target.Name}!"); target.Health = target.Health-(5*this.Strength); if(target.Health < 50) { target.Health = 0; target.IsAlive = false; } Console.WriteLine($"{target.Name} has {target.Health} left!"); } } public override void SpecialMove(Character target) { if(this.IsAlive == false) { Console.WriteLine($"Nice try, {this.Name} but you can't stretch your way out of death!"); } else { this.Health = this.MaxHealth; } } } }
9da7098d5fea13c0b6e89a99bed35b3eab07c246
C#
hahaking119/ds568
/SDG.Cache/CacheUtility.cs
2.75
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Caching; using System.Web; namespace SDG.Cache { public class CacheUtility { public static void Insert(string cacheKey, object value, CacheDependency cacheDependency) { HttpRuntime.Cache.Insert(cacheKey, value, cacheDependency, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(10.0)); } /// <summary> /// 插入缓存 /// </summary> /// <param name="cacheKey">缓存键名称</param> /// <param name="value">缓存对像</param> /// <param name="cacheDependency">缓存依赖项</param> /// <param name="cacheMinutes">缓存时间,以分钟为单位</param> /// <param name="IsAbsolute">是否使用绝对过期</param> public static void Insert(string cacheKey, object value, CacheDependency cacheDependency, double cacheMinutes, ExpiType expiType) { if (expiType.Equals(ExpiType.绝对过期)) { HttpRuntime.Cache.Insert(cacheKey, value, cacheDependency, DateTime.Now.AddMinutes(cacheMinutes), TimeSpan.Zero); } else { HttpRuntime.Cache.Insert(cacheKey, value, cacheDependency, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(cacheMinutes)); } } public static object Get(string cacheKey) { return HttpRuntime.Cache.Get(cacheKey); } public static void Remove(string cacheKey) { HttpRuntime.Cache.Remove(cacheKey); } public enum ExpiType { 绝对过期, 延时过期 } } }
d77785d8c83128a6841b4104a7f0e28471694ecc
C#
mandakiniagrawal/PromotionsEngine
/PromotionsEngine/Model/XProduct.cs
3.125
3
using PromotionsEngine.Interfaces; namespace PromotionsEngine.Models { class XProduct : IPack { public XProduct() { cProduct = new CProduct(); dProduct = new DProduct(); } readonly CProduct cProduct; readonly DProduct dProduct; public int ProductsCCount { get; set; } public int ProductsDCount { get; set; } public int GetPrice() { int promotionPrice; if (ProductsCCount > ProductsDCount) { promotionPrice = ProductsDCount; ProductsCCount -= ProductsDCount; } else if (ProductsCCount < ProductsDCount) { promotionPrice = ProductsDCount; ProductsDCount -= ProductsCCount; } else { promotionPrice = ProductsDCount; ProductsCCount = ProductsDCount = 0; } var x = 30 * promotionPrice + cProduct.GetPrice() * ProductsCCount + dProduct.GetPrice() * ProductsDCount; return x; } } }
2b629425fc2223b5de41961b1b57471e28163568
C#
bswanson58/NoiseMusicSystem
/MilkBottle/HueLighting/Dto/UiBulb.cs
2.59375
3
using System.Windows.Media; namespace HueLighting.Dto { public class UiBulb { private readonly Bulb mBulb; public Color LightColor { get; } public double Top => ( mBulb.Location.Y * 100 ) + 100; public double Left => ( mBulb.Location.X * 100 ) + 100; public double Height => mBulb.Location.Z + 2; public string Description => $"{mBulb.Name} ({mBulb.Id})"; public UiBulb( Bulb bulb, Color color ) { mBulb = bulb; LightColor = color; } } }
85024ab99f953dc6783d55102023cdf0f64c34be
C#
Eibwen/Ai-Challenge-2010-PlanetWars
/Fanny_Heirdoo Suite V2/botDebug/botDebugBase.cs
3.125
3
using botDebug; using System.Text; using System; using System.Linq; namespace PlanetDebug { /// <summary> /// Base class for the 'debugging system' /// It has not been thought out, I just tried to create a system that /// would leave as much intact from the original samples as possible. /// . /// If they ever update the default bots, integrating the new version into /// the debugger should be as simple as possible. /// </summary> public abstract class botDebugBase { StringBuilder _outputBuffer = new StringBuilder(); /// <summary> /// Gets or sets the ID. /// </summary> /// <value>The ID.</value> public int Id { get; set; } /// <summary> /// Resets this instance. /// </summary> public virtual void Reset() { } public void IssueOrder(string command) { _outputBuffer.AppendLine(command); if (IssueOrderCallback != null) { IssueOrderCallback(this.Id, command); } } public Func<int, string, int> IssueOrderCallback; /// <summary> /// Gets or sets the output buffer. /// </summary> /// <value>The output buffer.</value> public string OutputBuffer { get { return _outputBuffer.ToString(); } } /// <summary> /// Clears this instance. /// </summary> public void Clear() { _outputBuffer.Length = 0; } /// <summary> /// Gets or sets the game board data. /// </summary> /// <value>The game board data.</value> public string GameBoardData { get; set; } /// <summary> /// The pattern of the default bots would be to create a game board /// (GameWars) and then have the bot do a move on the board. /// I split this into two parts, here you should create the board and store it on a member. /// </summary> /// <param name="gameData">The game data.</param> public abstract void CreateGameBoardInstance(); /// <summary> /// In CreateGameBoardInstance you have created the gameboard, now use it with your bot. /// </summary> public abstract void DoMove(); /// <summary> /// Planets the can survive attack query. /// </summary> /// <param name="planetId">The planet id.</param> /// <returns></returns> public virtual bool QueryPlanetCanSurviveAttack(int planetId) { return true; } /// <summary> /// Determines whether [is dominating query]. /// </summary> /// <returns> /// <c>true</c> if [is dominating query]; otherwise, <c>false</c>. /// </returns> public virtual bool QueryIsDominating() { return false; } } }
9aac436a593aba1c5a01d656d9645cc768bd2ce5
C#
ryik5/mySCA2
/Classes/Common/TaskExtensions.cs
2.90625
3
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ASTA.Classes { public static class ForEachAsyncExtension { public static Task ForEachAsync<T>(this IEnumerable<T> source, int dop, Func<T, Task> body) { return Task.WhenAll(from partition in Partitioner.Create(source).GetPartitions(dop) select Task.Run(async delegate { using (partition) while (partition.MoveNext()) await body(partition.Current).ConfigureAwait(false); })); } } /* public static class TaskExtensions { public static Task ForEachAsync<T>(this IEnumerable<T> source, int dop, Func<T, Task> body) { return Task.WhenAll( from partition in Partitioner.Create(source).GetPartitions(dop) select Task.Run(async delegate { using (partition) while (partition.MoveNext()) await body(partition.Current); })); } public static Task ForEachAsyncWithExceptios<T>( this IEnumerable<T> source, int dop, Func<T, Task> body) { ConcurrentQueue<Exception> exceptions = null; return Task.WhenAll( from partition in Partitioner.Create(source).GetPartitions(dop) select Task.Run(async delegate { using (partition) { while (partition.MoveNext()) { try { await body(partition.Current); } catch(Exception e) { LazyInitializer. EnsureInitialized(ref exceptions).Enqueue(e); } } } })); } } */ }
86371c0a0b7b6a123c92c7be98fff73c2a60101f
C#
MatsLevi/DistroLab2
/DistroLab2/DistroLab2/Models/Mail_Models/MailUser.cs
3
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace DistroLab2.Models.Mail_Models { /// <summary> /// Model that contains user data /// </summary> public class MailUser { private int id { get; set; } private string username { get; set; } private int removedMess { get; set; } private int totalMess { get; set; } private int readMess { get; set; } /// <summary> /// empty constructor /// </summary> public MailUser() { id = -1; username = null; removedMess = -1; totalMess = -1; readMess = -1; } /// <summary> /// constructor taking username input /// </summary> /// <param name="username"></param> string containing user username public MailUser(string username) { id = -1; this.username = username; removedMess = 0; totalMess = 0; readMess = 0; } /// <summary> /// Constructor taking multiple inputs /// </summary> /// <param name="id"></param> int containing user id /// <param name="username"></param> string containing user username /// <param name="removedMess"></param> int containing number of removed messages /// <param name="totalMess"></param> int containing total recieved messages /// <param name="readMess"></param> int containing number of read messages public MailUser(int id, string username, int removedMess, int totalMess, int readMess) { this.id = id; this.username = username; this.removedMess = removedMess; this.totalMess = totalMess; this.readMess = readMess; } /// <summary> /// Getter and setter for username /// </summary> public string Username { get { return username; } set { username = value; } } } }
c4a3af7ef4ba61fbc0f0a8b86cc3745099ecee6d
C#
jasoncavaliere/leanandmean
/Samples/WritingToTheEventStore/WriterApp/ReadWriteCommon/Subscriber/OrderedStreamHandler.cs
2.875
3
using System; using System.Net; using System.Text; using EventStore.ClientAPI; using Newtonsoft.Json; using ReadWriteCommon.Publisher; namespace ReadWriteCommon.Subscriber { public interface IOrderedStreamHandler<TEventType> { void ReadStream(); } public abstract class OrderedStreamHandler<TEventType> : IOrderedStreamHandler<TEventType> { private readonly IHandleEvent<TEventType> _handleOrderCreated; private readonly EventStream _stream; protected OrderedStreamHandler(IHandleEvent<TEventType> handleOrderCreated) { _handleOrderCreated = handleOrderCreated; _stream = GetStreamInfo(); } public IEventStoreConnection BuildConnection() { var settings = ConnectionSettings.Create() .LimitRetriesForOperationTo(1) .LimitAttemptsForOperationTo(1) .LimitConcurrentOperationsTo(1) .FailOnNoServerResponse() .LimitReconnectionsTo(5); return EventStoreConnection.Create(settings, new IPEndPoint(IPAddress.Loopback, 1113)); } public EventStream GetStreamInfo(string streamName = null) { return new EventStream { EventFullTypeName = typeof(TEventType).FullName, StreamName = typeof(TEventType).Name }; } public void ReadStream() { var conn = BuildConnection(); conn.ConnectAsync().Wait(); conn.SubscribeToStreamFrom(_stream.StreamName, StreamPosition.Start ,true, (_, x) => { Console.WriteLine("Starting event {0}", x.Event.EventNumber); try { var data = JsonConvert.DeserializeObject<TEventType>(Encoding.ASCII.GetString(x.Event.Data)); _handleOrderCreated.Handle(data); Console.WriteLine("Wrote event # {0}, type {1}", x.Event.EventNumber, data.GetType().FullName); } catch (Exception ex) { Console.WriteLine("Error from event # {0}, type {1}", x.Event.EventNumber, ex.Message); throw; } }); Console.WriteLine("waiting for events. press enter to exit"); Console.ReadLine(); } } }
a8c3f123351c483392b3ebd54a84a75c7dc0c90d
C#
waltersoto/brief
/Brief/ConnectionString.cs
2.515625
3
 using System.Data.Common; namespace Brief { public class ConnectionString : DbConnectionStringBuilder { public ConnectionString() { } public ConnectionString(bool useOdbcRules) : base(useOdbcRules) { } public ConnectionString(string connectionString) : this(false, connectionString) { } public ConnectionString(bool useOdbcRules, string connectionString) : base(useOdbcRules) { ConnectionString = connectionString; } } }
e837e829d0aa725d8aaa240baa63008de30797f5
C#
HeshamMeneisi/WIS
/Windows Input Simulator/IconReader.cs
2.578125
3
using System.Runtime.InteropServices; using System.Drawing; using System; using System.IO; public class IconReader { // Fields private const uint conFILE_ATTRIBUTE_DIRECTORY = 0x10; private const uint conFILE_ATTRIBUTE_NORMAL = 0x80; private const int conMAX_PATH = 260; // Methods [DllImport("User32.dll")] private static extern int DestroyIcon(IntPtr hIcon); public static Icon GetFileIcon(string filePath, EnumIconSize size, bool addLinkOverlay) { EnumFileInfoFlags flags = EnumFileInfoFlags.ICON | EnumFileInfoFlags.USEFILEATTRIBUTES; if (addLinkOverlay) { flags |= EnumFileInfoFlags.LINKOVERLAY; } if (size == EnumIconSize.Small) { flags |= EnumFileInfoFlags.SMALLICON; } ShellFileInfo psfi = new ShellFileInfo(); SHGetFileInfo(filePath, 0x80, ref psfi, (uint)Marshal.SizeOf(psfi), (uint)flags); Icon icon = (Icon)Icon.FromHandle(psfi.hIcon).Clone(); DestroyIcon(psfi.hIcon); return icon; } public static Icon GetFileIconByExt(string fileExt, EnumIconSize size, bool addLinkOverlay) { Icon icon; string path = Path.GetTempPath() + Guid.NewGuid().ToString("N") + fileExt; try { File.WriteAllBytes(path, new byte[1]); icon = GetFileIcon(path, size, addLinkOverlay); } finally { try { File.Delete(path); } catch (Exception) { } } return icon; } public static Icon GetFolderIcon(EnumIconSize size, EnumFolderType folderType) { return GetFolderIcon(null, size, folderType); } public static Icon GetFolderIcon(string folderPath, EnumIconSize size, EnumFolderType folderType) { EnumFileInfoFlags flags = EnumFileInfoFlags.ICON | EnumFileInfoFlags.USEFILEATTRIBUTES; if (folderType == EnumFolderType.Open) { flags |= EnumFileInfoFlags.OPENICON; } if (EnumIconSize.Small == size) { flags |= EnumFileInfoFlags.SMALLICON; } ShellFileInfo psfi = new ShellFileInfo(); SHGetFileInfo(folderPath, 0x10, ref psfi, (uint)Marshal.SizeOf(psfi), (uint)flags); Icon icon = (Icon)Icon.FromHandle(psfi.hIcon).Clone(); DestroyIcon(psfi.hIcon); return icon; } [DllImport("Shell32.dll")] private static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref ShellFileInfo psfi, uint cbFileInfo, uint uFlags); // [Flags] private enum EnumFileInfoFlags : uint { ADDOVERLAYS = 0x20, ATTR_SPECIFIED = 0x20000, ATTRIBUTES = 0x800, DISPLAYNAME = 0x200, EXETYPE = 0x2000, ICON = 0x100, ICONLOCATION = 0x1000, LARGEICON = 0, LINKOVERLAY = 0x8000, OPENICON = 2, OVERLAYINDEX = 0x40, PIDL = 8, SELECTED = 0x10000, SHELLICONSIZE = 4, SMALLICON = 1, SYSICONINDEX = 0x4000, TYPENAME = 0x400, USEFILEATTRIBUTES = 0x10 } public enum EnumFolderType { Open, Closed } public enum EnumIconSize { Large, Small } [StructLayout(LayoutKind.Sequential)] private struct ShellFileInfo { public const int conNameSize = 80; public IntPtr hIcon; public int iIndex; public uint dwAttributes; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string szDisplayName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string szTypeName; } }
5bfb0a6a3edd69ebefc7fca669cf0dacb1bff8fd
C#
gauravgaikwad777/Magic-Estate-RealitySearch-ASP
/Assign5/SignUp.aspx.cs
2.53125
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Data.SqlClient; using System.Net.Mail; using System.Web.UI.WebControls; namespace Assign5 { public partial class SignUp : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { back.Visible = false; if(Session["usession"]!=null) { Panel1.Visible = false; back.Visible = true; Button2.Visible = false; Button1.Enabled = false; Label6.Text = "Please Sign Out First to Sign Up!<br/>"; } if (Session["usession"] == null) { Button3.Visible = false; } } protected void Button1_Click(object sender, EventArgs e) { if (Page.IsPostBack) { Page.Validate(); if (Page.IsValid) { string first = TextBox1.Text; string last = TextBox2.Text; string UserID = TextBox3.Text; string pass = TextBox4.Text; string cpass = TextBox5.Text; string email = TextBox6.Text; string securQ = TextBox7.Text; string securA = TextBox8.Text; int costmin = Convert.ToInt32(TextBox9.Text); int costmax = Convert.ToInt32(TextBox10.Text); int sizemin = Convert.ToInt32(TextBox11.Text); int sizemax = Convert.ToInt32(TextBox12.Text); string cat = DropDownList1.SelectedItem.Text; SqlConnection dbConnection = new SqlConnection(""); try { dbConnection.Open(); } catch (SqlException exception) { Response.Write("<p>Error code " + exception.Number + ": " + exception.Message + "</p>"); } finally { string SQLString = "SELECT * FROM usertable WHERE UserID='" + TextBox3.Text + "';"; SqlCommand checkIDTable = new SqlCommand(SQLString, dbConnection); SqlDataReader cc = checkIDTable.ExecuteReader(); if (costmin > costmax) { Label2.Text = "Minimum Cost must be lower them Maximum cost"; } if (sizemin > sizemax) { Label4.Text = "Minimum size must be lower them Maximum size"; } if (cc.HasRows) { UserAvailability.Text = "<br/><font color=\"red\"><b>User Id already exists</b></font><br/>"; } else { cc.Close(); Console.Write("Successfully selected the database"); string studentInfo = "INSERT INTO usertable VALUES('" + first + "', '" + last + "', '" + UserID + "', '" + pass + "', '" + cpass + "', '" + email + "', '" + securQ + "', '" + securA + "', '" + cat + "', '" + costmin + "', '" + costmax + "', '" + sizemin + "', '" + sizemax + "', '" + "True')"; string studentInfo1 = "INSERT INTO logintable VALUES('" + UserID + "', '" + pass + "');"; Console.Write("Inserted"); SqlCommand sqlCommand = new SqlCommand(studentInfo, dbConnection); sqlCommand.ExecuteNonQuery(); SqlCommand sqlCommand1 = new SqlCommand(studentInfo1, dbConnection); sqlCommand1.ExecuteNonQuery(); dbConnection.Close(); SmtpClient mailClient = new SmtpClient(); MailMessage mail = new MailMessage("magicestate3@gmail.com", TextBox6.Text); string body = "Congratulations, you have successfully Signed Up!! <br>" + "Welcome " + TextBox2.Text + ", " + TextBox1.Text + "!!!!!<br /> With Username : <b>" + TextBox3.Text + "</b><br /> and Password :<b> " + TextBox4.Text + "</b><br /> Confirm Password : " + TextBox5.Text + "<br /> EmailID : " + TextBox6.Text + "<br /> Security Question : " + TextBox7.Text + "<br /> Security Answer : " + TextBox8.Text + "<br /> Categories of Interest : " + cat + "<br /> Cost: Min : " + TextBox9.Text + " and Max :" + TextBox10.Text + "<br /> Size: Min : " + TextBox11.Text + " and Max :" + TextBox12.Text + "<br/>"; string path = Server.MapPath("images/isulogo.jpg"); LinkedResource logo = new LinkedResource(path); logo.ContentId = "MyLogo"; AlternateView altview = AlternateView.CreateAlternateViewFromString("<img src=cid:MyLogo/><br />" + body, null, "text/html"); altview.LinkedResources.Add(logo); mail.AlternateViews.Add(altview); mail.Subject = "Registration Confirmation"; mailClient.Send(mail); Response.Redirect("Registered.aspx"); } cc.Close(); } } } } protected void Button2_Click(object sender, EventArgs e) { Response.Redirect("Login.aspx"); } protected void back_Click(object sender, EventArgs e) { Response.Redirect("Confirmation.aspx"); } protected void Button3_Click(object sender, EventArgs e) { Session["usession"] = ""; Session.Clear(); Response.Redirect("Default.aspx"); } protected void Username_Changed(object sender, EventArgs e) { SqlConnection dbConnection = new SqlConnection(""); try { dbConnection.Open(); } catch (SqlException exception) { Response.Write("<p>Error code " + exception.Number + ": " + exception.Message + "</p>"); } finally { string SQLString = "SELECT * FROM usertable WHERE UserID='" + TextBox3.Text + "';"; SqlCommand checkIDTable = new SqlCommand(SQLString, dbConnection); SqlDataReader cc = checkIDTable.ExecuteReader(); if (cc.HasRows) { UserAvailability.Text = "Username taken, sorry."; UserAvailability.ForeColor = System.Drawing.Color.Red; } else { UserAvailability.Text = "Username available!"; } cc.Close(); dbConnection.Close(); } } } }
0b9f337786f5d1a864f282e37d900bb9c3757f9b
C#
SaurabhNijhawan/CSharpAlgorithmsAndDataStructures
/DSAndAlgorithms.Tests/ArrayAlgorithmsTests.cs
3.265625
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using DSAndAlgorithms.DataStructures.Arrays; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace DSAndAlgorithms.Tests { [TestClass] public class ArrayAlgorithmsTests { [TestMethod] public void ArrayAlgorithms_FindNonRepeatedElementsUsingMap_1_Missing_Element_Should_Return_Non_Repeated_Element() { // Arrange var input = new int[] {1,7,2,6,2,7,6}; // Act var output = ArrayAlgorithms.FindNonRepeatedElementUsingMap(input); // Assert Assert.AreEqual(1, output); } [TestMethod] public void ArrayAlgorithms_FindNonRepeatedElementsUsingMap_No_Missing_Elements_Should_Return_Minus_1() { // Arrange var input = new int[] { 1, 7, 2, 6, 2, 7, 6, 1 }; // Act var output = ArrayAlgorithms.FindNonRepeatedElementUsingMap(input); // Assert Assert.AreEqual(-1, output); } [TestMethod] public void ArrayAlgorithms_FindMissingElementUsingSum_Should_Return_Missing_Element() { // Arrange var input = new int[] { 1,4,0,3,2,7,6 }; // Act var output = ArrayAlgorithms.FindMissingNumberUsingSum(input); // Assert Assert.AreEqual(5, output); } [TestMethod] public void ArrayAlgorithms_FindMissingElementUsingXOR_Should_Return_Missing_Element() { // Arrange var input = new int[] { 1, 4, 0, 3, 2, 7, 6 }; // Act var output = ArrayAlgorithms.FindMissingNumberUsingXOR(input); // Assert Assert.AreEqual(5, output); } [TestMethod] public void ArrayAlgorithms_FindCombinationSuchThatPHValueIsNeutralized_Test() { // Arrange var input = new PhValue[] { new PhValue() { Element = "CA", Value = -3 }, new PhValue() { Element = "AR", Value = 3 }, new PhValue() { Element = "MN", Value = 6 }, new PhValue() { Element = "PD", Value = 8 } }; // Act ArrayAlgorithms.FindCombinationSuchThatPHValueIsNeutralized(input); } [TestMethod] public void ArrayAlgorithms_Replace0With5_Input_102_Output_ShouldBe_152_Test() { // Arrange var input = 102; // Act var output= ArrayAlgorithms.Replace0With5InIntegerValue(input); // Assert Assert.AreEqual(152, output); } [TestMethod] public void ArrayAlgorithms_Replace0With5_Input_1002_Output_ShouldBe_1552_Test() { // Arrange var input = 1002; // Act var output = ArrayAlgorithms.Replace0With5InIntegerValue(input); // Assert Assert.AreEqual(1552, output); } [TestMethod] public void ArrayAlgorithms_PrintMatrixInSpiralForm_Test() { // Arrange var input = new int[,] { {1,2,3,4,5}, {6,7,8,9,10}, {11,12,13,14,15} }; // Act ArrayAlgorithms.PrintMatrixInSpiralForm(input); } [TestMethod] public void Sample() { ChildClass cd = new ChildClass(); int a = 4; cd.Func(a); cd.Funct(new C()); } public void wrongmethod() { wrongmethod(); } private class B { } class C: B { } class BaseClass { public virtual void Func(int a) { Console.Write("base int"); } public virtual void Funct(C b) { } } class ChildClass: BaseClass { public override void Func(int a) { Console.Write("der int"); } public void Func(object a) { Console.Write("der object"); } public override void Funct(C b) { } public void Funct(B b) { } } } }
96f50b34fde46cbfef6a91c7cb23fb679615f2b2
C#
xibeilang524/AC
/AC.Base.Forms.Windows/Manages/Department.cs
2.5625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using AC.Base; namespace AC.Base.Forms.Windows.Manages { /// <summary> /// 路灯处各部门。 /// </summary> [ClassifyType("路灯处", true)] public class Department : Organization { /// <summary> /// 获取当前分类 16*16 像素图标。 /// </summary> /// <returns></returns> public override System.Drawing.Image GetIcon16() { return Properties.Resources.Organization16; } /// <summary> /// 获取当前分类 32*32 图标。 /// </summary> /// <returns></returns> public override System.Drawing.Image GetIcon32() { return Properties.Resources.Organization32; } private static bool IconIsSaved = false; private void IconSave() { if (IconIsSaved == false) { this.GetIcon16().Save(this.Application.TemporaryDirectory + this.GetType().Name + "16.gif"); this.GetIcon32().Save(this.Application.TemporaryDirectory + this.GetType().Name + "32.gif"); } } /// <summary> /// 获取当前分类 16*16 像素的图标路径。 /// </summary> /// <returns></returns> public override string GetIcon16Url() { this.IconSave(); return this.Application.TemporaryDirectoryRelativePath + this.GetType().Name + "16.gif"; } /// <summary> /// 获取当前分类 32*32像素的图标路径。 /// </summary> /// <returns></returns> public override string GetIcon32Url() { this.IconSave(); return this.Application.TemporaryDirectoryRelativePath + this.GetType().Name + "32.gif"; } } }
f6c931945ae51e2a12eaa8cb72a71d0e34bc4013
C#
smyleeface/JukeboxAlexa
/src/JukeboxAlexa/Library/Tests/DynamoDbTest.cs
2.734375
3
using System.Collections.Generic; using System.Linq; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.Model; using JukeboxAlexa.Library.TestFixtures; using Moq; using Xunit; namespace JukeboxAlexa.Library.Tests { public class DynamoDbTest { public SongFixtures SongFixtures = new SongFixtures(); [Fact] public void Parse_songs_from_database_response__one_song() { // Arrange var dynamodbClient = new Mock<IAmazonDynamoDB>(MockBehavior.Strict); var jukeboxDynamoDb = new JukeboxDynamoDb(dynamodbClient.Object, SongFixtures.TableName, SongFixtures.IndexNameSearchTitle, SongFixtures.IndexNameSearchTitleArtist, SongFixtures.TableName); var items = new List<Dictionary<string, AttributeValue>> { { new Dictionary<string, AttributeValue> { {"song_number", new AttributeValue {S = "123"}}, {"artist", new AttributeValue {S = "Lionel Ritche"}}, {"title", new AttributeValue {S = "Hello"}} } } }; var quesryResponse = new QueryResponse { Items = items }; // Act var parsedSongsList = jukeboxDynamoDb.ParseSongsFromDatabaseResponse(quesryResponse).ToList(); // Assert Assert.Equal("Lionel Ritche", parsedSongsList.FirstOrDefault().Artist); Assert.Equal("123", parsedSongsList.FirstOrDefault().SongNumber); Assert.Equal("Hello", parsedSongsList.FirstOrDefault().Title); } [Fact] public void Parse_songs_from_database_response__no_songs() { // Arrange var dynamodbClient = new Mock<IAmazonDynamoDB>(MockBehavior.Strict); var jukeboxDynamoDb = new JukeboxDynamoDb(dynamodbClient.Object, SongFixtures.TableName, SongFixtures.IndexNameSearchTitle, SongFixtures.IndexNameSearchTitleArtist, SongFixtures.TableName); var items = new List<Dictionary<string, AttributeValue>>(); var quesryResponse = new QueryResponse { Items = items }; // Act var parsedSongsList = jukeboxDynamoDb.ParseSongsFromDatabaseResponse(quesryResponse).ToList(); // Assert Assert.Empty(parsedSongsList); } [Fact] public void Parse_songs_from_database_response__multiple_songs() { // Arrange var dynamodbClient = new Mock<IAmazonDynamoDB>(MockBehavior.Strict); var jukeboxDynamoDb = new JukeboxDynamoDb(dynamodbClient.Object, SongFixtures.TableName, SongFixtures.IndexNameSearchTitle, SongFixtures.IndexNameSearchTitleArtist, SongFixtures.TableName); var items = new List<Dictionary<string, AttributeValue>> { SongFixtures.SongAttribute2, SongFixtures.SongAttribute3 }; var queryResponse = new QueryResponse { Items = items }; // Act var parsedSongsList = jukeboxDynamoDb.ParseSongsFromDatabaseResponse(queryResponse).ToList(); // Assert Assert.Contains(parsedSongsList, e => SongFixtures.Song2.Artist == e.Artist && SongFixtures.Song3.Artist == e.Artist); } } }
5ce3f723b83670e9e18db1d28189661262347868
C#
brookpatten/MrGibbs
/src/MrGibbs.Models/Message.cs
3.03125
3
using System; namespace MrGibbs.Models { public enum MessageCategory { System, Tactical, } public enum MessagePriority { Low=0, Normal=1, High=2 } /// <summary> /// Message which needs to be communicated to the user via some means /// </summary> public class Message { public MessageCategory Category { get; set; } public DateTime CreatedAt { get; set; } public DateTime? ShownAt { get; set; } public TimeSpan Duration { get; set;} public DateTime? HideAt { get { if (ShownAt.HasValue) { return ShownAt + Duration; } else { return null; } } } public MessagePriority Priority { get; set; } public string Text { get; set; } } }
b9920002126d5cea02c894376d994b7288d4bc7c
C#
shendongnian/download4
/code2/220266-4298321-9058498-2.cs
3.25
3
1) replace LoadFromFile in Loader.cs private static RandomObject LoadFromFile(string path) { try { var bf = new BinaryFormatter(); using (var fileStream = File.OpenRead(path)) using (var decompressed = new MemoryStream()) { using (var deflateStream = new DeflateStream(fileStream, CompressionMode.Decompress)) deflateStream.CopyTo(decompressed); decompressed.Seek(0, SeekOrigin.Begin); var profile = (RandomObject)bf.Deserialize(decompressed); profile.SavePath = path; return profile; } } catch (IOException e) { MessageBox.Show(e.Message); return null; } } 2) replace Save in Saver.cs as follows: public static bool Save(RandomObject profile, String path) { try { var bf = new BinaryFormatter(); using (var uncompressed = new MemoryStream()) using (var fileStream = File.Create(path)) { bf.Serialize(uncompressed, profile); uncompressed.Seek(0, SeekOrigin.Begin); using (var deflateStream = new DeflateStream(fileStream, CompressionMode.Compress)) uncompressed.CopyTo(deflateStream); } return true; } catch (IOException e) { MessageBox.Show(e.Message); return false; } }
051a6cd65aa358f491b4f97f2f0533d341a8565e
C#
gosystemsgmbh/RI_Framework
/RI.Framework.Common/Mathematic/Controllers/PIDController.cs
2.6875
3
using System.Diagnostics.CodeAnalysis; using RI.Framework.Utilities; using RI.Framework.Utilities.Exceptions; namespace RI.Framework.Mathematic.Controllers { /// <summary> /// Implements a PID controller. /// </summary> /// <remarks> /// <para> /// PID controllers compute an output (<see cref="Output" />) which acts as a control value to control or drive a process. /// The output is computed based on a desired value or outcome (called set point, <see cref="SetPoint" />) and the feedback or measurement from the process (called process variable, <see cref="ProcessVariable" />). /// The calculation uses the error (set point minus process variable) and several coefficients (proportional <see cref="KP" />; integral <see cref="KI" />; differential <see cref="KD" />). /// To deactivate a coefficient, its value can be set to 0.0f. /// </para> /// <para> /// See <see href="https://en.wikipedia.org/wiki/PID_controller"> https://en.wikipedia.org/wiki/PID_controller </see> for details about PID controllers and their theory of operation. /// </para> /// <para> /// When using a PID controller, be aware of steady-state-error, integral windup, noise sensitivity, and instability/oscillation. /// To increase stability, the output can be clamped using <see cref="OutputMin" /> and <see cref="OutputMax" />. /// Especially the differential component is sensitive to noise in the process variable, therefore the differential component is disabled by default (<see cref="KD" /> is 0.0). /// </para> /// <para> /// The following values are used after a new instance of <see cref="PIDController" /> is created or the controller has been reset using <see cref="Reset" />: /// <see cref="KP" />, <see cref="KI" /> are set to 1.0. /// <see cref="KD" /> is set to 0.0. /// <see cref="SetPoint" />, <see cref="ProcessVariable" />, <see cref="Output" />, <see cref="OutputUnclamped" /> are set to 0.0. /// <see cref="OutputMin" /> is set to <see cref="float.MinValue" /> and <see cref="OutputMax" /> is set to <see cref="float.MaxValue" />, effectively disable clamping of the output. /// <see cref="Error" />, <see cref="Integral" /> are set to 0.0. /// <see cref="Loops" /> is set to 0. /// </para> /// <para> /// The following values are updated with each computation: <see cref="SetPoint" /> (if changed), <see cref="ProcessVariable" />, <see cref="Output" />, <see cref="OutputUnclamped" />, <see cref="Error" />, <see cref="Integral" />, <see cref="Differential"/>, <see cref="Loops" />. /// </para> /// </remarks> /// <threadsafety static="false" instance="false" /> /// <example> /// <code language="cs"> /// <![CDATA[ /// // create the controller /// PIDController controller = new PIDController(); /// /// // set parameters /// controller.KP = 0.5f; /// controller.KI = 0.22f; /// controller.KD = 0.0f; /// /// // ... /// /// // update the controller once per frame /// // Time.deltaTime is used as timestep to ensure that the controller behaves framerate-independent /// float newSetting = controller.ComputeNewSetPoint(aim, feedback, Time.deltaTime); /// ]]> /// </code> /// </example> [SuppressMessage("ReSharper", "InconsistentNaming")] public sealed class PIDController : IController { private float _outputMax; private float _outputMin; private float _kd; private float _ki; private float _kp; #region Instance Constructor/Destructor /// <summary> /// Creates a new instance of <see cref="PIDController" />. /// </summary> public PIDController () { this.Reset(); } #endregion #region Instance Properties/Indexer /// <summary> /// Gets the current differential value used for the differential component. /// </summary> /// <value> /// The current differential value used for the differential component. /// </value> public float Differential { get; private set; } /// <summary> /// Gets the current error (set point minus process variable). /// </summary> /// <value> /// The current error (set point minus process variable). /// </value> public float Error { get; private set; } /// <summary> /// Gets the current integral value used for the integral component. /// </summary> /// <value> /// The current integral value used for the integral component. /// </value> public float Integral { get; private set; } /// <summary> /// Gets or sets the differential coefficient. /// </summary> /// <value> /// The differential coefficient. /// </value> /// <remarks> /// <note type="implement"> /// <see cref="Output"/> and <see cref="OutputUnclamped"/> are not updated when changing the value of <see cref="KD"/>. /// </note> /// </remarks> /// <exception cref="NotFiniteArgumentException"><paramref name="value"/> is NaN or infinity.</exception> public float KD { get => this._kd; set { if (value.IsNanOrInfinity()) { throw new NotFiniteArgumentException(nameof(value)); } this._kd = value; } } /// <summary> /// Gets or sets the integral coefficient. /// </summary> /// <value> /// The integral coefficient. /// </value> /// <remarks> /// <note type="implement"> /// <see cref="Output"/> and <see cref="OutputUnclamped"/> are not updated when changing the value of <see cref="KI"/>. /// </note> /// </remarks> /// <exception cref="NotFiniteArgumentException"><paramref name="value"/> is NaN or infinity.</exception> public float KI { get => this._ki; set { if (value.IsNanOrInfinity()) { throw new NotFiniteArgumentException(nameof(value)); } this._ki = value; } } /// <summary> /// Gets or sets the proportional coefficient. /// </summary> /// <value> /// The proportional coefficient. /// </value> /// <remarks> /// <note type="implement"> /// <see cref="Output"/> and <see cref="OutputUnclamped"/> are not updated when changing the value of <see cref="KP"/>. /// </note> /// </remarks> /// <exception cref="NotFiniteArgumentException"><paramref name="value"/> is NaN or infinity.</exception> public float KP { get => this._kp; set { if (value.IsNanOrInfinity()) { throw new NotFiniteArgumentException(nameof(value)); } this._kp = value; } } #endregion #region Interface: IController /// <inheritdoc /> public int Loops { get; private set; } /// <inheritdoc /> public float Output { get; private set; } /// <inheritdoc /> public float OutputMax { get => this._outputMax; set { if (value.IsNanOrInfinity()) { throw new NotFiniteArgumentException(nameof(value)); } this._outputMax = value; } } /// <inheritdoc /> public float OutputMin { get => this._outputMin; set { if (value.IsNanOrInfinity()) { throw new NotFiniteArgumentException(nameof(value)); } this._outputMin = value; } } /// <inheritdoc /> public float OutputUnclamped { get; private set; } /// <inheritdoc /> public float ProcessVariable { get; private set; } /// <inheritdoc /> public float SetPoint { get; private set; } /// <inheritdoc /> public float Compute (float processVariable) => this.ComputeWithNewSetPoint(this.SetPoint, processVariable, 1.0f); /// <inheritdoc /> public float Compute (float processVariable, float timestep) => this.ComputeWithNewSetPoint(this.SetPoint, processVariable, timestep); /// <inheritdoc /> public float ComputeWithNewSetPoint (float setPoint, float processVariable) => this.ComputeWithNewSetPoint(setPoint, processVariable, 1.0f); /// <inheritdoc /> public float ComputeWithNewSetPoint (float setPoint, float processVariable, float timestep) { if (setPoint.IsNanOrInfinity()) { throw new NotFiniteArgumentException(nameof(setPoint)); } if (processVariable.IsNanOrInfinity()) { throw new NotFiniteArgumentException(nameof(processVariable)); } if (timestep.IsNanOrInfinity()) { throw new NotFiniteArgumentException(nameof(timestep)); } this.Loops++; float error = setPoint - processVariable; float integral = this.Integral + (error * timestep); float differential = (error - this.Error) / timestep; float p = this.KP * error; float i = this.KI * integral; float d = this.KD * differential; float outputUnclamped = p + i + d; float output = outputUnclamped; if (output < this.OutputMin) { output = this.OutputMin; } if (output > this.OutputMax) { output = this.OutputMax; } this.SetPoint = setPoint; this.ProcessVariable = processVariable; this.Output = output; this.OutputUnclamped = outputUnclamped; this.Error = error; this.Integral = integral; this.Differential = differential; return output; } /// <inheritdoc /> public void Reset () { this.Loops = 0; this.KP = 1.0f; this.KI = 1.0f; this.KD = 0.0f; this.SetPoint = 0.0f; this.ProcessVariable = 0.0f; this.Output = 0.0f; this.OutputUnclamped = 0.0f; this.OutputMin = float.MinValue; this.OutputMax = float.MaxValue; this.Error = 0.0f; this.Integral = 0.0f; this.Differential = 0.0f; } #endregion } }
d65d659f296895086c4760d747c8bae6d8da2d96
C#
treviettreviet/apcrshr
/apcrshr/Site.Core.Repository/Implementation/UserRepository.cs
2.71875
3
using Site.Core.Common.Ultil.Enum; using Site.Core.Common.Ultil.Security; using Site.Core.Repository.Repository; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Site.Core.Repository.Implementation { public class UserRepository : IUserRepository { public object Insert(User item) { using (APCRSHREntities context = new APCRSHREntities()) { item.Password = Encryption.ComputeHash(item.Password, Algorithm.SHA384, null); context.Users.Add(item); context.SaveChanges(); return item.UserID; } } public void Update(User item) { using (APCRSHREntities context = new APCRSHREntities()) { var user = context.Users.Where(u => u.UserID.Equals(item.UserID)).SingleOrDefault(); if (user != null) { user.Email = item.Email; user.DateOfBirth = item.DateOfBirth; user.FullName = item.FullName; user.Locked = item.Locked; user.OtherEmail = item.OtherEmail; user.Password = string.IsNullOrEmpty(item.Password) ? user.Password : Encryption.ComputeHash(item.Password, Algorithm.SHA384, null); //user.UserName = item.UserName; user.UpdatedDate = DateTime.Now; user.Sex = item.Sex; user.PhoneNumber = item.PhoneNumber; user.Title = item.Title; user.MealPreference = item.MealPreference; user.DisabilitySpecialTreatment = item.DisabilitySpecialTreatment; user.Address = item.Address; user.City = item.City; user.Country = item.Country; user.WorkAddress = item.WorkAddress; user.Organization = item.Organization; user.RegistrationStatus = item.RegistrationStatus; context.SaveChanges(); } else { throw new Exception(string.Format("User id {0} invalid", item.UserID)); } } } public void Delete(object id) { using (APCRSHREntities context = new APCRSHREntities()) { var _id = id.ToString(); var user = context.Users.Where(a => a.UserID.Equals(_id)).SingleOrDefault(); if (user != null) { context.Users.Remove(user); context.SaveChanges(); } else { throw new Exception(string.Format("User id {0} invalid", id)); } } } public User FindByID(object id) { APCRSHREntities context = new APCRSHREntities(); var _id = id.ToString(); return context.Users.Where(a => a.UserID.Equals(_id)).SingleOrDefault(); } public User FindByEmail(string email) { APCRSHREntities context = new APCRSHREntities(); var _email = email.ToString(); return context.Users.Where(u => u.Email == _email).SingleOrDefault(); } public User FindByUserName(string username) { APCRSHREntities context = new APCRSHREntities(); return context.Users.Where(u => u.UserName.Equals(username)).SingleOrDefault(); } public IList<User> FindAll() { APCRSHREntities context = new APCRSHREntities(); return context.Users.ToList(); } public User Login(string username, string password) { using (APCRSHREntities context = new APCRSHREntities()) { User user = context.Users.Where(u => u.UserName.Equals(username)).SingleOrDefault(); if (user != null && Encryption.VerifyHash(password, Algorithm.SHA384, user.Password)) { return user; } return null; } } public IList<User> GetUserExceptMe(string userID) { APCRSHREntities context = new APCRSHREntities(); return context.Users.Where(u => !u.UserID.Equals(userID)).ToList(); } public void ChangePassword(string userID, string newPassword) { using (APCRSHREntities context = new APCRSHREntities()) { var user = context.Users.Where(u => u.UserID.Equals(userID)).SingleOrDefault(); if (user != null) { user.Password = string.IsNullOrEmpty(newPassword) ? user.Password : Encryption.ComputeHash(newPassword, Algorithm.SHA384, null); user.UpdatedDate = DateTime.Now; context.SaveChanges(); } else { throw new Exception(string.Format("User id {0} invalid", userID)); } } } public bool LockUser(string userID) { using (APCRSHREntities context = new APCRSHREntities()) { var user = context.Users.Where(a => a.UserID.Equals(userID)).SingleOrDefault(); if (user != null) { user.Locked = !user.Locked; context.SaveChanges(); return user.Locked; } else { throw new Exception(string.Format("User id {0} invalid", userID)); } } } public User FindStartWithID(string userID) { APCRSHREntities context = new APCRSHREntities(); return context.Users.Where(a => a.UserID.StartsWith(userID)).SingleOrDefault(); } public bool HasMainScholarship(string userID) { using (APCRSHREntities context = new APCRSHREntities()) { return context.MainScholarships.Where(m => m.UserID.Equals(userID)).Any(); } } public bool HasYouthScholarship(string userID) { using (APCRSHREntities context = new APCRSHREntities()) { return context.YouthScholarships.Where(y => y.UserID.Equals(userID)).Any(); } } } }
3eda4a1caeea179574c9e0071c2046bdcadf7e4d
C#
xuongnhon/BandwidthAlgorithms
/NetworkSimulator/NetworkSimulator/RoutingComponents/RoutingStrategies/RoutingStrategy.cs
2.671875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NetworkSimulator.NetworkComponents; namespace NetworkSimulator.RoutingComponents.RoutingStrategies { public abstract class RoutingStrategy { protected Topology _Topology; protected Dictionary<Link, double> _ResidualBandwidthCopy; public RoutingStrategy(Topology topology) { _Topology = topology; _ResidualBandwidthCopy = new Dictionary<Link, double>(); } // caoth: review :(( public abstract List<Link> GetPath(SimulatorComponents.Request request); //--> MUST DO //public abstract List<Link> GetPath(int sourceId, int destinationId, double bandwidth); //public abstract List<Link> GetPath(int sourceId, int destinationId, double bandwidth, long incomingTime, long responseTime, long releasingTime); //public abstract void Reroute(); /// <summary> /// Eliminate all links which have residual bandwidth less than demand and from a reduced network. /// </summary> /// <param name="demand">Bandwidth demand</param> protected void EliminateAllLinksNotSatisfy(double demand) { foreach (Link link in _Topology.Links) { _ResidualBandwidthCopy[link] = link.ResidualBandwidth; } foreach (Link link in _Topology.Links) { if (link.ResidualBandwidth < demand) link.ResidualBandwidth = 0; } } /// <summary> /// Restore topology /// </summary> protected void RestoreTopology() { foreach (Link link in _Topology.Links) { link.ResidualBandwidth = _ResidualBandwidthCopy[link]; } } } }
e142de00899dc3b2a457e48dc5226e8169086748
C#
OsvarK/Grid-And-Pathfinding-System-Unity
/Assets/Scripts/grid-system/None-Unity-Dependent/Pathfinding/Astar search algorithm/AStarAlgorithm.cs
3.21875
3
using System; using System.Collections.Generic; /// <summary>A* Pathfinding search from grid a grid class</summary> public class AStarAlgorithm { private Grid grid; public AStarAlgorithm(Grid grid) { this.grid = grid; // Creates the AStarCell data component for every cell in the grid Cell[,] cells = grid.GetGridArray(); for (int x = 0; x < grid.width; x++) { for (int y = 0; y < grid.height; y++) { cells[x, y].AddCellComponent(AStarCell.COMPONENT_KEY, new AStarCell(cells[x, y])); } } } /// <summary>Getting the path between two cells using a* search Algorithm.</summary> /// <param name="startCell">Where the search starts</param> /// <param name="endCell">Where the search ends</param> /// <param name="allowDiagonalPassBetweenNoneWalkable">Determines if the A* will search diagonaly, when there is two none walkable blocking each side.</param> /// <returns>List of cells, sorted in correct order</returns> public List<Cell> GetPath(AStarCell startCell, AStarCell endCell, bool disabelDiagonalPass = true) { int gridSize = grid.width * grid.height; Heap<AStarCell> openSet = new Heap<AStarCell>(gridSize); HashSet<AStarCell> closedSet = new HashSet<AStarCell>(); openSet.Add(startCell); while (openSet.Count > 0) { AStarCell currentCell = openSet.RemoveFirstNode(); closedSet.Add(currentCell); if (currentCell == endCell) { List<Cell> path = new List<Cell>(); Cell lookingAt = endCell.CellParent; while (lookingAt != startCell.CellParent) { path.Add(lookingAt); AStarCell aStarCell = AStarCell.GetComponentFrom(lookingAt); lookingAt = aStarCell.pathParentCell; } path.Reverse(); return path; } foreach (AStarCell neighberingCell in GetNeighberingCells(currentCell, disabelDiagonalPass)) { if (!neighberingCell.Walkable || closedSet.Contains(neighberingCell)) continue; int moveToNeigborCost = currentCell.GCost + GetDistanceBetweenCells(currentCell, neighberingCell); if (moveToNeigborCost < neighberingCell.GCost || !openSet.Contains(neighberingCell)) { neighberingCell.GCost = moveToNeigborCost; neighberingCell.HCost = GetDistanceBetweenCells(neighberingCell, endCell); neighberingCell.pathParentCell = currentCell.CellParent; if (!openSet.Contains(neighberingCell)) openSet.Add(neighberingCell); } } } return null; } /// <summary>Returns all the cells around the given cell.</summary> /// <param name="disabelDiagonalPass">Enables or disables diagonal searching between none walkables</param> private List<AStarCell> GetNeighberingCells(AStarCell centerCell, bool disabelDiagonalPass = true) { Cell cell = centerCell.CellParent; List<AStarCell> neighbors = new List<AStarCell>(); for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { if (x == 0 && y == 0) { continue; } int validX = cell.x + x; int validY = cell.y + y; if (validX >= 0 && validX < grid.width && validY >= 0 && validY < grid.height) { if (disabelDiagonalPass && Math.Abs(x) == 1 && Math.Abs(y) == 1) { // North East if (x == 1 && y == 1) { AStarCell north = AStarCell.GetComponentFrom(grid.GetCellFromGridCordinates(cell.x, cell.y + 1)); AStarCell east = AStarCell.GetComponentFrom(grid.GetCellFromGridCordinates(cell.x + 1, cell.y)); if (!north.Walkable && !east.Walkable) { continue; } } // North West else if (x == -1 && y == 1) { AStarCell north = AStarCell.GetComponentFrom(grid.GetCellFromGridCordinates(cell.x, cell.y + 1)); AStarCell west = AStarCell.GetComponentFrom(grid.GetCellFromGridCordinates(cell.x - 1, cell.y)); if (!north.Walkable && !west.Walkable) { continue; } } // South East else if (x == 1 && y == -1) { AStarCell south = AStarCell.GetComponentFrom(grid.GetCellFromGridCordinates(cell.x, cell.y - 1)); AStarCell east = AStarCell.GetComponentFrom(grid.GetCellFromGridCordinates(cell.x + 1, cell.y)); if (!south.Walkable && !east.Walkable) { continue; } } // South West else if (x == -1 && y == -1) { AStarCell south = AStarCell.GetComponentFrom(grid.GetCellFromGridCordinates(cell.x, cell.y - 1)); AStarCell east = AStarCell.GetComponentFrom(grid.GetCellFromGridCordinates(cell.x - 1, cell.y)); if (!south.Walkable && !east.Walkable) { continue; } } } Cell neighborCell = grid.GetCellFromGridCordinates(validX, validY); neighbors.Add(AStarCell.GetComponentFrom(neighborCell)); } } } return neighbors; } /// <summary> Retrives the distance between cells. </summary> private int GetDistanceBetweenCells(AStarCell cellA, AStarCell cellB) { int distanceX = Math.Abs(cellA.CellParent.x - cellB.CellParent.x); int distanceY = Math.Abs(cellA.CellParent.y - cellB.CellParent.y); if (distanceX > distanceY) return 14 * distanceY + 10 * (distanceX - distanceY); return 14 * distanceX + 10 * (distanceY - distanceX); } }
06a00b111c5df3c832202e2a697ff6f6a8056711
C#
Ginoooo/tIDE
/TileMapEditor/tIDE/Commands/TileSheetRemoveDependencyCommand.cs
2.71875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using xTile; using xTile.Dimensions; using xTile.Layers; using xTile.Tiles; using tIDE.Controls; namespace tIDE.Commands { internal struct TileSheetDependency { private Layer m_layer; private Location m_location; private Tile m_tile; internal TileSheetDependency(Layer layer, Location location, Tile tile) { m_layer = layer; m_location = location; m_tile = tile; } internal Layer Layer { get { return m_layer; } } internal Location Location { get { return m_location; } } internal Tile Tile { get { return m_tile; } } internal void Break() { m_layer.Tiles[m_location] = null; } internal void Restore() { m_layer.Tiles[m_location] = m_tile; } } internal class TileSheetRemoveDependencyCommand: Command { private Map m_map; private TileSheet m_tileSheet; private List<TileSheetDependency> m_tileSheetDependencies; public TileSheetRemoveDependencyCommand(Map map, TileSheet tileSheet) { m_map = map; m_tileSheet = tileSheet; m_description = "Remove dependencies on tile sheet \"" + tileSheet.Id + "\""; m_tileSheetDependencies = new List<TileSheetDependency>(); foreach (Layer layer in m_map.Layers) { Size layerSize = layer.LayerSize; Location location; for (location.Y = 0; location.Y < layerSize.Height; location.Y++) for (location.X = 0; location.X < layerSize.Width; location.X++) { Tile tile = layer.Tiles[location]; if (tile != null && tile.DependsOnTileSheet(m_tileSheet)) m_tileSheetDependencies.Add(new TileSheetDependency(layer, location, tile)); } } } public override void Do() { foreach (TileSheetDependency tileSheetDependency in m_tileSheetDependencies) tileSheetDependency.Break(); } public override void Undo() { foreach (TileSheetDependency tileSheetDependency in m_tileSheetDependencies) tileSheetDependency.Restore(); } } }
22af301154f9b2a65616122089d0694be652902c
C#
JRWolford/Cms
/Services/Cms.DisplaySettingsService/Contracts/IDisplaySettingsUnitOfWork.cs
2.515625
3
using Cms.DisplaySettingsService.Data.Entities; using System; namespace Cms.DisplaySettingsService.Contracts { /// <summary> /// The base contract for the display settings unit of work. /// </summary> public interface IDisplaySettingsUnitOfWork : IDisposable { /// <summary> /// Save any changes made to the data repositories. /// </summary> /// <returns> /// An integer indicating the result of the save changes call. /// </returns> int SaveChanges(); /// <summary> /// Discard any changes made to the data repositories. /// </summary> void DiscardChanges(); /// <summary> /// The accents repository. /// </summary> IReadableDisplaySettingRepository<Accent> Accents { get; } /// <summary> /// The themes repository. /// </summary> IReadableDisplaySettingRepository<Theme> Themes { get; } } }
e0a7b5f3dab6a344416a36deca91aa689332f3b4
C#
jonathan-sarmento/pneustore-back
/pneustoreAPI/Controllers/ProductController.cs
2.625
3
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using pneustoreAPI.API; using pneustoreAPI.Models; using pneustoreAPI.Services; namespace pneustoreAPI.Controllers { [ApiController] [Route("[controller]")] [AllowAnonymous] public class ProductController : APIBaseController { private readonly IService<Product> _service; public ProductController(IService<Product> service) { _service = service; } /// <summary> /// Retorna lista de produtos (pneus) cadastrados no banco de dados /// </summary> /// <returns></returns> [HttpGet] public IActionResult Index() => ApiOk(_service.GetAll()); /// <summary> /// Retorna produto especifíco cadastrado no banco /// </summary> /// <param name="id"></param> /// <returns></returns> [Route("{id}"), HttpGet] public IActionResult Get(int? id) => _service.Get(id) != null ? ApiOk(_service.Get(id)) : ApiNotFound($"Produto com id: {id} não existe."); } }
6ee49473f35086188ee9128b714dc99ef8c4b5fb
C#
aavtukhovich/BGUIR
/Session 2017/OOTPiSp/Ivanov/10 var/proj/proj/CustomClass.cs
3.375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace proj { class CustomClass // тут выводится результат //При реализации задания 1 функцию вывода содержимого объекта реали-зовать как внешнюю по отношению к классу { public static void ChangeFirstWords(CustomObject a, CustomObject b) // принимает два обьекта, выводит их начальное значение, вызывает ф-ции замены первых слов и выводит окончательный вариант { Console.WriteLine("In start strings:"); Console.WriteLine(" "); Console.WriteLine(" A string: {0}", a.GetValue()); Console.WriteLine(" B string: {0}", b.GetValue()); Console.WriteLine(" "); Console.WriteLine("Change first words in strings"); Console.WriteLine(" "); //делаем копии обьектов, используя конструктор копирования CustomObject modA = new CustomObject(a); CustomObject modB = new CustomObject(b); modA.SetFirstWord(b); modB.SetFirstWord(a); Console.WriteLine("After change strings:"); Console.WriteLine(" "); Console.WriteLine(" A string: {0}", modA.GetValue()); Console.WriteLine(" B string: {0}", modB.GetValue()); } } }
83330d67b90eb3556e24a2e01adbbb34237f3964
C#
zinofi/Umbrella
/Core/src/Umbrella.Utilities/Comparers/GenericEqualityComparer.cs
3.3125
3
using System; using System.Collections.Generic; namespace Umbrella.Utilities.Comparers { /// <summary> /// A generic comparer to allow for determining equality between 2 object instances /// of the same type. /// </summary> /// <typeparam name="TObject">The type of the object.</typeparam> /// <seealso cref="Umbrella.Utilities.Comparers.GenericEqualityComparer{TObject, TObject}" /> public class GenericEqualityComparer<TObject> : GenericEqualityComparer<TObject, TObject> { /// <summary> /// Initializes a new instance of the <see cref="GenericEqualityComparer{TObject}"/> class. /// </summary> /// <param name="propertySelector">The property selector delegate.</param> /// <param name="customComparer">An optional delegate for custom comparison instead of using the <paramref name="propertySelector" /> if possible.</param> public GenericEqualityComparer( Func<TObject, TObject> propertySelector, Func<TObject, TObject, bool>? customComparer = null) : base(propertySelector, customComparer) { } } /// <summary> /// A generic comparer to allow for determining equality between 2 object instances /// of the same type. /// </summary> /// <typeparam name="TObject">The type of the object instances to compare.</typeparam> /// <typeparam name="TProperty">The type of the property used for comparison.</typeparam> public class GenericEqualityComparer<TObject, TProperty> : EqualityComparer<TObject> { private readonly Func<TObject, TProperty> _propertySelector; private readonly Func<TObject, TObject, bool>? _customComparer; /// <summary> /// Create a new instance of the comparer using the specified delegate to select the value used to check /// for object instance equality. If a custom comparer is specified then that will be used instead with the property /// selector only being used to determine the HashCode for an object instance. /// <para> /// If a custom comparer is not specified then equality will be determined by trying to get values from each object using the <paramref name="propertySelector"/> and comparing those. /// </para> /// </summary> /// <param name="propertySelector">The property selector delegate.</param> /// <param name="customComparer">An optional delegate for custom comparison instead of using the <paramref name="propertySelector"/> if possible.</param> public GenericEqualityComparer(Func<TObject, TProperty> propertySelector, Func<TObject, TObject, bool>? customComparer = null) { Guard.ArgumentNotNull(propertySelector, nameof(propertySelector)); _propertySelector = propertySelector; _customComparer = customComparer; } /// <summary> /// Determines if the 2 provided object instances are equal. /// </summary> /// <param name="x">The first object instance.</param> /// <param name="y">The second object instance.</param> /// <returns>Whether or not the 2 object instances are equal.</returns> public override bool Equals(TObject x, TObject y) { // Check the objects for null combinations first. if (x == null && y == null) return true; if (x == null) return false; if (y == null) return false; if (_customComparer != null) return _customComparer(x, y); TProperty xProperty = _propertySelector(x); TProperty yProperty = _propertySelector(y); if (xProperty == null && yProperty == null) return true; if (xProperty == null) return false; if (yProperty == null) return false; // Check if we can compare the 2 values using the more efficient IEquatable interface to avoid any unnecessary boxing. if (xProperty is IEquatable<TProperty> xPropertyEquatable && yProperty is IEquatable<TProperty> yPropertyEquatable) return xPropertyEquatable.Equals(yPropertyEquatable); // Use the default mechanism as a last resort. return xProperty.Equals(yProperty); } /// <summary> /// Computes the hash code for the specified object instance. Internally this calls GetHashCode on the value that /// is returned by the propertySelector delegate supplied in the constructor. /// </summary> /// <param name="obj">The object instance to compute the hash code for.</param> /// <returns>The hash code</returns> public override int GetHashCode(TObject obj) => _propertySelector(obj)?.GetHashCode() ?? 0; } }
14b2c4e6d551dce4f0d23a474b2d2b7794d8e454
C#
iridinite/mightyena
/FormBoxRename.cs
2.859375
3
/* * Mightyena - A Gen-III Pokémon Save Editor * (C) Mika Molenkamp, 2017. */ using System.Windows.Forms; namespace Mightyena { public partial class FormBoxRename : Form { public string NewName { get { return txtNewName.Text; } } public FormBoxRename(int box, string current) { InitializeComponent(); lblPrompt.Text = $"What would you like to name Box {box}?"; txtCurrentName.Text = current; txtNewName.Focus(); } private void txtNewName_TextChanged(object sender, System.EventArgs e) { cmdOK.Enabled = txtNewName.TextLength > 0; } } }
abd7962fb8989a55bb5380d157b2b7061989f6b7
C#
luisrodriguez5/Capitulo-8
/Ejercicio 1/Program.cs
2.78125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ejercicio_1 { class Program { static void Main(string[] args) { String Cadena; Console.WriteLine("Ingrese una Cadena: "); Cadena = Console.ReadLine(); Console.WriteLine("La cadena Introducida es: " + Cadena); Console.ReadKey(); } } }
a0e442996d5be17c3f592364f1c7a96784a2c517
C#
Artemyev-Sergei/LD46
/Assets/Scripts/Utility/ScreenFader.cs
2.84375
3
using UnityEngine; using UnityEngine.UI; public class ScreenFader : MonoBehaviour { [SerializeField] protected float solidAlpha = 1f; // 1f is for fully opaque. [SerializeField] protected float clearAlpha = 0f; // 0f is for fully transparent. [SerializeField] private float fadeOnDuration = 2f; public float FadeOnDuration { get { return this.fadeOnDuration; } } [SerializeField] private float fadeOffDuration = 2f; public float FadeOffDuration { get { return this.fadeOffDuration; } } [SerializeField] private MaskableGraphic[] graphicsToFade; protected void SetAlpha(float alpha) { foreach (MaskableGraphic graphic in this.graphicsToFade) { if (graphic != null) { graphic.canvasRenderer.SetAlpha(alpha); } } } private void Fade(float targetAlpha, float duration) { foreach (MaskableGraphic graphic in this.graphicsToFade) { if (graphic != null) { graphic.CrossFadeAlpha(targetAlpha, duration, true); } } } public void FadeOn() { SetAlpha(this.clearAlpha); Fade(this.solidAlpha, this.fadeOnDuration); } public void FadeOff() { SetAlpha(this.solidAlpha); Fade(this.clearAlpha, this.fadeOffDuration); } }
0e11970d7962390f9e6b1ef31fb2e2e29833fd93
C#
ssjogedal/Library_Application
/Library/Models/Loan.cs
3.046875
3
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Library.Models { public class Loan { [Key] public int LoanId { get; set; } [Required] public DateTime TimeOfLoan { get; set; } [Required] public DateTime DueDate { get; set; } public DateTime? TimeOfReturn { get; set; } [Required] public virtual BookCopy BookCopy { get; set; } public virtual Member Member { get; set; } public bool Returned { get; set; } public Loan() { } public Loan(BookCopy _bookCopy, Member _member) { this.TimeOfLoan = DateTime.Now; this.DueDate = TimeOfLoan.AddDays(15); this.BookCopy = _bookCopy; this.Member = _member; this.Returned = false; } /// <summary> /// Checks if loan is overdue and changes state before adding to listbox /// </summary> /// <returns></returns> public override string ToString() { string state; if(DueDate < DateTime.Now) { state = "Overdue"; } else { state = "Not Overdue"; } return "Member: " + Member.Name + ", Book: " + BookCopy.Book.Title + TimeOfLoan + " " + state; } } }
f01313dfc9a8de580f184859686a58a1a9d96c57
C#
danieladebi/Personal-Portfolio
/Surgery Learning Tool/Kinect/WindowsGame1/WindowsGame1/Scripts/GameState.cs
3.390625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MyKinectGame { public class GameState { /**********************************************************************************************/ // Static: public static event Action<string> OnStateActivated; public static event Action<string> OnStateDeactivated; public static event Action<string> OnStateConditionCompleted; public static GameState ActiveState; private static Dictionary<string, GameState> GameStates = new Dictionary<string, GameState>(); /// <summary> /// Adds a new game state. /// </summary> /// <param name="name">The name of the state.</param> /// <param name="initHandler">This will be called only once the first time the state is entered.</param> /// <param name="enterHandler">This will be called every time the state is activated.</param> /// <param name="exitHandler">This will be called every time the state is deactivated.</param> /// <param name="updateHandler">This will be called every frame while the state is active.</param> public static void Add(string name, Action updateHandler = null, Action initHandler = null, Action enterHandler = null, Action exitHandler = null) { GameState state = new GameState() { Name = name, OnInit = initHandler, OnEnter = enterHandler, OnExit = exitHandler, OnUpdate = updateHandler }; if (GameStates.ContainsKey(name)) { GameStates[name] = state; } else { GameStates.Add(name, state); } } /// <summary> /// Sets the activate GameState. /// </summary> /// <param name="name">The name of the state to activate.</param> public static void Set(string name) { if (!GameStates.ContainsKey(name)) return; if (ActiveState != null && ActiveState.IsActive) ActiveState.Deactivate(); ActiveState = GameStates[name]; ActiveState.Activate(); } /// <summary> /// Returns the desired GameState if it exists. /// </summary> /// <param name="name">The name of the state to return.</param> public static GameState Get(string name) { if (!GameStates.ContainsKey(name)) return null; return GameStates[name]; } /// <summary> /// Returns the names of all the available states within a string array. /// </summary> public static string[] GetStates() { return GameStates.Keys.ToArray(); } public static void Complete(string nextState) { if (ActiveState == null) return; if (ActiveState.completed) return; if (OnStateConditionCompleted != null) { OnStateConditionCompleted(ActiveState.Name); } Set(nextState); } /**********************************************************************************************/ // Internal: /// <summary> /// Called only once the first time this state is entered. /// </summary> public Action OnInit; /// <summary> /// Called every time this state is activated. /// </summary> public Action OnEnter; /// <summary> /// Called every time this state is deactivated. /// </summary> public Action OnExit; /// <summary> /// Called every frame while this state is active. /// </summary> public Action OnUpdate; /// <summary> /// Returns if this state is currently active. /// </summary> public bool IsActive { get { return ActiveState == this; } } public string Name = string.Empty; private bool initialized = false; private bool completed = false; public void Activate() { if (!initialized) { initialized = true; if (OnInit != null) { OnInit(); } } if (OnEnter != null) { OnEnter(); } if (OnStateActivated != null) OnStateActivated(Name); } public void Deactivate() { if (OnExit != null) { OnExit(); } if (OnStateDeactivated != null) OnStateDeactivated(Name); } public GameState() { } } }
1a8ed813b7096b4a754fe21412e0af4ba755c4a6
C#
osjoberg/HtmlPerformanceKit
/HtmlPerformanceKit/StateMachine/Script/HtmlStateMachine.ScriptDataEscapedDashDashState.cs
2.796875
3
using HtmlPerformanceKit.Infrastructure; namespace HtmlPerformanceKit.StateMachine { internal partial class HtmlStateMachine { /// <summary> /// 8.2.4.24 Script data escaped dash dash state /// /// Consume the next input character: /// /// "-" (U+002D) /// Emit a U+002D HYPHEN-MINUS character token. /// /// "&lt;" (U+003C) /// Switch to the script data escaped less-than sign state. /// /// "&gt;" (U+003E) /// Switch to the script data state. Emit a U+003E GREATER-THAN SIGN character token. /// /// U+0000 NULL /// Parse error. Switch to the script data escaped state. Emit a U+FFFD REPLACEMENT CHARACTER character token. /// /// EOF /// Parse error. Switch to the data state. Reconsume the EOF character. /// /// Anything else /// Switch to the script data escaped state. Emit the current input character as a character token. /// </summary> private void ScriptDataEscapedDashDashState() { var currentInputCharacter = bufferReader.Consume(); switch (currentInputCharacter) { case '-': currentDataBuffer.Add('-'); return; case '<': State = ScriptDataEscapedLessThanSignState; return; case '>': State = ScriptDataState; currentDataBuffer.Add('>'); return; case HtmlChar.Null: ParseError(ParseErrorMessage.UnexpectedNullCharacterInStream); currentDataBuffer.Add(HtmlChar.ReplacementCharacter); return; case EofMarker: State = DataState; ParseError(ParseErrorMessage.UnexpectedEndOfFile); bufferReader.Reconsume(EofMarker); return; default: State = ScriptDataEscapedState; return; } } } }
86154dac64183f81a0c407bc8eb7e15336d6603a
C#
PixelSnake/bananacake
/parser/syntax/expressions/nodes/value/BoolValueNode.cs
3.046875
3
using System; using System.Text.RegularExpressions; using BCake.Parser.Syntax.Types; namespace BCake.Parser.Syntax.Expressions.Nodes.Value { public class BoolValueNode : ValueNode { public static PrimitiveType Type = new PrimitiveType(Namespace.Global.Scope, "bool", false, typeof(BoolValueNode)); public override Types.Type ReturnType { get => Type; } public BoolValueNode(Token token, bool value) : base(token) { Value = value; } /// <summary> /// This method is used to force the given object into the required type. /// If in any way possible, convert it. /// </summary> public static bool ToValueNode(object value, out ValueNode node) { if (value is bool b) { node = new BoolValueNode(Token.Anonymous(""), b); return true; } node = null; return false; } public new static ValueNode Parse(Token token) { if (token.Value == "true") return new BoolValueNode(token, true); if (token.Value == "false") return new BoolValueNode(token, false); return null; } } }
ac4bfac46d33fc10dae0a746247a5b7a2df8eae3
C#
mmarkwort/MORYX-Factory
/src/Moryx.ControlSystem/Processes/IActivityPool.cs
2.59375
3
// Copyright (c) 2021, Phoenix Contact GmbH & Co. KG // Licensed under the Apache License, Version 2.0 using System; using System.Collections.Generic; using Moryx.AbstractionLayer; namespace Moryx.ControlSystem.Processes { /// <summary> /// Access to all activities currently running or prepared by the process control /// </summary> public interface IActivityPool { /// <summary> /// Number of processes in the pool /// </summary> int ProcessCount { get; } /// <summary> /// Get all processes from the pool /// </summary> IReadOnlyList<IProcess> Processes { get; } /// <summary> /// Get process by id /// </summary> IProcess GetProcess(long id); /// <summary> /// Find an activity that meets certain criteria /// </summary> /// <returns>Activity if available, otherwise <value>null</value></returns> IReadOnlyList<IActivity> GetByCondition(Func<IActivity, bool> predicate); /// <summary> /// All open activities managed by the pool /// </summary> IReadOnlyList<IActivity> GetAllOpen(); /// <summary> /// All open activities managed by the pool of a certain process /// </summary> IReadOnlyList<IActivity> GetAllOpen(IProcess process); /// <summary> /// Raised if an process changed its state. /// If the process's state reached <c>Finished</c> the process is removed from the Pool after this event was fired. /// </summary> event EventHandler<ProcessUpdatedEventArgs> ProcessUpdated; /// <summary> /// Raised if an activity changed its state. /// If the activity's state reached <c>Finished</c> the activity is removed from the Pool after this event was fired. /// </summary> event EventHandler<ActivityUpdatedEventArgs> ActivityUpdated; } }