code
stringlengths 4
1.05M
| repo_name
stringlengths 6
104
| path
stringlengths 4
220
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 6
1.05M
|
---|---|---|---|---|---|
using System.Collections.Generic;
namespace ConsoleDemo.Visitor.v0
{
public class CommandsManager
{
readonly List<object> items = new List<object>();
// The client class has a structure (a list in this case) of items (commands).
// The client knows how to iterate through the structure
// The client would need to do different operations on the items from the structure when iterating it
}
} | iQuarc/Code-Design-Training | DesignPatterns/ConsoleDemo/Visitor/v0/CommandsManager.cs | C# | mit | 440 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("34_FactorialSum")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("34_FactorialSum")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("880c59c2-814b-4c4c-91b0-a6f62aa7f1f2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| steliyan/ProjectEuler | 34_FactorialSum/Properties/AssemblyInfo.cs | C# | mit | 1,406 |
namespace MyColors
{
partial class SimpleToolTip
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// label1
//
this.label1.BackColor = System.Drawing.Color.Transparent;
this.label1.Dock = System.Windows.Forms.DockStyle.Fill;
this.label1.Font = new System.Drawing.Font("Open Sans", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(0, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(305, 51);
this.label1.TabIndex = 0;
this.label1.Text = "label1";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// SimpleToolTip
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(305, 51);
this.ControlBox = false;
this.Controls.Add(this.label1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "SimpleToolTip";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.Text = "SimpleToolTip";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Label label1;
}
} | cborrow/MyColors | SimpleToolTip.Designer.cs | C# | mit | 2,497 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Gama.Atenciones.Wpf.Views
{
/// <summary>
/// Interaction logic for SearchBoxView.xaml
/// </summary>
public partial class SearchBoxView : UserControl
{
public SearchBoxView()
{
InitializeComponent();
}
}
}
| PFC-acl-amg/GamaPFC | GamaPFC/Gama.Atenciones.Wpf/Views/SearchBoxView.xaml.cs | C# | mit | 663 |
using System;
using System.Collections;
using System.Linq;
using Xunit;
namespace Popsql.Tests
{
public class SqlValuesTests
{
[Fact]
public void Add_WithNullValues_ThrowsArgumentNull()
{
var values = new SqlValues();
Assert.Throws<ArgumentNullException>(() => values.Add(null));
}
[Fact]
public void Count_ReturnsNumberOfItems()
{
var values = new SqlValues();
Assert.Equal(0, values.Count);
values.Add(Enumerable.Range(0, 5).Cast<SqlValue>());
Assert.Equal(1, values.Count);
values.Add(Enumerable.Range(5, 10).Cast<SqlValue>());
Assert.Equal(2, values.Count);
}
[Fact]
public void ExpressionType_ReturnsValues()
{
Assert.Equal(SqlExpressionType.Values, new SqlValues().ExpressionType);
}
[Fact]
public void GetEnumerator_ReturnsEnumerator()
{
var values = new SqlValues
{
Enumerable.Range(0, 5).Cast<SqlValue>(),
Enumerable.Range(5, 10).Cast<SqlValue>()
};
var enumerator = ((IEnumerable) values).GetEnumerator();
Assert.NotNull(enumerator);
int count = 0;
while (enumerator.MoveNext())
{
count++;
}
Assert.Equal(2, count);
}
}
} | WouterDemuynck/popsql | src/Popsql.Tests/SqlValuesTests.cs | C# | mit | 1,149 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
////////////////////////////////////////////////////////////////////////////
//
//
// Purpose: This class defines behaviors specific to a writing system.
// A writing system is the collection of scripts and
// orthographic rules required to represent a language as text.
//
//
////////////////////////////////////////////////////////////////////////////
namespace System.Globalization {
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class StringInfo
{
[OptionalField(VersionAdded = 2)]
private String m_str;
// We allow this class to be serialized but there is no conceivable reason
// for them to do so. Thus, we do not serialize the instance variables.
[NonSerialized] private int[] m_indexes;
// Legacy constructor
public StringInfo() : this(""){}
// Primary, useful constructor
public StringInfo(String value) {
this.String = value;
}
#region Serialization
[OnDeserializing]
private void OnDeserializing(StreamingContext ctx)
{
m_str = String.Empty;
}
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
if (m_str.Length == 0)
{
m_indexes = null;
}
}
#endregion Serialization
[System.Runtime.InteropServices.ComVisible(false)]
public override bool Equals(Object value)
{
StringInfo that = value as StringInfo;
if (that != null)
{
return (this.m_str.Equals(that.m_str));
}
return (false);
}
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetHashCode()
{
return this.m_str.GetHashCode();
}
// Our zero-based array of index values into the string. Initialize if
// our private array is not yet, in fact, initialized.
private int[] Indexes {
get {
if((null == this.m_indexes) && (0 < this.String.Length)) {
this.m_indexes = StringInfo.ParseCombiningCharacters(this.String);
}
return(this.m_indexes);
}
}
public String String {
get {
return(this.m_str);
}
set {
if (null == value) {
throw new ArgumentNullException(nameof(String),
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
this.m_str = value;
this.m_indexes = null;
}
}
public int LengthInTextElements {
get {
if(null == this.Indexes) {
// Indexes not initialized, so assume length zero
return(0);
}
return(this.Indexes.Length);
}
}
public String SubstringByTextElements(int startingTextElement) {
// If the string is empty, no sense going further.
if(null == this.Indexes) {
// Just decide which error to give depending on the param they gave us....
if(startingTextElement < 0) {
throw new ArgumentOutOfRangeException(nameof(startingTextElement),
Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
else {
throw new ArgumentOutOfRangeException(nameof(startingTextElement),
Environment.GetResourceString("Arg_ArgumentOutOfRangeException"));
}
}
return (this.SubstringByTextElements(startingTextElement, this.Indexes.Length - startingTextElement));
}
public String SubstringByTextElements(int startingTextElement, int lengthInTextElements) {
//
// Parameter checking
//
if(startingTextElement < 0) {
throw new ArgumentOutOfRangeException(nameof(startingTextElement),
Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
if(this.String.Length == 0 || startingTextElement >= this.Indexes.Length) {
throw new ArgumentOutOfRangeException(nameof(startingTextElement),
Environment.GetResourceString("Arg_ArgumentOutOfRangeException"));
}
if(lengthInTextElements < 0) {
throw new ArgumentOutOfRangeException(nameof(lengthInTextElements),
Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
if(startingTextElement > this.Indexes.Length - lengthInTextElements) {
throw new ArgumentOutOfRangeException(nameof(lengthInTextElements),
Environment.GetResourceString("Arg_ArgumentOutOfRangeException"));
}
int start = this.Indexes[startingTextElement];
if(startingTextElement + lengthInTextElements == this.Indexes.Length) {
// We are at the last text element in the string and because of that
// must handle the call differently.
return(this.String.Substring(start));
}
else {
return(this.String.Substring(start, (this.Indexes[lengthInTextElements + startingTextElement] - start)));
}
}
public static String GetNextTextElement(String str)
{
return (GetNextTextElement(str, 0));
}
////////////////////////////////////////////////////////////////////////
//
// Get the code point count of the current text element.
//
// A combining class is defined as:
// A character/surrogate that has the following Unicode category:
// * NonSpacingMark (e.g. U+0300 COMBINING GRAVE ACCENT)
// * SpacingCombiningMark (e.g. U+ 0903 DEVANGARI SIGN VISARGA)
// * EnclosingMark (e.g. U+20DD COMBINING ENCLOSING CIRCLE)
//
// In the context of GetNextTextElement() and ParseCombiningCharacters(), a text element is defined as:
//
// 1. If a character/surrogate is in the following category, it is a text element.
// It can NOT further combine with characters in the combinging class to form a text element.
// * one of the Unicode category in the combinging class
// * UnicodeCategory.Format
// * UnicodeCateogry.Control
// * UnicodeCategory.OtherNotAssigned
// 2. Otherwise, the character/surrogate can be combined with characters in the combinging class to form a text element.
//
// Return:
// The length of the current text element
//
// Parameters:
// String str
// index The starting index
// len The total length of str (to define the upper boundary)
// ucCurrent The Unicode category pointed by Index. It will be updated to the uc of next character if this is not the last text element.
// currentCharCount The char count of an abstract char pointed by Index. It will be updated to the char count of next abstract character if this is not the last text element.
//
////////////////////////////////////////////////////////////////////////
internal static int GetCurrentTextElementLen(String str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount)
{
Contract.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
Contract.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
if (index + currentCharCount == len)
{
// This is the last character/surrogate in the string.
return (currentCharCount);
}
// Call an internal GetUnicodeCategory, which will tell us both the unicode category, and also tell us if it is a surrogate pair or not.
int nextCharCount;
UnicodeCategory ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index + currentCharCount, out nextCharCount);
if (CharUnicodeInfo.IsCombiningCategory(ucNext)) {
// The next element is a combining class.
// Check if the current text element to see if it is a valid base category (i.e. it should not be a combining category,
// not a format character, and not a control character).
if (CharUnicodeInfo.IsCombiningCategory(ucCurrent)
|| (ucCurrent == UnicodeCategory.Format)
|| (ucCurrent == UnicodeCategory.Control)
|| (ucCurrent == UnicodeCategory.OtherNotAssigned)
|| (ucCurrent == UnicodeCategory.Surrogate)) // An unpair high surrogate or low surrogate
{
// Will fall thru and return the currentCharCount
} else {
int startIndex = index; // Remember the current index.
// We have a valid base characters, and we have a character (or surrogate) that is combining.
// Check if there are more combining characters to follow.
// Check if the next character is a nonspacing character.
index += currentCharCount + nextCharCount;
while (index < len)
{
ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out nextCharCount);
if (!CharUnicodeInfo.IsCombiningCategory(ucNext)) {
ucCurrent = ucNext;
currentCharCount = nextCharCount;
break;
}
index += nextCharCount;
}
return (index - startIndex);
}
}
// The return value will be the currentCharCount.
int ret = currentCharCount;
ucCurrent = ucNext;
// Update currentCharCount.
currentCharCount = nextCharCount;
return (ret);
}
// Returns the str containing the next text element in str starting at
// index index. If index is not supplied, then it will start at the beginning
// of str. It recognizes a base character plus one or more combining
// characters or a properly formed surrogate pair as a text element. See also
// the ParseCombiningCharacters() and the ParseSurrogates() methods.
public static String GetNextTextElement(String str, int index) {
//
// Validate parameters.
//
if (str==null) {
throw new ArgumentNullException(nameof(str));
}
Contract.EndContractBlock();
int len = str.Length;
if (index < 0 || index >= len) {
if (index == len) {
return (String.Empty);
}
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
int charLen;
UnicodeCategory uc = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out charLen);
return (str.Substring(index, GetCurrentTextElementLen(str, index, len, ref uc, ref charLen)));
}
public static TextElementEnumerator GetTextElementEnumerator(String str)
{
return (GetTextElementEnumerator(str, 0));
}
public static TextElementEnumerator GetTextElementEnumerator(String str, int index)
{
//
// Validate parameters.
//
if (str==null)
{
throw new ArgumentNullException(nameof(str));
}
Contract.EndContractBlock();
int len = str.Length;
if (index < 0 || (index > len))
{
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
return (new TextElementEnumerator(str, index, len));
}
/*
* Returns the indices of each base character or properly formed surrogate pair
* within the str. It recognizes a base character plus one or more combining
* characters or a properly formed surrogate pair as a text element and returns
* the index of the base character or high surrogate. Each index is the
* beginning of a text element within a str. The length of each element is
* easily computed as the difference between successive indices. The length of
* the array will always be less than or equal to the length of the str. For
* example, given the str \u4f00\u302a\ud800\udc00\u4f01, this method would
* return the indices: 0, 2, 4.
*/
public static int[] ParseCombiningCharacters(String str)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
Contract.EndContractBlock();
int len = str.Length;
int[] result = new int[len];
if (len == 0)
{
return (result);
}
int resultCount = 0;
int i = 0;
int currentCharLen;
UnicodeCategory currentCategory = CharUnicodeInfo.InternalGetUnicodeCategory(str, 0, out currentCharLen);
while (i < len) {
result[resultCount++] = i;
i += GetCurrentTextElementLen(str, i, len, ref currentCategory, ref currentCharLen);
}
if (resultCount < len)
{
int[] returnArray = new int[resultCount];
Array.Copy(result, returnArray, resultCount);
return (returnArray);
}
return (result);
}
}
}
| Dmitry-Me/coreclr | src/mscorlib/src/System/Globalization/StringInfo.cs | C# | mit | 14,973 |
using System.Collections.Generic;
using UnityEngine;
using System;
namespace AI
{
public class GreedyAIController : PlayerController
{
enum NextState
{
Wait, Draw, Play
}
private NextState nextState;
Dictionary<DominoController, List<DominoController>> placesToPlay = null;
private void Update()
{
switch (nextState)
{
case NextState.Wait:
return;
case NextState.Draw:
if (history.horizontalDominoes.Count > 0)
{
placesToPlay = PlacesToPlay();
if (placesToPlay.Count == 0)
{
base.DrawDomino();
placesToPlay = PlacesToPlay();
if (placesToPlay.Count == 0)
{
nextState = NextState.Wait;
gameController.PlayerIsBlocked(this);
return;
}
}
}
nextState = NextState.Play;
break;
case NextState.Play:
List<ChosenWayToPlay> waysToPlay = new List<ChosenWayToPlay>();
if (history.horizontalDominoes.Count == 0)
{
foreach (DominoController domino in dominoControllers)
{
waysToPlay.Add(new ChosenWayToPlay(domino, null));
}
}
else
{
foreach (KeyValuePair<DominoController, List<DominoController>> entry in placesToPlay)
{
List<DominoController> list = entry.Value;
foreach (DominoController chosenPlace in list)
{
ChosenWayToPlay chosenWayToPlay = new ChosenWayToPlay(entry.Key, chosenPlace);
waysToPlay.Add(chosenWayToPlay);
}
}
}
// From small to large
waysToPlay.Sort(delegate (ChosenWayToPlay x, ChosenWayToPlay y)
{
int xScore = GetScoreOfChosenWay(x);
int yScore = GetScoreOfChosenWay(y);
return xScore - yScore;
});
ChosenWayToPlay bestWayToPlay = waysToPlay[waysToPlay.Count - 1];
PlaceDomino(bestWayToPlay.chosenDomino, bestWayToPlay.chosenPlace, history);
dominoControllers.Remove(bestWayToPlay.chosenDomino);
// Debug
Debug.Log("Chosen Domino: " + bestWayToPlay.chosenDomino.leftValue + ", " + bestWayToPlay.chosenDomino.rightValue + ", " + bestWayToPlay.chosenDomino.upperValue + ", " + bestWayToPlay.chosenDomino.lowerValue);
if (bestWayToPlay.chosenPlace != null)
{
Debug.Log("Chosen Place: " + bestWayToPlay.chosenPlace.leftValue + ", " + bestWayToPlay.chosenPlace.rightValue + ", " + bestWayToPlay.chosenPlace.upperValue + ", " + bestWayToPlay.chosenPlace.lowerValue);
}
Debug.Log(Environment.StackTrace);
nextState = NextState.Wait;
gameController.PlayerPlayDomino(this, bestWayToPlay.chosenDomino, bestWayToPlay.chosenPlace);
break;
}
}
public override void PlayDomino()
{
nextState = NextState.Draw;
}
private Dictionary<DominoController, List<DominoController>> PlacesToPlay()
{
Dictionary<DominoController, List<DominoController>> placesToPlay = new Dictionary<DominoController, List<DominoController>>(dominoControllers.Count * 4);
foreach (DominoController domino in dominoControllers)
{
// Add places can be played for each domino
List<DominoController> places = base.ListOfValidPlaces(domino);
if (places == null)
{
continue;
}
placesToPlay.Add(domino, places);
}
return placesToPlay;
}
private int GetScoreOfChosenWay(ChosenWayToPlay wayToPlay)
{
int score = 0;
// If history has no domino
if (history.horizontalDominoes.Count == 0)
{
if (wayToPlay.chosenDomino.direction == DominoController.Direction.Horizontal)
{
int value = wayToPlay.chosenDomino.leftValue + wayToPlay.chosenDomino.rightValue;
score = (value % 5 == 0) ? value : 0;
}
else
{
int value = wayToPlay.chosenDomino.upperValue + wayToPlay.chosenDomino.lowerValue;
score = (value % 5 == 0) ? value : 0;
}
return score;
}
// Else that history has at least 1 domino
DominoController copiedDomino = Instantiate<DominoController>(wayToPlay.chosenDomino);
HistoryController copiedHistory = Instantiate<HistoryController>(history);
// Simulate to place a domino and then calculate the sum
PlaceDomino(copiedDomino, wayToPlay.chosenPlace, copiedHistory);
copiedHistory.Add(copiedDomino, wayToPlay.chosenPlace);
score = Utility.GetSumOfHistoryDominoes(copiedHistory.horizontalDominoes, copiedHistory.verticalDominoes, copiedHistory.spinner);
score = score % 5 == 0 ? score : 0;
Destroy(copiedDomino.gameObject);
Destroy(copiedHistory.gameObject);
return score;
}
private void PlaceDomino(DominoController chosenDomino, DominoController chosenPlace, HistoryController history)
{
DominoController clickedDomino = chosenPlace;
int horizontalLen = history.horizontalDominoes.Count;
int verticalLen = history.verticalDominoes.Count;
if (chosenDomino != null)
{
if (chosenPlace != null)
{
if (chosenPlace == history.horizontalDominoes[0])
{
if (clickedDomino.leftValue == -1)
{
if (chosenDomino.upperValue == clickedDomino.upperValue || chosenDomino.lowerValue == clickedDomino.upperValue)
{
chosenPlace = clickedDomino;
if (chosenDomino.upperValue == clickedDomino.upperValue)
chosenDomino.SetLeftRightValues(chosenDomino.lowerValue, chosenDomino.upperValue);
else
chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue);
return;
}
}
else
{
if (chosenDomino.upperValue == clickedDomino.leftValue && chosenDomino.upperValue == chosenDomino.lowerValue)
{
chosenPlace = clickedDomino;
return;
}
else if (chosenDomino.upperValue == clickedDomino.leftValue || chosenDomino.lowerValue == clickedDomino.leftValue)
{
chosenPlace = clickedDomino;
if (chosenDomino.upperValue == clickedDomino.leftValue)
chosenDomino.SetLeftRightValues(chosenDomino.lowerValue, chosenDomino.upperValue);
else
chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue);
return;
}
}
}
if (clickedDomino == history.horizontalDominoes[horizontalLen - 1])
{
if (clickedDomino.leftValue == -1)
{
if (chosenDomino.upperValue == clickedDomino.upperValue || chosenDomino.lowerValue == clickedDomino.upperValue)
{
chosenPlace = clickedDomino;
if (chosenDomino.upperValue == clickedDomino.upperValue)
chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue);
else
chosenDomino.SetLeftRightValues(chosenDomino.lowerValue, chosenDomino.upperValue);
return;
}
}
else
{
if (chosenDomino.upperValue == clickedDomino.rightValue && chosenDomino.upperValue == chosenDomino.lowerValue)
{
chosenPlace = clickedDomino;
return;
}
else if (chosenDomino.upperValue == clickedDomino.rightValue || chosenDomino.lowerValue == clickedDomino.rightValue)
{
chosenPlace = clickedDomino;
if (chosenDomino.upperValue == clickedDomino.rightValue)
chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue);
else
chosenDomino.SetLeftRightValues(chosenDomino.lowerValue, chosenDomino.upperValue);
return;
}
}
}
if (verticalLen > 0 && clickedDomino == history.verticalDominoes[0])
{
if (clickedDomino.leftValue == -1)
{
if (chosenDomino.upperValue == clickedDomino.upperValue && chosenDomino.upperValue == chosenDomino.lowerValue)
{
chosenPlace = clickedDomino;
chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue);
return;
}
else if (chosenDomino.upperValue == clickedDomino.upperValue || chosenDomino.lowerValue == clickedDomino.upperValue)
{
chosenPlace = clickedDomino;
if (chosenDomino.upperValue == clickedDomino.upperValue)
chosenDomino.SetUpperLowerValues(chosenDomino.lowerValue, chosenDomino.upperValue);
return;
}
}
else
{
if (chosenDomino.upperValue == clickedDomino.leftValue || chosenDomino.lowerValue == clickedDomino.leftValue)
{
chosenPlace = clickedDomino;
if (chosenDomino.upperValue == clickedDomino.leftValue)
chosenDomino.SetUpperLowerValues(chosenDomino.lowerValue, chosenDomino.upperValue);
return;
}
}
}
if (verticalLen > 0 && clickedDomino == history.verticalDominoes[verticalLen - 1])
{
if (clickedDomino.leftValue == -1)
{
if (chosenDomino.upperValue == clickedDomino.lowerValue && chosenDomino.upperValue == chosenDomino.lowerValue)
{
chosenPlace = clickedDomino;
chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue);
return;
}
else if (chosenDomino.upperValue == clickedDomino.lowerValue || chosenDomino.lowerValue == clickedDomino.lowerValue)
{
chosenPlace = clickedDomino;
if (chosenDomino.lowerValue == clickedDomino.lowerValue)
chosenDomino.SetUpperLowerValues(chosenDomino.lowerValue, chosenDomino.upperValue);
return;
}
}
else
{
if (chosenDomino.upperValue == clickedDomino.leftValue || chosenDomino.lowerValue == clickedDomino.leftValue)
{
chosenPlace = clickedDomino;
if (chosenDomino.lowerValue == clickedDomino.leftValue)
chosenDomino.SetUpperLowerValues(chosenDomino.lowerValue, chosenDomino.upperValue);
return;
}
}
}
}
else
{
if (chosenDomino.upperValue != chosenDomino.lowerValue)
chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue);
}
}
}
}
}
| hahamty/Dominoes | Game/Assets/Scripts/AI/GreedyAIController.cs | C# | mit | 14,285 |
/*
The MIT License (MIT)
Copyright (c) 2014 Mehmetali Shaqiri ([email protected])
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.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using openvpn.api.common.domain;
using openvpn.api.core.controllers;
using openvpn.api.shared;
using Raven.Client;
using openvpn.api.core.auth;
namespace openvpn.api.Controllers
{
public class UsersController : RavenDbApiController
{
/// <summary>
/// Get requested user by email
/// </summary>
[Route("api/users/{email}")]
public async Task<User> Get(string email)
{
return await Session.Query<User>().SingleOrDefaultAsync(u => u.Email == email);
}
/// <summary>
/// Get all users
/// </summary>
[Route("api/users/all")]
public async Task<IEnumerable<User>> Get()
{
var query = Session.Query<User>().OrderBy(u => u.Firstname).ToListAsync();
return await query;
}
[HttpPost]
public async Task<ApiStatusCode> Post([FromBody]User userModel)
{
var user = await Session.Query<User>().SingleOrDefaultAsync(u => u.Email == userModel.Email);
if (ModelState.IsValid)
{
if (user != null)
return ApiStatusCode.Exists;
await Session.StoreAsync(userModel);
return ApiStatusCode.Saved;
}
return ApiStatusCode.Error;
}
[HttpDelete]
[Route("api/users/{email}")]
public async Task<ApiStatusCode> Delete(string email)
{
var user = await Session.Query<User>().SingleOrDefaultAsync(u => u.Email == email);
if (user == null)
return ApiStatusCode.Error;
Session.Delete<User>(user);
return ApiStatusCode.Deleted;
}
[HttpPut]
public async Task<ApiStatusCode> Put(User userModel)
{
var user = await Session.Query<User>().SingleOrDefaultAsync(u => u.Email == userModel.Email);
if (user != null)
{
user.Firstname = userModel.Firstname;
user.Lastname = userModel.Lastname;
user.Certificates = userModel.Certificates;
await Session.SaveChangesAsync();
return ApiStatusCode.Saved;
}
return ApiStatusCode.Error;
}
}
} | spartanbeg/OpenVPN-Event-Viewer | openvpn.api/openvpn.api/Controllers/UsersController.cs | C# | mit | 3,668 |
namespace SharedWeekends.MVC.Areas.Administration.Controllers
{
using System.Web.Mvc;
using SharedWeekends.Data;
using SharedWeekends.MVC.Controllers;
[Authorize(Roles = "admin")]
public abstract class AdminController : BaseController
{
public AdminController(IWeekendsData data)
: base(data)
{
}
}
} | kalinalazarova1/SharedWeekends | SharedWeekends.MVC/Areas/Administration/Controllers/AdminController.cs | C# | mit | 369 |
#region License
// Distributed under the MIT License
// ============================================================
// Copyright (c) 2019 Hotcakes Commerce, LLC
//
// 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 DotNetNuke.Entities.Host;
using Hotcakes.Commerce.Configuration;
namespace Hotcakes.Commerce.Dnn
{
[Serializable]
public class DnnConfigurationManager : IConfigurationManager
{
public SmtpSettings SmtpSettings
{
get
{
var smtpSettings = new SmtpSettings();
var smtpHostParts = Host.SMTPServer.Split(':');
smtpSettings.Host = smtpHostParts[0];
if (smtpHostParts.Length > 1)
{
smtpSettings.Port = smtpHostParts[1];
}
switch (Host.SMTPAuthentication)
{
case "":
case "0": //anonymous
smtpSettings.UseAuth = false;
break;
case "1": //basic
smtpSettings.UseAuth = true;
break;
case "2": //NTLM
smtpSettings.UseAuth = false;
break;
}
smtpSettings.EnableSsl = Host.EnableSMTPSSL;
smtpSettings.Username = Host.SMTPUsername;
smtpSettings.Password = Host.SMTPPassword;
return smtpSettings;
}
}
}
} | HotcakesCommerce/core | Libraries/Hotcakes.Commerce.Dnn/DnnConfigurationManager.cs | C# | mit | 2,605 |
using CertificateManager.Entities;
using CertificateManager.Entities.Interfaces;
using System.Collections.Generic;
using System.Security.Claims;
namespace CertificateManager.Logic.Interfaces
{
public interface IAuditLogic
{
IEnumerable<AuditEvent> GetAllEvents();
void LogSecurityAuditSuccess(ClaimsPrincipal userContext, ILoggableEntity entity, EventCategory category);
void LogSecurityAuditFailure(ClaimsPrincipal userContext, ILoggableEntity entity, EventCategory category);
void LogOpsSuccess(ClaimsPrincipal userContext, string target, EventCategory category, string message);
void LogOpsError(ClaimsPrincipal userContext, string target, EventCategory category);
void LogOpsError(ClaimsPrincipal userContext, string target, EventCategory category, string message);
void InitializeMockData();
void ClearLogs(ClaimsPrincipal user);
}
}
| corymurphy/CertificateManager | CertificateManager.Logic/Interfaces/IAuditLogic.cs | C# | mit | 919 |
using Radical.Reflection;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
namespace Radical.Windows
{
static class PropertyInfoExtensions
{
public static string GetDisplayName(this PropertyInfo propertyInfo)
{
if (propertyInfo != null && propertyInfo.IsAttributeDefined<DisplayAttribute>())
{
var a = propertyInfo.GetAttribute<DisplayAttribute>();
return a.GetName();
}
if (propertyInfo != null && propertyInfo.IsAttributeDefined<DisplayNameAttribute>())
{
var a = propertyInfo.GetAttribute<DisplayNameAttribute>();
return a.DisplayName;
}
return null;
}
}
}
| RadicalFx/Radical.Windows | src/Radical.Windows/PropertyInfoExtensions.cs | C# | mit | 801 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SimpleCiphers.Models
{
public static class ArrayOperations
{
// Содержится ли text в encAbc. Если да, то возвращаются индексы в encAbc
// a b text = 1
// a 1 2 return x = 0, y = 0
// b 3 4 abc[0,0] = aa - расшифрованный
// encAbc[0,0] = 1 - зашифрованный
public static bool ContainsIn(string text, string[,] encAbc, out int x, out int y)
{
for (var i = 0; i < encAbc.GetLength(0); i++)
{
for (var j = 0; j < encAbc.GetLength(1); j++)
{
if (text != encAbc[i, j]) continue;
x = i;
y = j;
return true;
}
}
x = -1;
y = -1;
return false;
}
public static string[,] Turn1DTo2D(string[] encAbc)
{
var arr = new string[1, encAbc.Length];
for (var i = 0; i < encAbc.Length; i++)
{
arr[0, i] = $"{encAbc[i]}";
}
return arr;
}
}
} | slavitnas/SimpleCiphers | SimpleCiphers/Models/ArrayOperations.cs | C# | mit | 1,318 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using IdentityServer3.Core.Events;
using IdentityServer3.ElasticSearchEventService.Extensions;
using IdentityServer3.ElasticSearchEventService.Mapping;
using IdentityServer3.ElasticSearchEventService.Mapping.Configuration;
using Serilog.Events;
using Unittests.Extensions;
using Unittests.Proofs;
using Unittests.TestData;
using Xunit;
namespace Unittests
{
public class DefaultLogEventMapperTests
{
[Fact]
public void SpecifiedProperties_AreMapped()
{
var mapper = CreateMapper(b => b
.DetailMaps(c => c
.For<TestDetails>(m => m
.Map(d => d.String)
)
));
var details = new TestDetails
{
String = "Polse"
};
var logEvent = mapper.Map(CreateEvent(details));
logEvent.Properties.DoesContain(LogEventValueWith("Details.String", Quote("Polse")));
}
[Fact]
public void AlwaysAddedValues_AreAlwaysAdded()
{
var mapper = CreateMapper(b => b.AlwaysAdd("some", "value"));
var logEvent = mapper.Map(CreateEvent(new object()));
logEvent.Properties.DoesContain(LogEventValueWith("some", Quote("value")));
}
[Fact]
public void MapToSpecifiedName_MapsToSpecifiedName()
{
var mapper = CreateMapper(b => b
.DetailMaps(m => m
.For<TestDetails>(o => o
.Map("specificName", d => d.String)
)
));
var logEvent = mapper.Map(CreateEvent(new TestDetails {String = Some.String}));
logEvent.Properties.DoesContain(LogEventValueWith("Details.specificName", Quote(Some.String)));
}
[Fact]
public void PropertiesThatThrowsException_AreMappedAsException()
{
var mapper = CreateMapper(b => b
.DetailMaps(m => m
.For<TestDetails>(o => o
.Map(d => d.ThrowsException)
)
));
var logEvent = mapper.Map(CreateEvent(new TestDetails()));
logEvent.Properties.DoesContain(LogEventValueWith("Details.ThrowsException", s => s.StartsWith("\"threw")));
}
[Fact]
public void DefaultMapAllMembers_MapsAllPropertiesAndFieldsForDetails()
{
var mapper = CreateMapper(b => b
.DetailMaps(m => m
.DefaultMapAllMembers()
));
var logEvent = mapper.Map(CreateEvent(new TestDetails()));
var members = typeof (TestDetails).GetPublicPropertiesAndFields().Select(m => string.Format("Details.{0}", m.Name));
logEvent.Properties.DoesContainKeys(members);
}
[Fact]
public void ComplexMembers_AreMappedToJson()
{
var mapper = CreateMapper(b => b
.DetailMaps(m => m
.DefaultMapAllMembers()
));
var details = new TestDetails();
var logEvent = mapper.Map(CreateEvent(details));
var logProperty = logEvent.GetProperty<ScalarValue>("Details.Inner");
logProperty.Value.IsEqualTo(details.Inner.ToJsonSuppressErrors());
}
private static string Quote(string value)
{
return string.Format("\"{0}\"", value);
}
private static Expression<Func<KeyValuePair<string, LogEventPropertyValue>, bool>> LogEventValueWith(string key, Func<string,bool> satisfies)
{
return p => p.Key == key && satisfies(p.Value.ToString());
}
private static Expression<Func<KeyValuePair<string, LogEventPropertyValue>, bool>> LogEventValueWith(string key, string value)
{
return p => p.Key == key && p.Value.ToString() == value;
}
private static Event<T> CreateEvent<T>(T details)
{
return new Event<T>("category", "name", EventTypes.Information, 42, details);
}
private static DefaultLogEventMapper CreateMapper(Action<MappingConfigurationBuilder> setup)
{
var builder = new MappingConfigurationBuilder();
setup(builder);
return new DefaultLogEventMapper(builder.GetConfiguration());
}
}
} | johnkors/IdentityServer3.Contrib.ElasticSearchEventService | source/Unittests/DefaultLogEventMapperTests.cs | C# | mit | 4,525 |
#if false
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LionFire.Behaviors
{
public class Coroutine
{
}
}
#endif | jaredthirsk/LionFire.Behaviors | LionFire.Behaviors/Dependencies/Coroutines.cs | C# | mit | 208 |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
#pragma warning disable CA1801 // Remove unused parameter
#pragma warning disable IDE0060 // Remove unused parameter
using System;
using System.Linq;
using System.Text;
namespace OtherDll
{
/// <summary>
/// Aids with testing dataflow analysis _not_ doing interprocedural DFA.
/// </summary>
/// <remarks>
/// Since Roslyn doesn't support cross-binary DFA, and this class is
/// defined in a different binary, using this class from test source code
/// is a way to test handling of non-interprocedural results in dataflow
/// analysis implementations.
/// </remarks>
public class OtherDllClass<T>
where T : class
{
public OtherDllClass(T? constructedInput)
{
this.ConstructedInput = constructedInput;
}
public T? ConstructedInput { get; set; }
public T? Default
{
get => default;
set { }
}
public string RandomString
{
get
{
Random r = new Random();
byte[] bytes = new byte[r.Next(20) + 10];
r.NextBytes(bytes);
bytes = bytes.Where(b => b is >= ((byte)' ') and <= ((byte)'~')).ToArray();
return Encoding.ASCII.GetString(bytes);
}
set { }
}
public T? ReturnsConstructedInput()
{
return this.ConstructedInput;
}
public T? ReturnsDefault()
{
return default;
}
public T? ReturnsInput(T? input)
{
return input;
}
public T? ReturnsDefault(T? input)
{
return default;
}
public string ReturnsRandom(string input)
{
Random r = new Random();
byte[] bytes = new byte[r.Next(20) + 10];
r.NextBytes(bytes);
bytes = bytes.Where(b => b is >= ((byte)' ') and <= ((byte)'~')).ToArray();
return Encoding.ASCII.GetString(bytes);
}
public void SetsOutputToConstructedInput(out T? output)
{
output = this.ConstructedInput;
}
public void SetsOutputToDefault(out T? output)
{
output = default;
}
public void SetsOutputToInput(T? input, out T? output)
{
output = input;
}
public void SetsOutputToDefault(T? input, out T? output)
{
output = default;
}
public void SetsOutputToRandom(string input, out string output)
{
Random r = new Random();
byte[] bytes = new byte[r.Next(20) + 10];
r.NextBytes(bytes);
bytes = bytes.Where(b => b is >= ((byte)' ') and <= ((byte)'~')).ToArray();
output = Encoding.ASCII.GetString(bytes);
}
public void SetsReferenceToConstructedInput(ref T? output)
{
output = this.ConstructedInput;
}
public void SetsReferenceToDefault(ref T? output)
{
output = default;
}
public void SetsReferenceToInput(T? input, ref T? output)
{
output = input;
}
public void SetsReferenceToDefault(T? input, ref T? output)
{
output = default;
}
public void SetsReferenceToRandom(string input, ref string output)
{
Random r = new Random();
byte[] bytes = new byte[r.Next(20) + 10];
r.NextBytes(bytes);
bytes = bytes.Where(b => b is >= ((byte)' ') and <= ((byte)'~')).ToArray();
output = Encoding.ASCII.GetString(bytes);
}
}
}
| dotnet/roslyn-analyzers | src/TestReferenceAssembly/OtherDllClass.cs | C# | mit | 3,861 |
namespace InfluxData.Net.InfluxDb.Models.Responses
{
public class User
{
/// <summary>
/// User name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Whether or not the user is an administrator.
/// </summary>
public bool IsAdmin { get; set; }
}
}
| pootzko/InfluxData.Net | InfluxData.Net.InfluxDb/Models/Responses/User.cs | C# | mit | 346 |
using Argolis.Hydra.Annotations;
using Argolis.Models;
using Vocab;
namespace TestHydraApi
{
public class IssueFilter : ITemplateParameters<Issue>
{
[Property(Schema.title)]
public string Title { get; set; }
[Property(Schema.BaseUri + "year")]
[Range(Xsd.integer)]
public int? Year { get; set; }
}
} | wikibus/Argolis | src/Examples/TestHydraApi/IssueFilter.cs | C# | mit | 356 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Office = Microsoft.Office.Core;
// TODO: Follow these steps to enable the Ribbon (XML) item:
// 1: Copy the following code block into the ThisAddin, ThisWorkbook, or ThisDocument class.
// protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()
// {
// return new Ribbon();
// }
// 2. Create callback methods in the "Ribbon Callbacks" region of this class to handle user
// actions, such as clicking a button. Note: if you have exported this Ribbon from the Ribbon designer,
// move your code from the event handlers to the callback methods and modify the code to work with the
// Ribbon extensibility (RibbonX) programming model.
// 3. Assign attributes to the control tags in the Ribbon XML file to identify the appropriate callback methods in your code.
// For more information, see the Ribbon XML documentation in the Visual Studio Tools for Office Help.
namespace BadgerAddin2010
{
[ComVisible(true)]
public class Ribbon : Office.IRibbonExtensibility
{
private Office.IRibbonUI ribbon;
public Ribbon()
{
}
#region IRibbonExtensibility Members
public string GetCustomUI(string ribbonID)
{
//if ("Microsoft.Outlook.Mail.Read" == ribbonID)
// return GetResourceText("BadgerAddin2010.Ribbon.xml");
//else
return null;
}
#endregion
#region Ribbon Callbacks
//Create callback methods here. For more information about adding callback methods, visit http://go.microsoft.com/fwlink/?LinkID=271226
public void Ribbon_Load(Office.IRibbonUI ribbonUI)
{
this.ribbon = ribbonUI;
}
#endregion
#region Helpers
private static string GetResourceText(string resourceName)
{
Assembly asm = Assembly.GetExecutingAssembly();
string[] resourceNames = asm.GetManifestResourceNames();
for (int i = 0; i < resourceNames.Length; ++i)
{
if (string.Compare(resourceName, resourceNames[i], StringComparison.OrdinalIgnoreCase) == 0)
{
using (StreamReader resourceReader = new StreamReader(asm.GetManifestResourceStream(resourceNames[i])))
{
if (resourceReader != null)
{
return resourceReader.ReadToEnd();
}
}
}
}
return null;
}
#endregion
}
}
| dchanko/Badger | BadgerAddin2010/Ribbon.cs | C# | mit | 2,794 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace MusicStore.Api
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
| Ico093/TelerikAcademy | WebServesesAndCloud/Homework/01.ASP.NETWebAPI/WebApi/MusicStore.Api/App_Start/WebApiConfig.cs | C# | mit | 591 |
using System.Web.Mvc;
using Microsoft.Practices.Unity;
using Unity.Mvc4;
namespace MVCForum.IOC
{
public static class Bootstrapper
{
public static IUnityContainer Initialise()
{
var container = BuildUnityContainer();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
return container;
}
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
RegisterTypes(container);
return container;
}
public static void RegisterTypes(IUnityContainer container)
{
}
}
} | unclefrost/extrem.web | MVCForum.IOC/Bootstrapper.cs | C# | mit | 797 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using InTheHand.Net;
using InTheHand.Net.Sockets;
using InTheHand.Net.Bluetooth;
namespace NXTLib
{
public static class Utils
{
public static string AddressByte2String(byte[] address, bool withcolons)
{
//BluetoothAddress adr = new BluetoothAddress(address);
//string c = adr.ToString();
string[] str = new string[6];
for (int i = 0; i < 6; i++)
str[i] = address[5 - i].ToString("x2");
string sep = ":";
if (!withcolons) { sep = ""; }
string a = string.Join(sep, str);
return a;
}
public static byte[] AddressString2Byte(string address, bool withcolons)
{
byte[] a = new byte[6];
int sep = 3;
if (!withcolons) { sep = 2; }
for (int i = 0; i < 6; i++)
{
byte b = byte.Parse(address.Substring(i * sep, 2), System.Globalization.NumberStyles.HexNumber);
a[5 - i] = b;
}
return a;
}
public static List<Brick> Combine(List<Brick> bricks1, List<Brick> bricks2)
{
List<Brick> bricks = new List<Brick>();
bricks.AddRange(bricks1);
bricks.AddRange(bricks2);
return bricks;
}
private static Int64 GetValue(this string value)
{
if (string.IsNullOrWhiteSpace(value))
{
return 0;
}
Int64 output;
// TryParse returns a boolean to indicate whether or not
// the parse succeeded. If it didn't, you may want to take
// some action here.
Int64.TryParse(value, out output);
return output;
}
}
}
| smo-key/NXTLib | nxtlib/src/Utils.cs | C# | mit | 1,877 |
namespace UCloudSDK.Models
{
/// <summary>
/// 获取流量信息
/// <para>
/// http://docs.ucloud.cn/api/ucdn/get_ucdn_traffic.html
/// </para>
/// </summary>
public partial class GetUcdnTrafficRequest
{
/// <summary>
/// 默认Action名称
/// </summary>
private string _action = "GetUcdnTraffic";
/// <summary>
/// API名称
/// <para>
/// GetUcdnTraffic
/// </para>
/// </summary>
public string Action
{
get { return _action; }
set { _action = value; }
}
/// <summary>
/// None
/// </summary>
public string 不需要提供参数 { get; set; }
}
}
| icyflash/ucloud-csharp-sdk | UCloudSDK/Models/UCDN/GetUcdnTrafficRequest.cs | C# | mit | 808 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Andersc.CodeLib.Tester.Helpers
{
public class Book
{
public string Title { get; set; }
public string Publisher { get; set; }
public int Year { get; set; }
}
}
| anderscui/cslib | Andersc.CodeLib.Test/Helpers/Book.cs | C# | mit | 295 |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Demo05")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Demo05")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
//若要开始生成可本地化的应用程序,请在
//<PropertyGroup> 中的 .csproj 文件中
//设置 <UICulture>CultureYouAreCodingWith</UICulture>。例如,如果您在源文件中
//使用的是美国英语,请将 <UICulture> 设置为 en-US。然后取消
//对以下 NeutralResourceLanguage 特性的注释。更新
//以下行中的“en-US”以匹配项目文件中的 UICulture 设置。
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //主题特定资源词典所处位置
//(在页面或应用程序资源词典中
// 未找到某个资源的情况下使用)
ResourceDictionaryLocation.SourceAssembly //常规资源词典所处位置
//(在页面、应用程序或任何主题特定资源词典中
// 未找到某个资源的情况下使用)
)]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 内部版本号
// 修订号
//
// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| HungryAnt/AntWpfDemos | AntWpfDemos/Demo05/Properties/AssemblyInfo.cs | C# | mit | 2,195 |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CultureInfoEditor.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("CultureInfoEditor.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| dparvin/CultureInfoEditor | Code/CultureInfoEditor/Properties/Resources.Designer.cs | C# | mit | 2,793 |
#region References
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using Speedy;
#endregion
namespace Scribe.Data.Entities
{
public class Page : ModifiableEntity
{
#region Constructors
[SuppressMessage("ReSharper", "VirtualMemberCallInContructor")]
public Page()
{
Versions = new Collection<PageVersion>();
}
#endregion
#region Properties
public virtual PageVersion ApprovedVersion { get; set; }
public virtual int? ApprovedVersionId { get; set; }
public virtual PageVersion CurrentVersion { get; set; }
public virtual int? CurrentVersionId { get; set; }
/// <summary>
/// Gets or sets a flag to indicated this pages has been "soft" deleted.
/// </summary>
public bool IsDeleted { get; set; }
public virtual ICollection<PageVersion> Versions { get; set; }
#endregion
}
} | BobbyCannon/Scribe | Scribe.Data/Entities/Page.cs | C# | mit | 889 |
using MineLib.Core;
using MineLib.Core.Data;
using MineLib.Core.IO;
using ProtocolClassic.Data;
namespace ProtocolClassic.Packets.Server
{
public struct LevelFinalizePacket : IPacketWithSize
{
public Position Coordinates;
public byte ID { get { return 0x04; } }
public short Size { get { return 7; } }
public IPacketWithSize ReadPacket(IProtocolDataReader reader)
{
Coordinates = Position.FromReaderShort(reader);
return this;
}
IPacket IPacket.ReadPacket(IProtocolDataReader reader)
{
return ReadPacket(reader);
}
public IPacket WritePacket(IProtocolStream stream)
{
Coordinates.ToStreamShort(stream);
return this;
}
}
}
| MineLib/ProtocolClassic | Packets/Server/LevelFinalize.cs | C# | mit | 812 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace ASP.NET_Core_Email.Models.ManageViewModels
{
public class ConfigureTwoFactorViewModel
{
public string SelectedProvider { get; set; }
public ICollection<SelectListItem> Providers { get; set; }
}
}
| elanderson/ASP.NET-Core-Email | ASP.NET-Core-Email/src/ASP.NET-Core-Email/Models/ManageViewModels/ConfigureTwoFactorViewModel.cs | C# | mit | 378 |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DataBindingHomeWork.Account {
public partial class RegisterExternalLogin {
/// <summary>
/// email control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox email;
}
}
| Spurch/ASP-.NET-WebForms | DataBindingHomeWork/Account/RegisterExternalLogin.aspx.designer.cs | C# | mit | 781 |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rotate : MonoBehaviour {
public Vector3 m_rotate;
public float m_speed;
void Start()
{
transform.rotation = Random.rotation;
}
// Update is called once per frame
void Update () {
transform.Rotate(m_rotate*Time.deltaTime* m_speed);
}
}
| a172862967/ProceduralSphere | KGProceduralSphere/Assets/Demo/Rotate.cs | C# | mit | 373 |
using Portal.CMS.Entities.Enumerators;
using Portal.CMS.Services.Generic;
using Portal.CMS.Services.PageBuilder;
using Portal.CMS.Web.Architecture.ActionFilters;
using Portal.CMS.Web.Architecture.Extensions;
using Portal.CMS.Web.Areas.PageBuilder.ViewModels.Component;
using Portal.CMS.Web.ViewModels.Shared;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Web.SessionState;
namespace Portal.CMS.Web.Areas.PageBuilder.Controllers
{
[AdminFilter(ActionFilterResponseType.Modal)]
[SessionState(SessionStateBehavior.ReadOnly)]
public class ComponentController : Controller
{
private readonly IPageSectionService _pageSectionService;
private readonly IPageComponentService _pageComponentService;
private readonly IImageService _imageService;
public ComponentController(IPageSectionService pageSectionService, IPageComponentService pageComponentService, IImageService imageService)
{
_pageSectionService = pageSectionService;
_pageComponentService = pageComponentService;
_imageService = imageService;
}
[HttpGet]
[OutputCache(Duration = 86400)]
public async Task<ActionResult> Add()
{
var model = new AddViewModel
{
PageComponentTypeList = await _pageComponentService.GetComponentTypesAsync()
};
return View("_Add", model);
}
[HttpPost]
[ValidateInput(false)]
public async Task<JsonResult> Add(int pageSectionId, string containerElementId, string elementBody)
{
elementBody = elementBody.Replace("animated bounce", string.Empty);
await _pageComponentService.AddAsync(pageSectionId, containerElementId, elementBody);
return Json(new { State = true });
}
[HttpPost]
public async Task<ActionResult> Delete(int pageSectionId, string elementId)
{
try
{
await _pageComponentService.DeleteAsync(pageSectionId, elementId);
return Json(new { State = true });
}
catch (Exception ex)
{
return Json(new { State = false, Message = ex.InnerException });
}
}
[HttpPost]
[ValidateInput(false)]
public async Task<ActionResult> Edit(int pageSectionId, string elementId, string elementHtml)
{
await _pageComponentService.EditElementAsync(pageSectionId, elementId, elementHtml);
return Content("Refresh");
}
[HttpGet]
public async Task<ActionResult> EditImage(int pageSectionId, string elementId, string elementType)
{
var imageList = await _imageService.GetAsync();
var model = new ImageViewModel
{
SectionId = pageSectionId,
ElementType = elementType,
ElementId = elementId,
GeneralImages = new PaginationViewModel
{
PaginationType = "general",
TargetInputField = "SelectedImageId",
ImageList = imageList.Where(x => x.ImageCategory == ImageCategory.General)
},
IconImages = new PaginationViewModel
{
PaginationType = "icon",
TargetInputField = "SelectedImageId",
ImageList = imageList.Where(x => x.ImageCategory == ImageCategory.Icon)
},
ScreenshotImages = new PaginationViewModel
{
PaginationType = "screenshot",
TargetInputField = "SelectedImageId",
ImageList = imageList.Where(x => x.ImageCategory == ImageCategory.Screenshot)
},
TextureImages = new PaginationViewModel
{
PaginationType = "texture",
TargetInputField = "SelectedImageId",
ImageList = imageList.Where(x => x.ImageCategory == ImageCategory.Texture)
}
};
return View("_EditImage", model);
}
[HttpPost]
public async Task<JsonResult> EditImage(ImageViewModel model)
{
try
{
var selectedImage = await _imageService.GetAsync(model.SelectedImageId);
await _pageComponentService.EditImageAsync(model.SectionId, model.ElementType, model.ElementId, selectedImage.CDNImagePath());
return Json(new { State = true, Source = selectedImage.CDNImagePath() });
}
catch (Exception)
{
return Json(new { State = false });
}
}
[HttpGet]
public ActionResult EditVideo(int pageSectionId, string widgetWrapperElementId, string videoPlayerElementId)
{
var model = new VideoViewModel
{
SectionId = pageSectionId,
WidgetWrapperElementId = widgetWrapperElementId,
VideoPlayerElementId = videoPlayerElementId,
VideoUrl = string.Empty
};
return View("_EditVideo", model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> EditVideo(VideoViewModel model)
{
try
{
await _pageComponentService.EditSourceAsync(model.SectionId, model.VideoPlayerElementId, model.VideoUrl);
return Json(new { State = true });
}
catch (Exception)
{
return Json(new { State = false });
}
}
[HttpGet]
public ActionResult EditContainer(int pageSectionId, string elementId)
{
var model = new ContainerViewModel
{
SectionId = pageSectionId,
ElementId = elementId
};
return View("_EditContainer", model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> EditContainer(ContainerViewModel model)
{
await _pageSectionService.EditAnimationAsync(model.SectionId, model.ElementId, model.Animation.ToString());
return Content("Refresh");
}
[HttpPost]
[ValidateInput(false)]
public async Task<ActionResult> Link(int pageSectionId, string elementId, string elementHtml, string elementHref, string elementTarget)
{
await _pageComponentService.EditAnchorAsync(pageSectionId, elementId, elementHtml, elementHref, elementTarget);
return Content("Refresh");
}
[HttpPost]
public async Task<JsonResult> Clone(int pageSectionId, string elementId, string componentStamp)
{
await _pageComponentService.CloneElementAsync(pageSectionId, elementId, componentStamp);
return Json(new { State = true });
}
}
} | tommcclean/PortalCMS | Portal.CMS.Web/Areas/PageBuilder/Controllers/ComponentController.cs | C# | mit | 7,137 |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// ActionOnDispose.cs
//
//
// Implemention of IDisposable that runs a delegate on Dispose.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
namespace System.Threading.Tasks.Dataflow.Internal
{
/// <summary>Provider of disposables that run actions.</summary>
internal sealed class Disposables
{
/// <summary>An IDisposable that does nothing.</summary>
internal readonly static IDisposable Nop = new NopDisposable();
/// <summary>Creates an IDisposable that runs an action when disposed.</summary>
/// <typeparam name="T1">Specifies the type of the first argument.</typeparam>
/// <typeparam name="T2">Specifies the type of the second argument.</typeparam>
/// <param name="action">The action to invoke.</param>
/// <param name="arg1">The first argument.</param>
/// <param name="arg2">The second argument.</param>
/// <returns>The created disposable.</returns>
internal static IDisposable Create<T1, T2>(Action<T1, T2> action, T1 arg1, T2 arg2)
{
Contract.Requires(action != null, "Non-null disposer action required.");
return new Disposable<T1, T2>(action, arg1, arg2);
}
/// <summary>Creates an IDisposable that runs an action when disposed.</summary>
/// <typeparam name="T1">Specifies the type of the first argument.</typeparam>
/// <typeparam name="T2">Specifies the type of the second argument.</typeparam>
/// <typeparam name="T3">Specifies the type of the third argument.</typeparam>
/// <param name="action">The action to invoke.</param>
/// <param name="arg1">The first argument.</param>
/// <param name="arg2">The second argument.</param>
/// <param name="arg3">The third argument.</param>
/// <returns>The created disposable.</returns>
internal static IDisposable Create<T1, T2, T3>(Action<T1, T2, T3> action, T1 arg1, T2 arg2, T3 arg3)
{
Contract.Requires(action != null, "Non-null disposer action required.");
return new Disposable<T1, T2, T3>(action, arg1, arg2, arg3);
}
/// <summary>A disposable that's a nop.</summary>
[DebuggerDisplay("Disposed = true")]
private sealed class NopDisposable : IDisposable
{
void IDisposable.Dispose() { }
}
/// <summary>An IDisposable that will run a delegate when disposed.</summary>
[DebuggerDisplay("Disposed = {Disposed}")]
private sealed class Disposable<T1, T2> : IDisposable
{
/// <summary>First state argument.</summary>
private readonly T1 _arg1;
/// <summary>Second state argument.</summary>
private readonly T2 _arg2;
/// <summary>The action to run when disposed. Null if disposed.</summary>
private Action<T1, T2> _action;
/// <summary>Initializes the ActionOnDispose.</summary>
/// <param name="action">The action to run when disposed.</param>
/// <param name="arg1">The first argument.</param>
/// <param name="arg2">The second argument.</param>
internal Disposable(Action<T1, T2> action, T1 arg1, T2 arg2)
{
Contract.Requires(action != null, "Non-null action needed for disposable");
_action = action;
_arg1 = arg1;
_arg2 = arg2;
}
/// <summary>Gets whether the IDisposable has been disposed.</summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
private bool Disposed { get { return _action == null; } }
/// <summary>Invoke the action.</summary>
void IDisposable.Dispose()
{
Action<T1, T2> toRun = _action;
if (toRun != null &&
Interlocked.CompareExchange(ref _action, null, toRun) == toRun)
{
toRun(_arg1, _arg2);
}
}
}
/// <summary>An IDisposable that will run a delegate when disposed.</summary>
[DebuggerDisplay("Disposed = {Disposed}")]
private sealed class Disposable<T1, T2, T3> : IDisposable
{
/// <summary>First state argument.</summary>
private readonly T1 _arg1;
/// <summary>Second state argument.</summary>
private readonly T2 _arg2;
/// <summary>Third state argument.</summary>
private readonly T3 _arg3;
/// <summary>The action to run when disposed. Null if disposed.</summary>
private Action<T1, T2, T3> _action;
/// <summary>Initializes the ActionOnDispose.</summary>
/// <param name="action">The action to run when disposed.</param>
/// <param name="arg1">The first argument.</param>
/// <param name="arg2">The second argument.</param>
/// <param name="arg3">The third argument.</param>
internal Disposable(Action<T1, T2, T3> action, T1 arg1, T2 arg2, T3 arg3)
{
Contract.Requires(action != null, "Non-null action needed for disposable");
_action = action;
_arg1 = arg1;
_arg2 = arg2;
_arg3 = arg3;
}
/// <summary>Gets whether the IDisposable has been disposed.</summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
private bool Disposed { get { return _action == null; } }
/// <summary>Invoke the action.</summary>
void IDisposable.Dispose()
{
Action<T1, T2, T3> toRun = _action;
if (toRun != null &&
Interlocked.CompareExchange(ref _action, null, toRun) == toRun)
{
toRun(_arg1, _arg2, _arg3);
}
}
}
}
}
| cuteant/dotnet-tpl-dataflow | source/Internal/ActionOnDispose.cs | C# | mit | 5,481 |
using System;
using System.Collections.Generic;
using Esb.Transport;
namespace Esb.Message
{
public interface IMessageQueue
{
void Add(Envelope message);
IEnumerable<Envelope> Messages { get; }
Envelope GetNextMessage();
void SuspendMessages(Type messageType);
void ResumeMessages(Type messageType);
void RerouteMessages(Type messageType);
void RemoveMessages(Type messageType);
event EventHandler<EventArgs> OnMessageArived;
IRouter Router { get; set; }
}
} | Xynratron/WorkingCluster | Esb/Message/IMessageQueue.cs | C# | mit | 548 |
//-----------------------------------------------------------------------
// <copyright file="LocalizableFormBase.cs" company="Hyperar">
// Copyright (c) Hyperar. All rights reserved.
// </copyright>
// <author>Matías Ezequiel Sánchez</author>
//-----------------------------------------------------------------------
namespace Hyperar.HattrickUltimate.UserInterface
{
using System;
using System.Windows.Forms;
using Interface;
/// <summary>
/// ILocalizableForm base implementation.
/// </summary>
public partial class LocalizableFormBase : Form, ILocalizableForm
{
#region Public Methods
/// <summary>
/// Populates controls' properties with the corresponding localized string.
/// </summary>
public virtual void PopulateLanguage()
{
}
#endregion Public Methods
#region Protected Methods
/// <summary>
/// Raises the System.Windows.Forms.Form.Load event.
/// </summary>
/// <param name="e">An System.EventArgs that contains the event data.</param>
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.PopulateLanguage();
}
#endregion Protected Methods
}
} | hyperar/Hattrick-Ultimate | Hyperar.HattrickUltimate.UserInterface/LocalizableFormBase.cs | C# | mit | 1,283 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Pelasoft.AspNet.Mvc.Slack.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Pelasoft.AspNet.Mvc.Slack.Tests")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("75d28683-1b61-4d8d-87c7-89d8d199d752")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| peterlanoie/aspnet-mvc-slack | src/Pelasoft.AspNet.Mvc.Slack.Tests/Properties/AssemblyInfo.cs | C# | mit | 1,398 |
//-----------------------------------------------------------------------
// <copyright file="IDemPlateFileGenerator.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation 2011. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.Research.Wwt.Sdk.Core
{
/// <summary>
/// Interface for DEM plate file generator.
/// </summary>
public interface IDemPlateFileGenerator
{
/// <summary>
/// Gets the number of processed tiles for the level in context.
/// </summary>
long TilesProcessed { get; }
/// <summary>
/// This function is used to create the plate file from already generated DEM pyramid.
/// </summary>
/// <param name="serializer">
/// DEM tile serializer to retrieve the tile.
/// </param>
void CreateFromDemTile(IDemTileSerializer serializer);
}
}
| WorldWideTelescope/wwt-tile-sdk | Core/IDemPlateFileGenerator.cs | C# | mit | 977 |
namespace PlacesToEat.Data.Common
{
using System;
using System.Data.Entity;
using System.Linq;
using Contracts;
using Models;
public class DbUserRepository<T> : IDbUserRepository<T>
where T : class, IAuditInfo, IDeletableEntity
{
public DbUserRepository(DbContext context)
{
if (context == null)
{
throw new ArgumentException("An instance of DbContext is required to use this repository.", nameof(context));
}
this.Context = context;
this.DbSet = this.Context.Set<T>();
}
private IDbSet<T> DbSet { get; }
private DbContext Context { get; }
public IQueryable<T> All()
{
return this.DbSet.AsQueryable().Where(x => !x.IsDeleted);
}
public IQueryable<T> AllWithDeleted()
{
return this.DbSet.AsQueryable();
}
public void Delete(T entity)
{
entity.IsDeleted = true;
entity.DeletedOn = DateTime.UtcNow;
}
public T GetById(string id)
{
return this.DbSet.Find(id);
}
public void HardDelete(T entity)
{
this.DbSet.Remove(entity);
}
public void Save()
{
this.Context.SaveChanges();
}
}
}
| tcholakov/PlacesToEat | Source/Data/PlacesToEat.Data.Common/DbUserRepository{T}.cs | C# | mit | 1,375 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Ninject.Modules;
using Ninject.Extensions.Conventions;
namespace SongManager.Web.NinjectSupport
{
/// <summary>
/// Automatically loads all Boot Modules and puts them into the Ninject Dependency Resolver
/// </summary>
public class DependencyBindingsModule : NinjectModule
{
public override void Load()
{
// Bind all BootModules
Kernel.Bind( i => i.FromAssembliesMatching( "SongManager.Web.dll", "SongManager.Web.Core.dll", "SongManager.Web.Data.dll", "SongManager.Core.dll" )
.SelectAllClasses()
.InheritedFrom( typeof( SongManager.Core.Boot.IBootModule ) )
.BindSingleInterface()
);
}
}
} | fjeller/ADC2016_Mvc5Sample | SongManager/SongManager.Web/NinjectSupport/DependencyBindingsModule.cs | C# | mit | 725 |
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Web;
namespace Umbraco.Core
{
///<summary>
/// Extension methods for dictionary & concurrentdictionary
///</summary>
internal static class DictionaryExtensions
{
/// <summary>
/// Method to Get a value by the key. If the key doesn't exist it will create a new TVal object for the key and return it.
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TVal"></typeparam>
/// <param name="dict"></param>
/// <param name="key"></param>
/// <returns></returns>
public static TVal GetOrCreate<TKey, TVal>(this IDictionary<TKey, TVal> dict, TKey key)
where TVal : class, new()
{
if (dict.ContainsKey(key) == false)
{
dict.Add(key, new TVal());
}
return dict[key];
}
/// <summary>
/// Updates an item with the specified key with the specified value
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
/// <param name="dict"></param>
/// <param name="key"></param>
/// <param name="updateFactory"></param>
/// <returns></returns>
/// <remarks>
/// Taken from: http://stackoverflow.com/questions/12240219/is-there-a-way-to-use-concurrentdictionary-tryupdate-with-a-lambda-expression
///
/// If there is an item in the dictionary with the key, it will keep trying to update it until it can
/// </remarks>
public static bool TryUpdate<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dict, TKey key, Func<TValue, TValue> updateFactory)
{
TValue curValue;
while (dict.TryGetValue(key, out curValue))
{
if (dict.TryUpdate(key, updateFactory(curValue), curValue))
return true;
//if we're looping either the key was removed by another thread, or another thread
//changed the value, so we start again.
}
return false;
}
/// <summary>
/// Updates an item with the specified key with the specified value
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
/// <param name="dict"></param>
/// <param name="key"></param>
/// <param name="updateFactory"></param>
/// <returns></returns>
/// <remarks>
/// Taken from: http://stackoverflow.com/questions/12240219/is-there-a-way-to-use-concurrentdictionary-tryupdate-with-a-lambda-expression
///
/// WARNING: If the value changes after we've retreived it, then the item will not be updated
/// </remarks>
public static bool TryUpdateOptimisitic<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dict, TKey key, Func<TValue, TValue> updateFactory)
{
TValue curValue;
if (!dict.TryGetValue(key, out curValue))
return false;
dict.TryUpdate(key, updateFactory(curValue), curValue);
return true;//note we return true whether we succeed or not, see explanation below.
}
/// <summary>
/// Converts a dictionary to another type by only using direct casting
/// </summary>
/// <typeparam name="TKeyOut"></typeparam>
/// <typeparam name="TValOut"></typeparam>
/// <param name="d"></param>
/// <returns></returns>
public static IDictionary<TKeyOut, TValOut> ConvertTo<TKeyOut, TValOut>(this IDictionary d)
{
var result = new Dictionary<TKeyOut, TValOut>();
foreach (DictionaryEntry v in d)
{
result.Add((TKeyOut)v.Key, (TValOut)v.Value);
}
return result;
}
/// <summary>
/// Converts a dictionary to another type using the specified converters
/// </summary>
/// <typeparam name="TKeyOut"></typeparam>
/// <typeparam name="TValOut"></typeparam>
/// <param name="d"></param>
/// <param name="keyConverter"></param>
/// <param name="valConverter"></param>
/// <returns></returns>
public static IDictionary<TKeyOut, TValOut> ConvertTo<TKeyOut, TValOut>(this IDictionary d, Func<object, TKeyOut> keyConverter, Func<object, TValOut> valConverter)
{
var result = new Dictionary<TKeyOut, TValOut>();
foreach (DictionaryEntry v in d)
{
result.Add(keyConverter(v.Key), valConverter(v.Value));
}
return result;
}
/// <summary>
/// Converts a dictionary to a NameValueCollection
/// </summary>
/// <param name="d"></param>
/// <returns></returns>
public static NameValueCollection ToNameValueCollection(this IDictionary<string, string> d)
{
var n = new NameValueCollection();
foreach (var i in d)
{
n.Add(i.Key, i.Value);
}
return n;
}
/// <summary>
/// Merges all key/values from the sources dictionaries into the destination dictionary
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TK"></typeparam>
/// <typeparam name="TV"></typeparam>
/// <param name="destination">The source dictionary to merge other dictionaries into</param>
/// <param name="overwrite">
/// By default all values will be retained in the destination if the same keys exist in the sources but
/// this can changed if overwrite = true, then any key/value found in any of the sources will overwritten in the destination. Note that
/// it will just use the last found key/value if this is true.
/// </param>
/// <param name="sources">The other dictionaries to merge values from</param>
public static void MergeLeft<T, TK, TV>(this T destination, IEnumerable<IDictionary<TK, TV>> sources, bool overwrite = false)
where T : IDictionary<TK, TV>
{
foreach (var p in sources.SelectMany(src => src).Where(p => overwrite || destination.ContainsKey(p.Key) == false))
{
destination[p.Key] = p.Value;
}
}
/// <summary>
/// Merges all key/values from the sources dictionaries into the destination dictionary
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TK"></typeparam>
/// <typeparam name="TV"></typeparam>
/// <param name="destination">The source dictionary to merge other dictionaries into</param>
/// <param name="overwrite">
/// By default all values will be retained in the destination if the same keys exist in the sources but
/// this can changed if overwrite = true, then any key/value found in any of the sources will overwritten in the destination. Note that
/// it will just use the last found key/value if this is true.
/// </param>
/// <param name="source">The other dictionary to merge values from</param>
public static void MergeLeft<T, TK, TV>(this T destination, IDictionary<TK, TV> source, bool overwrite = false)
where T : IDictionary<TK, TV>
{
destination.MergeLeft(new[] {source}, overwrite);
}
/// <summary>
/// Returns the value of the key value based on the key, if the key is not found, a null value is returned
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TVal">The type of the val.</typeparam>
/// <param name="d">The d.</param>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
public static TVal GetValue<TKey, TVal>(this IDictionary<TKey, TVal> d, TKey key, TVal defaultValue = default(TVal))
{
if (d.ContainsKey(key))
{
return d[key];
}
return defaultValue;
}
/// <summary>
/// Returns the value of the key value based on the key as it's string value, if the key is not found, then an empty string is returned
/// </summary>
/// <param name="d"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string GetValueAsString<TKey, TVal>(this IDictionary<TKey, TVal> d, TKey key)
{
if (d.ContainsKey(key))
{
return d[key].ToString();
}
return String.Empty;
}
/// <summary>
/// Returns the value of the key value based on the key as it's string value, if the key is not found or is an empty string, then the provided default value is returned
/// </summary>
/// <param name="d"></param>
/// <param name="key"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static string GetValueAsString<TKey, TVal>(this IDictionary<TKey, TVal> d, TKey key, string defaultValue)
{
if (d.ContainsKey(key))
{
var value = d[key].ToString();
if (value != string.Empty)
return value;
}
return defaultValue;
}
/// <summary>contains key ignore case.</summary>
/// <param name="dictionary">The dictionary.</param>
/// <param name="key">The key.</param>
/// <typeparam name="TValue">Value Type</typeparam>
/// <returns>The contains key ignore case.</returns>
public static bool ContainsKeyIgnoreCase<TValue>(this IDictionary<string, TValue> dictionary, string key)
{
return dictionary.Keys.InvariantContains(key);
}
/// <summary>
/// Converts a dictionary object to a query string representation such as:
/// firstname=shannon&lastname=deminick
/// </summary>
/// <param name="d"></param>
/// <returns></returns>
public static string ToQueryString(this IDictionary<string, object> d)
{
if (!d.Any()) return "";
var builder = new StringBuilder();
foreach (var i in d)
{
builder.Append(String.Format("{0}={1}&", HttpUtility.UrlEncode(i.Key), i.Value == null ? string.Empty : HttpUtility.UrlEncode(i.Value.ToString())));
}
return builder.ToString().TrimEnd('&');
}
/// <summary>The get entry ignore case.</summary>
/// <param name="dictionary">The dictionary.</param>
/// <param name="key">The key.</param>
/// <typeparam name="TValue">The type</typeparam>
/// <returns>The entry</returns>
public static TValue GetValueIgnoreCase<TValue>(this IDictionary<string, TValue> dictionary, string key)
{
return dictionary.GetValueIgnoreCase(key, default(TValue));
}
/// <summary>The get entry ignore case.</summary>
/// <param name="dictionary">The dictionary.</param>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
/// <typeparam name="TValue">The type</typeparam>
/// <returns>The entry</returns>
public static TValue GetValueIgnoreCase<TValue>(this IDictionary<string, TValue> dictionary, string key, TValue defaultValue)
{
key = dictionary.Keys.FirstOrDefault(i => i.InvariantEquals(key));
return key.IsNullOrWhiteSpace() == false
? dictionary[key]
: defaultValue;
}
}
}
| lars-erik/Umbraco-CMS | src/Umbraco.Core/DictionaryExtensions.cs | C# | mit | 12,153 |
namespace CSharpGL
{
partial class FormPropertyGrid
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.propertyGrid1 = new System.Windows.Forms.PropertyGrid();
this.SuspendLayout();
//
// propertyGrid1
//
this.propertyGrid1.Dock = System.Windows.Forms.DockStyle.Fill;
this.propertyGrid1.Font = new System.Drawing.Font("宋体", 12F);
this.propertyGrid1.Location = new System.Drawing.Point(0, 0);
this.propertyGrid1.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.propertyGrid1.Name = "propertyGrid1";
this.propertyGrid1.Size = new System.Drawing.Size(534, 545);
this.propertyGrid1.TabIndex = 0;
//
// FormProperyGrid
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(534, 545);
this.Controls.Add(this.propertyGrid1);
this.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.Name = "FormProperyGrid";
this.Text = "FormPropertyGrid";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.PropertyGrid propertyGrid1;
}
} | bitzhuwei/CSharpGL | Infrastructure/CSharpGL.Models/FormPropertyGrid.Designer.cs | C# | mit | 2,212 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
namespace Umbraco.Core.Models.EntityBase
{
/// <summary>
/// A base class for use to implement IRememberBeingDirty/ICanBeDirty
/// </summary>
public abstract class TracksChangesEntityBase : IRememberBeingDirty
{
/// <summary>
/// Tracks the properties that have changed
/// </summary>
private readonly IDictionary<string, bool> _propertyChangedInfo = new Dictionary<string, bool>();
/// <summary>
/// Tracks the properties that we're changed before the last commit (or last call to ResetDirtyProperties)
/// </summary>
private IDictionary<string, bool> _lastPropertyChangedInfo = null;
/// <summary>
/// Property changed event
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Method to call on a property setter.
/// </summary>
/// <param name="propertyInfo">The property info.</param>
protected virtual void OnPropertyChanged(PropertyInfo propertyInfo)
{
_propertyChangedInfo[propertyInfo.Name] = true;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyInfo.Name));
}
}
/// <summary>
/// Indicates whether a specific property on the current entity is dirty.
/// </summary>
/// <param name="propertyName">Name of the property to check</param>
/// <returns>True if Property is dirty, otherwise False</returns>
public virtual bool IsPropertyDirty(string propertyName)
{
return _propertyChangedInfo.Any(x => x.Key == propertyName);
}
/// <summary>
/// Indicates whether the current entity is dirty.
/// </summary>
/// <returns>True if entity is dirty, otherwise False</returns>
public virtual bool IsDirty()
{
return _propertyChangedInfo.Any();
}
/// <summary>
/// Indicates that the entity had been changed and the changes were committed
/// </summary>
/// <returns></returns>
public bool WasDirty()
{
return _lastPropertyChangedInfo != null && _lastPropertyChangedInfo.Any();
}
/// <summary>
/// Indicates whether a specific property on the current entity was changed and the changes were committed
/// </summary>
/// <param name="propertyName">Name of the property to check</param>
/// <returns>True if Property was changed, otherwise False. Returns false if the entity had not been previously changed.</returns>
public virtual bool WasPropertyDirty(string propertyName)
{
return WasDirty() && _lastPropertyChangedInfo.Any(x => x.Key == propertyName);
}
/// <summary>
/// Resets the remembered dirty properties from before the last commit
/// </summary>
public void ForgetPreviouslyDirtyProperties()
{
_lastPropertyChangedInfo.Clear();
}
/// <summary>
/// Resets dirty properties by clearing the dictionary used to track changes.
/// </summary>
/// <remarks>
/// Please note that resetting the dirty properties could potentially
/// obstruct the saving of a new or updated entity.
/// </remarks>
public virtual void ResetDirtyProperties()
{
ResetDirtyProperties(true);
}
/// <summary>
/// Resets dirty properties by clearing the dictionary used to track changes.
/// </summary>
/// <param name="rememberPreviouslyChangedProperties">
/// true if we are to remember the last changes made after resetting
/// </param>
/// <remarks>
/// Please note that resetting the dirty properties could potentially
/// obstruct the saving of a new or updated entity.
/// </remarks>
public virtual void ResetDirtyProperties(bool rememberPreviouslyChangedProperties)
{
if (rememberPreviouslyChangedProperties)
{
//copy the changed properties to the last changed properties
_lastPropertyChangedInfo = _propertyChangedInfo.ToDictionary(v => v.Key, v => v.Value);
}
_propertyChangedInfo.Clear();
}
/// <summary>
/// Used by inheritors to set the value of properties, this will detect if the property value actually changed and if it did
/// it will ensure that the property has a dirty flag set.
/// </summary>
/// <param name="setValue"></param>
/// <param name="value"></param>
/// <param name="propertySelector"></param>
/// <returns>returns true if the value changed</returns>
/// <remarks>
/// This is required because we don't want a property to show up as "dirty" if the value is the same. For example, when we
/// save a document type, nearly all properties are flagged as dirty just because we've 'reset' them, but they are all set
/// to the same value, so it's really not dirty.
/// </remarks>
internal bool SetPropertyValueAndDetectChanges<T>(Func<T, T> setValue, T value, PropertyInfo propertySelector)
{
var initVal = value;
var newVal = setValue(value);
if (!Equals(initVal, newVal))
{
OnPropertyChanged(propertySelector);
return true;
}
return false;
}
}
} | zidad/Umbraco-CMS | src/Umbraco.Core/Models/EntityBase/TracksChangesEntityBase.cs | C# | mit | 5,915 |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34011
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WinFormsApp.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| kobush/SharpDX-Tutorials | WinFormsApp/Properties/Settings.Designer.cs | C# | mit | 1,068 |
using Foundation;
using System;
using System.Linq;
using UIKit;
namespace UICatalog
{
public partial class BaseSearchController : UITableViewController, IUISearchResultsUpdating
{
private const string CellIdentifier = "searchResultsCell";
private readonly string[] allItems =
{
"Here's", "to", "the", "crazy", "ones.", "The", "misfits.", "The", "rebels.",
"The", "troublemakers.", "The", "round", "pegs", "in", "the", "square", "holes.", "The", "ones", "who",
"see", "things", "differently.", "They're", "not", "fond", "of", @"rules.", "And", "they", "have", "no",
"respect", "for", "the", "status", "quo.", "You", "can", "quote", "them,", "disagree", "with", "them,",
"glorify", "or", "vilify", "them.", "About", "the", "only", "thing", "you", "can't", "do", "is", "ignore",
"them.", "Because", "they", "change", "things.", "They", "push", "the", "human", "race", "forward.",
"And", "while", "some", "may", "see", "them", "as", "the", "crazy", "ones,", "we", "see", "genius.",
"Because", "the", "people", "who", "are", "crazy", "enough", "to", "think", "they", "can", "change",
"the", "world,", "are", "the", "ones", "who", "do."
};
private string[] items;
private string query;
public BaseSearchController(IntPtr handle) : base(handle) { }
public override void ViewDidLoad()
{
base.ViewDidLoad();
items = allItems;
}
protected void ApplyFilter(string filter)
{
query = filter;
items = string.IsNullOrEmpty(query) ? allItems : allItems.Where(s => s.Contains(query)).ToArray();
TableView.ReloadData();
}
public override nint RowsInSection(UITableView tableView, nint section)
{
return items.Length;
}
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
var cell = tableView.DequeueReusableCell(CellIdentifier, indexPath);
cell.TextLabel.Text = items[indexPath.Row];
return cell;
}
#region IUISearchResultsUpdating
[Export("updateSearchResultsForSearchController:")]
public void UpdateSearchResultsForSearchController(UISearchController searchController)
{
// UpdateSearchResultsForSearchController is called when the controller is being dismissed
// to allow those who are using the controller they are search as the results controller a chance to reset their state.
// No need to update anything if we're being dismissed.
if (searchController.Active)
{
ApplyFilter(searchController.SearchBar.Text);
}
}
#endregion
}
} | xamarin/monotouch-samples | UICatalog/UICatalog/Controllers/Search/SearchControllers/BaseSearchController.cs | C# | mit | 2,884 |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CssMerger.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CssMerger.Tests")]
[assembly: AssemblyCopyright("Copyright © 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM componenets. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f7c36817-3ade-4d22-88b3-aca652491500")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | gudmundurh/CssMerger | CssMerger.Tests/Properties/AssemblyInfo.cs | C# | mit | 1,331 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;
namespace Podcasts.Converters
{
public class PodcastDurationConverter : TypedConverter<TimeSpan?, string>
{
public override string Convert(TimeSpan? duration, object parameter, string language)
{
if (!duration.HasValue)
{
return "--";
}
else if (duration.Value.TotalHours >= 1.0)
{
return duration?.ToString(@"h\:mm\:ss");
}
else
{
return duration?.ToString(@"m\:ss");
}
}
public override TimeSpan? ConvertBack(string value, object parameter, string language)
{
throw new NotImplementedException();
}
}
} | AndrewGaspar/Podcasts | Podcasts.Shared/Converters/PodcastDurationConverter.cs | C# | mit | 904 |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace NetsuiteEnvironmentViewer
{
//http://stackoverflow.com/questions/6442911/how-do-i-sync-scrolling-in-2-treeviews-using-the-slider
public partial class MyTreeView : TreeView
{
public MyTreeView() : base()
{
}
private List<MyTreeView> linkedTreeViews = new List<MyTreeView>();
/// <summary>
/// Links the specified tree view to this tree view. Whenever either treeview
/// scrolls, the other will scroll too.
/// </summary>
/// <param name="treeView">The TreeView to link.</param>
public void AddLinkedTreeView(MyTreeView treeView)
{
if (treeView == this)
throw new ArgumentException("Cannot link a TreeView to itself!", "treeView");
if (!linkedTreeViews.Contains(treeView))
{
//add the treeview to our list of linked treeviews
linkedTreeViews.Add(treeView);
//add this to the treeview's list of linked treeviews
treeView.AddLinkedTreeView(this);
//make sure the TreeView is linked to all of the other TreeViews that this TreeView is linked to
for (int i = 0; i < linkedTreeViews.Count; i++)
{
//get the linked treeview
var linkedTreeView = linkedTreeViews[i];
//link the treeviews together
if (linkedTreeView != treeView)
linkedTreeView.AddLinkedTreeView(treeView);
}
}
}
/// <summary>
/// Sets the destination's scroll positions to that of the source.
/// </summary>
/// <param name="source">The source of the scroll positions.</param>
/// <param name="dest">The destinations to set the scroll positions for.</param>
private void SetScrollPositions(MyTreeView source, MyTreeView dest)
{
//get the scroll positions of the source
int horizontal = User32.GetScrollPos(source.Handle, Orientation.Horizontal);
int vertical = User32.GetScrollPos(source.Handle, Orientation.Vertical);
//set the scroll positions of the destination
User32.SetScrollPos(dest.Handle, Orientation.Horizontal, horizontal, true);
User32.SetScrollPos(dest.Handle, Orientation.Vertical, vertical, true);
}
protected override void WndProc(ref Message m)
{
//process the message
base.WndProc(ref m);
//pass scroll messages onto any linked views
if (m.Msg == User32.WM_VSCROLL || m.Msg == User32.WM_MOUSEWHEEL)
{
foreach (var linkedTreeView in linkedTreeViews)
{
//set the scroll positions of the linked tree view
SetScrollPositions(this, linkedTreeView);
//copy the windows message
Message copy = new Message
{
HWnd = linkedTreeView.Handle,
LParam = m.LParam,
Msg = m.Msg,
Result = m.Result,
WParam = m.WParam
};
//pass the message onto the linked tree view
linkedTreeView.ReceiveWndProc(ref copy);
}
}
}
/// <summary>
/// Recieves a WndProc message without passing it onto any linked treeviews. This is useful to avoid infinite loops.
/// </summary>
/// <param name="m">The windows message.</param>
private void ReceiveWndProc(ref Message m)
{
base.WndProc(ref m);
}
/// <summary>
/// Imported functions from the User32.dll
/// </summary>
private class User32
{
public const int WM_VSCROLL = 0x115;
public const int WM_MOUSEWHEEL = 0x020A;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int GetScrollPos(IntPtr hWnd, System.Windows.Forms.Orientation nBar);
[DllImport("user32.dll")]
public static extern int SetScrollPos(IntPtr hWnd, System.Windows.Forms.Orientation nBar, int nPos, bool bRedraw);
}
}
}
| zacarius89/NetsuiteEnvironmentViewer | NetsuiteEnvironmentViewer/windowsFormClients/treeViewClient.cs | C# | mit | 3,736 |
using System;
namespace monomart.Models.Domain
{
public class MM_GetBrand
{
public virtual int id { get; set; }
public virtual string name { get; set; }
}
}
| darkoverlordofdata/monomart | monomart/Models/Domain/MM_GetBrand.cs | C# | mit | 179 |
// <copyright file="DataTypeDefinitionMappingRegistrar.cs" company="Logikfabrik">
// Copyright (c) 2016 anton(at)logikfabrik.se. Licensed under the MIT license.
// </copyright>
namespace Logikfabrik.Umbraco.Jet.Mappings
{
using System;
/// <summary>
/// The <see cref="DataTypeDefinitionMappingRegistrar" /> class. Utility class for registering data type definition mappings.
/// </summary>
public static class DataTypeDefinitionMappingRegistrar
{
/// <summary>
/// Registers the specified data type definition mapping.
/// </summary>
/// <typeparam name="T">The type to register the specified data type definition mapping for.</typeparam>
/// <param name="dataTypeDefinitionMapping">The data type definition mapping.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="dataTypeDefinitionMapping" /> is <c>null</c>.</exception>
public static void Register<T>(IDataTypeDefinitionMapping dataTypeDefinitionMapping)
{
if (dataTypeDefinitionMapping == null)
{
throw new ArgumentNullException(nameof(dataTypeDefinitionMapping));
}
var type = typeof(T);
var registry = DataTypeDefinitionMappings.Mappings;
if (registry.ContainsKey(type))
{
if (registry[type].GetType() == dataTypeDefinitionMapping.GetType())
{
return;
}
registry.Remove(type);
}
registry.Add(type, dataTypeDefinitionMapping);
}
}
} | aarym/uJet | src/Logikfabrik.Umbraco.Jet/Mappings/DataTypeDefinitionMappingRegistrar.cs | C# | mit | 1,637 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VaiFundos
{
class Program
{
static void Main(string[] args)
{
GerenciadorCliente gerenciador = new GerenciadorCliente();
FundosEmDolar fundo_dolar1 = new FundosEmDolar("Fundos USA", "FSA");
FundosEmDolar fundo_dolar2 = new FundosEmDolar("Cambio USA", "CSA");
FundosEmReal fundo_real1 = new FundosEmReal("Fundo Deposito Interbancario", "DI");
FundosEmReal fundo_real2 = new FundosEmReal("Atmos Master", "FIA");
int opcao = 0;
Console.WriteLine("*==============Vai Fundos===================*");
Console.WriteLine("*-------------------------------------------*");
Console.WriteLine("*1------Cadastro Cliente--------------------*");
Console.WriteLine("*2------Fazer Aplicacao---------------------*");
Console.WriteLine("*3------Listar Clientes---------------------*");
Console.WriteLine("*4------Relatorio Do Cliente----------------*");
Console.WriteLine("*5------Relatorio Do Fundo------------------*");
Console.WriteLine("*6------Transferir Aplicacao De Fundo-------*");
Console.WriteLine("*7------Resgatar Aplicacao------------------*");
Console.WriteLine("*8------Sair Do Sistema --------------------*");
Console.WriteLine("*===========================================*");
Console.WriteLine("Informe a opcao Desejada:");
opcao = int.Parse(Console.ReadLine());
while(opcao >= 1 && opcao < 8)
{
if (opcao == 1)
{
Console.WriteLine("Informe o nome do Cliente Que deseja Cadastrar");
gerenciador.cadastrarCliente(Console.ReadLine());
Console.WriteLine("Toque uma tecla para voltar ao menu principal:");
Console.ReadKey();
Console.Clear();
}
else if (opcao == 2)
{
int codFundo = 0;
Console.WriteLine("Cod: 1-{0}", fundo_dolar1.getInfFundo());
Console.WriteLine("Cod: 2-{0}", fundo_dolar2.getInfFundo());
Console.WriteLine("Cod: 3-{0}", fundo_real1.getInfFundo());
Console.WriteLine("Cod: 4-{0}", fundo_real2.getInfFundo());
Console.WriteLine("Informe o Codigo Do Fundo que Deseja Aplicar");
codFundo = int.Parse(Console.ReadLine());
if (codFundo == 1)
{
double valorAplicacao = 0;
int codCliente = 0;
gerenciador.listarClientes();
Console.WriteLine("Informe o Codigo do Cliente que Deseja Aplicar:");
codCliente = int.Parse(Console.ReadLine());
Console.WriteLine("Informe o valor da Aplicacao");
valorAplicacao = double.Parse(Console.ReadLine());
fundo_dolar1.Aplicar(valorAplicacao, codCliente, gerenciador);
Console.WriteLine("Toque uma tecla para voltar ao menu principal:");
Console.ReadKey();
Console.Clear();
}
else if (codFundo == 2)
{
double valorAplicacao = 0;
int codCliente = 0;
gerenciador.listarClientes();
Console.WriteLine("Informe o Codigo do Cliente que Deseja Aplicar:");
codCliente = int.Parse(Console.ReadLine());
Console.WriteLine("Informe o valor da Aplicacao");
valorAplicacao = double.Parse(Console.ReadLine());
fundo_dolar2.Aplicar(valorAplicacao, codCliente, gerenciador);
Console.WriteLine("Toque uma tecla para voltar ao menu principal:");
Console.ReadKey();
Console.Clear();
}
else if (codFundo == 3)
{
double valorAplicacao = 0;
int codCliente = 0;
gerenciador.listarClientes();
Console.WriteLine("Informe o Codigo do Cliente que Deseja Aplicar:");
codCliente = int.Parse(Console.ReadLine());
Console.WriteLine("Informe o valor da Aplicacao");
valorAplicacao = double.Parse(Console.ReadLine());
fundo_real1.Aplicar(valorAplicacao, codCliente, gerenciador);
Console.WriteLine("Toque uma tecla para voltar ao menu principal:");
Console.ReadKey();
Console.Clear();
}
else if (codFundo == 4)
{
double valorAplicacao = 0;
int codCliente = 0;
gerenciador.listarClientes();
Console.WriteLine("Informe o Codigo do Cliente que Deseja Aplicar:");
codCliente = int.Parse(Console.ReadLine());
Console.WriteLine("Informe o valor da Aplicacao");
valorAplicacao = double.Parse(Console.ReadLine());
fundo_real2.Aplicar(valorAplicacao, codCliente, gerenciador);
Console.WriteLine("Toque uma tecla para voltar ao menu principal:");
Console.ReadKey();
Console.Clear();
}
}
else if (opcao == 3)
{
Console.Clear();
Console.WriteLine("Clientes Cadastrados:");
gerenciador.listarClientes();
Console.WriteLine("Toque uma tecla para voltar ao menu principal:");
Console.ReadKey();
}
else if (opcao == 4)
{
int codCliente = 0;
Console.WriteLine("Clientes Cadastrados");
gerenciador.listarClientes();
codCliente = int.Parse(Console.ReadLine());
gerenciador.relatorioCliente(gerenciador.buscaCliente(codCliente));
Console.WriteLine("Toque uma tecla para voltar ao menu principal:");
Console.ReadKey();
}
else if (opcao == 5)
{
int codFundo = 0;
Console.WriteLine("1-{0}", fundo_dolar1.getInfFundo());
Console.WriteLine("2-{0}", fundo_dolar2.getInfFundo());
Console.WriteLine("3-{0}", fundo_real1.getInfFundo());
Console.WriteLine("4-{0}", fundo_real2.getInfFundo());
Console.WriteLine("Informe o Codigo Do Fundo que Deseja o Relatorio");
codFundo = int.Parse(Console.ReadLine());
if (codFundo == 1)
{
fundo_dolar1.relatorioFundo();
Console.WriteLine("Toque uma tecla para voltar ao menu principal:");
Console.ReadKey();
Console.Clear();
}
else if (codFundo == 2)
{
fundo_dolar2.relatorioFundo();
Console.WriteLine("Toque uma tecla para voltar ao menu principal:");
Console.ReadKey();
Console.Clear();
}
else if (codFundo == 3)
{
fundo_real1.relatorioFundo();
Console.WriteLine("Toque uma tecla para voltar ao menu principal:");
Console.ReadKey();
Console.Clear();
}
else if (codFundo == 4)
{
fundo_real2.relatorioFundo();
Console.WriteLine("Toque uma tecla para voltar ao menu principal:");
Console.ReadKey();
Console.Clear();
}
}
else if (opcao == 6)
{
Console.WriteLine("Fundos De Investimentos Disponiveis");
Console.WriteLine("1-{0}", fundo_dolar1.getInfFundo());
Console.WriteLine("2-{0}", fundo_dolar2.getInfFundo());
Console.WriteLine("3-{0}", fundo_real1.getInfFundo());
Console.WriteLine("4-{0}", fundo_real2.getInfFundo());
int codFundoOrigem = 0;
int codDestino = 0;
int codCliente = 0;
double valor = 0;
Console.WriteLine("Informe o Codigo do fundo que deseja transferir");
codFundoOrigem = int.Parse(Console.ReadLine());
gerenciador.listarClientes();
Console.WriteLine("Informe o codigo do cliente que deseja realizar a transferencia");
codCliente = int.Parse(Console.ReadLine());
Console.WriteLine("Informe o valor da aplicacao que deseja transferir");
valor = double.Parse(Console.ReadLine());
if(codFundoOrigem == 1)
{
Console.WriteLine("Fundos De Investimentos Disponiveis Para Troca");
Console.WriteLine("2-{0}", fundo_dolar2.getInfFundo());
Console.WriteLine("Informe o Codigo do fundo que recebera a aplicacao");
codDestino = int.Parse(Console.ReadLine());
if (codDestino == 2)
{
fundo_dolar1.TrocarFundo(codCliente,valor,fundo_dolar2,'D');
}
}
else if(codFundoOrigem == 2)
{
Console.WriteLine("Fundos De Investimentos Disponiveis Para Troca");
Console.WriteLine("1-{0}", fundo_dolar1.getInfFundo());
Console.WriteLine("Informe o Codigo do fundo que recebera a aplicacao");
codDestino = int.Parse(Console.ReadLine());
if (codDestino == 1)
{
fundo_dolar2.TrocarFundo(codCliente, valor, fundo_dolar1,'D');
}
}
else if(codFundoOrigem == 3)
{
Console.WriteLine("Fundos De Investimentos Disponiveis Para Troca");
Console.WriteLine("4-{0}", fundo_real2.getInfFundo());
Console.WriteLine("Informe o Codigo do fundo que recebera a aplicacao");
codDestino = int.Parse(Console.ReadLine());
if (codDestino == 4)
{
fundo_real1.TrocarFundo(codCliente, valor, fundo_real2,'R');
}
}
else if(codFundoOrigem == 4)
{
Console.WriteLine("Fundos De Investimentos Disponiveis Para Troca");
Console.WriteLine("3-{0}", fundo_real1.getInfFundo());
Console.WriteLine("Informe o Codigo do fundo que recebera a aplicacao");
codDestino = int.Parse(Console.ReadLine());
if (codDestino == 3)
{
fundo_real2.TrocarFundo(codCliente, valor, fundo_real1,'R');
}
}
Console.WriteLine("Troca Efetuada");
Console.WriteLine("Toque uma tecla para voltar ao menu principal:");
Console.ReadKey();
Console.Clear();
}
else if(opcao == 7)
{
Console.WriteLine("Fundos De Investimentos Disponiveis");
Console.WriteLine("1-{0}", fundo_dolar1.getInfFundo());
Console.WriteLine("2-{0}", fundo_dolar2.getInfFundo());
Console.WriteLine("3-{0}", fundo_real1.getInfFundo());
Console.WriteLine("4-{0}", fundo_real2.getInfFundo());
int codFundo = 0;
int codCliente = 0;
double valor = 0;
Console.WriteLine("Informe o Codigo do Fundo Que Deseja Sacar");
codFundo = int.Parse(Console.ReadLine());
gerenciador.listarClientes();
Console.WriteLine("Informe o codigo do cliente que deseja realizar o saque");
codCliente = int.Parse(Console.ReadLine());
Console.WriteLine("Informe o valor da aplicacao que deseja sacar");
valor = double.Parse(Console.ReadLine());
if(codFundo == 1)
{
fundo_dolar1.resgate(valor,codCliente,gerenciador);
}
else if(codFundo == 2)
{
fundo_dolar2.resgate(valor, codCliente, gerenciador);
}
else if(codFundo == 3)
{
fundo_real1.resgate(valor, codCliente, gerenciador);
}
else if(codFundo == 4)
{
fundo_real2.resgate(valor, codCliente, gerenciador);
}
Console.WriteLine("Toque uma tecla para voltar ao menu principal:");
Console.ReadKey();
Console.Clear();
}
Console.WriteLine("*==============Vai Fundos===================*");
Console.WriteLine("*-------------------------------------------*");
Console.WriteLine("*1------Cadastro Cliente--------------------*");
Console.WriteLine("*2------Fazer Aplicacao---------------------*");
Console.WriteLine("*3------Listar Clientes---------------------*");
Console.WriteLine("*4------Relatorio Do Cliente----------------*");
Console.WriteLine("*5------Relatorio Do Fundo------------------*");
Console.WriteLine("*6------Transferir Aplicacao De Fundo-------*");
Console.WriteLine("*7------Resgatar Aplicacao------------------*");
Console.WriteLine("*8------Sair Do Sistema --------------------*");
Console.WriteLine("*===========================================*");
Console.WriteLine("Informe a opcao Desejada:");
opcao = int.Parse(Console.ReadLine());
}
}
}
}
| jescocard/VaiFundosUCL | VaiFundos/VaiFundos/Program.cs | C# | mit | 15,664 |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WPFProtocolHandler.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| arunjeetsingh/SampleCode | UniversalAppLaunchingWPFApp/WPFProtocolHandler/Properties/Settings.Designer.cs | C# | mit | 1,075 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Julas.Utils;
using Julas.Utils.Collections;
using Julas.Utils.Extensions;
using TheArtOfDev.HtmlRenderer.WinForms;
using Ozeki.VoIP;
using VoipClient;
namespace Client
{
public partial class ConversationForm : Form
{
private volatile bool _isInCall = false;
private readonly string _thisUserId;
private readonly string _otherUserId;
private readonly HtmlPanel _htmlPanel;
private readonly Color _textColor = Color.Black;
private readonly Color _timestampColor = Color.DarkGray;
private readonly Color _thisUserColor = Color.DodgerBlue;
private readonly Color _otherUserColor = Color.DarkOrange;
private readonly Color _enabledBtnColor = Color.FromArgb(255, 255, 255);
private readonly Color _disabledBtnColor = Color.FromArgb(226, 226, 226);
private readonly int _fontSize = 1;
private readonly VoipClientModule _voipClient;
public event Action<string> MessageSent;
public event Action Call;
public event Action HangUp;
public ConversationForm(string thisUserId, string otherUserId, string hash_pass, VoipClientModule voipClient)
{
_thisUserId = thisUserId;
_otherUserId = otherUserId;
_voipClient = voipClient;
InitializeComponent();
this.Text = $"Conversation with {otherUserId}";
_htmlPanel = new HtmlPanel();
panel1.Controls.Add(_htmlPanel);
_htmlPanel.Dock = DockStyle.Fill;
_voipClient.PhoneStateChanged += VoipClientOnPhoneStateChanged;
}
public new void Dispose()
{
_voipClient.PhoneStateChanged -= VoipClientOnPhoneStateChanged;
base.Dispose(true);
}
private void VoipClientOnPhoneStateChanged(PhoneState phoneState)
{
Invoke(() =>
{
if (!phoneState.OtherUserId.IsOneOf(null, _otherUserId) || phoneState.Status.IsOneOf(PhoneStatus.Registering))
{
btnCall.Enabled = false;
btnHangUp.Enabled = false;
btnCall.BackColor = _disabledBtnColor;
btnHangUp.BackColor = _disabledBtnColor;
return;
}
else
{
switch (phoneState.Status)
{
case PhoneStatus.Calling:
{
btnCall.Enabled = false;
btnHangUp.Enabled = true;
btnCall.BackColor = _disabledBtnColor;
btnHangUp.BackColor = _enabledBtnColor;
break;
}
case PhoneStatus.InCall:
{
btnCall.Enabled = false;
btnHangUp.Enabled = true;
btnCall.BackColor = _disabledBtnColor;
btnHangUp.BackColor = _enabledBtnColor;
break;
}
case PhoneStatus.IncomingCall:
{
btnCall.Enabled = true;
btnHangUp.Enabled = true;
btnCall.BackColor = _enabledBtnColor;
btnHangUp.BackColor = _enabledBtnColor;
break;
}
case PhoneStatus.Registered:
{
btnCall.Enabled = true;
btnHangUp.Enabled = false;
btnCall.BackColor = _enabledBtnColor;
btnHangUp.BackColor = _disabledBtnColor;
break;
}
}
}
});
}
public void AppendMessageFromOtherUser(string message)
{
AppendMessage(message, _otherUserId, _otherUserColor);
}
private void AppendMessageFromThisUser(string message)
{
AppendMessage(message, _thisUserId, _thisUserColor);
}
private void AppendMessage(string msg, string from, Color nameColor)
{
StringBuilder sb = new StringBuilder();
sb.Append("<p>");
sb.Append($"<b><font color=\"{GetHexColor(nameColor)}\" size=\"{_fontSize}\">{from}</font></b> ");
sb.Append($"<font color=\"{GetHexColor(_timestampColor)}\" size=\"{_fontSize}\">{DateTime.Now.ToString("HH:mm:ss")}</font>");
sb.Append("<br/>");
sb.Append($"<font color=\"{GetHexColor(_textColor)}\" size=\"{_fontSize}\">{msg}</font>");
sb.Append("</p>");
_htmlPanel.Text += sb.ToString();
_htmlPanel.VerticalScroll.Value = _htmlPanel.VerticalScroll.Maximum;
}
private string GetHexColor(Color color)
{
return $"#{color.R.ToString("x2").ToUpper()}{color.G.ToString("x2").ToUpper()}{color.B.ToString("x2").ToUpper()}";
}
private void SendMessage()
{
if (!tbInput.Text.IsNullOrWhitespace())
{
MessageSent?.Invoke(tbInput.Text.Trim());
AppendMessageFromThisUser(tbInput.Text.Trim());
tbInput.Text = "";
tbInput.SelectionStart = 0;
}
}
private void tbInput_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '\r' || e.KeyChar == '\n')
{
e.Handled = true;
SendMessage();
}
}
private void btnSend_Click(object sender, EventArgs e)
{
SendMessage();
}
private void ConversationForm_Load(object sender, EventArgs e)
{
VoipClientOnPhoneStateChanged(_voipClient.PhoneState);
}
private void Invoke(Action action)
{
if(this.InvokeRequired)
{
this.Invoke(new MethodInvoker(action));
}
else
{
action();
}
}
private void btnCall_Click(object sender, EventArgs e)
{
btnCall.Enabled = false;
btnHangUp.Enabled = false;
btnCall.BackColor = _disabledBtnColor;
btnHangUp.BackColor = _disabledBtnColor;
switch (_voipClient.PhoneState.Status)
{
case PhoneStatus.IncomingCall:
{
_voipClient.AnswerCall();
break;
}
case PhoneStatus.Registered:
{
_voipClient.StartCall(_otherUserId);
break;
}
}
}
private void btnHangUp_Click(object sender, EventArgs e)
{
btnCall.Enabled = false;
btnHangUp.Enabled = false;
btnCall.BackColor = _disabledBtnColor;
btnHangUp.BackColor = _disabledBtnColor;
switch (_voipClient.PhoneState.Status)
{
case PhoneStatus.IncomingCall:
{
_voipClient.RejectCall();
break;
}
case PhoneStatus.InCall:
{
_voipClient.EndCall();
break;
}
case PhoneStatus.Calling:
{
_voipClient.EndCall();
break;
}
}
}
}
}
| EMJK/Projekt_WTI_TIP | Client/ConversationForm.cs | C# | mit | 8,027 |
using System;
using System.Diagnostics.CodeAnalysis;
namespace Delimited.Data.Exceptions
{
[Serializable, ExcludeFromCodeCoverage]
public class DelimitedReaderException : Exception
{
//
// For guidelines regarding the creation of new exception types, see
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp
// and
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp07192001.asp
//
public DelimitedReaderException() { }
public DelimitedReaderException(string message) : base(message) { }
public DelimitedReaderException(string message, Exception inner) : base(message, inner) { }
protected DelimitedReaderException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
}
}
| putridparrot/Delimited.Data | Delimited.Data/Exceptions/DelimitedReaderException.cs | C# | mit | 904 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using log4net;
using Newtonsoft.Json;
using RoboticsTxt.Lib.Contracts;
using RoboticsTxt.Lib.Contracts.Configuration;
namespace RoboticsTxt.Lib.Components.Sequencer
{
internal class PositionStorageAccessor
{
private readonly ApplicationConfiguration applicationConfiguration;
private readonly ILog logger = LogManager.GetLogger(typeof(PositionStorageAccessor));
public PositionStorageAccessor(ApplicationConfiguration applicationConfiguration)
{
this.applicationConfiguration = applicationConfiguration;
}
private const string FileNamePattern = "Positions_{0}.json";
public bool WritePositionsToFile(IEnumerable<Position> positions)
{
try
{
var positionsJson = JsonConvert.SerializeObject(positions, Formatting.Indented);
var fileName = string.Format(FileNamePattern, applicationConfiguration.ApplicationName);
var stream = new FileStream(fileName, FileMode.Create);
var streamWriter = new StreamWriter(stream);
streamWriter.Write(positionsJson);
streamWriter.Flush();
this.logger.Info($"{positions.Count()} positions written to file {fileName}.");
}
catch (Exception exception)
{
this.logger.Error(exception);
return false;
}
return true;
}
public List<Position> LoadPositionsFromFile()
{
var positions = new List<Position>();
var fileName = string.Format(FileNamePattern, applicationConfiguration.ApplicationName);
if (!File.Exists(fileName))
return positions;
try
{
var stream = new FileStream(fileName, FileMode.Open);
var streamReader = new StreamReader(stream);
var positionsJson = streamReader.ReadToEnd();
positions = JsonConvert.DeserializeObject<List<Position>>(positionsJson);
this.logger.Info($"{positions.Count} positions loaded from file {fileName}.");
}
catch (Exception exception)
{
this.logger.Error(exception);
}
return positions;
}
}
}
| artiso-solutions/robotics-txt-net | TxtControllerLib/Components/Sequencer/PositionStorageAccessor.cs | C# | mit | 2,440 |
using UnityEngine;
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
// Emanuel Strömgren
public class DebugTrackerVisualizer : MonoBehaviour {
private BinaryFormatter m_Formatter = new BinaryFormatter();
private BinaryFormatter Formatter
{
get { return m_Formatter; }
}
[SerializeField]
[ContextMenuItem("Load File Data", "LoadData")]
private string m_FileName = "";
public string FileName
{
get { return m_FileName; }
}
private TrackerData m_Data;
public TrackerData Data
{
get { return m_Data; }
protected set { m_Data = value; }
}
[SerializeField]
private float m_ColorRate = 10f;
private float ColorRate
{
get { return m_ColorRate / 1000f; }
}
[SerializeField]
private float m_DirectionLength = 1f;
private float DirectionLength
{
get { return m_DirectionLength; }
}
[SerializeField]
[Range(1, 100)]
private int m_TimeStampStep = 10;
private int TimeStampStep
{
get { return m_TimeStampStep; }
}
#if UNITY_EDITOR
void OnDrawGizmosSelected()
{
if (Data.TrackerTime != null)
{
for (int i = 0; i < Data.TrackerTime.Count; i += TimeStampStep)
{
GUIStyle Style = new GUIStyle();
Style.normal.textColor = Color.HSVToRGB((Data.TrackerTime[i] * ColorRate) % 1f, 1f, 1f);
UnityEditor.Handles.Label(Data.PlayerPosition[i] + new Vector3(0f, 1f, 0f), Data.TrackerTime[i].ToString("0.00") + "s", Style);
}
}
}
void OnDrawGizmos()
{
if (Data.TrackerTime != null)
{
for (int i = 0; i < Data.TrackerTime.Count; i++)
{
Gizmos.color = Color.HSVToRGB((Data.TrackerTime[i] * ColorRate) % 1f, 1f, 1f);
if (i > 0)
{
Gizmos.DrawLine(Data.PlayerPosition[i - 1], Data.PlayerPosition[i]);
}
Gizmos.DrawRay(Data.PlayerPosition[i], Data.PlayerDirection[i] * DirectionLength);
}
}
}
#endif
void LoadData()
{
using (Stream FileStream = File.Open(FileName, FileMode.Open))
{
Data = ((SerializableTrackerData)Formatter.Deserialize(FileStream)).Deserialize();
}
}
}
| Towkin/DravenklovaUnity | Assets/Dravenklova/Scripts/PawnScripts/PlayerScripts/DebugTrackerVisualizer.cs | C# | mit | 2,459 |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#if XR_MANAGEMENT_ENABLED
using UnityEngine.XR.Management;
#endif // XR_MANAGEMENT_ENABLED
namespace Microsoft.MixedReality.Toolkit.Utilities
{
/// <summary>
/// Utilities that abstract XR settings functionality so that the MRTK need not know which
/// implementation is being used.
/// </summary>
public static class XRSettingsUtilities
{
#if !UNITY_2020_2_OR_NEWER && UNITY_2019_3_OR_NEWER && XR_MANAGEMENT_ENABLED
private static bool? isXRSDKEnabled = null;
#endif // !UNITY_2020_2_OR_NEWER && UNITY_2019_3_OR_NEWER && XR_MANAGEMENT_ENABLED
/// <summary>
/// Checks if an XR SDK plug-in is installed that disables legacy VR. Returns false if so.
/// </summary>
public static bool XRSDKEnabled
{
get
{
#if UNITY_2020_2_OR_NEWER
return true;
#elif UNITY_2019_3_OR_NEWER && XR_MANAGEMENT_ENABLED
if (!isXRSDKEnabled.HasValue)
{
XRGeneralSettings currentSettings = XRGeneralSettings.Instance;
if (currentSettings != null && currentSettings.AssignedSettings != null)
{
#pragma warning disable CS0618 // Suppressing the warning to support xr management plugin 3.x and 4.x
isXRSDKEnabled = currentSettings.AssignedSettings.loaders.Count > 0;
#pragma warning restore CS0618
}
else
{
isXRSDKEnabled = false;
}
}
return isXRSDKEnabled.Value;
#else
return false;
#endif // UNITY_2020_2_OR_NEWER
}
}
}
}
| DDReaper/MixedRealityToolkit-Unity | Assets/MRTK/Core/Utilities/XRSettingsUtilities.cs | C# | mit | 1,780 |
using System;
using Xamarin.Forms;
namespace EmployeeApp
{
public partial class ClaimDetailPage : ContentPage
{
private ClaimViewModel model;
public ClaimDetailPage(ClaimViewModel cl)
{
InitializeComponent();
model = cl;
BindingContext = model;
ToolbarItem optionbutton = new ToolbarItem
{
Text = "Options",
Order = ToolbarItemOrder.Default,
Priority = 0
};
ToolbarItems.Add(optionbutton);
optionbutton.Clicked += OptionsClicked;
if (model.ImageUrl.StartsWith("http:") || model.ImageUrl.StartsWith("https:"))
{
claimCellImage.Source = new UriImageSource { CachingEnabled = false, Uri = new Uri(model.ImageUrl) };
}
claimHintStackLayout.SetBinding(IsVisibleProperty, new Binding { Source = BindingContext, Path = "Status", Converter = new ClaminShowDetailHintConvert(), Mode = BindingMode.OneWay });
claimHintIcon.SetBinding(Image.IsVisibleProperty, new Binding { Source = BindingContext, Path = "Status", Converter = new ClaminShowDetailHintIconConvert(), Mode = BindingMode.OneWay });
claimHintTitle.SetBinding(Label.TextProperty, new Binding { Source = BindingContext, Path = "Status", Converter = new ClaminDetailHintTitleConvert(), Mode = BindingMode.OneWay });
claimHintMessage.SetBinding(Label.TextProperty, new Binding { Source = BindingContext, Path = "Status", Converter = new ClaminDetailHintMessageConvert(), Mode = BindingMode.OneWay });
claimHintFrame.SetBinding(Frame.BackgroundColorProperty, new Binding { Source = BindingContext, Path = "Status", Converter = new ClaminDetailHintBkConvert(), Mode = BindingMode.OneWay });
claimHintMessage.SetBinding(Label.TextColorProperty, new Binding { Source = BindingContext, Path = "Status", Converter = new ClaminDetailHintMsgColorConvert(), Mode = BindingMode.OneWay });
InitGridView();
this.Title = "#" + cl.Name;
}
private void InitGridView()
{
if (mainPageGrid.RowDefinitions.Count == 0)
{
claimDetailStackLayout.Padding = new Thickness(0, Display.Convert(40));
claimHintStackLayout.HeightRequest = Display.Convert(110);
Display.SetGridRowsHeight(claimHintGrid, new string[] { "32", "36" });
claimHintIcon.WidthRequest = Display.Convert(32);
claimHintIcon.HeightRequest = Display.Convert(32);
Display.SetGridRowsHeight(mainPageGrid, new string[] { "50", "46", "20", "54", "176", "30", "40", "54", "36", "44", "440", "1*"});
claimDescription.Margin = new Thickness(0, Display.Convert(14));
}
}
public async void OptionsClicked(object sender, EventArgs e)
{
var action = await DisplayActionSheet(null, "Cancel", null, "Approve", "Contact policy holder", "Decline");
switch (action)
{
case "Approve":
model.Status = ClaimStatus.Approved;
model.isNew = false;
break;
case "Decline":
model.Status = ClaimStatus.Declined;
model.isNew = false;
break;
}
}
}
}
| TBag/canviz | Mobile/EmployeeApp/EmployeeApp/EmployeeApp/Views/ClaimDetailPage.xaml.cs | C# | mit | 3,471 |
/*
Copyright (C) 2013-2015 MetaMorph Software, Inc
Permission is hereby granted, free of charge, to any person obtaining a
copy of this data, including any software or models in source or binary
form, as well as any drawings, specifications, and documentation
(collectively "the Data"), to deal in the Data without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Data, and to
permit persons to whom the Data 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 Data.
THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
=======================
This version of the META tools is a fork of an original version produced
by Vanderbilt University's Institute for Software Integrated Systems (ISIS).
Their license statement:
Copyright (C) 2011-2014 Vanderbilt University
Developed with the sponsorship of the Defense Advanced Research Projects
Agency (DARPA) and delivered to the U.S. Government with Unlimited Rights
as defined in DFARS 252.227-7013.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this data, including any software or models in source or binary
form, as well as any drawings, specifications, and documentation
(collectively "the Data"), to deal in the Data without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Data, and to
permit persons to whom the Data 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 Data.
THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
*/
using System;
using System.Runtime.InteropServices;
using GME.Util;
using GME.MGA;
namespace GME.CSharp
{
abstract class ComponentConfig
{
// Set paradigm name. Provide * if you want to register it for all paradigms.
public const string paradigmName = "CyPhyML";
// Set the human readable name of the interpreter. You can use white space characters.
public const string componentName = "CyPhyPrepareIFab";
// Specify an icon path
public const string iconName = "CyPhyPrepareIFab.ico";
public const string tooltip = "CyPhyPrepareIFab";
// If null, updated with the assembly path + the iconName dynamically on registration
public static string iconPath = null;
// Uncomment the flag if your component is paradigm independent.
public static componenttype_enum componentType = componenttype_enum.COMPONENTTYPE_INTERPRETER;
public const regaccessmode_enum registrationMode = regaccessmode_enum.REGACCESS_SYSTEM;
public const string progID = "MGA.Interpreter.CyPhyPrepareIFab";
public const string guid = "D3B4ECEE-36EC-4753-9B10-312084B48F2A";
}
}
| pombredanne/metamorphosys-desktop | metamorphosys/META/src/CyPhyPrepareIFab/ComponentConfig.cs | C# | mit | 3,987 |
using NUnit.Framework;
using Ploeh.AutoFixture;
using RememBeer.Models.Dtos;
using RememBeer.Tests.Utils;
namespace RememBeer.Tests.Models.Dtos
{
[TestFixture]
public class BeerDtoTests : TestClassBase
{
[Test]
public void Setters_ShouldSetProperties()
{
var id = this.Fixture.Create<int>();
var breweryId = this.Fixture.Create<int>();
var name = this.Fixture.Create<string>();
var breweryName = this.Fixture.Create<string>();
var dto = new BeerDto();
dto.Id = id;
dto.BreweryId = breweryId;
dto.Name = name;
dto.BreweryName = breweryName;
Assert.AreEqual(id, dto.Id);
Assert.AreEqual(breweryId, dto.BreweryId);
Assert.AreSame(name, dto.Name);
Assert.AreSame(breweryName, dto.BreweryName);
}
}
}
| J0hnyBG/RememBeerMe | src/RememBeer.Tests/Models/Dtos/BeerDtoTests.cs | C# | mit | 908 |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
- Downloads last month
- 2