text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualBasic;
using BugTracker.Entities;
using System.Data;
namespace BugTracker.DataAccessLayer
{
class DetalleCompraDao
{
public IList<DetalleCompra> GetAll()
{
List<DetalleCompra> listadoBugs = new List<DetalleCompra>();
var strSQL = "SELECT codDetalle, idCompra, codProducto, cantidad, precio FROM DetalleCompra WHERE borrado=0";
var resultadoConsulta = DBHelper.GetDBHelper().ConsultaSQL(strSQL);
foreach( DataRow row in resultadoConsulta.Rows)
{
listadoBugs.Add(MappingBug(row));
};
return listadoBugs;
}
private DetalleCompra MappingBug(DataRow row)
{
DetalleCompra oDetalleCompra = new DetalleCompra
{
CodDetalle= Convert.ToInt32(row["codDetalle"].ToString()),
IdCompra= Convert.ToInt32(row["idCompra"].ToString()),
CodProducto= Convert.ToInt32(row["codProducto"].ToString()),
Cantidad= Convert.ToInt32(row["cantidad"].ToString()),
Precio= float.Parse(row["precio"].ToString())
};
return oDetalleCompra;
}
}
}
|
using System;
namespace SwaByRef // 값을 참조해서 바꿔줌
{
class MainApp // 메인 클래스를 선언한다.
{
static void Swap (ref int a, ref int b) // Swap이라는 하위 메소드를 선언하고 ref형 int a와 b를 선언한다. 이 ref변수를 사용하면 매개 변수가 변수나 상수로부터 값을 복사하는 것과는 달리, 매개 변수가 메소드에 넘겨진 원본 변수를 직접 참조한다. 따라서 메소드 안에서 매개 변수를 수정하면 이 매개 변수가 참조하고 있는 원본 변수에 수정이 이루어 지게 된다.
{
int temp = b; // temp변수를 선언하고 b값을 집어넣는다. 얘는 원래 위 괄호안에서 미리 ref 변수와 같이 선언해 줘도 무방하다.
b = a; // a값을 집어넣는다.
a = temp; // temp값을 집어넣는다.
}
static void Main(string[] args) // 메인 메소드 시작
{
int x = 3; // x를 선언하고 3을 집어넣는다.
int y = 4; // y를 선언하고 4를 집어넣는다.
Console.WriteLine("x:{0}, y:{1}", x, y); // 현재의 x,y 값 3,4가 출련된다.
Swap(ref x, ref y); // Swap메소드의 ref 변수 안에 있는 연산을 하고 돌아온다. 즉 x와 y값이 뒤바뀐다.
Console.WriteLine("x:{0}, y:{1}", x, y); // 뒤바뀐 x,y 값을 출력한다.
}
}
}
|
using System.Diagnostics;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;
namespace Crystal.Plot2D.Charts
{
/// <summary>
/// Interaction logic for AboutWindow.xaml
/// </summary>
internal partial class AboutWindow : Window
{
public AboutWindow()
{
InitializeComponent();
}
private void Hyperlink_Click(object sender, RoutedEventArgs e)
{
Hyperlink source = (Hyperlink)sender;
Process.Start(source.NavigateUri.ToString());
}
private void Window_KeyDown(object sender, KeyEventArgs e)
{
// close on Esc or Enter pressed
if (e.Key == Key.Escape || e.Key == Key.Enter)
{
Close();
}
}
private void Hyperlink_Click_1(object sender, RoutedEventArgs e)
{
Hyperlink source = (Hyperlink)sender;
Process.Start(source.NavigateUri.ToString());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using OpenQA.Selenium;
namespace WebAutomationFramework.Pages
{
public class BasePage
{
private readonly IWebDriver _driver;
public BasePage(IWebDriver driver, By pageLocator)
{
_driver = driver;
AssertElementIsDisplayed(pageLocator, 20);
}
private void AssertElementIsDisplayed(By elementId, int timeout)
{
for (var i = 0; i < timeout; i++)
{
try
{
_driver.FindElement(elementId);
return;
}
catch (NoSuchElementException)
{
}
Thread.Sleep(TimeSpan.FromSeconds(1));
}
throw new Exception($"Could not find element {elementId} on page {GetType().Name}");
}
}
}
|
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
public partial class PimpMyEditorInspector2 : Editor
{
[RunBeforeOnInspectorGUI]
protected void GroupInspector()
{
GroupInspectorApply(first);
GroupInspectorCascade(first);
}
protected void GroupInspectorApply(SP sp)
{
SerializedProperty p = serializedObject.FindProperty(sp.path);
if (p != null)
{
if(!p.propertyPath.Contains("]") || (p.propertyPath.LastIndexOf("]") < p.propertyPath.LastIndexOf(".")))
{
System.Reflection.FieldInfo fi = GetSerializedPropertyFieldInfo(p);
if (fi != null)
{
object[] att = fi.GetCustomAttributes(typeof(GroupAttribute), true);
if (att.Length > 0)
{
GroupAttribute g = (GroupAttribute)att[0];
sp.gr = g.name == "" ? null : g.name;
sp.gt = g.tooltip == "" ? null : g.tooltip;
}
else
{
att = fi.GetCustomAttributes(typeof(Group), true);
if (att.Length > 0)
{
Group g = (Group)att[0];
sp.gr = g.name == "" ? null : g.name;
sp.gt = g.tooltip == "" ? null : g.tooltip;
}
else
{
att = fi.GetCustomAttributes(typeof(GroupedAttribute), true);
if (att.Length > 0)
{
GroupedAttribute g = (GroupedAttribute)att[0];
sp.gr = g.name == "" ? null : g.name;
sp.gt = g.tooltip == "" ? null : g.tooltip;
}
}
}
}
}
}
for (int i = 0; i < sp.children.Count; i++)
{
GroupInspectorApply(sp.children[i]);
}
}
protected void GroupInspectorCascade(SP sp)
{
for (int i = 0; i < sp.children.Count; i++)
{
if (sp.children[i].gr != null)
{
List<string> help = new List<string>();
if(sp.children[i].gt != null)
help.Add(sp.children[i].gt);
int grouped = 0;
for (int j = i+1; j < sp.children.Count; j++)
{
if (sp.children[j].gr == sp.children[i].gr)
{
if (sp.children[j].gt != null && !help.Contains(sp.children[j].gt))
help.Add(sp.children[j].gt);
SP tmp = sp.children[j];
sp.children.RemoveAt(j);
sp.children.Insert(i + grouped + 1, tmp);
grouped++;
}
}
if (help.Count > 0)
{
sp.children[i].gt = "";
for (int h = 0; h < help.Count; h++)
{
sp.children[i].gt += (i != 0 ? " " : "") + help[h];
}
}
i += grouped;
}
GroupInspectorCascade(sp.children[i]);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace KartObjects
{
/// <summary>
/// Документ внесения/изъятия
/// </summary>
[Serializable]
public class EncashmentRecord:Entity
{
[DBIgnoreAutoGenerateParam]
[DBIgnoreReadParam]
public override string FriendlyName
{
get { return "Документ внесения/изъятия"; }
}
/// <summary>
/// Внесение +, Изъятие -
/// </summary>
public int DirectionOperation
{
get;
set;
}
/// <summary>
/// Дата операции
/// </summary>
public DateTime DateOperation
{
get;
set;
}
/// <summary>
/// Сумма операции
/// </summary>
public Decimal SumOperation
{
get;
set;
}
}
}
|
// ReSharper disable All
using Irony.Interpreter.Ast;
using Irony.Parsing;
namespace Bitbrains.AmmyParser
{
partial class AmmyGrammar
{
public void AutoInit()
{
// generator : AssemblyStart:94
comma_opt.Rule = Empty | comma;
int_number_optional.Rule = Empty | Number;
using_directive.Rule = using_ns_directive;
using_directives_opt.Rule = Empty | using_directives;
object_setting.Rule = object_property_setting;
object_settings_opt.Rule = Empty | object_settings;
ammy_bind_source_opt.Rule = Empty | ammy_bind_source;
ammy_bind_source_source.Rule = ammy_bind_source_ancestor | ammy_bind_source_element_name | ammy_bind_source_this;
ammy_bind_set_opt.Rule = Empty | ammy_bind_set;
ammy_bind_set_Mode_enum_values.Rule = ToTerm("TwoWay") | ToTerm("OneWay") | ToTerm("OneTime") | ToTerm("OneWayToSource") | ToTerm("Default");
ammy_bind_set_Mode.Rule = ToTerm("Mode") + ":" + ammy_bind_set_Mode_enum_values + comma_opt;
ammy_bind_set_NotifyOnSourceUpdated.Rule = ToTerm("NotifyOnSourceUpdated") + ":" + boolean + comma_opt;
ammy_bind_set_NotifyOnTargetUpdated.Rule = ToTerm("NotifyOnTargetUpdated") + ":" + boolean + comma_opt;
ammy_bind_set_NotifyOnValidationError.Rule = ToTerm("NotifyOnValidationError") + ":" + boolean + comma_opt;
ammy_bind_set_ValidatesOnExceptions.Rule = ToTerm("ValidatesOnExceptions") + ":" + boolean + comma_opt;
ammy_bind_set_ValidatesOnDataErrors.Rule = ToTerm("ValidatesOnDataErrors") + ":" + boolean + comma_opt;
ammy_bind_set_ValidatesOnNotifyDataErrors.Rule = ToTerm("ValidatesOnNotifyDataErrors") + ":" + boolean + comma_opt;
ammy_bind_set_StringFormat.Rule = ToTerm("StringFormat") + ":" + TheStringLiteral + comma_opt;
ammy_bind_set_BindingGroupName.Rule = ToTerm("BindingGroupName") + ":" + TheStringLiteral + comma_opt;
ammy_bind_set_FallbackValue.Rule = ToTerm("FallbackValue") + ":" + Number + comma_opt;
ammy_bind_set_IsAsync.Rule = ToTerm("IsAsync") + ":" + boolean + comma_opt;
ammy_bind_set_item.Rule = ammy_bind_set_Mode | ammy_bind_set_NotifyOnSourceUpdated | ammy_bind_set_NotifyOnTargetUpdated | ammy_bind_set_NotifyOnValidationError | ammy_bind_set_ValidatesOnExceptions | ammy_bind_set_ValidatesOnDataErrors | ammy_bind_set_ValidatesOnNotifyDataErrors | ammy_bind_set_StringFormat | ammy_bind_set_BindingGroupName | ammy_bind_set_FallbackValue | ammy_bind_set_IsAsync;
ammy_bind_set_items.Rule = MakePlusRule(ammy_bind_set_items, null, ammy_bind_set_item);
ammy_bind_set_items_opt.Rule = Empty | ammy_bind_set_items;
ammy_property_name.Rule = identifier;
ammy_property_value.Rule = primary_expression | ammy_bind;
primary_expression.Rule = literal;
expression.Rule = primary_expression;
mixin_or_alias_argument.Rule = identifier;
mixin_or_alias_arguments_opt.Rule = Empty | mixin_or_alias_arguments;
object_name_opt.Rule = Empty | object_name;
statement.Rule = mixin_definition | object_definition;
statements_opt.Rule = Empty | statements;
}
public void AutoInit2()
{
// generator : AssemblyStart:116
MarkPunctuation(":", "BindingGroupName", "FallbackValue", "IsAsync", "Mode", "NotifyOnSourceUpdated", "NotifyOnTargetUpdated", "NotifyOnValidationError", "StringFormat", "ValidatesOnDataErrors", "ValidatesOnExceptions", "ValidatesOnNotifyDataErrors");
}
public NonTerminal comma_opt = new NonTerminal("comma_opt", typeof(AstOptNode));
public NonTerminal int_number_optional = new NonTerminal("int_number_optional", typeof(AstOptNode));
public NonTerminal boolean = new NonTerminal("boolean", typeof(AstBoolean));
public NonTerminal literal = new NonTerminal("literal", typeof(AstLiteral));
public NonTerminal qual_name_segment = new NonTerminal("qual_name_segment", typeof(AstQualNameSegment));
public NonTerminal qual_name_segments_opt2 = new NonTerminal("qual_name_segments_opt2", typeof(AstQualNameSegmentsOpt2));
public NonTerminal qual_name_with_targs = new NonTerminal("qual_name_with_targs", typeof(AstQualNameWithTargs));
public NonTerminal identifier_or_builtin = new NonTerminal("identifier_or_builtin", typeof(AstIdentifierOrBuiltin));
public NonTerminal using_ns_directive = new NonTerminal("using_ns_directive", typeof(AstUsingNsDirective));
public NonTerminal using_directive = new NonTerminal("using_directive", typeof(AstUsingDirective));
public NonTerminal using_directives = new NonTerminal("using_directives", typeof(AstUsingDirectives));
public NonTerminal using_directives_opt = new NonTerminal("using_directives_opt", typeof(AstOptNode));
public NonTerminal mixin_definition = new NonTerminal("mixin_definition", typeof(AstMixinDefinition));
public NonTerminal object_setting = new NonTerminal("object_setting", typeof(AstObjectSetting));
public NonTerminal object_settings = new NonTerminal("object_settings", typeof(AstObjectSettings));
public NonTerminal object_settings_opt = new NonTerminal("object_settings_opt", typeof(AstOptNode));
public NonTerminal ammy_bind = new NonTerminal("ammy_bind", typeof(AstAmmyBind));
public NonTerminal ammy_bind_source = new NonTerminal("ammy_bind_source", typeof(AstAmmyBindSource));
public NonTerminal ammy_bind_source_opt = new NonTerminal("ammy_bind_source_opt", typeof(AstOptNode));
public NonTerminal ammy_bind_source_source = new NonTerminal("ammy_bind_source_source", typeof(AstAmmyBindSourceSource));
public NonTerminal ammy_bind_source_ancestor = new NonTerminal("ammy_bind_source_ancestor", typeof(AstAmmyBindSourceAncestor));
public NonTerminal ammy_bind_source_element_name = new NonTerminal("ammy_bind_source_element_name", typeof(AstAmmyBindSourceElementName));
public NonTerminal ammy_bind_source_this = new NonTerminal("ammy_bind_source_this", typeof(AstAmmyBindSourceThis));
public NonTerminal ammy_bind_set = new NonTerminal("ammy_bind_set", typeof(AstAmmyBindSet));
public NonTerminal ammy_bind_set_opt = new NonTerminal("ammy_bind_set_opt", typeof(AstOptNode));
public NonTerminal ammy_bind_set_Mode_enum_values = new NonTerminal("ammy_bind_set_Mode_enum_values", typeof(AstAmmyBindSetModeEnumValues));
public NonTerminal ammy_bind_set_Mode = new NonTerminal("ammy_bind_set_Mode", typeof(AstAmmyBindSetMode));
public NonTerminal ammy_bind_set_NotifyOnSourceUpdated = new NonTerminal("ammy_bind_set_NotifyOnSourceUpdated", typeof(AstAmmyBindSetNotifyOnSourceUpdated));
public NonTerminal ammy_bind_set_NotifyOnTargetUpdated = new NonTerminal("ammy_bind_set_NotifyOnTargetUpdated", typeof(AstAmmyBindSetNotifyOnTargetUpdated));
public NonTerminal ammy_bind_set_NotifyOnValidationError = new NonTerminal("ammy_bind_set_NotifyOnValidationError", typeof(AstAmmyBindSetNotifyOnValidationError));
public NonTerminal ammy_bind_set_ValidatesOnExceptions = new NonTerminal("ammy_bind_set_ValidatesOnExceptions", typeof(AstAmmyBindSetValidatesOnExceptions));
public NonTerminal ammy_bind_set_ValidatesOnDataErrors = new NonTerminal("ammy_bind_set_ValidatesOnDataErrors", typeof(AstAmmyBindSetValidatesOnDataErrors));
public NonTerminal ammy_bind_set_ValidatesOnNotifyDataErrors = new NonTerminal("ammy_bind_set_ValidatesOnNotifyDataErrors", typeof(AstAmmyBindSetValidatesOnNotifyDataErrors));
public NonTerminal ammy_bind_set_StringFormat = new NonTerminal("ammy_bind_set_StringFormat", typeof(AstAmmyBindSetStringFormat));
public NonTerminal ammy_bind_set_BindingGroupName = new NonTerminal("ammy_bind_set_BindingGroupName", typeof(AstAmmyBindSetBindingGroupName));
public NonTerminal ammy_bind_set_FallbackValue = new NonTerminal("ammy_bind_set_FallbackValue", typeof(AstAmmyBindSetFallbackValue));
public NonTerminal ammy_bind_set_IsAsync = new NonTerminal("ammy_bind_set_IsAsync", typeof(AstAmmyBindSetIsAsync));
public NonTerminal ammy_bind_set_item = new NonTerminal("ammy_bind_set_item", typeof(AstAmmyBindSetItem));
public NonTerminal ammy_bind_set_items = new NonTerminal("ammy_bind_set_items", typeof(AstAmmyBindSetItems));
public NonTerminal ammy_bind_set_items_opt = new NonTerminal("ammy_bind_set_items_opt", typeof(AstOptNode));
public NonTerminal object_property_setting = new NonTerminal("object_property_setting", typeof(AstObjectPropertySetting));
public NonTerminal ammy_property_name = new NonTerminal("ammy_property_name", typeof(AstAmmyPropertyName));
public NonTerminal ammy_property_value = new NonTerminal("ammy_property_value", typeof(AstAmmyPropertyValue));
public NonTerminal primary_expression = new NonTerminal("primary_expression", typeof(AstPrimaryExpression));
public NonTerminal expression = new NonTerminal("expression", typeof(AstExpression));
public NonTerminal mixin_or_alias_argument = new NonTerminal("mixin_or_alias_argument", typeof(AstMixinOrAliasArgument));
public NonTerminal mixin_or_alias_arguments = new NonTerminal("mixin_or_alias_arguments", typeof(AstMixinOrAliasArguments));
public NonTerminal mixin_or_alias_arguments_opt = new NonTerminal("mixin_or_alias_arguments_opt", typeof(AstOptNode));
public NonTerminal object_definition = new NonTerminal("object_definition", typeof(AstObjectDefinition));
public NonTerminal object_name = new NonTerminal("object_name", typeof(AstObjectName));
public NonTerminal object_name_opt = new NonTerminal("object_name_opt", typeof(AstOptNode));
public NonTerminal statement = new NonTerminal("statement", typeof(AstStatement));
public NonTerminal statements = new NonTerminal("statements", typeof(AstStatements));
public NonTerminal statements_opt = new NonTerminal("statements_opt", typeof(AstOptNode));
public NonTerminal ammyCode = new NonTerminal("ammyCode", typeof(AstAmmyCode));
}
/// <summary>
/// AST class for ammy_bind terminal
/// </summary>
public partial class AstAmmyBind : BbExpressionListNode, IAstAmmyPropertyValueProvider
{
}
/// <summary>
/// AST class for ammy_bind_set terminal
/// </summary>
public partial class AstAmmyBindSet : BbExpressionListNode
{
}
/// <summary>
/// AST class for ammy_bind_set_BindingGroupName terminal
/// </summary>
public partial class AstAmmyBindSetBindingGroupName : BbExpressionListNode, IAstAmmyBindSetItemProvider
{
protected override int[] GetMap()
{
return new [] { 0 };
}
public const string Keyword = "BindingGroupName";
}
/// <summary>
/// AST class for ammy_bind_set_FallbackValue terminal
/// </summary>
public partial class AstAmmyBindSetFallbackValue : BbExpressionListNode, IAstAmmyBindSetItemProvider
{
protected override int[] GetMap()
{
return new [] { 0 };
}
public const string Keyword = "FallbackValue";
}
/// <summary>
/// AST class for ammy_bind_set_IsAsync terminal
/// </summary>
public partial class AstAmmyBindSetIsAsync : BbExpressionListNode, IAstAmmyBindSetItemProvider
{
protected override int[] GetMap()
{
return new [] { 0 };
}
public const string Keyword = "IsAsync";
}
/// <summary>
/// AST class for ammy_bind_set_item terminal
/// </summary>
public partial class AstAmmyBindSetItem : BbExpressionListNode
{
protected override int[] GetMap()
{
return new [] { 0 };
}
}
/// <summary>
/// AST class for ammy_bind_set_items terminal
/// </summary>
public partial class AstAmmyBindSetItems : ExpressionListNode<IAstAmmyBindSetItem>
{
}
/// <summary>
/// AST class for ammy_bind_set_Mode terminal
/// </summary>
public partial class AstAmmyBindSetMode : BbExpressionListNode, IAstAmmyBindSetItemProvider
{
protected override int[] GetMap()
{
return new [] { 0 };
}
public const string Keyword = "Mode";
}
/// <summary>
/// AST class for ammy_bind_set_Mode_enum_values terminal
/// </summary>
public partial class AstAmmyBindSetModeEnumValues : EnumValueNode
{
}
/// <summary>
/// AST class for ammy_bind_set_NotifyOnSourceUpdated terminal
/// </summary>
public partial class AstAmmyBindSetNotifyOnSourceUpdated : BbExpressionListNode, IAstAmmyBindSetItemProvider
{
protected override int[] GetMap()
{
return new [] { 0 };
}
public const string Keyword = "NotifyOnSourceUpdated";
}
/// <summary>
/// AST class for ammy_bind_set_NotifyOnTargetUpdated terminal
/// </summary>
public partial class AstAmmyBindSetNotifyOnTargetUpdated : BbExpressionListNode, IAstAmmyBindSetItemProvider
{
protected override int[] GetMap()
{
return new [] { 0 };
}
public const string Keyword = "NotifyOnTargetUpdated";
}
/// <summary>
/// AST class for ammy_bind_set_NotifyOnValidationError terminal
/// </summary>
public partial class AstAmmyBindSetNotifyOnValidationError : BbExpressionListNode, IAstAmmyBindSetItemProvider
{
protected override int[] GetMap()
{
return new [] { 0 };
}
public const string Keyword = "NotifyOnValidationError";
}
/// <summary>
/// AST class for ammy_bind_set_StringFormat terminal
/// </summary>
public partial class AstAmmyBindSetStringFormat : BbExpressionListNode, IAstAmmyBindSetItemProvider
{
protected override int[] GetMap()
{
return new [] { 0 };
}
public const string Keyword = "StringFormat";
}
/// <summary>
/// AST class for ammy_bind_set_ValidatesOnDataErrors terminal
/// </summary>
public partial class AstAmmyBindSetValidatesOnDataErrors : BbExpressionListNode, IAstAmmyBindSetItemProvider
{
protected override int[] GetMap()
{
return new [] { 0 };
}
public const string Keyword = "ValidatesOnDataErrors";
}
/// <summary>
/// AST class for ammy_bind_set_ValidatesOnExceptions terminal
/// </summary>
public partial class AstAmmyBindSetValidatesOnExceptions : BbExpressionListNode, IAstAmmyBindSetItemProvider
{
protected override int[] GetMap()
{
return new [] { 0 };
}
public const string Keyword = "ValidatesOnExceptions";
}
/// <summary>
/// AST class for ammy_bind_set_ValidatesOnNotifyDataErrors terminal
/// </summary>
public partial class AstAmmyBindSetValidatesOnNotifyDataErrors : BbExpressionListNode, IAstAmmyBindSetItemProvider
{
protected override int[] GetMap()
{
return new [] { 0 };
}
public const string Keyword = "ValidatesOnNotifyDataErrors";
}
/// <summary>
/// AST class for ammy_bind_source terminal
/// </summary>
public partial class AstAmmyBindSource : BbExpressionListNode
{
protected override int[] GetMap()
{
return new [] { 0 };
}
}
/// <summary>
/// AST class for ammy_bind_source_ancestor terminal
/// </summary>
public partial class AstAmmyBindSourceAncestor : BbExpressionListNode, IAstAmmyBindSourceSourceProvider
{
}
/// <summary>
/// AST class for ammy_bind_source_element_name terminal
/// </summary>
public partial class AstAmmyBindSourceElementName : BbExpressionListNode, IAstAmmyBindSourceSourceProvider
{
protected override int[] GetMap()
{
return new [] { 0 };
}
}
/// <summary>
/// AST class for ammy_bind_source_source terminal
/// </summary>
public partial class AstAmmyBindSourceSource : BbExpressionListNode
{
protected override int[] GetMap()
{
return new [] { 0 };
}
}
/// <summary>
/// AST class for ammy_bind_source_this terminal
/// </summary>
public partial class AstAmmyBindSourceThis : BbExpressionListNode, IAstAmmyBindSourceSourceProvider
{
}
/// <summary>
/// AST class for ammyCode terminal
/// </summary>
public partial class AstAmmyCode : ExpressionListNode<System.Object>
{
}
/// <summary>
/// AST class for ammy_property_name terminal
/// </summary>
public partial class AstAmmyPropertyName : BbExpressionListNode
{
protected override int[] GetMap()
{
return new [] { 0 };
}
}
/// <summary>
/// AST class for ammy_property_value terminal
/// </summary>
public partial class AstAmmyPropertyValue : BbExpressionListNode
{
protected override int[] GetMap()
{
return new [] { 0 };
}
}
/// <summary>
/// AST class for boolean terminal
/// </summary>
public partial class AstBoolean : AstNode
{
}
/// <summary>
/// AST class for expression terminal
/// </summary>
public partial class AstExpression : BbExpressionListNode
{
protected override int[] GetMap()
{
return new [] { 0 };
}
}
/// <summary>
/// AST class for identifier_or_builtin terminal
/// </summary>
public partial class AstIdentifierOrBuiltin : BbExpressionListNode
{
}
/// <summary>
/// AST class for literal terminal
/// </summary>
public partial class AstLiteral : BbExpressionListNode, IAstPrimaryExpressionProvider
{
protected override int[] GetMap()
{
return new [] { 0 };
}
}
/// <summary>
/// AST class for mixin_definition terminal
/// </summary>
public partial class AstMixinDefinition : BbExpressionListNode, IAstStatementProvider
{
}
/// <summary>
/// AST class for mixin_or_alias_argument terminal
/// </summary>
public partial class AstMixinOrAliasArgument : BbExpressionListNode
{
protected override int[] GetMap()
{
return new [] { 0 };
}
}
/// <summary>
/// AST class for mixin_or_alias_arguments terminal
/// </summary>
public partial class AstMixinOrAliasArguments : ExpressionListNode<System.Object>
{
}
/// <summary>
/// AST class for object_definition terminal
/// </summary>
public partial class AstObjectDefinition : BbExpressionListNode, IAstStatementProvider
{
}
/// <summary>
/// AST class for object_name terminal
/// </summary>
public partial class AstObjectName : BbExpressionListNode
{
protected override int[] GetMap()
{
return new [] { 0 };
}
}
/// <summary>
/// AST class for object_property_setting terminal
/// </summary>
public partial class AstObjectPropertySetting : BbExpressionListNode, IAstObjectSettingProvider
{
}
/// <summary>
/// AST class for object_setting terminal
/// </summary>
public partial class AstObjectSetting : BbExpressionListNode
{
protected override int[] GetMap()
{
return new [] { 0 };
}
}
/// <summary>
/// AST class for object_settings terminal
/// </summary>
public partial class AstObjectSettings : ExpressionListNode<IAstObjectSetting>
{
}
/// <summary>
/// AST class for primary_expression terminal
/// </summary>
public partial class AstPrimaryExpression : BbExpressionListNode, IAstAmmyPropertyValueProvider, IAstExpressionProvider
{
protected override int[] GetMap()
{
return new [] { 0 };
}
}
/// <summary>
/// AST class for qual_name_segment terminal
/// </summary>
public partial class AstQualNameSegment : BbExpressionListNode
{
}
/// <summary>
/// AST class for qual_name_segments_opt2 terminal
/// </summary>
public partial class AstQualNameSegmentsOpt2 : BbExpressionListNode
{
}
/// <summary>
/// AST class for qual_name_with_targs terminal
/// </summary>
public partial class AstQualNameWithTargs : BbExpressionListNode
{
}
/// <summary>
/// AST class for statement terminal
/// </summary>
public partial class AstStatement : BbExpressionListNode
{
protected override int[] GetMap()
{
return new [] { 0 };
}
}
/// <summary>
/// AST class for statements terminal
/// </summary>
public partial class AstStatements : ExpressionListNode<IAstStatement>
{
}
/// <summary>
/// AST class for using_directive terminal
/// </summary>
public partial class AstUsingDirective : BbExpressionListNode
{
protected override int[] GetMap()
{
return new [] { 0 };
}
}
/// <summary>
/// AST class for using_directives terminal
/// </summary>
public partial class AstUsingDirectives : ExpressionListNode<IAstUsingDirective>
{
}
/// <summary>
/// AST class for using_ns_directive terminal
/// </summary>
public partial class AstUsingNsDirective : BbExpressionListNode, IAstUsingDirectiveProvider
{
protected override int[] GetMap()
{
return new [] { 0 };
}
}
public partial interface IAstAmmyBindSetItem
{
}
public partial interface IAstAmmyBindSetItemProvider
{
IAstAmmyBindSetItem GetData(Irony.Interpreter.ScriptThread thread);
}
public partial interface IAstAmmyBindSourceSource
{
}
public partial interface IAstAmmyBindSourceSourceProvider
{
IAstAmmyBindSourceSource GetData(Irony.Interpreter.ScriptThread thread);
}
public partial interface IAstAmmyPropertyValue
{
}
public partial interface IAstAmmyPropertyValueProvider
{
IAstAmmyPropertyValue GetData(Irony.Interpreter.ScriptThread thread);
}
public partial interface IAstExpression
{
}
public partial interface IAstExpressionProvider
{
IAstExpression GetData(Irony.Interpreter.ScriptThread thread);
}
public partial interface IAstObjectSetting
{
}
public partial interface IAstObjectSettingProvider
{
IAstObjectSetting GetData(Irony.Interpreter.ScriptThread thread);
}
public partial interface IAstPrimaryExpression
{
}
public partial interface IAstPrimaryExpressionProvider
{
IAstPrimaryExpression GetData(Irony.Interpreter.ScriptThread thread);
}
public partial interface IAstStatement
{
}
public partial interface IAstStatementProvider
{
IAstStatement GetData(Irony.Interpreter.ScriptThread thread);
}
public partial interface IAstUsingDirective
{
}
public partial interface IAstUsingDirectiveProvider
{
IAstUsingDirective GetData(Irony.Interpreter.ScriptThread thread);
}
}
|
using FluentMigrator;
namespace Profiling2.Migrations.Migrations
{
// modifies person export to be compatible with Career table adjustments
[Migration(201305151740)]
public class UpdatePersonProfileCareerProcs : Migration
{
public override void Down()
{
}
public override void Up()
{
Execute.EmbeddedScript("201305151739_GetPersonProfile_CareerInformation.sql");
Execute.EmbeddedScript("201305151740_GetPersonProfile_CurrentPosition.sql");
}
}
}
|
using BradescoPGP.Common;
using BradescoPGP.Repositorio;
using BradescoPGP.Web.Models;
using BradescoPGP.Web.Services;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;
namespace BradescoPGP.Web.Controllers
{
[Authorize]
public class PipelineController : AbstractController
{
private readonly PGPEntities _context;
private readonly FiltroService filtroService;
private AjaxResponses ajaxResponses = new AjaxResponses();
public PipelineController(DbContext context) : base(context)
{
_context = context as PGPEntities;
filtroService = new FiltroService(_context);
}
// GET: Pipeline
public ActionResult Index(FiltrosTelas filtros = null)
{
var pipelines = default(List<PipelineViewModel>);
var pipes = default(List<Pipeline>);
if (HasFilterPipeline(filtros))
{
pipelines = filtroService.FiltraPipeline(filtros, MatriculaUsuario, Cargo);
}
else
{
var minDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-12);
if (User.IsInRole("Especialista"))
{
pipes = _context.Pipeline.Where(p => p.MatriculaConsultor == MatriculaUsuario &&
(p.DataProrrogada.HasValue ? p.DataProrrogada >= minDate : false || p.DataPrevista >= minDate)).ToList();
pipelines = pipes.ConvertAll(p => PipelineViewModel.Mapear(p));
}
else if (User.IsInRole("Gestor"))
{
pipes = _context.Pipeline.Join(_context.Usuario,
pipe => pipe.MatriculaConsultor,
usu => usu.Matricula,
(pipe, usu) => new { pipe, usu }
).Where(result => result.usu.MatriculaSupervisor == MatriculaUsuario &&
(result.pipe.DataPrevista >= minDate && result.pipe.DataProrrogada != null || result.pipe.DataPrevista >= minDate)).ToList()
.Select(r => r.pipe).ToList();
pipelines = pipes.ConvertAll(p => PipelineViewModel.Mapear(p));
}
else
{
var result = _context.Pipeline
.Where(p => p.DataPrevista >= minDate && p.DataProrrogada != null || p.DataPrevista >= minDate).ToList();
pipelines = result.ConvertAll(p => PipelineViewModel.Mapear(p));
}
}
ViewBag.Especialistas = SelectListItemGenerator.Especialistas();
ViewBag.Status = SelectListItemGenerator.Status(EventosStatusMotivosOrigens.Pipeline.ToString());
ViewBag.Motivos = SelectListItemGenerator.Motivos(EventosStatusMotivosOrigens.Pipeline.ToString())/* selectList["Motivos"]*/;
ViewBag.Origens = SelectListItemGenerator.Origens(EventosStatusMotivosOrigens.Pipeline.ToString()) /*selectList["Origens"]*/;
ViewBag.Titulo = "Pipelines";
return View(pipelines);
}
public ActionResult ExportarExcel(FiltrosTelas filtros = null)
{
var pipelines = default(List<PipelineViewModel>);
var pipes = default(List<Pipeline>);
var excel = default(byte[]);
var usuarios = _context.Usuario.ToDictionary(k => k.Matricula, v => v.Equipe);
if (HasFilterPipeline(filtros))
{
pipelines = filtroService.FiltraPipeline(filtros, MatriculaUsuario, Cargo);
}
else
{
var minDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-12);
var maxDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month));
if (User.IsInRole("Especialista"))
{
pipes = _context.Pipeline.Where(p => p.MatriculaConsultor == MatriculaUsuario &&
(p.DataProrrogada.HasValue ? p.DataProrrogada >= minDate : false || p.DataPrevista >= minDate)).ToList();
pipelines = pipes.ConvertAll(p => PipelineViewModel.Mapear(p));
}
else if (User.IsInRole("Gestor"))
{
pipes = _context.Pipeline.Join(_context.Usuario,
pipe => pipe.MatriculaConsultor,
usu => usu.Matricula,
(pipe, usu) => new { pipe, usu }
).Where(result => result.usu.MatriculaSupervisor == MatriculaUsuario &&
(result.pipe.DataPrevista >= minDate && result.pipe.DataProrrogada != null || result.pipe.DataPrevista >= minDate)).ToList()
.Select(r => r.pipe).ToList();
pipelines = pipes.ConvertAll(p => PipelineViewModel.Mapear(p));
}
else
{
var result = _context.Pipeline
.Where(p => p.DataPrevista >= minDate && p.DataProrrogada != null || p.DataPrevista >= minDate).ToList();
pipelines = result.ConvertAll(p => PipelineViewModel.Mapear(p));
}
}
pipelines.ForEach(p =>
{
p.Equipe = usuarios[p.Matricula];
});
excel = GerarExcel(pipelines, "Pipelines");
return File(excel, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Pipelines_Export_PGPWEB.xlsx");
}
[HttpPost]
public ActionResult AtualizarPipeline(Pipeline pipe, string urlRedirect)
{
var pipelineViewModel = new List<PipelineViewModel>();
var pipes = ajaxResponses.AtualizarPipeline(pipe);
if (pipes.Count > 0)
{
pipelineViewModel = pipes.ConvertAll(p => PipelineViewModel.Mapear(p));
}
return Redirect(urlRedirect);
//return JsonConvert.SerializeObject(pipelineViewModel, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
}
public string ObterPipe(int idPipe)
{
var pipeline = _context.Pipeline.Include(p => p.Status).Include(p => p.Origem).Include(p => p.Motivo).FirstOrDefault(p => p.Id == idPipe);
var pipeViewMoel = PipelineViewModel.Mapear(pipeline);
var origens = _context.Origem.Where(o => o.Evento == "Pipeline").ToList();
var selectListItens = new List<SelectListItem>();
origens.ForEach(o =>
{
if (o.Id != pipeViewMoel.OrigemId)
{
selectListItens.Add(new SelectListItem { Text = o.Descricao, Value = o.Id.ToString() });
}
else
{
selectListItens.Add(new SelectListItem { Text = o.Descricao, Value = o.Id.ToString(), Selected = true });
}
});
ViewBag.Origens = selectListItens;
return JsonConvert.SerializeObject(pipeViewMoel, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
}
public String NovoPipeline(Pipeline pipeline)
{
if (pipeline == null)
{
return string.Empty;
}
if (ajaxResponses.NovoPipeline(pipeline, out List<Pipeline> pipes))
{
var pipeViewModel = pipes.ConvertAll(p => PipelineViewModel.Mapear(p));
return JsonConvert.SerializeObject(new { status = true, dados = pipeViewModel },
new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
}
return JsonConvert.SerializeObject(new { status = false });
}
[HttpPost]
public JsonResult ResetarStatus(int id)
{
try
{
var pipeline = _context.Pipeline.First(t => t.Id == id);
pipeline.StatusId = 4;
pipeline.MotivoId = null;
pipeline.ValorAplicado = null;
pipeline.DataProrrogada = null;
_context.SaveChanges();
}
catch (Exception)
{
return Json(new { status = false, evento = "Pipeline" });
}
return Json(new { status = true, evento = "Pipeline" });
}
private bool HasFilterPipeline(FiltrosTelas filtros)
{
return !String.IsNullOrEmpty(filtros.Especialista) || !String.IsNullOrEmpty(filtros.Agencia) ||
!String.IsNullOrEmpty(filtros.Conta) || !String.IsNullOrEmpty(filtros.Situacao.ToString()) ||
filtros.De != null || filtros.Ate != null || !String.IsNullOrEmpty(filtros.Equipe);
}
}
} |
using SSISTeam9.Models;
using SSISTeam9.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Threading.Tasks;
using SSISTeam9.Filters;
namespace SSISTeam9.Controllers
{
public class RepresentativeController : Controller
{
private readonly IEmailService emailService;
public RepresentativeController()
{
emailService = new EmailService();
}
// GET: Representative
[DeptHeadFilter]
public ActionResult ChangeRepresentative(string employee,string sessionId)
{
Employee emp = EmployeeService.GetUserBySessionId(sessionId);
long deptId = emp.DeptId;
long currentRep = DepartmentService.GetCurrentRep(deptId);
bool all = DelegateService.CheckPreviousHeadForNav(deptId);
bool permanentHead = ((emp.EmpRole == "HEAD" && emp.EmpDisplayRole == "HEAD") || (emp.EmpRole == "EMPLOYEE" && emp.EmpDisplayRole == "HEAD"));
ViewData["all"] = all;
ViewData["permanentHead"] = permanentHead;
if (employee != null)
{
long newRep = long.Parse(employee);
EmailNotification notice = new EmailNotification();
RepresentativeService.UpdateEmployeeRole(newRep, currentRep, deptId);
Employee newRepMailReceiver = EmployeeService.GetEmployeeById(newRep);
Employee oldRepMailReceiver = EmployeeService.GetEmployeeById(currentRep);
Task.Run(() => {
notice.ReceiverMailAddress = newRepMailReceiver.Email;
emailService.SendMail(notice, EmailTrigger.ON_ASSIGNED_AS_DEPT_REP);
notice.ReceiverMailAddress = oldRepMailReceiver.Email;
emailService.SendMail(notice, EmailTrigger.ON_REMOVED_DEPT_REP);
});
}
List<Employee> employees = RepresentativeService.GetEmployeesByDepartment(deptId);
ViewData["employees"] = employees;
ViewData["sessionId"] = sessionId;
return View();
}
}
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
namespace ManageDomain.DAL
{
public class ProjectDal
{
public List<Models.Project> GetPage(CCF.DB.DbConn dbconn, string keywords, int pno, int pagesize, out int totalcount)
{
string sql = string.Format("select * from project where state<>-1 and (codeName like concat('%',@keywords,'%') or title like concat('%',@keywords,'%') ) limit @startindex,@pagesize");
var models = dbconn.Query<Models.Project>(sql, new { keywords = keywords, startindex = pagesize * (pno - 1), pagesize = pagesize }).ToList();
string countsql = string.Format("select count(1) from project where state<>-1 and (codeName like concat('%',@keywords,'%') or title like concat('%',@keywords,'%') ); ");
totalcount = dbconn.ExecuteScalar<int>(countsql, new { keywords = keywords });
return models;
}
public Models.Project GetDetail(CCF.DB.DbConn dbconn, int projectId)
{
string sql = "select * from project where projectid=@projectid ;";
var model = dbconn.Query<Models.Project>(sql, new { projectId = projectId }).FirstOrDefault();
return model;
}
public Models.Project AddProject(CCF.DB.DbConn dbconn, Models.Project model)
{
string sql = "INSERT INTO `project`(`CodeName`,`Title`,`State`,`createTime`,`remark`)VALUES(@codeName,@title,@state,now(),@remark);";
dbconn.ExecuteSql(sql, new
{
codeName = model.CodeName ?? "",
title = model.Title ?? "",
state = model.State,
remark = model.Remark ?? ""
});
int id = dbconn.GetIdentity();
model.ProjectId = id;
return model;
}
public int EditProject(CCF.DB.DbConn dbconn, Models.Project model)
{
StringBuilder sql = new StringBuilder();
sql.Append("UPDATE `project`");
sql.Append("SET ");
sql.Append("`CodeName` = @codeName,");
sql.Append("`Title` = @title,");
sql.Append("`State` = @state,");
sql.Append("`updateTime` =now(),");
sql.Append("`remark` = @remark ");
sql.Append("WHERE `projectId` = @projectId;");
int r = dbconn.ExecuteSql(sql.ToString(), new
{
projectId = model.ProjectId,
codeName = model.CodeName ?? "",
title = model.Title ?? "",
state = model.State,
remark = model.Remark ?? ""
});
return r;
}
public int DeleteProject(CCF.DB.DbConn dbconn, int projectId)
{
string sql = "update project set state=-1 where projectId=@projectId";
int r = dbconn.ExecuteSql(sql, new { projectId = projectId });
return r;
}
public List<Models.ProjectConfig> GetProjectConfig(CCF.DB.DbConn dbconn, int projectid)
{
string sql = "select * from projectconfig where projectId = @projectid;";
var models = dbconn.Query<Models.ProjectConfig>(sql, new { projectid = projectid });
return models;
}
public int SetProjectConfig(CCF.DB.DbConn dbconn, int projectid, List<Models.ProjectConfig> configs)
{
dbconn.ExecuteSql("delete from projectconfig where projectid=@projectid", new { projectid = projectid });
string insertsql = "insert into projectconfig (projectId,configKey,configValue,remark) values(@projectid,@configkey,@configvalue,@remark );";
foreach (var a in configs)
{
a.ProjectId = projectid;
dbconn.ExecuteSql(insertsql, new
{
projectid = a.ProjectId,
configkey = a.ConfigKey,
configvalue = a.ConfigValue ?? "",
remark = a.Remark ?? ""
});
}
return configs.Count;
}
public int SynConfig(CCF.DB.DbConn dbconn, string configkey)
{
Models.ProjectConfig config = dbconn.Query<Models.ProjectConfig>("select * from projectconfig where configkey=@configkey;", new { configkey = configkey }).FirstOrDefault();
if (config == null)
return 0;
var serverprojects = dbconn.Query<Models.ServerProject>("select serverproject from serverproject where projectid=@projectid", new { projectid = config.ProjectId });
string updatesql = "update serverprojectconfig set canDelete=0 where projectid=@projectid and configkey=@configkey";
string insertsql = "insert into serverprojectconfig (serverprojectid,configkey,projectid,configvalue,candelete,remark) values(@serverprojectid,@configkey,@projectid,@configvalue,0,@remark);";
foreach (var a in serverprojects)
{
int update_rows = dbconn.ExecuteSql(updatesql, new { projectid = config.ProjectId, configkey = config.ConfigKey, configvalue = config.ConfigValue, remark = config.Remark ?? "" });
if (update_rows == 0)
{
update_rows = dbconn.ExecuteSql(insertsql, new { serverprojectid = a.ServerProjectId, projectid = config.ProjectId, configkey = config.ConfigKey, configvalue = config.ConfigValue, remark = config.Remark ?? "" });
}
}
return serverprojects.Count;
}
public List<Models.Project> GetMinProjects(CCF.DB.DbConn dbconn, int topcount)
{
string sql = "select * from project where state<>-1 order by createtime desc limit " + topcount;
return dbconn.Query<Models.Project>(sql);
}
public List<Models.ProjectVersion> GetProjectVersions(CCF.DB.DbConn dbconn, int projectid)
{
string sql = "select * from projectversion where projectid=@projectid;";
return dbconn.Query<Models.ProjectVersion>(sql, new { projectid = projectid });
}
public Models.ProjectVersion GetProjectVersion(CCF.DB.DbConn dbconn, int versionid)
{
string sql = "select * from projectversion where versionid=@versionid;";
return dbconn.Query<Models.ProjectVersion>(sql, new { versionid = versionid }).FirstOrDefault();
}
public Models.ProjectVersion AddProjectVersion(CCF.DB.DbConn dbconn, Models.ProjectVersion model)
{
string sql = "insert into projectversion( projectid,versionNo,createtime,versioninfo,downloadurl,remark) values(@projectid,@versionno,now(),@versioninfo,@downloadurl,@remark);";
dbconn.ExecuteSql(sql, new
{
projectid = model.ProjectId,
versionno = model.VersionNo,
versioninfo = model.VersionInfo ?? "",
downloadurl = model.DownloadUrl,
remark = model.Remark ?? ""
});
model.VersionId = dbconn.GetIdentity();
return model;
}
public int UpdateProjectVersion(CCF.DB.DbConn dbconn, Models.ProjectVersion model)
{
string sql = "update projectversion set versionNo=@versionno,versioninfo=@versioninfo,downloadurl=@downloadurl,remark=@remark where versionId=@versionid;";
int r = dbconn.ExecuteSql(sql, new
{
versionid = model.VersionId,
versionno = model.VersionNo,
versioninfo = model.VersionInfo ?? "",
downloadurl = model.DownloadUrl,
remark = model.Remark ?? ""
});
return r;
}
}
}
|
using UnityEngine;
using System.Collections;
public class GameInputController : Singleton<GameInputController> {
string [] inputKeys = new string [61]{
"backspace","delete","tab","return","pause","escape","space",
"up","down","right","left","insert","home","end","page up","page down",
"0","1","2","3","4","5","6","7","8","9",
"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
"numlock","caps lock","scroll lock","right shift","left shift","right ctrl","left ctrl","right alt","left alt"
};
public bool joystickDpadCanInputVertical = true;
public bool joystickDpadCanInputHorizontal = true;
WaitForSeconds inputIntervalDelaySeconds;
const float inputDelay = 0.2f;
public bool canMove;
public bool canInteract;
public bool displayingDialog;
bool menuOpened;
bool pendingBranchChoice;
string upKeyString = "w";
string downKeyString = "s";
string leftKeyString = "a";
string rightKeyString = "d";
string confirmKeyString = "return";
string cancelKeyString = "escape";
string menuKeyString = "l";
string additionalInfoKeyString = "k";
string changMoveSpeedKeyString = "space";
string startKeyString = "p";
string selectKeyString = "o";
public enum DualShockInput {
Up,
Down,
Left,
Right,
Cross = 330,
Circle = 331,
Square = 332,
Triangle = 333,
L1 = 334,
R1 = 335,
Select = 336,
Start = 337,
L2,
R2
}
KeyCode joystickCancelKeyCode = KeyCode.JoystickButton0;
KeyCode joystickConfirmKeyCode = KeyCode.JoystickButton1;
KeyCode joystickAdditionalInfoKeyCode = KeyCode.JoystickButton2;
KeyCode joystickMenuKeyCode = KeyCode.JoystickButton3;
KeyCode joystickPrevKeyCode = KeyCode.JoystickButton4;
KeyCode joystickNextKeyCode = KeyCode.JoystickButton5;
KeyCode joystickSelectKeyCode = KeyCode.JoystickButton6;
KeyCode joystickStartKeyCode = KeyCode.JoystickButton7;
bool willRun;
bool setKey = false;
void Awake () {
inputIntervalDelaySeconds = new WaitForSeconds (inputDelay);
}
// Use this for initialization
void Start () {
}
public void SetSelectKey (string selectedKey) {
confirmKeyString = selectedKey;
Debug.Log ("select key set to : " + confirmKeyString);
setKey = false;
}
// Update is called once per frame
void Update () {
if (Config.instance.controlMode == ControlMode.Pc) {
foreach (string item in inputKeys) {
if (Input.GetKeyDown (item)) {
if (item == upKeyString)
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Up);
else if (item == downKeyString)
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Down);
else if (item == leftKeyString)
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Left);
else if (item == rightKeyString)
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Right);
else if (item == confirmKeyString)
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Confirm);
else if (item == cancelKeyString)
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Cancel);
else if (item == menuKeyString)
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Menu);
else if (item == additionalInfoKeyString)
GameEvent.PressButton (GameVariables.Enums.InputButtonName.AdditionalInfo);
else if (item == startKeyString)
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Start);
else if (item == selectKeyString)
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Select);
}
//handle holding button for movement
else if (Input.GetKey (item)) {
//Debug.Log("get key");
if (item == upKeyString)
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Up);
else if (item == downKeyString)
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Down);
else if (item == leftKeyString)
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Left);
else if (item == rightKeyString)
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Right);
}
if (Input.GetKeyUp (item)) {
/*
else if(item == selectKeyString)
SelectKey(false);
else if(item == cancelKeyString)
CancelKey(false);
else */
if (item == upKeyString)
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Up);
else if (item == downKeyString)
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Down);
else if (item == leftKeyString)
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Left);
else if (item == rightKeyString)
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Right);
}
}
}
else if (Config.instance.controlMode == ControlMode.Dualshock) {
if (Input.GetKeyDown (joystickCancelKeyCode))//X
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Cancel);
if (Input.GetKeyDown (joystickConfirmKeyCode))//O
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Confirm);
if (Input.GetKeyDown (joystickAdditionalInfoKeyCode))//[]
GameEvent.PressButton (GameVariables.Enums.InputButtonName.AdditionalInfo);
if (Input.GetKeyDown (joystickMenuKeyCode))//Tri
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Menu);
if (Input.GetKeyDown (joystickPrevKeyCode))//L1
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Prev);
if (Input.GetKeyDown (joystickNextKeyCode))//R1
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Next);
if (Input.GetKeyDown (joystickSelectKeyCode))//Select
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Select);
if (Input.GetKeyDown (joystickStartKeyCode))//Start
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Start);
if (Input.GetKeyDown (KeyCode.JoystickButton8))//L3
Debug.Log ("L3");
if (Input.GetKeyDown (KeyCode.JoystickButton9))//R3
Debug.Log ("R3");
if (joystickDpadCanInputHorizontal) {
if (Input.GetAxis ("D-Pad LR") == -1)
StartCoroutine (handleDpadInput (2));
else if (Input.GetAxis ("D-Pad LR") == 1)
StartCoroutine (handleDpadInput (3));
}
if (joystickDpadCanInputVertical) {
if (Input.GetAxis ("D-Pad UD") == 1)
StartCoroutine (handleDpadInput (0));
else if (Input.GetAxis ("D-Pad UD") == -1)
StartCoroutine (handleDpadInput (1));
}
/*
if (Input.GetAxis ("Left AnalogX") != 0)
Debug.Log ("Left Analog X : " + Input.GetAxis ("Left AnalogX"));
if (Input.GetAxis ("Left AnalogY") != 0)
Debug.Log ("Left Analog Y : " + Input.GetAxis ("Left AnalogY"));
if (Input.GetAxis ("Right AnalogX") != 0)
Debug.Log ("Right Analog X : " + Input.GetAxis ("Right AnalogX"));
if (Input.GetAxis ("Right AnalogY") != 0)
Debug.Log ("Right Analog Y : " + Input.GetAxis ("Right AnalogY"));
*/
if (Input.GetAxis ("Left AnalogX") != 0 || Input.GetAxis ("Left AnalogY") != 0)
GameEvent.MoveLeftAnalog (Input.GetAxis ("Left AnalogX"), Input.GetAxis ("Left AnalogY"));
//playerControl.AnalogMove (Input.GetAxis ("Left AnalogX"), Input.GetAxis ("Left AnalogY"));
if (Input.GetAxis ("Right AnalogX") != 0 || Input.GetAxis ("Right AnalogY") != 0)
GameEvent.MoveRightAnalog (Input.GetAxis ("Right AnalogX"), Input.GetAxis ("Right AnalogY"));
//playerControl.RotateCamera (Input.GetAxis ("Right AnalogX"), Input.GetAxis ("Right AnalogY"));
}
}
IEnumerator handleDpadInput (int direction) {
//up
if (direction == 0) {
joystickDpadCanInputVertical = false;
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Up);
yield return inputIntervalDelaySeconds;
joystickDpadCanInputVertical = true;
}
//down
else if (direction == 1) {
joystickDpadCanInputVertical = false;
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Down);
yield return inputIntervalDelaySeconds;
joystickDpadCanInputVertical = true;
}
//left
else if (direction == 2) {
joystickDpadCanInputHorizontal = false;
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Left);
yield return inputIntervalDelaySeconds;
joystickDpadCanInputHorizontal = true;
}
//right
else if (direction == 3) {
joystickDpadCanInputHorizontal = false;
GameEvent.PressButton (GameVariables.Enums.InputButtonName.Right);
yield return inputIntervalDelaySeconds;
joystickDpadCanInputHorizontal = true;
}
}
}
|
using Restaurants.Domain;
namespace Restaurants.Application
{
public interface ICustomerAppService : IAppServiceBase<Customer>
{
Customer GetByEmail(string email);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PizzaNameDefs
{
public List<string> MeatPrefixes;
public List<string> VegPrefixes;
public List<string> MeatSuffixes;
public List<string> VegSuffixes;
}
|
using CapaDatos;
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using Tulpep.NotificationWindow;
namespace CapaUsuario.Compras
{
public partial class FrmStock : Form
{
//private DUsuario usuarioLogueado;
//public DUsuario UsuarioLogueado { get => usuarioLogueado; set => usuarioLogueado = value; }
private bool nuevo;
private DStock dStock = new DStock();
public FrmStock()
{
InitializeComponent();
}
private void FrmStock_Load(object sender, EventArgs e)
{
WindowState = FormWindowState.Maximized;
ActualizarComboBoxes();
ActualizarListados();
MarcaComboBox.SelectedIndex = -1;
FrmStock_SizeChanged(sender, e);
}
private void ActualizarListados()
{
SelectStock();
DStockMarca dStockMarca = new DStockMarca();
DgvStockMarca.DataSource = dStockMarca.SelectStockMarca();
DgvStockMarca.Refresh();
}
private void SelectStock()
{
DgvStock.DataSource = dStock.SelectStock();
DgvStock.Refresh();
}
private void ActualizarComboBoxes()
{
//DMedida dMedida = new DMedida();
//MedidaComboBox.DataSource = null;
//MedidaComboBox.DataSource = dMedida.SelectMedidas();
//MedidaComboBox.DisplayMember = "nombre";
//MedidaComboBox.ValueMember = "cod_med";
DMarca dMarca = new DMarca();
MarcaComboBox.DataSource = null;
MarcaComboBox.DataSource = dMarca.SelectMarcas();
MarcaComboBox.DisplayMember = "Nombre";
MarcaComboBox.ValueMember = "CodMarca";
DCategorias dCategorias = new DCategorias();
CategoriaComboBox.DataSource = null;
CategoriaComboBox.DataSource = dCategorias.SelectCategorias();
CategoriaComboBox.DisplayMember = "nombre";
CategoriaComboBox.ValueMember = "cod_cat";
}
private void FrmStock_SizeChanged(object sender, EventArgs e)
{
DgvStock.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
DgvStockMarca.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
}
private void HabilitarCampos()
{
NombreTextBox.ReadOnly = false;
StockOptimoTextBox.ReadOnly = false;
StockCriticoTextBox.ReadOnly = false;
MarcaComboBox.SelectedIndex = -1;
CategoriaComboBox.Enabled = true;
//MedidaComboBox.DataSource = null;
AgregarMarcaMedidaButton.Enabled = false;
CancelarButton.Enabled = true;
GuardarDatosButton.Enabled = true;
AgregarProductoButton.Enabled = false;
ModificarButton.Enabled = false;
BorrarButton.Enabled = false;
NombreTextBox.Focus();
}
private void DeshabilitarCampos()
{
NombreTextBox.ReadOnly = true;
StockOptimoTextBox.ReadOnly = true;
StockCriticoTextBox.ReadOnly = true;
CategoriaComboBox.Enabled = false;
MarcaComboBox.Enabled = false;
MedidaComboBox.Enabled = false;
CancelarButton.Enabled = false;
GuardarDatosButton.Enabled = false;
AgregarMarcaMedidaButton.Enabled = true;
AgregarProductoButton.Enabled = true;
ModificarButton.Enabled = true;
BorrarButton.Enabled = true;
}
private bool ValidarCampos()
{
//Nombre
if (NombreTextBox.Text.Trim() == string.Empty)
{
errorProvider1.SetError(NombreTextBox, "Debe ingresar un nombre");
NombreTextBox.Focus();
return false;
}
errorProvider1.Clear();
//Categoria
if (CategoriaComboBox.SelectedIndex == -1)
{
errorProvider1.SetError(CategoriaComboBox, "Debe seleccionar una categoría");
CategoriaComboBox.Focus();
return false;
}
errorProvider1.Clear();
return true;
}
private void LimpiarCampos()
{
CodProdTextBox.Text = string.Empty;
NombreTextBox.Text = string.Empty;
CategoriaComboBox.SelectedIndex = -1;
MedidaComboBox.SelectedIndex = -1;
MarcaComboBox.SelectedIndex = -1;
StockActualTextBox.Text = string.Empty;
StockOptimoTextBox.Text = string.Empty;
StockCriticoTextBox.Text = string.Empty;
}
private bool ValidarMarcaMedida()
{
////Marca
if (MarcaComboBox.SelectedIndex == -1)
{
errorProvider1.SetError(MarcaComboBox, "Debe seleccionar una marca");
MarcaComboBox.Focus();
return false;
}
errorProvider1.Clear();
//Medida
if (MedidaComboBox.SelectedIndex == -1)
{
errorProvider1.SetError(MedidaComboBox, "Debe seleccionar una medida");
MedidaComboBox.Focus();
return false;
}
errorProvider1.Clear();
return true;
}
private void GetProducto()
{
CodProdTextBox.Text = DgvStock.SelectedRows[0].Cells[0].Value.ToString();
NombreTextBox.Text = DgvStock.SelectedRows[0].Cells[1].Value.ToString();
CategoriaComboBox.SelectedItem = DgvStock.SelectedRows[0].Cells[5].Value.ToString();
StockActualTextBox.Text = DgvStock.SelectedRows[0].Cells[2].Value.ToString();
StockOptimoTextBox.Text = DgvStock.SelectedRows[0].Cells[3].Value.ToString();
StockCriticoTextBox.Text = DgvStock.SelectedRows[0].Cells[4].Value.ToString();
}
private void AgregarProductoButton_Click_1(object sender, EventArgs e)
{
nuevo = true;
HabilitarCampos();
StockActualTextBox.Text = "0";
NombreTextBox.Focus();
}
private void CancelarButton_Click_1(object sender, EventArgs e)
{
LimpiarCampos();
errorProvider1.Dispose();
DeshabilitarCampos();
}
private void GuardarDatosButton_Click_1(object sender, EventArgs e)
{
if (!ValidarCampos()) return;
var rta = MessageBox.Show(nuevo ? "¿Guardar datos?" : "¿Actualizar producto?", "Confirmación", MessageBoxButtons.YesNo,
MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
if (rta == DialogResult.No) return;
if (nuevo)
{
string msg = dStock.InsertStock(NombreTextBox.Text.Trim(),
0,
int.Parse(StockOptimoTextBox.Text.Trim()),
int.Parse(StockCriticoTextBox.Text.Trim()),
(int)CategoriaComboBox.SelectedValue);
var popup1 = new PopupNotifier()
{
Image = msg == "Se ingresó el registro correctamente" ? Properties.Resources.sql_success1 : Properties.Resources.sql_error,
TitleText = "Mensaje",
ContentText = msg,
ContentFont = new Font("Segoe UI Bold", 11F),
TitleFont = new Font("Segoe UI Bold", 10F),
ImagePadding = new Padding(10)
};
popup1.Popup();
}
else
{
string msg = dStock.UpdateStock(int.Parse(CodProdTextBox.Text),
NombreTextBox.Text.Trim(),
int.Parse(StockOptimoTextBox.Text.Trim()),
int.Parse(StockCriticoTextBox.Text.Trim()),
(int)CategoriaComboBox.SelectedValue);
/// CAMBIAR POR POPUPNOTIFIER
var popup1 = new PopupNotifier()
{
Image = msg == "Se modificó el registro correctamente" ? Properties.Resources.stock_updated64 :
Properties.Resources.sql_error,
TitleText = "Mensaje",
ContentText = "Producto modificado correctamente",
ContentFont = new Font("Segoe UI Bold", 11F),
TitleFont = new Font("Segoe UI Bold", 10F),
ImagePadding = new Padding(10)
};
popup1.Popup();
}
DeshabilitarCampos();
errorProvider1.Dispose();
LimpiarCampos();
ActualizarListados();
}
private void BusquedaTextBox_TextChanged_1(object sender, EventArgs e)
{
if(BusquedaTextBox.Text.Trim() != string.Empty)
{
dStock = new DStock();
DgvStock.DataSource = dStock.SelectStockByNombre(BusquedaTextBox.Text);
DgvStock.Refresh();
}
else
{
SelectStock();
}
}
private void BorrarButton_Click_1(object sender, EventArgs e)
{
DialogResult rta = MessageBox.Show("¿Está seguro de borrar el registro?" +
Environment.NewLine + "Si continúa, borrará las asociaciones del producto con marca(s) y/o medida(s)", "Confirmación",
MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
if (rta == DialogResult.No) return;
//En el futuro, se deberán agregar comprobaciones de interferencia en transacciones para evitar el borrado
//Comprobamos que ningún proveedor provea el producto
var dproveedores = new DProveedores();
int codProducto = (int)DgvStock.SelectedRows[0].Cells[0].Value;
if (dproveedores.ExisteStockProveedor(codProducto))
{
MessageBox.Show("El producto tiene proveedores asociados, no puede eliminarse",
"Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
//Borramos primero las referencia en stock_marca y stock_medida
string msg, msg2;
var stockMarca = new DStockMarca();
var stockMedida = new DStockMedida();
msg = stockMarca.DeleteStockMarca(codProducto);
msg2 = stockMedida.DeleteStockMedida(codProducto);
MessageBox.Show(msg, "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessageBox.Show(msg2, "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
try
{
dStock.DeleteStock(codProducto);
var popup1 = new PopupNotifier()
{
Image = Properties.Resources.info100,
TitleText = "Mensaje",
ContentText = "El producto ha sido borrado con exito",
ContentFont = new Font("Segoe UI Bold", 11F),
TitleFont = new Font("Segoe UI Bold", 10F)
};
popup1.Popup();
}
catch (Exception ex)
{
var popup1 = new PopupNotifier()
{
Image = Properties.Resources.info100,
TitleText = "Mensaje",
ContentText = $"Error al eliminar: {ex.Message}",
ContentFont = new Font("Segoe UI Bold", 11F),
TitleFont = new Font("Segoe UI Bold", 10F)
};
popup1.Popup();
return;
}
ActualizarListados();
}
private void ModificarButton_Click_1(object sender, EventArgs e)
{
HabilitarCampos();
MarcaComboBox.Enabled = false;
MedidaComboBox.Enabled = false;
nuevo = false;
GetProducto();
materialTabControl1.SelectedTab = tabPage1;
}
private void AgregarMarcaMedidaButton_Click_2(object sender, EventArgs e)
{
AgregarMarcaMedidaButton.Enabled = false;
GuardarMarcaMedidaButton.Enabled = true;
CancelarMarcaMedida.Enabled = true;
MarcaComboBox.Enabled = true;
MedidaComboBox.Enabled = true;
ActualizarButton.Enabled = false;
ActualizarStockButton.Enabled = false;
AgregarProductoButton.Enabled = false;
GuardarDatosButton.Enabled = false;
CancelarButton.Enabled = false;
ActualizarMedidas();
materialTabControl1.SelectedTab = tabPage3;
}
private void ActualizarMedidas()
{
var medida = new DMedida();
var categoria = DgvStock.SelectedRows[0].Cells[5].Value.ToString();
MedidaComboBox.DataSource = null;
MedidaComboBox.DataSource = medida.SelectCodAndNombreMedidaByCategoria(categoria);
MedidaComboBox.DisplayMember = "Nombre";
MedidaComboBox.ValueMember = "CodMed";
}
private void ActualizarStockButton_Click_1(object sender, EventArgs e)
{
try
{
ActualizarListados();
MessageBox.Show("Lista de productos actualizada", "Mensaje",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"No se pudo actualizar la lista de productos: {ex.Message}", "Mensaje",
MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
}
private void ActualizarButton_Click_1(object sender, EventArgs e)
{
try
{
ActualizarListados();
MessageBox.Show("Lista de productos por marca actualizada", "Mensaje",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"No se pudo actualizar la lista de productos por marca: {ex.Message}",
"Mensaje",
MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
}
private void GuardarMarcaMedidaButton_Click(object sender, EventArgs e)
{
if (!ValidarMarcaMedida()) return;
var stockMedida = new DStockMedida();
var stockMarca = new DStockMarca();
int codProducto = (int)DgvStock.SelectedRows[0].Cells[0].Value;
string msg = stockMarca.InsertStockMarca((int)MarcaComboBox.SelectedValue, codProducto);
string msg2 = stockMedida.InsertStockMedida((int)MedidaComboBox.SelectedValue, codProducto);
MessageBox.Show(msg, "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessageBox.Show(msg2, "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
CancelarMarcaMedida_Click(sender, e);
ActualizarButton_Click_1(sender, e);
}
private void CancelarMarcaMedida_Click(object sender, EventArgs e)
{
MarcaComboBox.SelectedIndex = -1;
errorProvider1.Dispose();
AgregarMarcaMedidaButton.Enabled = true;
GuardarMarcaMedidaButton.Enabled = false;
CancelarMarcaMedida.Enabled = false;
MarcaComboBox.Enabled = false;
MedidaComboBox.Enabled = false;
ActualizarButton.Enabled = true;
ActualizarStockButton.Enabled = true;
AgregarProductoButton.Enabled = true;
GuardarDatosButton.Enabled = false;
CancelarButton.Enabled = false;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace GridPlacing
{
public class MasterGrid : MonoBehaviour
{
public static MasterGrid instance;
private GridPlacer[] gridsPlacer;
private void Awake()
{
if(MasterGrid.instance == null)
{
MasterGrid.instance = this;
}
if (GameObject.FindObjectsOfType<GridPlacer>().Length == 0)
{
Debug.LogError("There are no grids in the scene");
}
else
{
instance.gridsPlacer = GameObject.FindObjectsOfType<GridPlacer>();
}
}
public static GridPlacer FindGridByID(int id)
{
if (instance.gridsPlacer == null)
return null;
foreach (GridPlacer grid in instance.gridsPlacer)
{
if (grid.gridID == id)
{
return grid;
}
}
Debug.LogError("AttachToGrid is asking for an ID that doesn't exist. Check that there is a grid with that ID.");
return null;
}
}
}
|
using DotNet.Utilities;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
namespace SouGouImgCrawler
{
class Program
{
static void Main(string[] args)
{
//List<Thread> threads = new List<Thread>();
while (true)
{
Console.WriteLine("请输入关键词:");
String keyWord = Console.ReadLine().Trim();
if (!string.IsNullOrEmpty(keyWord.Trim()))
{
//
Thread t = new Thread(() =>
{
#region 抓取任务开始
String start = "";
string taskKeyWord = keyWord;
HttpHelper http = new HttpHelper();
//每一次抓取
//大于totalItems/48时停止
Int32 count = 1;
Random random = new Random();
while (true)
{
start = (48 * count).ToString();
HttpItem item = new HttpItem()
{
URL = "http://pic.sogou.com/pics?query=" + taskKeyWord + "&mood=0&picformat=0&mode=1&di=0&clusterfilter=off&p=40230504&dp=1&start=" + start + "&reqType=ajax&tn=0&reqFrom=result",//URL 必需项
Method = "get",//URL 可选项 默认为Get
IsToLower = false,//得到的HTML代码是否转成小写 可选项默认转小写
Referer = "",//来源URL 可选项
Postdata = "",//Post数据 可选项GET时不需要写
Timeout = 100000,//连接超时时间 可选项默认为100000
ReadWriteTimeout = 30000,//写入Post数据超时时间 可选项默认为30000
UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)",//用户的浏览器类型,版本,操作系统 可选项有默认值
ContentType = "text/html",//返回类型 可选项有默认值
Allowautoredirect = false,//是否根据301跳转 可选项
//CerPath = "d:\123.cer",//证书绝对路径 可选项不需要证书时可以不写这个参数
//Connectionlimit = 1024,//最大连接数 可选项 默认为1024
ResultType = ResultType.String
};
HttpResult result = http.GetHtml(item);
string html = result.Html;
string cookie = result.Cookie;
//Console.WriteLine("【" + Thread.CurrentThread.ManagedThreadId + "】-" + html);
//解析结果,得到停止条件
System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
SouGouImgModel model = js.Deserialize<SouGouImgModel>(html);
if (Convert.ToInt32(start) >= Convert.ToInt32(model.totalItems.Replace(",", "")))
//if (model.items.Count==0)
{
Console.WriteLine("结束时间:【" + DateTime.Now + "】-任务关键字:" + taskKeyWord);
break;
}
Console.WriteLine("当前个数:"+model.items.Count+"==请求总个数:"+start+"==MaxEnd:"+model.maxEnd+"==总个数:"+model.totalItems);
//下一轮
int span = random.Next(3000, 10000);
Thread.Sleep(span);
//Console.WriteLine(count);
count++;
}
#endregion
});
//threads.Add(t);
t.Start();
Console.WriteLine("开始时间:【" + DateTime.Now + "】-任务关键字:" + keyWord);
}
}
}
}
}
|
using System;
namespace Fingo.Auth.Domain.Policies.ConfigurationClasses
{
public class UserAccountExpirationDateConfiguration : PolicyConfiguration
{
public DateTime ExpirationDate { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
namespace Starbucks
{
[DataContract]
public class FailureWithReason : Failure
{
[DataMember]
public ReasonChildWithParent reason { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace wsApiEPayment.Models.Openpay
{
public class RespuestaVenta
{
}
public class RespuestaCargo {
public string Rembolso { get; set; }
public string FechaCreacion { get; set; }
public string HoraCreacion { get; set; }
public string Cantidad { get; set; }
public string Estatus { get; set; }
public string Descripcion { get; set; }
public string TipoTransacion { get; set; }
public string TipoOperacion { get; set; }
public string Metodo { get; set; }
public RespuestaTarjeta Tarjeta { get; set; }
public string MensajeError { get; set; }
public string CuentaBanco { get; set; }
public string Autorizacion { get; set; }
public string IdOrden { get; set; }
public string Conciliacion { get; set; }
public string IdCargo { get; set; }
public string IdPagoElectronico { get; set; }
public CancelarPago CargoCancelado { get; set; }
}
public class RespuestaTarjeta {
public string Fecha { get; set; }
public string Banco { get; set; }
public string PagoAprobado { get; set; }
public string TitularTarjeta { get; set; }
public string Mes { get; set; }
public string Anio { get; set; }
public string Tarjeta { get; set; }
public string Marca { get; set; }
public string CargoAprobado { get; set; }
public string NumeroBanco { get; set; }
public string TipoTarjeta { get; set; }
public string Id { get; set; }
}
public class CancelarPago {
public string id { get; set; }
public string Cantidad { get; set; }
public string Autorizacion { get; set; }
public string Metodo { get; set; }
public string TipoOperacion { get; set; }
public string TipoTransacion { get; set; }
public string Estatus { get; set; }
public string Descripcion { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Euler_Logic.Problems.AdventOfCode.Y2022 {
public class Problem05 : AdventOfCodeBase {
private Dictionary<int, LinkedList<char>> _crates;
private List<Instruction> _instructions;
public override string ProblemName => "Advent of Code 2022: 5";
public override string GetAnswer() {
return Answer1(Input()).ToString();
}
public override string GetAnswer2() {
return Answer2(Input()).ToString();
}
private string Answer1(List<string> input) {
GetInput(input);
Perform(false);
return GetTop();
}
private string Answer2(List<string> input) {
GetInput(input);
Perform(true);
return GetTop();
}
private string GetTop() {
var top = new List<char>();
foreach (var crate in _crates.OrderBy(x => x.Key)) {
top.Add(crate.Value.First.Value);
}
return new string(top.ToArray());
}
private void Perform(bool multiple) {
foreach (var instruction in _instructions) {
var from = _crates[instruction.From];
var to = _crates[instruction.To];
if (!multiple) {
Move_Single(from, to, instruction);
} else {
Move_Mulitple(from, to, instruction);
}
}
}
private void Move_Mulitple(LinkedList<char> from, LinkedList<char> to, Instruction instruction) {
LinkedListNode<char> last = null;
for (int count = 1; count <= instruction.Count; count++) {
var digit = from.First.Value;
from.RemoveFirst();
if (last == null) {
to.AddFirst(digit);
last = to.First;
} else {
to.AddAfter(last, digit);
last = last.Next;
}
}
}
private void Move_Single(LinkedList<char> from, LinkedList<char> to, Instruction instruction) {
for (int count = 1; count <= instruction.Count; count++) {
var digit = from.First.Value;
from.RemoveFirst();
to.AddFirst(digit);
}
}
private void GetInput(List<string> input) {
int index = GetInput_Crates(input);
GetInput_Instructions(input, index);
}
private int GetInput_Crates(List<string> input) {
int lineIndex = 0;
_crates = new Dictionary<int, LinkedList<char>>();
do {
var line = input[lineIndex];
if (line.Substring(0, 2) == " 1") break;
int charIndex = line.IndexOf('[');
do {
int column = charIndex / 4 + 1;
if (!_crates.ContainsKey(column)) _crates.Add(column, new LinkedList<char>());
_crates[column].AddLast(line.Substring(charIndex + 1, 1)[0]);
charIndex = line.IndexOf('[', charIndex + 1);
} while (charIndex != -1);
lineIndex++;
} while (true);
return lineIndex + 2;
}
private void GetInput_Instructions(List<string> input, int indexStart) {
_instructions = new List<Instruction>();
for (int index = indexStart; index < input.Count; index++) {
var line = input[index];
var split = line.Split(' ');
_instructions.Add(new Instruction() {
Count = Convert.ToInt32(split[1]),
From = Convert.ToInt32(split[3]),
To = Convert.ToInt32(split[5])
});
}
}
private class Instruction {
public int Count { get; set; }
public int From { get; set; }
public int To { get; set; }
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class class_orb : MonoBehaviour
{
public Material mat_normal;
public Material mat_glow;
private Renderer rend;
public int int_id;
public AudioSource audioSource;
public GameObject GO_gameLogic;
void Start()
{
/// Get the renderer of the ball
rend = GetComponent<Renderer>();
}
public void fn_initOrb()
{
Debug.Log("Initializing Orb: " + int_id);
rend.material = mat_normal;
}
public void fn_click()
{
audioSource.Play();
rend.material = mat_normal;
GO_gameLogic.GetComponent<class_gameLogic>().fn_clickedOrb(this.transform.position, int_id);
}
public void fn_pointerEnter()
{
rend.material = mat_glow;
}
public void fn_pointerExit()
{
rend.material = mat_normal;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneController : MonoBehaviour
{
public static SceneController instance;
private string nextScene;
private void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
}
else if (instance != this)
{
Destroy(gameObject);
}
}
public void LoadScene(string scene)
{
nextScene = scene;
}
public void RestartScene()
{
LoadScene(SceneManager.GetActiveScene().name);
}
}
|
using System.Threading.Tasks;
using ECommon.Components;
using ECommon.Dapper;
using ECommon.IO;
using ENode.Infrastructure;
using ENode.Sample.Common;
using ENode.Sample.Domain;
namespace ENode.Sample.Denormalizers
{
//[Component]
public class NoteDenormalizer : AbstractDenormalizer,
IMessageHandler<NoteCreatedEvent>,
IMessageHandler<NoteTitleChangedEvent>
{
public Task<AsyncTaskResult> HandleAsync(NoteCreatedEvent evnt)
{
return TryInsertRecordAsync(connection => connection.InsertAsync(new
{
Id = evnt.AggregateRootId,
Title = evnt.Title,
CreatedOn = evnt.Timestamp,
UpdatedOn = evnt.Timestamp,
Version = evnt.Version,
EventSequence = evnt.Sequence
}, ConfigSettings.NoteTable));
}
public Task<AsyncTaskResult> HandleAsync(NoteTitleChangedEvent evnt)
{
return TryUpdateRecordAsync(connection => connection.UpdateAsync(new
{
Title = evnt.Title,
UpdatedOn = evnt.Timestamp,
Version = evnt.Version,
EventSequence = evnt.Sequence
}, new
{
Id = evnt.AggregateRootId,
Version = evnt.Version - 1
}, ConfigSettings.NoteTable));
}
}
}
|
using System;
using System.Globalization;
namespace NStandard
{
public static class DateTimeOffsetEx
{
/// <summary>
/// Gets the DateTimeOffset(UTC) of UnixMinValue.
/// </summary>
/// <returns></returns>
public static readonly DateTimeOffset UnixMinValue = new(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
/// <summary>
/// Converts a Unix time expressed as the number of milliseconds that have elapsed
/// since 1970-01-01T00:00:00Z to a <see cref="DateTimeOffset"/> value.
/// </summary>
/// <param name="milliseconds"></param>
/// <returns></returns>
public static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds)
{
#if NETCOREAPP1_0_OR_GREATER || NETSTANDARD1_3_OR_GREATER || NET46_OR_GREATER
return DateTimeOffset.FromUnixTimeMilliseconds(milliseconds);
#else
if (milliseconds < -62135596800000L || milliseconds > 253402300799999L)
{
throw new ArgumentOutOfRangeException("milliseconds", SR.Format(SR.ArgumentOutOfRange_Range, -62135596800000L, 253402300799999L));
}
long ticks = milliseconds * 10000 + 621355968000000000L;
return new DateTimeOffset(ticks, TimeSpan.Zero);
#endif
}
/// <summary>
/// Converts a Unix time expressed as the number of seconds that have elapsed since
/// 1970-01-01T00:00:00Z to a <see cref="DateTimeOffset"/> value.
/// </summary>
/// <param name="seconds"></param>
/// <returns></returns>
public static DateTimeOffset FromUnixTimeSeconds(long seconds)
{
#if NETCOREAPP1_0_OR_GREATER || NETSTANDARD1_3_OR_GREATER || NET46_OR_GREATER
return DateTimeOffset.FromUnixTimeSeconds(seconds);
#else
if (seconds < -62135596800L || seconds > 253402300799L)
{
throw new ArgumentOutOfRangeException("seconds", SR.Format(SR.ArgumentOutOfRange_Range, -62135596800L, 253402300799L));
}
long ticks = seconds * 10000000 + 621355968000000000L;
return new DateTimeOffset(ticks, TimeSpan.Zero);
#endif
}
/// <summary>
/// The number of complete years in the period. [ Similar as DATEDIF(*, *, "Y") function in Excel. ]
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
public static int Years(DateTimeOffset start, DateTimeOffset end)
{
var offset = end.Year - start.Year;
var target = DateTimeOffsetExtensions.AddYears(start, offset);
if (end >= start) return end >= target ? offset : offset - 1;
else return end <= target ? offset : offset + 1;
}
/// <summary>
/// The number of complete months in the period, similar as DATEDIF(*, *, "M") function in Excel.
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
public static int Months(DateTimeOffset start, DateTimeOffset end)
{
var offset = (end.Year - start.Year) * 12 + end.Month - start.Month;
var target = DateTimeOffsetExtensions.AddMonths(start, offset);
if (end >= start) return end >= target ? offset : offset - 1;
else return end <= target ? offset : offset + 1;
}
/// <summary>
/// The number of complete years in the period, expressed in whole and fractional year. [ Similar as DATEDIF(*, *, "Y") function in Excel. ]
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
public static double TotalYears(DateTimeOffset start, DateTimeOffset end)
{
var integer = Years(start, end);
var targetStart = DateTimeOffsetExtensions.AddYears(start, integer);
if (end >= start)
{
var targetEnd = DateTimeOffsetExtensions.AddYears(start, integer + 1);
var fractional = (end - targetStart).TotalDays / (targetEnd - targetStart).TotalDays;
return integer + fractional;
}
else
{
var targetEnd = DateTimeOffsetExtensions.AddYears(start, integer - 1);
var fractional = (targetStart - end).TotalDays / (targetStart - targetEnd).TotalDays;
return integer - fractional;
}
}
/// <summary>
/// The number of complete months in the period, return a double value.
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
public static double TotalMonths(DateTimeOffset start, DateTimeOffset end)
{
var integer = Months(start, end);
var targetStart = DateTimeOffsetExtensions.AddMonths(start, integer);
if (end >= start)
{
var targetEnd = DateTimeOffsetExtensions.AddMonths(start, integer + 1);
var fractional = (end - targetStart).TotalDays / (targetEnd - targetStart).TotalDays;
return integer + fractional;
}
else
{
var targetEnd = DateTimeOffsetExtensions.AddMonths(start, integer - 1);
var fractional = (targetStart - end).TotalDays / (targetStart - targetEnd).TotalDays;
return integer - fractional;
}
}
/// <summary>
/// Gets a DateTimeOffset for the specified week of year.
/// </summary>
/// <param name="year"></param>
/// <param name="week"></param>
/// <param name="offset"></param>
/// <param name="weekStart"></param>
/// <returns></returns>
public static DateTimeOffset ParseFromWeek(int year, int week, TimeSpan offset, DayOfWeek weekStart = DayOfWeek.Sunday)
{
var day1 = new DateTimeOffset(year, 1, 1, 0, 0, 0, offset);
var week0 = DateTimeOffsetExtensions.PastDay(day1, weekStart, true);
if (week0.Year == year) week0 = week0.AddDays(-7);
return week0.AddDays(week * 7);
}
/// <summary>
/// Converts the specified string representation of a date and time to its System.DateTimeOffset
/// equivalent using the specified format and culture-specific format information.
/// The format of the string representation must match the specified format exactly.
/// </summary>
/// <param name="s"></param>
/// <param name="format"></param>
/// <returns></returns>
public static DateTimeOffset ParseExtract(string s, string format)
{
return DateTimeOffset.ParseExact(s, format, CultureInfo.CurrentCulture);
}
/// <summary>
/// Converts the specified string representation of a date and time to its System.DateTimeOffset
/// equivalent using the specified format, culture-specific format information, and
/// style. The format of the string representation must match the specified format
/// exactly. The method returns a value that indicates whether the conversion succeeded.
/// </summary>
/// <param name="s"></param>
/// <param name="format"></param>
/// <param name="result"></param>
/// <returns></returns>
public static bool TryParseExtract(string s, string format, out DateTimeOffset result)
{
return DateTimeOffset.TryParseExact(s, format, CultureInfo.CurrentCulture, DateTimeStyles.None, out result);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using CODE.Framework.Wpf.Utilities;
namespace CODE.Framework.Wpf.Layout
{
/// <summary>
/// This class produces an outline like a property sheet in Visual Studio
/// </summary>
public class PropertySheet : Panel
{
private List<ControlPair> _lastControls;
private double _labelWidth;
private readonly ScrollBar _scrollVertical = new ScrollBar {Visibility = Visibility.Collapsed, Orientation = Orientation.Vertical, SmallChange = 25, LargeChange = 250};
private AdornerLayer _adorner;
private double _lastTotalHeight = -1;
/// <summary>
/// Initializes a new instance of the <see cref="PropertySheet"/> class.
/// </summary>
public PropertySheet()
{
IsHitTestVisible = true;
ClipToBounds = true;
Background = Brushes.Transparent;
if (GroupHeaderRenderer == null) GroupHeaderRenderer = new PropertySheetHeaderRenderer();
Loaded += (s, e) => CreateScrollbars();
IsVisibleChanged += (s, e) => HandleScrollBarVisibility(_lastTotalHeight);
MouseWheel += (s, e) =>
{
if (_scrollVertical.Visibility == Visibility.Visible)
_scrollVertical.Value -= e.Delta;
};
}
/// <summary>Padding for child elements</summary>
public Thickness Padding
{
get { return (Thickness)GetValue(PaddingProperty); }
set { SetValue(PaddingProperty, value); }
}
/// <summary>Padding for child elements</summary>
public static readonly DependencyProperty PaddingProperty = DependencyProperty.Register("Padding", typeof(Thickness), typeof(PropertySheet), new PropertyMetadata(new Thickness(0), InvalidateOnChange));
private static void InvalidateOnChange(DependencyObject d, DependencyPropertyChangedEventArgs args)
{
var sheet = d as PropertySheet;
if (sheet == null) return;
sheet.InvalidateMeasure();
sheet.InvalidateArrange();
sheet.InvalidateVisual();
}
/// <summary>Vertical spacing between rows of elements in the property sheet</summary>
public double VerticalElementSpacing
{
get { return (double)GetValue(VerticalElementSpacingProperty); }
set { SetValue(VerticalElementSpacingProperty, value); }
}
/// <summary>Vertical spacing between rows of elements in the property sheet</summary>
public static readonly DependencyProperty VerticalElementSpacingProperty = DependencyProperty.Register("VerticalElementSpacing", typeof(double), typeof(PropertySheet), new PropertyMetadata(3d, InvalidateOnChange));
/// <summary>Horizontal spacing between label and edit elements</summary>
public double HorizontalElementSpacing
{
get { return (double)GetValue(HorizontalElementSpacingProperty); }
set { SetValue(HorizontalElementSpacingProperty, value); }
}
/// <summary>Horizontal spacing between label and edit elements</summary>
public static readonly DependencyProperty HorizontalElementSpacingProperty = DependencyProperty.Register("HorizontalElementSpacing", typeof(double), typeof(PropertySheet), new PropertyMetadata(3d, InvalidateOnChange));
/// <summary>Defines the horizontal space between the main edit control and subsequent flow controls</summary>
/// <value>The additional flow element spacing.</value>
public double AdditionalFlowElementSpacing
{
get { return (double)GetValue(AdditionalFlowElementSpacingProperty); }
set { SetValue(AdditionalFlowElementSpacingProperty, value); }
}
/// <summary>Defines the horizontal space between the main edit control and subsequent flow controls</summary>
/// <value>The additional flow element spacing.</value>
public static readonly DependencyProperty AdditionalFlowElementSpacingProperty = DependencyProperty.Register("AdditionalFlowElementSpacing", typeof(double), typeof(PropertySheet), new PropertyMetadata(3d, InvalidateOnChange));
/// <summary>Object used to render group headers</summary>
public IPropertySheetHeaderRenderer GroupHeaderRenderer
{
get { return (IPropertySheetHeaderRenderer)GetValue(GroupHeaderRendererProperty); }
set { SetValue(GroupHeaderRendererProperty, value); }
}
/// <summary>Object used to render group headers</summary>
public static readonly DependencyProperty GroupHeaderRendererProperty = DependencyProperty.Register("GroupHeaderRenderer", typeof (IPropertySheetHeaderRenderer), typeof (PropertySheet), new PropertyMetadata(null, InvalidateOnChange));
/// <summary>If set to true, renders group headers, if group information is set on child elements</summary>
/// <remarks>Group information should be set on the label elements within the child collection (the odd numbered elements)</remarks>
public bool ShowGroupHeaders
{
get { return (bool)GetValue(ShowGroupHeadersProperty); }
set { SetValue(ShowGroupHeadersProperty, value); }
}
/// <summary>If set to true, renders group headers, if group information is set on child elements</summary>
/// <remarks>Group information should be set on the label elements within the child collection (the odd numbered elements)</remarks>
public static readonly DependencyProperty ShowGroupHeadersProperty = DependencyProperty.Register("ShowGroupHeaders", typeof(bool), typeof(PropertySheet), new PropertyMetadata(true, InvalidateOnChange));
/// <summary>
/// When overridden in a derived class, measures the size in layout required for child elements and determines a size for the <see cref="T:System.Windows.FrameworkElement" />-derived class.
/// </summary>
/// <param name="availableSize">The available size that this element can give to child elements. Infinity can be specified as a value to indicate that the element will size to whatever content is available.</param>
/// <returns>The size that this element determines it needs during layout, based on its calculations of child element sizes.</returns>
protected override Size MeasureOverride(Size availableSize)
{
var availableSizeInternal = availableSize;
if (Padding.Top > 0 || Padding.Bottom > 0 || Padding.Right > 0 || Padding.Left > 0)
{
var availableHeight = availableSize.Height - Padding.Top - Padding.Bottom;
if (availableHeight < 0d) availableHeight = 0d;
var availableWidth = availableSize.Width - Padding.Left - Padding.Right;
if (availableWidth < 0d) availableWidth = 0d;
availableSizeInternal = GeometryHelper.NewSize(availableWidth, availableHeight);
}
_lastControls = GetControls();
InvalidateVisual();
var widestLabel = 0d;
var totalHeight = 0d;
var foundGroupHeader = false;
var groupPadding = new Thickness();
if (ShowGroupHeaders && GroupHeaderRenderer != null) foundGroupHeader = _lastControls.Where(c => c.Label != null).Any(control => !string.IsNullOrEmpty(SimpleView.GetGroupTitle(control.Label)));
if (foundGroupHeader)
{
groupPadding = GroupHeaderRenderer.GetHeaderPaddingUsedForRendering("X");
availableSizeInternal = GeometryHelper.NewSize(Math.Max(availableSizeInternal.Width - groupPadding.Left, 0), Math.Max(availableSizeInternal.Height, 0));
}
foreach (var control in _lastControls.Where(c => c.Label != null))
{
control.Label.Measure(availableSizeInternal);
if (!control.LabelSpansFullWidth) // For widest-label measurements, we do not consider span labels, since they always use the full width
widestLabel = Math.Max(control.Label.DesiredSize.Width, widestLabel);
}
foreach (var control in _lastControls.Where(c => !c.LabelSpansFullWidth && c.Edit != null))
{
var currentMaxWidth = SnapToPixel(availableSizeInternal.Width - widestLabel - HorizontalElementSpacing - groupPadding.Left);
for (var flowControlCounter = control.AdditionalEditControls.Count - 1; flowControlCounter >= 0; flowControlCounter--)
{
var flowControl = control.AdditionalEditControls[flowControlCounter];
var availableEditSize = GeometryHelper.NewSize(currentMaxWidth, availableSize.Height);
flowControl.Measure(availableEditSize);
currentMaxWidth = Math.Max(SnapToPixel(currentMaxWidth - flowControl.DesiredSize.Width), 0);
}
control.Edit.Measure(GeometryHelper.NewSize(currentMaxWidth, availableSize.Height));
}
var currentGroupIsExpanded = true;
foreach (var control in _lastControls)
{
var itemHeight = 0d;
if (control.Label != null) itemHeight = control.Label.DesiredSize.Height;
if (control.Edit != null && !control.LabelSpansFullWidth)
{
itemHeight = Math.Max(itemHeight, control.Edit.DesiredSize.Height);
foreach (var flowControl in control.AdditionalEditControls)
itemHeight = Math.Max(itemHeight, flowControl.DesiredSize.Height);
}
itemHeight = SnapToPixel(itemHeight);
if (ShowGroupHeaders && control.Label != null && GroupHeaderRenderer != null && SimpleView.GetGroupBreak(control.Label))
{
var groupHeader = SimpleView.GetGroupTitle(control.Label) ?? string.Empty;
if (!_renderedGroups.ContainsKey(groupHeader)) _renderedGroups.Add(groupHeader, new PropertySheetGroupHeaderInfo {IsExpanded = true});
currentGroupIsExpanded = _renderedGroups[groupHeader].IsExpanded;
var currentPadding = GroupHeaderRenderer.GetHeaderPaddingUsedForRendering(string.IsNullOrEmpty(groupHeader) ? "X" : groupHeader);
_renderedGroups[groupHeader].Height = currentPadding.Top;
totalHeight += SnapToPixel(currentPadding.Top);
}
if (currentGroupIsExpanded) totalHeight += itemHeight + VerticalElementSpacing;
}
_labelWidth = widestLabel;
totalHeight += Padding.Top + Padding.Bottom;
_lastTotalHeight = totalHeight;
HandleScrollBarVisibility(totalHeight, availableSize);
if (_scrollVertical.Visibility == Visibility.Visible)
{
foreach (var control in _lastControls.Where(c => !c.LabelSpansFullWidth && c.Edit != null))
{
var currentMaxWidth = SnapToPixel(SnapToPixel(availableSizeInternal.Width - widestLabel - HorizontalElementSpacing - SystemParameters.VerticalScrollBarWidth - 1));
for (var flowControlCounter = control.AdditionalEditControls.Count - 1; flowControlCounter >= 0; flowControlCounter--)
{
var flowControl = control.AdditionalEditControls[flowControlCounter];
var availableEditSize = GeometryHelper.NewSize(currentMaxWidth, availableSize.Height);
flowControl.Measure(availableEditSize);
currentMaxWidth = Math.Max(SnapToPixel(currentMaxWidth - flowControl.DesiredSize.Width), 0);
}
control.Edit.Measure(GeometryHelper.NewSize(currentMaxWidth, availableSize.Height));
}
}
return GeometryHelper.NewSize(availableSize.Width, Math.Min(totalHeight, availableSize.Height));
}
private readonly Dictionary<string, PropertySheetGroupHeaderInfo> _renderedGroups = new Dictionary<string, PropertySheetGroupHeaderInfo>();
private class PropertySheetGroupHeaderInfo
{
public bool IsExpanded { get; set; }
public double LastRenderTopPosition { get; set; }
public double Height { get; set; }
}
private void HandleScrollBarVisibility(double totalHeight, Size availableSize = new Size())
{
if (availableSize.Height < .1d && availableSize.Width < .1d)
availableSize = GeometryHelper.NewSize(ActualWidth, ActualHeight);
if (!IsVisible)
{
if (_scrollVertical.Visibility == Visibility.Visible)
{
_scrollVertical.Visibility = Visibility.Collapsed;
InvalidateMeasure();
InvalidateArrange();
InvalidateVisual();
}
return;
}
if (double.IsInfinity(availableSize.Height)) _scrollVertical.Visibility = Visibility.Collapsed;
else if (totalHeight > availableSize.Height)
{
if (_scrollVertical.Visibility != Visibility.Visible)
{
_scrollVertical.Visibility = Visibility.Visible;
InvalidateMeasure();
InvalidateArrange();
InvalidateVisual();
}
_scrollVertical.Maximum = totalHeight - availableSize.Height;
_scrollVertical.ViewportSize = availableSize.Height;
}
else
_scrollVertical.Visibility = Visibility.Collapsed;
}
private void CreateScrollbars()
{
_adorner = AdornerLayer.GetAdornerLayer(this);
if (_adorner == null) return;
_adorner.Add(new PropertySheetScrollAdorner(this, _scrollVertical) { Visibility = Visibility.Visible });
_scrollVertical.ValueChanged += (s, e) => DispatchInvalidateScroll();
}
private void DispatchInvalidateScroll()
{
InvalidateMeasure();
InvalidateArrange();
InvalidateVisual();
}
/// <summary>
/// When overridden in a derived class, positions child elements and determines a size for a <see cref="T:System.Windows.FrameworkElement" /> derived class.
/// </summary>
/// <param name="finalSize">The final area within the parent that this element should use to arrange itself and its children.</param>
/// <returns>The actual size used.</returns>
protected override Size ArrangeOverride(Size finalSize)
{
var finalSizeInternal = finalSize;
if (Padding.Top > 0 || Padding.Bottom > 0 || Padding.Right > 0 || Padding.Left > 0)
{
var availableHeight = finalSize.Height - Padding.Top - Padding.Bottom;
if (availableHeight < 0d) availableHeight = 0d;
var availableWidth = finalSize.Width - Padding.Left - Padding.Right;
if (availableWidth < 0d) availableWidth = 0d;
finalSizeInternal = GeometryHelper.NewSize(availableWidth, availableHeight);
}
if (_lastControls == null) return base.ArrangeOverride(finalSize);
var finalWidth = finalSizeInternal.Width;
if (_scrollVertical.Visibility == Visibility.Visible) finalWidth = Math.Max(finalWidth - SystemParameters.VerticalScrollBarWidth, 1);
var offsetTop = 0d;
if (_scrollVertical.Visibility == Visibility.Visible) offsetTop = _scrollVertical.Value*-1;
var currentTop = offsetTop + Padding.Top;
if (!ShowGroupHeaders || GroupHeaderRenderer == null)
foreach (var control in _lastControls)
{
var lineHeight = 0d;
if (control.Label != null) lineHeight = control.Label.DesiredSize.Height;
if (control.Edit != null) lineHeight = Math.Max(lineHeight, control.Edit.DesiredSize.Height);
lineHeight = SnapToPixel(lineHeight);
if (control.Label != null)
{
if (!control.LabelSpansFullWidth)
control.Label.Arrange(GeometryHelper.NewRect(Padding.Left, currentTop, _labelWidth, lineHeight));
else
control.Label.Arrange(GeometryHelper.NewRect(Padding.Left, currentTop, SnapToPixel(finalWidth), lineHeight));
}
if (control.Edit != null && !control.LabelSpansFullWidth)
{
var editLeft = SnapToPixel(_labelWidth + HorizontalElementSpacing + Padding.Left);
var editWidth = Math.Max(SnapToPixel(finalWidth - editLeft + Padding.Left), 0);
for (var flowControlCounter = control.AdditionalEditControls.Count - 1; flowControlCounter >= 0; flowControlCounter--)
{
var flowControl = control.AdditionalEditControls[flowControlCounter];
var flowWidth = Math.Min(flowControl.DesiredSize.Width, editWidth);
flowControl.Arrange(GeometryHelper.NewRect(editLeft + editWidth - flowWidth, currentTop, flowWidth, lineHeight));
editWidth -= (flowWidth + AdditionalFlowElementSpacing);
if (editWidth < 0.1) editWidth = 0d;
}
control.Edit.Arrange(GeometryHelper.NewRect(editLeft, currentTop, editWidth, lineHeight));
}
currentTop += lineHeight + VerticalElementSpacing;
}
else
{
var itemIndent = GroupHeaderRenderer.GetHeaderPaddingUsedForRendering("X").Left;
var currentGroupIsExpanded = true;
foreach (var control in _lastControls)
{
var lineHeight = 0d;
if (control.Label != null) lineHeight = control.Label.DesiredSize.Height;
if (control.Edit != null) lineHeight = Math.Max(lineHeight, control.Edit.DesiredSize.Height);
lineHeight = SnapToPixel(lineHeight);
if (control.Label != null && SimpleView.GetGroupBreak(control.Label))
{
var groupTitle = SimpleView.GetGroupTitle(control.Label);
if (_renderedGroups.ContainsKey(groupTitle))
{
currentGroupIsExpanded = _renderedGroups[groupTitle].IsExpanded;
currentTop += _renderedGroups[groupTitle].Height;
}
}
if (currentGroupIsExpanded)
{
if (control.Label != null)
{
control.Label.Visibility = Visibility.Visible;
if (!control.LabelSpansFullWidth)
control.Label.Arrange(GeometryHelper.NewRect(Padding.Left + itemIndent, currentTop, _labelWidth, lineHeight));
else
control.Label.Arrange(GeometryHelper.NewRect(Padding.Left + itemIndent, currentTop, SnapToPixel(finalWidth - itemIndent), lineHeight));
}
if (control.Edit != null)
{
control.Edit.Visibility = Visibility.Visible;
var editLeft = SnapToPixel(_labelWidth + HorizontalElementSpacing + Padding.Left + itemIndent);
var editWidth = Math.Max(SnapToPixel(finalWidth - editLeft + Padding.Left), 0);
for (var flowControlCounter = control.AdditionalEditControls.Count - 1; flowControlCounter >= 0; flowControlCounter--)
{
var flowControl = control.AdditionalEditControls[flowControlCounter];
var flowWidth = Math.Min(flowControl.DesiredSize.Width, editWidth);
flowControl.Visibility = Visibility.Visible;
flowControl.Arrange(GeometryHelper.NewRect(editLeft + editWidth - flowWidth, currentTop, flowWidth, lineHeight));
editWidth -= (flowWidth + AdditionalFlowElementSpacing);
if (editWidth < 0.1) editWidth = 0d;
}
control.Edit.Arrange(GeometryHelper.NewRect(editLeft, currentTop, editWidth, lineHeight));
}
currentTop += lineHeight + VerticalElementSpacing;
}
else
{
if (control.Label != null) control.Label.Visibility = Visibility.Collapsed;
if (control.Edit != null) control.Edit.Visibility = Visibility.Collapsed;
foreach (var flowControl in control.AdditionalEditControls)
flowControl.Visibility = Visibility.Collapsed;
}
}
}
return base.ArrangeOverride(finalSize);
}
private static double SnapToPixel(double number)
{
if ((int) number < number) number = (int) number + 1d;
if (number <= 0.1d) number = 0d;
return number;
}
/// <summary>
/// Gets the controls in pairs.
/// </summary>
/// <returns>List<ControlPair>.</returns>
private List<ControlPair> GetControls()
{
var controls = new List<ControlPair>();
for (var controlCounter = 0; controlCounter < Children.Count; controlCounter++)
{
var child = Children[controlCounter];
if (child.Visibility == Visibility.Collapsed) continue;
var controlPair = new ControlPair(0d);
if (SimpleView.GetIsStandAloneEditControl(child))
controlPair.Edit = child;
else
{
controlPair.Label = child;
if (SimpleView.GetSpanFullWidth(child))
controlPair.LabelSpansFullWidth = true;
else if (!SimpleView.GetIsStandAloneLabel(child))
{
var editControlIndex = controlCounter + 1;
if (Children.Count > editControlIndex)
controlPair.Edit = Children[editControlIndex];
controlCounter++; // We are skipping the next control since we already accounted for it
while (true) // We check if the next control might flow with the current edit control
{
if (Children.Count <= controlCounter + 1) break;
if (!SimpleView.GetFlowsWithPrevious(Children[controlCounter + 1])) break;
controlPair.AdditionalEditControls.Add(Children[controlCounter + 1]);
controlCounter++;
}
}
}
controls.Add(controlPair);
}
return controls;
}
/// <summary>
/// Invoked when an unhandled MouseDown attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.
/// </summary>
/// <param name="e">The <see cref="T:System.Windows.Input.MouseButtonEventArgs" /> that contains the event data. This event data reports details about the mouse button that was pressed and the handled state.</param>
protected override void OnMouseDown(MouseButtonEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed && e.ClickCount == 1)
foreach (var control in _lastControls)
if (control.Label != null && SimpleView.GetGroupBreak(control.Label))
{
var groupTitle = SimpleView.GetGroupTitle(control.Label);
if (_renderedGroups.ContainsKey(groupTitle))
{
var group = _renderedGroups[groupTitle];
var y = group.LastRenderTopPosition;
var positionY = e.GetPosition(this).Y;
if (positionY >= y && positionY <= y + group.Height)
{
e.Handled = true;
group.IsExpanded = !group.IsExpanded;
InvalidateMeasure();
InvalidateArrange();
InvalidateVisual();
return;
}
}
}
base.OnMouseDown(e);
}
/// <summary>
/// Draws the content of a <see cref="T:System.Windows.Media.DrawingContext" /> object during the render pass of a <see cref="T:System.Windows.Controls.Panel" /> element.
/// </summary>
/// <param name="dc">The <see cref="T:System.Windows.Media.DrawingContext" /> object to draw.</param>
protected override void OnRender(DrawingContext dc)
{
base.OnRender(dc);
if (!ShowGroupHeaders || GroupHeaderRenderer == null) return;
var offsetTop = 0d;
if (_scrollVertical.Visibility == Visibility.Visible) offsetTop = _scrollVertical.Value * -1;
var currentTop = offsetTop + Padding.Top;
var currentGroupIsExpanded = true;
foreach (var control in _lastControls)
{
var lineHeight = 0d;
if (control.Label != null) lineHeight = control.Label.DesiredSize.Height;
if (control.Edit != null) lineHeight = Math.Max(lineHeight, control.Edit.DesiredSize.Height);
lineHeight = SnapToPixel(lineHeight);
if (control.Label != null && SimpleView.GetGroupBreak(control.Label))
{
var groupTitle = SimpleView.GetGroupTitle(control.Label);
if (_renderedGroups.ContainsKey(groupTitle))
{
currentGroupIsExpanded = _renderedGroups[groupTitle].IsExpanded;
var group = _renderedGroups[groupTitle];
var width = ActualWidth - Padding.Left - Padding.Right;
if (_scrollVertical.Visibility == Visibility.Visible) width -= SystemParameters.VerticalScrollBarWidth;
dc.PushTransform(new TranslateTransform(Padding.Left, currentTop));
GroupHeaderRenderer.RenderHeader(dc, currentTop, width, groupTitle, group.IsExpanded);
dc.Pop();
group.LastRenderTopPosition = currentTop;
currentTop += _renderedGroups[groupTitle].Height;
}
}
if (currentGroupIsExpanded) currentTop += lineHeight + VerticalElementSpacing;
}
}
}
/// <summary>Adorner UI for scrollbars of the edit form control</summary>
public class PropertySheetScrollAdorner : Adorner
{
private readonly ScrollBar _vertical;
/// <summary>Constructor</summary>
/// <param name="adornedElement">Adorned element PropertySheet</param>
/// <param name="vertical">The vertical scrollbar.</param>
public PropertySheetScrollAdorner(PropertySheet adornedElement, ScrollBar vertical) : base(adornedElement)
{
_vertical = vertical;
CheckControlForExistingParent(_vertical);
AddVisualChild(_vertical);
}
/// <summary>Implements any custom measuring behavior for the adorner.</summary>
/// <param name="constraint">A size to constrain the adorner to.</param>
/// <returns>A <see cref="T:System.Windows.Size"/> object representing the amount of layout space needed by the adorner.</returns>
protected override Size MeasureOverride(Size constraint)
{
_vertical.Measure(constraint);
if (!double.IsInfinity(constraint.Height) && !double.IsInfinity(constraint.Width))
return constraint;
return new Size(100000, 100000);
}
/// <summary>When overridden in a derived class, positions child elements and determines a size for a <see cref="T:System.Windows.FrameworkElement"/> derived class.</summary>
/// <param name="finalSize">The final area within the parent that this element should use to arrange itself and its children.</param>
/// <returns>The actual size used.</returns>
protected override Size ArrangeOverride(Size finalSize)
{
var surfaceSize = AdornedElement.RenderSize;
if (_vertical.Visibility == Visibility.Visible)
_vertical.Arrange(GeometryHelper.NewRect(surfaceSize.Width - SystemParameters.VerticalScrollBarWidth, 0, SystemParameters.VerticalScrollBarWidth, surfaceSize.Height));
return finalSize;
}
private void CheckControlForExistingParent(FrameworkElement element)
{
DependencyObject parent = null;
if (element.Parent != null) parent = element.Parent;
if (parent == null)
parent = VisualTreeHelper.GetParent(element);
if (parent != null)
{
var parentContent = parent as ContentControl;
if (parentContent != null)
{
parentContent.Content = null;
return;
}
var panelContent = parent as Panel;
if (panelContent != null)
{
panelContent.Children.Remove(element);
return;
}
var adorner = parent as PropertySheetScrollAdorner;
if (adorner != null)
adorner.RemoveVisualChild(element);
}
}
/// <summary>Gets the number of visual child elements within this element.</summary>
/// <returns>The number of visual child elements for this element.</returns>
protected override int VisualChildrenCount
{
get { return 1; }
}
/// <summary>Overrides <see cref="M:System.Windows.Media.Visual.GetVisualChild(System.Int32)"/>, and returns a child at the specified index from a collection of child elements.</summary>
/// <param name="index">The zero-based index of the requested child element in the collection.</param>
/// <returns>The requested child element. This should not return null; if the provided index is out of range, an exception is thrown.</returns>
protected override Visual GetVisualChild(int index)
{
return _vertical;
}
}
/// <summary>Fundamental interface for a header renderer for the property sheet</summary>
public interface IPropertySheetHeaderRenderer
{
/// <summary>Returns the spacing used by header rendering</summary>
/// <param name="headerText">Header text to be rendered</param>
/// <returns>Margin used (note: only top and left are respected)</returns>
Thickness GetHeaderPaddingUsedForRendering(string headerText);
/// <summary>Performs the actual header rendering</summary>
/// <param name="dc">DrawingContext</param>
/// <param name="top">Indicates the current top render position</param>
/// <param name="actualWidth">Maximum actual width of the render area</param>
/// <param name="headerText">Header text that is to be rendered</param>
/// <param name="isExpanded">Indicates whether the header is expanded (or collapsed)</param>
void RenderHeader(DrawingContext dc, double top, double actualWidth, string headerText, bool isExpanded);
}
/// <summary>Renderer object for headers on the property sheet renderer</summary>
public class PropertySheetHeaderRenderer : FrameworkElement, IPropertySheetHeaderRenderer
{
/// <summary>Font family</summary>
public FontFamily FontFamily
{
get { return (FontFamily)GetValue(FontFamilyProperty); }
set { SetValue(FontFamilyProperty, value); }
}
/// <summary>Font family</summary>
public static readonly DependencyProperty FontFamilyProperty = DependencyProperty.Register("FontFamily", typeof(FontFamily), typeof(PropertySheetHeaderRenderer), new PropertyMetadata(new FontFamily("Segoe UI")));
/// <summary>Font size</summary>
public double FontSize
{
get { return (double)GetValue(FontSizeProperty); }
set { SetValue(FontSizeProperty, value); }
}
/// <summary>Font size</summary>
public static readonly DependencyProperty FontSizeProperty = DependencyProperty.Register("FontSize", typeof(double), typeof(PropertySheetHeaderRenderer), new PropertyMetadata(16d));
/// <summary>Font style</summary>
public FontStyle FontStyle
{
get { return (FontStyle)GetValue(FontStyleProperty); }
set { SetValue(FontStyleProperty, value); }
}
/// <summary>Font style</summary>
public static readonly DependencyProperty FontStyleProperty = DependencyProperty.Register("FontStyle", typeof(FontStyle), typeof(PropertySheetHeaderRenderer), new PropertyMetadata(FontStyles.Normal));
/// <summary>Font weight</summary>
public FontWeight FontWeight
{
get { return (FontWeight)GetValue(FontWeightProperty); }
set { SetValue(FontWeightProperty, value); }
}
/// <summary>Font weight</summary>
public static readonly DependencyProperty FontWeightProperty = DependencyProperty.Register("FontWeight", typeof(FontWeight), typeof(PropertySheetHeaderRenderer), new PropertyMetadata(FontWeights.Normal));
/// <summary>Foreground brush</summary>
public Brush Foreground
{
get { return (Brush)GetValue(ForegroundProperty); }
set { SetValue(ForegroundProperty, value); }
}
/// <summary>Foreground brush</summary>
public static readonly DependencyProperty ForegroundProperty = DependencyProperty.Register("Foreground", typeof(Brush), typeof(PropertySheetHeaderRenderer), new PropertyMetadata(Brushes.Black));
/// <summary>Background brush</summary>
public Brush Background
{
get { return (Brush)GetValue(BackgroundProperty); }
set { SetValue(BackgroundProperty, value); }
}
/// <summary>Background brush</summary>
public static readonly DependencyProperty BackgroundProperty = DependencyProperty.Register("Background", typeof(Brush), typeof(PropertySheetHeaderRenderer), new PropertyMetadata(null));
/// <summary>Indentation for all the items when the property sheet shows groups</summary>
public double ItemIndentation
{
get { return (double)GetValue(ItemIndentationProperty); }
set { SetValue(ItemIndentationProperty, value); }
}
/// <summary>Indentation for all the items when the property sheet shows groups</summary>
public static readonly DependencyProperty ItemIndentationProperty = DependencyProperty.Register("ItemIndentation", typeof(double), typeof(PropertySheetHeaderRenderer), new PropertyMetadata(20d));
/// <summary>Brush to render an expanded icon</summary>
public Brush ExpandedIcon
{
get { return (Brush)GetValue(ExpandedIconProperty); }
set { SetValue(ExpandedIconProperty, value); }
}
/// <summary>Brush to render an expanded icon</summary>
public static readonly DependencyProperty ExpandedIconProperty = DependencyProperty.Register("ExpandedIcon", typeof(Brush), typeof(PropertySheetHeaderRenderer), new PropertyMetadata(null));
/// <summary>Brush to render an collapsed icon</summary>
public Brush CollapsedIcon
{
get { return (Brush)GetValue(CollapsedIconProperty); }
set { SetValue(CollapsedIconProperty, value); }
}
/// <summary>Brush to render an collapsed icon</summary>
public static readonly DependencyProperty CollapsedIconProperty = DependencyProperty.Register("CollapsedIcon", typeof(Brush), typeof(PropertySheetHeaderRenderer), new PropertyMetadata(null));
/// <summary>Returns the spacing used by header rendering</summary>
/// <param name="headerText">Header text to be rendered</param>
/// <returns>Margin used (note: only top and left are respected)</returns>
public Thickness GetHeaderPaddingUsedForRendering(string headerText)
{
var ft = new FormattedText(headerText, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface(FontFamily, FontStyle, FontWeight, FontStretches.Normal), FontSize, Foreground) {MaxLineCount = 1, MaxTextWidth = 100000};
return new Thickness(ItemIndentation, ft.Height + 5, 0d, 0d);
}
/// <summary>Performs the actual header rendering</summary>
/// <param name="dc">DrawingContext</param>
/// <param name="top">Indicates the current top render position</param>
/// <param name="actualWidth">Maximum actual width of the render area</param>
/// <param name="headerText">Header text that is to be rendered</param>
/// <param name="isExpanded">Indicates whether the header is expanded (or collapsed)</param>
public void RenderHeader(DrawingContext dc, double top, double actualWidth, string headerText, bool isExpanded)
{
var internalText = headerText;
if (string.IsNullOrEmpty(internalText)) internalText = "X";
var areaHeight = GetHeaderPaddingUsedForRendering(internalText).Top;
if (areaHeight < 1 || actualWidth < 1) return;
if (Background != null) dc.DrawRectangle(Background, null, GeometryHelper.NewRect(0, 2, actualWidth, areaHeight - 5));
var ft = new FormattedText(headerText, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface(FontFamily, FontStyle, FontWeight, FontStretches.Normal), FontSize, Foreground) {MaxLineCount = 1, MaxTextWidth = Math.Max(actualWidth - ItemIndentation - 5, 0), Trimming = TextTrimming.CharacterEllipsis};
var heightWidth = ItemIndentation - 10;
if (heightWidth > areaHeight - 2) heightWidth = areaHeight - 2;
var iconRect = GeometryHelper.NewRect(2, (int)((areaHeight - heightWidth) / 2), heightWidth, heightWidth);
var interactionBrush = isExpanded ? GetExpandedIconBrush() : GetCollapsedIconBrush();
dc.DrawRectangle(interactionBrush, null, iconRect);
dc.DrawText(ft, new Point(ItemIndentation, 0d));
}
private Brush GetCollapsedIconBrush()
{
if (CollapsedIcon == null)
{
var resource = Application.Current.TryFindResource("CODE.Framework-Icon-Collapsed");
if (resource != null) CollapsedIcon = resource as Brush;
}
return CollapsedIcon ?? (CollapsedIcon = Brushes.Red);
}
private Brush GetExpandedIconBrush()
{
if (ExpandedIcon == null)
{
var resource = Application.Current.TryFindResource("CODE.Framework-Icon-Expanded");
if (resource != null) ExpandedIcon = resource as Brush;
}
return ExpandedIcon ?? (ExpandedIcon = Brushes.Black);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player_Skin_Controller : MonoBehaviour
{
public int SelectedSkin;
private int SeleccionSkinAnterior; // esto se hace para saber cuando cambia el skin.
public Skins[] Skins;
//
private GameObject cuerpo;
public void Awake()
{
SeleccionSkinAnterior = SelectedSkin;
}
void Start()
{
if (SelectedSkin >= Skins.Length)
{
while (SelectedSkin >= Skins.Length)
{
SelectedSkin = SelectedSkin - Skins.Length;
}
}
if (SelectedSkin < 0)
{
SelectedSkin = SelectedSkin + Skins.Length;
}
CambiaSkin(this.gameObject, SelectedSkin);
}
void Update()
{
//Esto hace que no te puedas elegir un skin que no existe.
if (SelectedSkin >= Skins.Length)
{
while (SelectedSkin >= Skins.Length)
{
SelectedSkin = SelectedSkin - Skins.Length;
}
}
if (SelectedSkin < 0)
{
SelectedSkin = SelectedSkin + Skins.Length;
}//
//veo si cambio el numero del skin. De esta manera tambien puedo cambiar el skin en tiempo de ejecucion.
if (SelectedSkin != SeleccionSkinAnterior)
{
SeleccionSkinAnterior = SelectedSkin;
CambiaSkin(this.gameObject, SelectedSkin);
}
}
public void CambiaSkin(GameObject Player, int nroSkin)
{
cuerpo = Player.transform.Find("cuerpo").gameObject;
cuerpo.transform.Find("CARA").GetComponent<SpriteRenderer>().sprite = Skins[nroSkin].cara;
cuerpo.transform.Find("Cuerpo").GetComponent<SpriteRenderer>().sprite = Skins[nroSkin].cuerpo;
cuerpo.transform.Find("mano DER").GetComponent<SpriteRenderer>().sprite = Skins[nroSkin].manoDER;
cuerpo.transform.Find("mano IZQ").GetComponent<SpriteRenderer>().sprite = Skins[nroSkin].manoIZQ;
}
}
[System.Serializable]
public class Skins
{
public string Nombre;
public Sprite cara, cuerpo, manoIZQ, manoDER;
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using lsc.Common;
using lsc.Model;
using Microsoft.EntityFrameworkCore;
namespace lsc.Dal
{
public class EmailTemplateDal
{
private static EmailTemplateDal ins;
public static EmailTemplateDal Ins => ins ?? (ins = new EmailTemplateDal());
public async Task<int> AddAsync(EmailTemplate emailTemplate)
{
int id = 0;
try
{
DataContext dataContext = new DataContext();
var entity = await dataContext.EmailTemplates.AddAsync(emailTemplate);
await dataContext.SaveChangesAsync();
id = entity.Entity.Id;
}
catch (Exception e)
{
ClassLoger.Error("EmailTemplateDal.AddAsync", e);
}
return id;
}
public async Task<EmailTemplate> GetById(int id)
{
try
{
DataContext dataContext = new DataContext();
var entity = await dataContext.EmailTemplates.FindAsync(id);
return entity;
}
catch (Exception e)
{
ClassLoger.Error("EmailTemplateDal.GetById", e);
}
return null;
}
public EmailTemplate GetByIds(int id)
{
try
{
DataContext dataContext = new DataContext();
var entity = dataContext.EmailTemplates.Find(id);
return entity;
}
catch (Exception e)
{
ClassLoger.Error("EmailTemplateDal.GetByIds", e);
}
return null;
}
public async Task<bool> DelAsync(EmailTemplate emailTemplate)
{
bool flag = false;
try
{
DataContext dataContext = new DataContext();
dataContext.EmailTemplates.Remove(emailTemplate);
await dataContext.SaveChangesAsync();
flag = true;
}
catch (Exception e)
{
ClassLoger.Error("EmailTemplateDal.DelAsync", e);
}
return flag;
}
public async Task<List<EmailTemplate>> GetList()
{
try
{
DataContext dataContext = new DataContext();
var list = await dataContext.EmailTemplates.ToListAsync();
return list;
}
catch (Exception e)
{
ClassLoger.Error("EmailTemplateDal.GetList", e);
}
return null;
}
}
}
|
// The MIT License (MIT)
// Copyright (c) 2015 Intis Telecom
// 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 Intis.SDK;
using Intis.SDK.Exceptions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Test
{
[TestClass]
public class HlrResponseTest
{
const string Login = "your api login";
const string ApiKey = "your api key here";
const string ApiHost = "http://api.host.com/get/";
[TestMethod]
public void TestMakeHlrRequest()
{
IApiConnector connector = new LocalApiConnector(getData());
var client = new IntisClient(Login, ApiKey, ApiHost, connector);
var phones = new[] { 442073238000, 442073238001 };
var hlrResponse = client.MakeHlrRequest(phones);
foreach (var one in hlrResponse)
{
var id = one.Id;
var imsi = one.Imsi;
var destination = one.Destination;
var mcc = one.Mcc;
var mnc = one.Mnc;
var originalCountryCode = one.OriginalCountryCode;
var originalCountryName = one.OriginalCountryName;
var originalNetworkName = one.OriginalNetworkName;
var originalNetworkPrefix = one.OriginalNetworkPrefix;
var portedCountryName = one.PortedCountryName;
var portedCountryPrefix = one.PortedCountryPrefix;
var portedNetworkName = one.PortedNetworkName;
var portedNetworkPrefix = one.PortedNetworkPrefix;
var pricePerMessage = one.PricePerMessage;
var roamingCountryName = one.RoamingCountryName;
var roamingCountryPrefix = one.RoamingCountryPrefix;
var roamingNetworkName = one.RoamingNetworkName;
var roamingNetworkPrefix = one.RoamingNetworkPrefix;
var status = one.Status;
var isPorted = one.IsPorted;
var isInRoaming = one.IsInRoaming;
}
Assert.IsNotNull(hlrResponse);
}
[TestMethod]
[ExpectedException(typeof(HlrResponseException))]
public void TestMakeHlrRequestException()
{
IApiConnector connector = new LocalApiConnector(getErrorData());
var client = new IntisClient(Login, ApiKey, ApiHost, connector);
var phones = new[] { 442073238000, 442073238001 };
client.MakeHlrRequest(phones);
}
private string getData()
{
return "[{\"id\":\"4133004490987800000001\",\"destination\":\"442073238000\",\"message_id\":\"x6ikubibd4y5ljdnttxt\",\"IMSI\":\"250017224827276\",\"stat\":\"DELIVRD\",\"error\":\"0\",\"orn\":\"Landline\",\"pon\":\"Landline\",\"ron\":\"Landline\",\"mccmnc\":\"25001\",\"rcn\":\"United Kingdom\",\"ppm\":\"932\",\"onp\":\"91788\",\"ocn\":\"United Kingdom\",\"ocp\":\"7\",\"is_ported\":\"false\",\"rnp\":\"917\",\"rcp\":\"7\",\"is_roaming\":\"false\",\"pnp\":\"442073238000\",\"pcn\":\"United Kingdom\",\"pcp\":\"7\",\"total_price\":\"0.2\",\"request_id\":\"607a199fb7dc99e68af1196f659c23cf\",\"request_time\":\"2014-10-14 19:27:29\"}," +
"{\"id\":\"4115440762085900000001\",\"destination\":\"442073238001\",\"message_id\":\"l9likizqtxau2e5gbbho\",\"IMSI\":\"250017145699048\",\"stat\":\"DELIVRD\",\"error\":\"0\",\"orn\":\"Landline\",\"pon\":\"Landline\",\"ron\":\"Landline\",\"mccmnc\":\"25001\",\"rcn\":\"United Kingdom\",\"ppm\":\"932\",\"onp\":\"93718\",\"ocn\":\"United Kingdom\",\"ocp\":\"7\",\"is_ported\":\"true\",\"rnp\":\"91701\",\"rcp\":\"7\",\"is_roaming\":\"false\",\"pnp\":\"442073238001\",\"pcn\":\"United Kingdom\",\"pcp\":\"7\",\"total_price\":\"0.2\",\"request_id\":\"79cdde57cea85f1cc2728f7c0d48f0bd\",\"request_time\":\"2014-09-24 11:34:36\"}]";
}
private string getErrorData()
{
return "{\"error\":4}";
}
}
}
|
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
namespace NStandard.Json.Net.Converters
{
public class PhysicalAddressConverter : JsonConverter
{
public override bool CanConvert(Type objectType) => objectType == typeof(PhysicalAddress);
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return reader.TokenType switch
{
JsonToken.Null => null,
JsonToken.String => PhysicalAddress.Parse(reader.Value as string),
_ => throw new NotSupportedException($"{reader.TokenType} is not supported."),
};
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var valueType = value.GetType();
if (!CanConvert(valueType)) throw new InvalidOperationException($"The converter specified on '{writer.Path}' is not compatible with the type '{typeof(PhysicalAddress)}'.");
var bytes = ((PhysicalAddress)value).GetAddressBytes();
var enumerator = bytes.GetEnumerator();
var sb = new StringBuilder(30);
if (enumerator.MoveNext())
{
sb.Append(((byte)enumerator.Current).ToString("X2"));
while (enumerator.MoveNext())
{
sb.Append('-');
sb.Append(((byte)enumerator.Current).ToString("X2"));
}
}
serializer.Serialize(writer, sb.ToString());
}
}
}
|
using GeoAPI.Extensions.Networks;
using NetTopologySuite.Extensions.Coverages;
namespace NetTopologySuite.Extensions.Networks
{
public static class BranchFeatureExtensions
{
public static NetworkLocation ToNetworkLocation(this IBranchFeature branchFeature)
{
return new NetworkLocation(branchFeature.Branch, branchFeature.Offset);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
namespace The_V_Logger
{
class Program
{
static void Main(string[] args)
{
HashSet<string> usernames = new HashSet<string>();
//Pesho followed by ....
var userFollowers = new Dictionary<string, HashSet<string>>();
//pesho is following ....
var userFollowing = new Dictionary<string, HashSet<string>>();
while(true)
{
string input = Console.ReadLine();
if(input== "Statistics")
{
break;
}
string[] splitedInput = input.Split();
if(splitedInput.Length==4)
{
string username = splitedInput[0];
usernames.Add(username);
userFollowers.Add(username, new HashSet<string>()); // 2 nachina za inicializaciq
userFollowing[username] = new HashSet<string>();
}
else
{
string heFollows = splitedInput[0];
string followed = splitedInput[2];
if(usernames.Contains(heFollows) && usernames.Contains(followed) && heFollows != followed)
{
userFollowers[followed].Add(heFollows);
userFollowing[heFollows].Add(followed);
}
}
}
Console.WriteLine($"The V-Logger has a total of { usernames.Count} vloggers in its logs.");
var topUser = userFollowers
.OrderByDescending(x => x.Value.Count)
.ThenBy(x => userFollowing[x.Key].Count())
.FirstOrDefault();
Console.WriteLine($"1. {topUser.Key} : {topUser.Value.Count} followers, {userFollowing[topUser.Key].Count} following");
foreach (var username in topUser.Value.OrderBy(x => x))
{
Console.WriteLine($"* {username}");
}
int count = 2;
foreach (var kvp in userFollowers.Where(x=>x.Key != topUser.Key))
{
Console.WriteLine($"{count}. {kvp.Key} : {kvp.Value.Count} followers, {userFollowing[kvp.Key].Count} following");
count++;
}
}
}
}
|
using System;
using Simpler;
using WebApplication1.Models;
namespace WebApplication1.Tasks
{
public class SaveChargeTask : SimpleTask
{
public ChargeDetails Charge { get; set; }
public override void Execute()
{
try
{
SharedDb.SqlServer.Execute(@"INSERT INTO [dbo].[ChargeDetails]
([Token]
,[Amount]
,[ReferenceId]
,[IsRefunded]
,[AmountRefunded]
,[Created]
,[InvoiceId])
VALUES
(@Token,
@Amount,
@ReferenceId,
@IsRefunded,
@AmountRefunded,
@Created,
@InvoiceId)", Charge);
Charge.Signature.Token = Charge.Token;
SharedDb.SqlServer.Execute(@"INSERT INTO [dbo].[Signature]
([Token]
,[Data])
VALUES
(@Token
,@Data)", Charge.Signature);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace CSharp.ExpressCompiler
{
/// <summary>
/// https://www.infoq.com/articles/expression-compiler/
/// </summary>
public class BasicExample
{
}
}
|
using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Threading.Tasks;
namespace TRPO_labe_6.Models.FileWorkers
{
public class JsonFileSerializer<TType> : JsonFile<TType>
where TType : class
{
private bool _alreadyEmpty = false;
public JsonFileSerializer(string path) : base(path) { }
public void Rewrite(TType @object)
{
if (!_alreadyEmpty)
WriteEmptySpace();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(TargetType);
using (FileStream fs = new FileStream(Path, FileMode.OpenOrCreate))
serializer.WriteObject(fs, @object);
_alreadyEmpty = false;
}
public async Task RewriteAsync(TType @object)
{
await WriteEmptySpaceAsync();
await Task.Run(() => Rewrite(@object));
_alreadyEmpty = true;
}
private void WriteEmptySpace()
{
using (var writer = new StreamWriter(Path, false))
writer.Write(String.Empty);
}
private async Task WriteEmptySpaceAsync()
{
using (var writer = new StreamWriter(Path, false))
await writer.WriteAsync(String.Empty);
}
}
}
|
using org.mariuszgromada.math.mxparser;
using System;
using System.Collections.Generic;
using System.Linq;
namespace PP_Optimalization.Service
{
public interface IMathService
{
MathData GetExamples(ValuesData valuesData);
}
public class MathService : IMathService
{
private int[] _aTab = new int[100];
private int[] _bTab = new int[100];
private int[] _xTab = new int[100];
private int[] tab = new int[50];
private int[][] __aTab = new int[100][];
private int[][] __bTab = new int[100][];
private int[][] __cTab = new int[100][];
private int[][] __t1Tab = new int[100][];
private int[][] __t2Tab = new int[100][];
private int _a;
private int _c;
private int _d;
private ValuesData _valuesData;
public MathService()
{
for (var i = 0; i < 50; i++)
{
tab[i] = i;
}
for (var i = 0; i < 100; i++)
{
_aTab[i] = i;
_bTab[i] = i;
_xTab[i] = i;
__aTab[i] = new int[100];
__bTab[i] = new int[100];
__cTab[i] = new int[100];
__t1Tab[i] = new int[100];
__t2Tab[i] = new int[100];
for (var j = 0; j < 100; j++)
{
__aTab[i][j] = j;
__bTab[i][j] = j;
__cTab[i][j] = j;
__t1Tab[i][j] = j;
__t2Tab[i][j] = j;
}
}
_valuesData = new ValuesData();
}
public MathData GetExamples(ValuesData valuesData)
{
_a = Convert.ToInt32(valuesData.A);
_c = Convert.ToInt32(valuesData.C);
_d = Convert.ToInt32(valuesData.D);
return Factory(valuesData);
}
private MathData Factory(ValuesData valuesData)
{
var data = new MathData();
_valuesData = valuesData;
var equations = EquationsFactory(valuesData);
var dictionary = equations.GroupBy(z => z.Name).ToDictionary(y => y.Key, y => y.ToList());
var values = new List<string>
{
"a = " + valuesData.A,
"b = " + valuesData.B,
"c = " + valuesData.C,
"d = " + valuesData.D,
"e = " + valuesData.E,
"x = " + valuesData.X,
"n = " + valuesData.N,
"count = " + valuesData.Count
};
data.Values = valuesData;
data.EquationsDictionary = dictionary;
return data;
}
private List<EquationData> EquationsFactory(ValuesData v)
{
int i = 0;
var list = new List<EquationData>
{
new EquationData(i++, "Minimalizacja liczby operacji przy wartościowaniu wyrażeń arytmetycznych")
{
Before = MinimizeOperationNumber(v, EquationType.Before),
After = MinimizeOperationNumber(v, EquationType.After)
},
new EquationData(i++, "Minimalizacja liczby operacji przy wartościowaniu wyrażeń arytmetycznych")
{
Before = MinimizeOperationNumber(v, EquationType.Before),
After = MinimizeOperationNumber(v, EquationType.AfterAnother)
},
new EquationData(i++, "Minimalizacja liczby operacji przy wartościowaniu wyrażeń arytmetycznych")
{
Before = MinimizeOperationNumber2(v, EquationType.Before),
After = MinimizeOperationNumber2(v, EquationType.After)
},
new EquationData(i++, "Minimalizacja liczby operacji przy wartościowaniu wyrażeń arytmetycznych")
{
Before = MinimizeOperationNumber3(v, EquationType.Before),
After = MinimizeOperationNumber3(v, EquationType.After)
},
new EquationData(i++, "Minimalizacja liczby operacji przy wartościowaniu wyrażeń arytmetycznych")
{
Before = MinimizeOperationNumber4(v, EquationType.Before),
After = MinimizeOperationNumber4(v, EquationType.After)
},
new EquationData(i++, "Likwidacja zmiennych z jednokrotnym odwołaniem")
{
Before = ReductionOfSingleRef(v, EquationType.Before),
After = ReductionOfSingleRef(v, EquationType.After)
},
new EquationData(i++, "Stosowanie oszczędniejszych operacji")
{
Before = MoreEconomicOperations(v, EquationType.Before),
After = MoreEconomicOperations(v, EquationType.After)
},
new EquationData(i++, "Stosowanie oszczędniejszych operacji")
{
Before = MoreEconomicOperations2(v, EquationType.Before),
After = MoreEconomicOperations2(v, EquationType.After)
},
new EquationData(i++, "Stosowanie oszczędniejszych operacji")
{
Before = MoreEconomicOperations3(v, EquationType.Before),
After = MoreEconomicOperations3(v, EquationType.After)
},
new EquationData(i++, "Stosowanie oszczędniejszych operacji")
{
Before = MoreEconomicOperations4(v, EquationType.Before),
After = MoreEconomicOperations4(v, EquationType.After)
},
new EquationData(i++, "Stosowanie oszczędniejszych operacji")
{
Before = MoreEconomicOperations5(v, EquationType.Before),
After = MoreEconomicOperations5(v, EquationType.After)
},
new EquationData(i++, "Wyliczanie wartości stałych")
{
Before = Constants(v, EquationType.Before),
After = Constants(v, EquationType.After)
},
new EquationData(i++, "Stosowanie efektywniejszych instrukcji")
{
Before = MoreEfficientOperations(v, EquationType.Before),
After = MoreEfficientOperations(v, EquationType.After)
},
new EquationData(i++, "Stosowanie efektywniejszych instrukcji")
{
Before = new Equation("a = 0 \nfor(int nr = 0; nr < 50; nr++) { \nif(tab[nr] < a) a = tab[nr]; \n}" , v.Count, z => EfficientInstructions(EquationType.Before)),
After = new Equation("a = 0; \nfor (int nr = 0; nr < 50; nr++) { \nx = tab[nr]; \na = x < a ? x : a; \n}", v.Count, z => EfficientInstructions(EquationType.AfterAnother))
},
new EquationData(i++, "Eliminacja obliczeń redundantnych")
{
Before = EliminationRedundantCalcs(v, EquationType.Before),
After = EliminationRedundantCalcs(v, EquationType.After)
},
new EquationData(i++, "Konwersja typów")
{
Before = new Equation("y = i1 + f1 + i2 + f2 + i3 + f3 + i4 + f4" , v.Count, z => TypeConversion(EquationType.Before)),
After = new Equation("y = i1 + i2 + i3 + i4 + f1 + f2 + f3 + f4", v.Count, z => TypeConversion(EquationType.After))
},
new EquationData(i++, "Optymalizacja globalna: Rozwijanie pętli")
{
Before = new Equation("for (int nr = 0; nr < 10; nr++) \ntab1[nr] = 0;" , v.Count, z => ExpandLoop(EquationType.Before)),
After = new Equation("tab[0] = 0 \n... tab[10] = 10", v.Count, z => ExpandLoop(EquationType.After))
},
new EquationData(i++, "Łączenie pętli")
{
Before = new Equation(@"for(int nr=0; nr<100; nr++) \ntab1[nr]=0;
\nfor (int nr = 0; nr < 100; nr++)
\ntab2[nr]=0;", v.Count, z => JoinLoop(EquationType.Before)),
After = new Equation(@"for(int nr=0; nr<100; nr++){ \ntab1[nr]=0;
\ntab2[nr]=1; }",
v.Count, z => JoinLoop(EquationType.After))
},
new EquationData(i++, "Przenoszenie operacji niezmienniczych w pętli poza pętle (w tym konwersji typów)")
{
Before = MoveUnusedOutOfLoopEquation(v, EquationType.Before),
After = MoveUnusedOutOfLoopEquation(v, EquationType.After)
},
new EquationData(i++, "Przenoszenie testowania poza pętle")
{
Before = new Equation(String.Concat("for (int nr = 0; nr < 100; nr++)", Environment.NewLine,
"if (W) x[nr] = a[nr] + b[nr];", Environment.NewLine,
"else x[nr] = a[nr] - b[nr];", Environment.NewLine)
, v.Count, z => MoveTestingOutOfLoop(v.W, EquationType.Before)),
After = new Equation(String.Concat("if (W)", Environment.NewLine,
"for (int nr = 0; nr < 100; nr++)", Environment.NewLine,
"x[nr] = a[nr] + b[nr];", Environment.NewLine,
"else", Environment.NewLine,
"for (int nr = 0; nr < 100; nr++)", Environment.NewLine,
"x[nr] = a[nr] - b[nr];")
, v.Count, z => MoveTestingOutOfLoop(v.W, EquationType.After))
},
new EquationData(i++, "Minimalizacja liczby indeksów w odwołaniach do elementów tablic")
{
Before = new Equation(String.Concat("for (int nr1 = 0; nr1 < 100; nr1++)", Environment.NewLine,
"for (int nr2 = 1; nr2 < 100; nr2++){", Environment.NewLine,
"a[nr1][nr2] = 0;", Environment.NewLine,
"for (int nr3 = 1; nr3 < 100; nr3++)", Environment.NewLine,
"a[nr1][nr2] = a[nr1][nr2] + b[nr2][nr3] + c[nr3][nr2]; }", Environment.NewLine)
, v.Count, z => MinimizingNumberOfIndexes(EquationType.Before)),
After = new Equation(String.Concat("for (int nr1 = 0; nr1 < 100; nr1++) ", Environment.NewLine,
"for (int nr2 = 1; nr2 < 100; nr2++){", Environment.NewLine,
"pom = 0;", Environment.NewLine,
"for (int nr3 = 1; nr3 < 100; nr3++)", Environment.NewLine,
"pom = pom + __bTab[nr2][nr3] + __cTab[nr3][nr2];")
, v.Count, z => MinimizingNumberOfIndexes(EquationType.After))
},
};
return list;
}
private Equation MinimizeOperationNumber(ValuesData v, EquationType type)
{
if (type == EquationType.Before)
{
var formula = "Math.Pow(x, 2) / b - a * x / b";
var numberFormula = string.Format("Math.Pow({0}, 2) / {1} - {2} * {0} / {1}", v.X, v.B, v.A);
return new Equation(formula, numberFormula, v.Count, z => Math.Pow(v.X, 2) / v.B - v.A * v.X / v.B);
}
else if (type == EquationType.After)
{
var formula = "(x * x - x * a) / b";
var numberFormula = string.Format("({0} * {0} - {0} * {2}) / {1}", v.X, v.B, v.A);
return new Equation(formula, numberFormula, v.Count, z => (v.X * v.X - v.X * v.A) / v.B);
}
else
{
var formula = "x * (x - a) / b";
var numberFormula = string.Format("{0} * ({0} - {1}) / {2}", v.X, v.A, v.B);
return new Equation(formula, numberFormula, v.Count, z => v.X * (v.X - v.A) / v.B);
}
}
private Equation MinimizeOperationNumber2(ValuesData v, EquationType type)
{
if (type == EquationType.Before)
{
var formula = "a * b * c + a * b * d + a * e";
var numberFormula = string.Format("{0} * {1} * {2} + {0} * {1} * {3} + {0} * {4}", v.A, v.B, v.C, v.D, v.E);
return new Equation(formula, numberFormula, v.Count, z => v.A * v.B * v.C + v.A * v.B * v.D + v.A * v.E);
}
else
{
var formula = "a * (b * (c + d) + e)";
var numberFormula = string.Format("{0} * ({1} * ({2} + {3}) + {4})", v.A, v.B, v.C, v.D, v.E);
return new Equation(formula, numberFormula, v.Count, z => v.A * (v.B * (v.C + v.D) + v.E));
}
}
private Equation MinimizeOperationNumber3(ValuesData v, EquationType type)
{
if (type == EquationType.Before)
{
var formula = "a[n] * x * n + a[n - 1] * x *(n - 1)+ ... + a[1] * x + a[0]";
var numberFormula = string.Format("a[n] * {0} * {1} + a[n - 1] * {0} *(n - 1)+ ... + a[1] * {0} + a[0]", v.X, v.N);
return new Equation(formula, numberFormula, v.Count, z => Series(v.N, v.X, EquationType.Before));
}
else
{
var formula = "...((a[n] * x + a[n - 1]) * x + a[n - 2] * x + ... + a[1]) * x + a[0]";
var numberFormula = string.Format("...((a[n] * {0} + a[n - 1]) * {0} + a[n - 2] * {0} + ... + a[1]) * {0} + a[0]", v.X);
return new Equation(formula, numberFormula, v.Count, z => Series(v.N, v.X, EquationType.After));
}
}
private Equation MinimizeOperationNumber4(ValuesData v, EquationType type)
{
if (type == EquationType.Before)
{
var formula = "-a + b";
var numberFormula = string.Format("-{0} + {1}", v.A, v.B);
return new Equation(formula, numberFormula, v.Count, z => -v.A + v.B);
}
else
{
var formula = "b - a";
var numberFormula = string.Format("{0} - {1}", v.A, v.B);
return new Equation(formula, numberFormula, v.Count, z => v.B - v.A);
}
}
private Equation ReductionOfSingleRef(ValuesData v, EquationType type)
{
if (type == EquationType.Before)
{
var formula = "d = a + b * c \ny = d + e";
var numberFormula = string.Format("d = {0} + {1} * {2} \ny = {3} + {4}", v.A, v.B, v.C, v.D, v.E);
return new Equation(formula, numberFormula, v.Count, z => ReductionOfVarWithSingleRef(v.A, v.B, v.C, v.E));
}
else
{
var formula = "y = a + b * c + e";
var numberFormula = string.Format("y = {0} + {1} * {2} + {3}", v.A, v.B, v.C, v.E);
return new Equation(formula, numberFormula, v.Count, z => v.A + v.B * v.C + v.E);
}
}
private Equation MoreEconomicOperations(ValuesData v, EquationType type)
{
if (type == EquationType.Before)
{
var formula = "2 * a";
var numberFormula = string.Format("2 * {0}", v.A);
return new Equation(formula, numberFormula, v.Count, z => 2 * v.A);
}
else
{
var formula = "a + a";
var numberFormula = string.Format("{0} + {0}", v.A);
return new Equation(formula, numberFormula, v.Count, z => v.A + v.A);
}
}
private Equation MoreEconomicOperations2(ValuesData v, EquationType type)
{
if (type == EquationType.Before)
{
var formula = "3 * a";
var numberFormula = string.Format("3 * {0}", v.A);
return new Equation(formula, numberFormula, v.Count, z => 3 * v.A);
}
else
{
var formula = "a + a + a";
var numberFormula = string.Format("{0} + {0} + {0}", v.A);
return new Equation(formula, numberFormula, v.Count, z => v.A + v.A + v.A);
}
}
private Equation MoreEconomicOperations3(ValuesData v, EquationType type)
{
if (type == EquationType.Before)
{
var formula = "4 * a";
var numberFormula = string.Format("4 * {0}", v.A);
return new Equation(formula, numberFormula, v.Count, z => 4 * v.A);
}
else
{
var formula = "a = a + a \na = a + a";
var numberFormula = string.Format("a = {0} + {0} \na = {0} + {0}", v.A);
return new Equation(formula, numberFormula, v.Count, z => EconomicalOperation1(v.A));
}
}
private Equation MoreEconomicOperations4(ValuesData v, EquationType type)
{
if (type == EquationType.Before)
{
var formula = "a / 2";
var numberFormula = string.Format("{0} / 2", v.A);
return new Equation(formula, numberFormula, v.Count, z => v.A / 2);
}
else
{
var formula = "a * 0.5";
var numberFormula = string.Format("{0} * 0.5", v.A);
return new Equation(formula, numberFormula, v.Count, z => v.A * 0.5);
}
}
private Equation MoreEconomicOperations5(ValuesData v, EquationType type)
{
if (type == EquationType.Before)
{
var formula = "y = c / x \nz = a + b / x";
var numberFormula = string.Format("y = {2} / {3} \nz = {0} + {1} / {3}", v.A, v.B, v.C, v.X);
return new Equation(formula, numberFormula, v.Count, z => EconomicalOperation2(v.A, v.B, v.C, v.X, EquationType.Before));
}
else
{
var formula = "xOdwr = 1.0 / x \ny = c * xOdwr \nz = a + b * xOdwr";
var numberFormula = string.Format("xOdwr = 1.0 / {3} \ny = {2} * xOdwr \nz = {0} + {1} * xOdwr", v.A, v.B, v.C, v.X);
return new Equation(formula, numberFormula, v.Count, z => EconomicalOperation2(v.A, v.B, v.C, v.X, EquationType.After));
}
}
private Equation Constants(ValuesData v, EquationType type)
{
if (type == EquationType.Before)
{
var formula = "b = 4 * a * atan(1) / 180 + c";
var numberFormula = string.Format("b = 4 * {0} * atan(1) / 180 + {1}", v.A, v.C);
return new Equation(formula, numberFormula, v.Count, z => 4 * v.A * Math.Atan(1) / 180 + v.C);
}
else
{
var formula = "b = a * 0.017453292519943295 + c";
var numberFormula = string.Format("b = {0} * 0.017453292519943295 + {1}", v.A, v.C);
return new Equation(formula, numberFormula, v.Count, z => v.A * 0.017453292519943295 + v.C);
}
}
private Equation MoreEfficientOperations(ValuesData v, EquationType type)
{
if (type == EquationType.Before)
{
var formula = "a = 0 \nfor(int nr = 0; nr < 50; nr++) { \nif(tab[nr] < a) a = tab[nr]; \n}";
var numberFormula = "a = 0 \nfor(int nr = 0; nr < 50; nr++) { \nif(tab[nr] < a) a = tab[nr]; \n}";
return new Equation(formula, numberFormula, v.Count, z => EfficientInstructions(EquationType.Before));
}
else
{
var formula = "a = 0; \nfor (int nr = 0; nr < 50; nr++) { \nx = tab[nr]; \nif (x < a) a = x; \n}";
var numberFormula = "a = 0; \nfor (int nr = 0; nr < 50; nr++) { \nx = tab[nr]; \nif (x < a) a = x; \n}";
return new Equation(formula, numberFormula, v.Count, z => EfficientInstructions(EquationType.After));
}
}
private Equation MoreEfficientOperations2(ValuesData v, EquationType type)
{
if (type == EquationType.Before)
{
var formula = "a = 0 \nfor(int nr = 0; nr < 50; nr++) { \nif(tab[nr] < a) a = tab[nr]; \n}";
var numberFormula = "a = 0 \nfor(int nr = 0; nr < 50; nr++) { \nif(tab[nr] < a) a = tab[nr]; \n}";
return new Equation(formula, numberFormula, v.Count, z => EfficientInstructions(EquationType.Before));
}
else
{
var formula = "a = 0; \nfor (int nr = 0; nr < 50; nr++) { \nx = tab[nr]; \nif (x < a) a = x; \n}";
var numberFormula = "a = 0; \nfor (int nr = 0; nr < 50; nr++) { \nx = tab[nr]; \nif (x < a) a = x; \n}";
return new Equation(formula, numberFormula, v.Count, z => EfficientInstructions(EquationType.After));
}
}
private Equation EliminationRedundantCalcs(ValuesData v, EquationType type)
{
if (type == EquationType.Before)
{
var formula = "y = x + a / b * c \nz = e + a / b * c";
var numberFormula = string.Format("y = {4} + {0} / {1} * {2} \nz = {3} + {0} / {1} * {2}", v.A, v.B, v.C, v.E, v.X);
return new Equation(formula, numberFormula, v.Count, z => EliminationRedundantCalculations(v.A, v.B, v.C, v.E, v.X, EquationType.Before));
}
else
{
var formula = "abc = a / b * c \ny = a + abc \nz = e + abc";
var numberFormula = string.Format("abc = {0} / {1} * {2} \ny = {0} + abc \nz = {3} + abc", v.A, v.B, v.C, v.E);
return new Equation(formula, numberFormula, v.Count, z => EliminationRedundantCalculations(v.A, v.B, v.C, v.E, v.X, EquationType.After));
}
}
//todo
private Equation MoveUnusedOutOfLoopEquation(ValuesData v, EquationType type)
{
if (type == EquationType.Before)
{
var formula = String.Concat("for(int nr1=0; nr1<100; nr1++)", Environment.NewLine,
"for (int nr2 = 1; nr2 < 100; nr2++)", Environment.NewLine,
"t1[nr1][nr2] = t2[nr1][nr2] + a / nr1 - c / d;");
var numberFormula = string.Format("for(int nr1=0; nr1<100; nr1++)", Environment.NewLine,
"for (int nr2 = 1; nr2 < 100; nr2++)", Environment.NewLine,
"t1[nr1][nr2] = t2[nr1][nr2] + {0} / nr1 - {1} / {2};", v.A, v.C, v.D);
return new Equation(formula, numberFormula, v.Count, z => MoveUnusedOutOfLoop(v.A, v.C, v.D, EquationType.Before));
}
else
{
var formula = String.Concat("cd=c/d;", Environment.NewLine,
"for(int nr1 = 0; nr1 < 100; nr1++){", Environment.NewLine,
"abcd = a / nr1 - cd;", Environment.NewLine,
"for(int nr2 = 1; nr2<100; nr2++)", Environment.NewLine,
"t1[nr1][nr2] = t2[nr1][nr2] + abcd; }");
var numberFormula = string.Format("cd = {1} / {2};", Environment.NewLine,
"for(int nr1 = 0; nr1<100; nr1++){", Environment.NewLine,
"abcd = {0} / nr1 - cd;", Environment.NewLine,
"for(int nr2=1; nr2<100; nr2++)", Environment.NewLine,
"t1[nr1][nr2] = t2[nr1][nr2] + abcd; }", v.A, v.B, v.C, v.E);
return new Equation(formula, numberFormula, v.Count, z => MoveUnusedOutOfLoop(v.A, v.C, v.D, EquationType.After));
}
}
private double MinimizingNumberOfIndexes(EquationType type)
{
int pom;
if (type == EquationType.Before)
{
for (int nr1 = 0; nr1 < 100; nr1++)
for (int nr2 = 1; nr2 < 100; nr2++)
{
__aTab[nr1][nr2] = 0;
for (int nr3 = 1; nr3 < 100; nr3++)
__aTab[nr1][nr2] = __aTab[nr1][nr2] + __bTab[nr2][nr3] + __cTab[nr3][nr2];
}
}
else
{
for (int nr1 = 0; nr1 < 100; nr1++)
for (int nr2 = 1; nr2 < 100; nr2++)
{
pom = 0;
for (int nr3 = 1; nr3 < 100; nr3++)
pom = pom + __bTab[nr2][nr3] + __cTab[nr3][nr2];
}
}
return 0;
}
private double MoveTestingOutOfLoop(int w, EquationType type)
{
var W = w == 1 ? true : false;
if (type == EquationType.Before)
{
for (int nr = 0; nr < 100; nr++)
if (W) _xTab[nr] = _aTab[nr] + _bTab[nr];
else _xTab[nr] = _aTab[nr] - _bTab[nr];
}
else
{
if (W)
for (int nr = 0; nr < 100; nr++)
_xTab[nr] = _aTab[nr] + _bTab[nr];
else
for (int nr = 0; nr < 100; nr++)
_xTab[nr] = _aTab[nr] - _bTab[nr];
}
return 0;
}
private double MoveUnusedOutOfLoop(double a, double c, double d, EquationType type)
{
double cd;
double abcd;
if (type == EquationType.Before)
{
for (int nr1 = 1; nr1 < 100; nr1++)
for (int nr2 = 1; nr2 < 100; nr2++)
__t1Tab[nr1][nr2] = __t2Tab[nr1][nr2] + _a / nr1 - _c / _d;
}
else
{
cd = c / d;
for (int nr1 = 1; nr1 < 100; nr1++)
{
abcd = a / nr1 - cd;
for (int nr2 = 1; nr2 < 100; nr2++)
__t1Tab[nr1][nr2] = __t2Tab[nr1][nr2] + Convert.ToInt32(abcd);
}
}
return 0;
}
private double JoinLoop(EquationType type)
{
if (type == EquationType.Before)
{
for (int nr = 0; nr < 100; nr++)
_aTab[nr] = 0;
for (int nr = 0; nr < 100; nr++)
_bTab[nr] = 1;
}
else
{
for (int nr = 0; nr < 100; nr++)
{
_aTab[nr] = 0;
_bTab[nr] = 1;
}
}
return 0;
}
private double ExpandLoop(EquationType type)
{
int[] tab = new int[10];
if (type == EquationType.Before)
{
for (int nr = 0; nr < 10; nr++)
{
tab[nr] = 0;
}
}
else
{
tab[0] = 0;
tab[1] = 0;
tab[2] = 0;
tab[3] = 0;
tab[4] = 0;
tab[5] = 0;
tab[6] = 0;
tab[7] = 0;
tab[8] = 0;
tab[9] = 0;
}
return 0;
}
private float TypeConversion(EquationType type)
{
int i1 = 1, i2 = 2, i3 = 3, i4 = 4;
float f1 = 1.0f, f2 = 2.0f, f3 = 3.0f, f4 = 4.0f;
if (type == EquationType.Before)
{
var y = i1 + f1 + i2 + f2 + i3 + f3 + i4 + f4;
return y;
}
else
{
var y = i1 + i2 + i3 + i4 + f1 + f2 + f3 + f4;
return y;
}
}
private double EliminationRedundantCalculations(double a, double b, double c, double e, double x, EquationType type)
{
if (type == EquationType.Before)
{
double y = x + a / b * c;
double z = e + a / b * c;
return z;
}
else
{
double abc = a / b * c;
double y = a + abc;
double z = e + abc;
return z;
}
}
private double EfficientInstructions(EquationType type)
{
int a;
int x;
if (type == EquationType.Before)
{
a = 0;
for (int nr = 0; nr < 50; nr++)
{
if (tab[nr] < a)
a = tab[nr];
}
}
else if (type == EquationType.After)
{
a = 0;
for (int nr = 0; nr < 50; nr++)
{
x = tab[nr];
if (x < a) a = x;
}
}
else
{
a = 0;
for (int nr = 0; nr < 50; nr++)
{
x = tab[nr];
a = x < a ? x : a;
}
}
return Convert.ToDouble(a);
}
private double EconomicalOperation1(double a)
{
a = a + a;
a = a + a;
return a;
}
private double EconomicalOperation2(double a, double b, double c, double x, EquationType type)
{
if (type == EquationType.Before)
{
double y = c / x;
double z = a + b / x;
return z;
}
else
{
double xOdwr = 1.0 / x;
double y = c * xOdwr;
double z = a + b * xOdwr;
return z;
}
}
private double ReductionOfVarWithSingleRef(double a, double b, double c, double e)
{
double d = a + b * c;
return d + e;
}
private double Series(int n, double x, EquationType type)
{
double[] array = new double[n];
double result = array[0];
if (type == EquationType.Before)
{
for (int i = 1; i < array.Length; i++)
{
result += array[i] * x * n;
}
}
else
{
for (int i = 1; i < array.Length; i++)
{
result += array[i] * x;
}
result *= n;
}
return result;
}
}
public enum EquationType
{
Before = 1,
After = 2,
AfterAnother = 3
}
public class MathData
{
public Dictionary<string, List<EquationData>> EquationsDictionary { get; set; }
public ValuesData Values { get; set; }
public double NetSummaryTime { get; set; }
public double JsSummaryTime { get; set; }
}
public class EquationData
{
public int Id { get; set; }
public string Name { get; set; }
public Equation Before { get; set; }
public Equation After { get; set; }
public EquationData(int id, string name)
{
Id = id;
Name = name;
}
}
public class Equation
{
public string Formula { get; set; }
public string ValuesFormula { get; set; }
public List<string> Values { get; set; }
public double Result { get; set; }
public double NetTimeTaken { get; set; }
public double JSTimeTaken { get; set; }
public Func<double, double> Func { get; set; }
public ValuesData ValuesData { get; set; }
public Equation(string formula, int count, Func<double, float> func)
{
ValuesFormula = formula;
Formula = formula;
Calculate(count, func);
}
public Equation(string formula, string valuesFormula, int count, Func<double, float> func)
{
ValuesFormula = valuesFormula;
Formula = formula;
Calculate(count, func);
}
public Equation(string formula, int count, Func<double, double> func)
{
ValuesFormula = formula;
Formula = formula;
Calculate(count, func);
}
public Equation(string formula, string valuesFormula, int count, Func<double, double> func)
{
ValuesFormula = valuesFormula;
Formula = formula;
Calculate(count, func);
}
private void Calculate(int count, Func<double, double> func)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
for (var i = 0; i < count; i++)
{
Result = func(count);
}
watch.Stop();
NetTimeTaken = watch.Elapsed.TotalMilliseconds;
}
private void Calculate(int count, Func<double, float> func)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
for (var i = 0; i < count; i++)
{
Result = func(count);
}
watch.Stop();
NetTimeTaken = watch.Elapsed.TotalMilliseconds;
}
}
public class ValuesData
{
public double A { get; set; }
public double B { get; set; }
public double C { get; set; }
public double D { get; set; }
public double E { get; set; }
public double X { get; set; }
public int W { get; set; }
public int N { get; set; }
public int Count { get; set; }
}
}
|
using Crystal.Plot2D.Charts;
using System;
using System.Collections.Generic;
using System.Windows;
namespace Crystal.Plot2D
{
[Obsolete("Works incorrectly", true)]
public sealed class InclinationFilter : PointsFilterBase
{
private double criticalAngle = 179;
public double CriticalAngle
{
get { return criticalAngle; }
set
{
if (criticalAngle != value)
{
criticalAngle = value;
RaiseChanged();
}
}
}
#region IPointFilter Members
public override List<Point> Filter(List<Point> points)
{
if (points.Count == 0)
{
return points;
}
List<Point> res = new() { points[0] };
int i = 1;
while (i < points.Count)
{
bool added = false;
int j = i;
while (!added && (j < points.Count - 1))
{
Point x1 = res[res.Count - 1];
Point x2 = points[j];
Point x3 = points[j + 1];
double a = (x1 - x2).Length;
double b = (x2 - x3).Length;
double c = (x1 - x3).Length;
double angle13 = Math.Acos((a * a + b * b - c * c) / (2 * a * b));
double degrees = 180 / Math.PI * angle13;
if (degrees < criticalAngle)
{
res.Add(x2);
added = true;
i = j + 1;
}
else
{
j++;
}
}
// reached the end of resultPoints
if (!added)
{
res.Add(points.GetLast());
break;
}
}
return res;
}
#endregion
}
}
|
using System;
using MongoDB.Bson;
using MongoDB.Driver;
namespace playmongodb
{
class Program
{
static readonly MongoClient _dbClient;
static Program()
{
_dbClient = new MongoClient(DatabaseSettings.ConnectionString);
new SeedDataProvider(
DatabaseSettings.ConnectionString,
DatabaseSettings.DatabaseName)
.SeedData();
}
static void PrintCommands()
{
System.Console.WriteLine("Create task: task_name;deadline");
System.Console.WriteLine("Edit task: task_id;task_name");
System.Console.WriteLine("Find tasks: _ft;title");
}
static void Main(string[] args)
{
while (true)
{
var taskCollection = GetCollection<MongoTask>(MongoTask.CollectionName);
PrintTaskCollection(taskCollection);
PrintCommands();
var input = Console.ReadLine();
Console.Clear();
var taskParts = input.Split(';');
if (int.TryParse(taskParts[0], out int taskId))
{
//edition or completion
}
else
{
if (taskParts[0] == "_ft")
{
//var filter = Builders<MongoTask>.Filter.Eq("Title", taskParts[1]);
//var tasks = taskCollection.Find(filter).FirstOrDefault();
var collection = GetCollection<MongoTask>(MongoTask.CollectionName);
var filter3 = Builders<MongoTask>.Filter.Regex("Title", new BsonRegularExpression($".*{taskParts[1]}.*"));
var tasks = collection.Find<MongoTask>(filter3).ToList();
foreach (var item in tasks)
{
System.Console.WriteLine($"{item.Id} - {item.Title}");
}
Console.ReadLine();
continue;
}
//find:
//creation
var task = new MongoTask
{
Title = taskParts[0]
};
if (taskParts.Length > 1)
{
task.Deadline = DateTime.Parse(taskParts[1]);
}
else
{
task.Deadline = null;
}
taskCollection.InsertOne(task);
}
}
}
static IMongoCollection<T> GetCollection<T>(string collectionName)
{
var db = _dbClient.GetDatabase(DatabaseSettings.DatabaseName);
return db.GetCollection<T>(collectionName);
}
static void PrintTaskCollection(IMongoCollection<MongoTask> tasks)
{
const string tableFormat = "{0,30}{1,50}{2,30}";
System.Console.WriteLine(tableFormat, "Id", "Title", "Deadline");
/* Another way to read all documents
var documents = tasks.Find(new MongoDB.Bson.BsonDocument()).ToList();
foreach (var task in documents)
{
System.Console.WriteLine(tableFormat, task.Id, task.Title, task.Deadline);
}
*/
foreach (var task in tasks.AsQueryable())
{
System.Console.WriteLine(tableFormat, task.Id, task.Title, task.Deadline);
}
}
}
}
|
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace NStandard
{
#if NET7_0_OR_GREATER
public static class BitConverterEx
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Int128 ToInt128(ReadOnlySpan<byte> value)
{
if (value.Length < 16)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
return Unsafe.ReadUnaligned<Int128>(ref MemoryMarshal.GetReference(value));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static UInt128 ToUInt128(ReadOnlySpan<byte> value)
{
if (value.Length < 16)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
return Unsafe.ReadUnaligned<UInt128>(ref MemoryMarshal.GetReference(value));
}
public static Int128 ToInt128(this byte[] value, int startIndex)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if ((uint)startIndex >= (uint)value.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), ExceptionResource.ArgumentOutOfRange_IndexMustBeLess.ToResourceString());
}
if (startIndex > value.Length - 16)
{
throw new ArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall.ToResourceString(), nameof(value));
}
return Unsafe.ReadUnaligned<Int128>(ref value[startIndex]);
}
public static UInt128 ToUInt128(this byte[] value, int startIndex)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if ((uint)startIndex >= (uint)value.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), ExceptionResource.ArgumentOutOfRange_IndexMustBeLess.ToResourceString());
}
if (startIndex > value.Length - 16)
{
throw new ArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall.ToResourceString(), nameof(value));
}
return Unsafe.ReadUnaligned<UInt128>(ref value[startIndex]);
}
public static byte[] GetBytes(Int128 value)
{
byte[] array = new byte[16];
Unsafe.As<byte, Int128>(ref array[0]) = value;
return array;
}
public static byte[] GetBytes(UInt128 value)
{
byte[] array = new byte[16];
Unsafe.As<byte, UInt128>(ref array[0]) = value;
return array;
}
public static bool TryWriteBytes(Span<byte> destination, Int128 value)
{
if (destination.Length < 16)
{
return false;
}
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
return true;
}
public static bool TryWriteBytes(Span<byte> destination, UInt128 value)
{
if (destination.Length < 16)
{
return false;
}
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
return true;
}
}
#endif
}
|
using Dapper;
using Dapper.FastCrud;
using Microsoft.Extensions.Options;
using CarRental.API.Common.SettingsOptions;
using CarRental.API.DAL.Entities;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
namespace CarRental.API.DAL.DataServices.Car
{
public class CarDataService : BaseDataService, ICarDataService
{
private const string SpReadAll = "dbo.GetMyCars";
private const string SpUpdate = "UpdateCar";
private const string SpMarkAvailability = "MarkCarAsReceived";
public CarDataService(IOptions<DatabaseOptions> databaseOptions)
: base(databaseOptions)
{
}
/// <summary>
/// Dapper.FastCrud example
/// </summary>
public async Task<CarItem> GetAsync(Guid id)
{
using (var conn = await GetOpenConnectionAsync())
{
return await conn.GetAsync(new CarItem() { Id = id });
}
}
/// <summary>
/// Dapper with stored procedure
/// </summary>
public async Task<IEnumerable<CarItem>> GetAllAsync()
{
using (var conn = await GetOpenConnectionAsync())
{
return await conn.QueryAsync<CarItem>(
sql: SpReadAll,
commandType: CommandType.StoredProcedure);
}
}
public async Task<CarItem> CreateAsync(CarItem car)
{
using (var conn = await GetOpenConnectionAsync())
{
car.Id = Guid.NewGuid();
car.CreatedOn = DateTime.Now;
car.UpdatedOn = DateTime.Now;
conn.Insert(car);
}
return car;
}
public async Task<CarItem> DeleteAsync(Guid id)
{
using (var conn = await GetOpenConnectionAsync())
{
conn.Delete<CarItem>(new CarItem { Id = id});
}
return null;
}
public async Task<IEnumerable<CarItem>> UpsertAsync(CarItem car)
{
using (var conn = await GetOpenConnectionAsync())
{
return await conn.QueryAsync<CarItem>(
param: new
{
Id = car.Id,
Brand = car.Brand,
Model = car.Model,
},
sql: SpUpdate,
commandType: CommandType.StoredProcedure);
}
}
public async Task<IEnumerable<CarItem>> MarkCarAsAvailable(CarItem car)
{
var parameters = new DynamicParameters();
parameters.Add("MileageUntilService", dbType: DbType.Int64, direction: ParameterDirection.Output);
using (var conn = await GetOpenConnectionAsync())
{
return await conn.QueryAsync<CarItem>(
param: new
{
Id = car.Id,
Mileage = car.Mileage,
},
sql: SpMarkAvailability,
commandType: CommandType.StoredProcedure);
}
car.MileageUntilService = parameters.Get<int>("MileageUntilService");
}
}
}
|
using Cs_Gerencial.Dominio.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_Gerencial.Aplicacao.Interfaces
{
public interface IAppServicoPessoas: IAppServicoBase<Pessoas>
{
List<string> ObterListaOrgaoEmissor();
List<string> ObterListaProfissao();
List<Pessoas> ObterListaPessoasPorCpfCnpj(string cpfCnpj);
Pessoas SalvarAlteracao(Pessoas pessoa);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IRAPShared;
using IRAP.Global;
namespace IRAP.Entity.FVS
{
public class LineKPI_BTS
{
private Quantity planQuantity = new Quantity();
private Quantity btsQuantity = new Quantity();
private Quantity actualQuantity = new Quantity();
/// <summary>
/// KPI指标名(BTS)
/// </summary>
public string KPIName { get; set; }
/// <summary>
/// KPI值(% 为单位,不必换算,加上 % 即可)
/// </summary>
public decimal KPIValue { get; set; }
/// <summary>
/// 应完成百分比
/// </summary>
public decimal BTSProgress { get; set; }
/// <summary>
/// 实际完成百分比
/// </summary>
public decimal ActualProgress { get; set; }
/// <summary>
/// 累计进度状态;
/// 0-正常(95%--105%) 绿色;
/// 1-偏快(105%--110%) 淡黄;
/// 2-过快(大于 110%) 深黄;
/// 3-偏慢(90%--95%) 桃红;
/// 4-过慢(小于 90%) 大红
/// </summary>
public int BTSStatus { get; set; }
/// <summary>
/// 颜色RGB值(6位16进制)
/// </summary>
public string RGBColor { get; set; }
/// <summary>
/// 生产工单号
/// </summary>
public string PWONo { get; set; }
/// <summary>
/// 产品编号
/// </summary>
public string ProductNo { get; set; }
/// <summary>
/// 数量放大数量级
/// </summary>
public int QtyScale
{
get { return planQuantity.Scale; }
set
{
planQuantity.Scale = value;
btsQuantity.Scale = value;
actualQuantity.Scale = value;
}
}
/// <summary>
/// 计量单位(前台呈现暂时不用)
/// </summary>
public string UnitOfMeasure
{
get { return planQuantity.UnitOfMeasure; }
set
{
planQuantity.UnitOfMeasure = value;
btsQuantity.UnitOfMeasure = value;
actualQuantity.UnitOfMeasure = value;
}
}
/// <summary>
/// 计划产量
/// </summary>
public long PlanQty
{
get { return planQuantity.IntValue; }
set { planQuantity.IntValue = value; }
}
/// <summary>
/// 实际开始时间
/// </summary>
public string ActualStartTime { get; set; }
/// <summary>
/// 至指定时间应完成产量
/// </summary>
public long BTSQty
{
get { return btsQuantity.IntValue; }
set { btsQuantity.IntValue = value; }
}
/// <summary>
/// 实际完成数量
/// </summary>
public long ActualQty
{
get { return actualQuantity.IntValue; }
set { actualQuantity.IntValue = value; }
}
[IRAPORMMap(ORMMap = false)]
public Quantity PlanQuantity
{
get { return planQuantity; }
}
[IRAPORMMap(ORMMap = false)]
public Quantity BTSQuantity
{
get { return BTSQuantity; }
}
[IRAPORMMap(ORMMap = false)]
public Quantity ActualQuantity
{
get { return actualQuantity; }
}
public LineKPI_BTS Clone()
{
LineKPI_BTS rlt = MemberwiseClone() as LineKPI_BTS;
rlt.planQuantity = planQuantity.Clone();
rlt.btsQuantity = btsQuantity.Clone();
rlt.actualQuantity = actualQuantity.Clone();
return rlt;
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using TrackLauncher.Helpers;
namespace TrackLauncher.ViewModel
{
class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate{ };
private RelayCommand _closeCommand;
public ICommand CloseCommand
{
get
{
if(_closeCommand == null)
{
_closeCommand = new RelayCommand(param => Close(), param => CanClose());
}
return _closeCommand;
}
}
internal void RaisePropertyChanged(string property)
{
if(property != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
public event Action RequestClose;
public virtual void Close()
{
RequestClose?.Invoke();
}
public virtual bool CanClose()
{
return true;
}
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class UiManager : MonoBehaviour
{
public Text vittoriaP1;
public Text vittoriaP2;
void Start ()
{
vittoriaP1.gameObject.SetActive(false);
vittoriaP2.gameObject.SetActive(false);
}
void Update()
{
if (Input.GetKey(KeyCode.Escape))
{
Application.Quit();
}
}
public void winP1()
{
vittoriaP1.gameObject.SetActive(true);
}
public void winP2()
{
//Debug.Log("COME GET SOME");
vittoriaP2.gameObject.SetActive(true);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PluginDevelopment.Model;
using PluginDevelopment.DAL;
using PluginDevelopment.DAL.EF.IDAL;
using PluginDevelopment.DAL.EF.DALContainer;
namespace PluginDevelopment.BLL
{
public class UserService : BaseService<user>, IUserService
{
readonly IUserDal _userDal = DAL.EF.DALContainer.Container.Resolve<IUserDal>();
public override void SetDal()
{
Dal = _userDal;
}
}
}
|
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace StarlightRiver.Items
{
public class QuickMaterial : ModItem
{
string Matname;
string Mattooltip;
int Maxstack;
int Value;
int Rare;
public QuickMaterial(string name, string tooltip, int maxstack, int value, int rare)
{
Matname = name;
Mattooltip = tooltip;
Maxstack = maxstack;
Value = value;
Rare = rare;
}
public override void SetStaticDefaults()
{
DisplayName.SetDefault(Matname);
Tooltip.SetDefault(Mattooltip);
}
public override void SetDefaults()
{
item.width = 16;
item.height = 16;
item.maxStack = Maxstack;
item.value = Value;
item.rare = Rare;
}
}
public class QuickTileItem : ModItem
{
public string Itemname;
public string Itemtooltip;
int Tiletype;
int Rare;
public QuickTileItem(string name, string tooltip, int placetype, int rare)
{
Itemname = name;
Itemtooltip = tooltip;
Tiletype = placetype;
Rare = rare;
}
public override void SetStaticDefaults()
{
DisplayName.SetDefault(Itemname);
Tooltip.SetDefault(Itemtooltip);
}
public override void SetDefaults()
{
item.width = 16;
item.height = 16;
item.maxStack = 999;
item.useTurn = true;
item.autoReuse = true;
item.useAnimation = 15;
item.useTime = 10;
item.useStyle = 1;
item.consumable = true;
item.createTile = Tiletype;
}
}
}
|
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
public class TopDownCamera {
// @Camera owner (player, npc, enemy...)
private Transform m_target;
// @Position offset from owner
private Vector3 m_offset;
// @Constructor
public TopDownCamera (Transform target, Vector3 offset) {
this.m_target = target;
this.m_offset = offset;
}
// @Follow target
public void FollowTarget (Transform cameraTransform)
{
cameraTransform.position = m_target.transform.position + m_offset;
}
}
|
using System;
namespace BizApplication
{
/// <summary>
/// Base class to build server side applications.
/// Contains methods for interact with the server and for share data.
/// </summary>
public abstract class ApplicationInstanceBase
{
//#### Declaration
private Guid applicationId;
protected ApplicationResponse response;
protected ApplicationRequest request;
//#### Constructor
public ApplicationInstanceBase()
{
this.applicationId = Guid.NewGuid();
}
/// <summary>
/// Entry point for all client requests.
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
public ApplicationResponse ProcessRequest(ApplicationRequest req)
{
///
/// Firstable we clean the application data for the new request
///
this.request = req;
this.response = null;
LastRequest = DateTime.Now;
NewRequest();
return this.response;
}
protected abstract void NewRequest();
/// <summary>
/// Incomging shared response from an application
/// </summary>
/// <param name="sender">the application that elaborate the response</param>
/// <param name="response"></param>
/// <param name="req">the initial request</param>
public abstract void OnNewShareResponse(ApplicationInstanceBase sender, ApplicationResponse response, ApplicationRequest req);
/// <summary>
/// Called by the server when disposed
/// </summary>
public abstract void UnloadApplication();
//#### Return the application setting
public abstract ApplicationSettings Info { get; }
//#### Unique identifier application Id
public Guid ApplicationId{get { return applicationId; } }
//#### Last datetime request
public DateTime LastRequest { get; set; }
}
}
|
using Microsoft.EntityFrameworkCore;
using Quizlet_Server.Data;
using Quizlet_Server.Entities;
using Quizlet_Server.Interfaces.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Quizlet_Server.Services
{
public class LopHocService : ILopHocService
{
private AppDbContext appDbContext { get; set; }
public LopHocService()
{
appDbContext = new AppDbContext();
}
public IQueryable<LopHoc> GetDanhSachLopHoc(int TKId, string keywords)
{
var query = appDbContext.LopHocs.Include(x => x.TaiKhoan)
.Include(x => x.LopHoc_HocSinhs)
.Include(x => x.HocPhans)
.Where(x => x.TaiKhoanID == TKId)
.AsQueryable();
//if (keywords == "all") return query;
//if (!string.IsNullOrEmpty(keywords))
//{
// keywords = keywords.ToLower();
// query = query.Where(lh => lh.TenLopHoc.ToLower().Contains(keywords)
// || lh.TaiKhoan.TenNguoiDung.ToLower().Contains(keywords)
// || lh.MoTa.ToLower().Contains(keywords)
// );
//}
return query;
}
public LopHoc GetLopHocById(int lopHocId)
{
var lh = appDbContext.LopHocs.Include(x => x.TaiKhoan)
.Include(x => x.LopHoc_HocSinhs)
.Include(x => x.HocPhans)
.AsQueryable()
.FirstOrDefault(x => x.LopHocID == lopHocId);
return lh;
}
public LopHoc CreateLopHoc(LopHoc lopHoc)
{
appDbContext.LopHocs.Add(lopHoc);
appDbContext.SaveChanges();
return lopHoc;
}
public LopHoc UpdateLopHoc(int lopHocId, LopHoc lopHoc)
{
if (appDbContext.LopHocs.Any(sp => sp.LopHocID == lopHocId))
{
var currentLopHoc = GetLopHocById(lopHocId);
currentLopHoc.TenLopHoc = lopHoc.TenLopHoc;
currentLopHoc.MoTa = lopHoc.MoTa;
appDbContext.LopHocs.Update(currentLopHoc);
appDbContext.SaveChanges();
return currentLopHoc;
}
else
throw new Exception($"lop hoc {lopHocId} is not exist.");
}
public void DeleteLopHoc(int lopHocId)
{
if (appDbContext.LopHocs.Any(lh => lh.LopHocID == lopHocId))
{
var lopHocCanXoa = GetLopHocById(lopHocId);
appDbContext.LopHocs.Remove(lopHocCanXoa);
appDbContext.SaveChanges();
}
else
{
throw new Exception($"Lop Hoc {lopHocId} is not exist.");
}
}
public IQueryable<LopHoc_HocSinh> GetDanhSachHocVienByLopHocID(int lopHocID)
{
var query = appDbContext.LopHoc_HocSinhs.Include(x => x.LopHoc).AsQueryable();
query = query.Where(hv => hv.LopHocID == lopHocID);
return query;
}
public IQueryable<HocPhan> GetDanhSachHocPhanByLopHocID(int lopHocID)
{
var query = appDbContext.HocPhans.Include(x => x.LopHoc).AsQueryable();
query = query.Where(hp => hp.LopHocID == lopHocID);
return query;
}
}
} |
using System.Collections.Generic;
using System.Linq;
using Fingo.Auth.DbAccess.Models.Base;
using Fingo.Auth.DbAccess.Models.Statuses;
namespace Fingo.Auth.Domain.Infrastructure.ExtensionMethods
{
public static class CheckIsInUserStatuses
{
public static T WithStatuses<T>(this T model , params UserStatus[] list) where T : BaseEntityWithUserStatus
{
if (list.Length == 0)
return model;
if (model == null)
return null;
return list.Any(t => model.Status == t) ? model : null;
}
public static IEnumerable<T> WithStatuses<T>(this IEnumerable<T> modelList , params UserStatus[] list)
where T : BaseEntityWithUserStatus
{
if (list.Length == 0)
return modelList;
if (modelList == null)
return null;
var modelWithStatuses = new List<T>();
foreach (var model in modelList)
if (list.Any(s => model.Status == s))
modelWithStatuses.Add(model);
return modelWithStatuses;
}
public static T WithoutStatuses<T>(this T model , params UserStatus[] list) where T : BaseEntityWithUserStatus
{
if (list.Length == 0)
return model;
if (model == null)
return null;
return list.Any(t => model.Status == t) ? null : model;
}
public static IEnumerable<T> WithoutStatuses<T>(this IEnumerable<T> modelList , params UserStatus[] list)
where T : BaseEntityWithUserStatus
{
if (list.Length == 0)
return modelList;
if (modelList == null)
return null;
var modelWithStatuses = new List<T>();
foreach (var model in modelList)
if (list.All(s => model.Status != s))
modelWithStatuses.Add(model);
return modelWithStatuses;
}
}
} |
using System.Collections.Generic;
using System.Linq;
namespace Euler_Logic.Problems {
public class Problem109: ProblemBase {
private List<Hit> _hits = new List<Hit>();
private Dictionary<int, Hit> _doubles = new Dictionary<int, Hit>();
private List<Hit> _dart1;
private List<List<Hit>> _dart2;
/*
Unusually easy for a problem rated 45%. The total number of ways of checking out for any score
is the sum of the total number of ways of checking out with 1 dart, plus with 2 darts, plus with
3 darts. So we just need to calculate these three individual values for each score 2 to 99.
If the current score is N, the number of ways of checking out with 1 dart is any double equal
to N. The number of ways of checking out with 2 darts is for all darts K where N - K is equal
to some dart that is double.
For calculating with 3 darts, we have to consider the constraint of what makes a distinct way.
A way is distinct from another way if (1) it ends on a different double, or (2) the first two
darts are not the same between the two ways. This is easily solved by simply looping through
each dart for the first dart, and then for each dart on the second dart starting with the first
dart (instead of beginning).
*/
public override string ProblemName {
get { return "109: Darts"; }
}
public override string GetAnswer() {
Initialize();
return Solve().ToString();
}
private void Initialize() {
int power = 0;
for (int num = 1; num <= 20; num++) {
_hits.Add(new Hit() {
IsDouble = false,
Value = num,
Key = "S" + num
});
_hits.Add(new Hit() {
IsDouble = true,
Value = num * 2,
Key = "D" + num
});
_doubles.Add(num * 2, _hits.Last());
_hits.Add(new Hit() {
IsDouble = false,
Value = num * 3,
Key = "T" + num
});
power += 3;
}
_hits.Add(new Hit() {
IsDouble = false,
Value = 25,
Key = "S25"
});
_hits.Add(new Hit() {
IsDouble = true,
Value = 50,
Key = "D25"
});
_doubles.Add(50, _hits.Last());
}
private int Solve() {
int count = 0;
for (int remaining = 2; remaining < 100; remaining++) {
count += Solve(remaining);
}
return count;
}
private int Solve(int remaining) {
int count = 0;
_dart1 = new List<Hit>();
_dart2 = new List<List<Hit>>();
count += (_doubles.ContainsKey(remaining) ? 1 : 0);
count += SolveDart1(remaining);
count += SolveDart2(remaining);
return count;
}
private int SolveDart1(int remaining) {
foreach (var hit in _hits) {
var final = remaining - hit.Value;
if (_doubles.ContainsKey(final)) {
var doub = _doubles[final];
_dart1.Add(hit);
}
}
return _dart1.Count;
}
private int SolveDart2(int remaining) {
for (int hit1Index = 0; hit1Index < _hits.Count; hit1Index++) {
for (int hit2Index = hit1Index; hit2Index < _hits.Count; hit2Index++) {
var hit1 = _hits[hit1Index];
var hit2 = _hits[hit2Index];
if (_doubles.ContainsKey(remaining - hit1.Value - hit2.Value)) {
_dart2.Add(new List<Hit>());
_dart2.Last().Add(hit1);
_dart2.Last().Add(hit2);
}
}
}
return _dart2.Count;
}
private class Hit {
public int Value { get; set; }
public bool IsDouble { get; set; }
public string Key { get; set; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RakNet;
namespace InternalSwigTestApp
{
public class FileListTransferCB : FileListTransferCBInterface
{
}
}
|
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.Shapes;
using System.Windows.Threading;
using Z.Framework.Model;
using Z.Framework.WorkBench.Tools;
namespace Z.Framework.WorkBench
{
/// <summary>
/// SystemFramework.xaml 的交互逻辑
/// </summary>
public partial class SystemFramework : Window
{
#region Delegates
#endregion
#region ViewModels
private Account_Info UserInfo { set; get; }
#endregion
public SystemFramework()
{
InitializeComponent();
#region 获取windows缩放比例
using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromHwnd(IntPtr.Zero))
{
float dpiX = graphics.DpiX;
float dpiY = graphics.DpiY;
switch (Convert.ToInt32(dpiX))
{
case 96:
DPIAdpter.Zoom = 1;
break;
case 120:
DPIAdpter.Zoom = 1.25;
break;
case 144:
DPIAdpter.Zoom = 1.5;
break;
case 192:
DPIAdpter.Zoom = 2;
break;
default:
DPIAdpter.Zoom = 1;
break;
}
}
if (SystemParameters.PrimaryScreenWidth < 1360 || SystemParameters.PrimaryScreenHeight < 760)
{
if (SystemParameters.PrimaryScreenWidth * DPIAdpter.Zoom > 1360
&& SystemParameters.PrimaryScreenHeight * DPIAdpter.Zoom > 760)
{
//实际分辨率足够 ,缩放的太大了
MessageBox.Show("您目前的缩放比例过大,\r请在显示设置中调整缩放比例,\r系统即将退出!");
}
else
{
MessageBox.Show("您的分辨率过小,\r无法达到系统最低要求,\r系统将退出!");
}
Application.Current.Shutdown(1);
}
#endregion
}
void Login()
{
var size = new Size()
{
Height = this.ActualHeight - 50,
Width = MainPanel.ActualWidth,
};
var l = new SystemLoginPage(size);
// l.login += L_login;
MainPanel.Children.Add(l);
//LogoutAnimation();
//if (NeedLogin)
//{
//}
// else
//{
//User.Uid = 1;
// User.IsLogin = true;
//LoginAnimation();
// }
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
#region 登录注销事件
if (UserInfo == null || UserInfo.LoginState != true)
{
Login();
}
#endregion
}
#region 窗体边框、缩放、最大最小化、拖拽事件
public Point Mypoint; //窗体坐标
public Size Mysize; //窗体大小
bool normalState = true;
Rect rcnormal;//定义一个全局rect记录还原状态下窗口的位置和大小。
private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
{
if (this.ActualHeight > SystemParameters.WorkArea.Height || this.ActualWidth > SystemParameters.WorkArea.Width)
{
this.WindowState = System.Windows.WindowState.Normal;
WindowMaximize();
}
if (MainPanel.Children != null && MainPanel.Children.Count > 0)
{
foreach(var child in MainPanel.Children)
{
if(child is SystemLoginPage)
{
(child as SystemLoginPage).Width = this.Width;
(child as SystemLoginPage).Height = this.Height - 50;
}
}
}
}
/// <summary>
/// 最大化
/// </summary>
private void WindowMaximize()
{
this.BorderThickness = new Thickness(0);
rcnormal = new Rect(this.Left, this.Top, this.Width, this.Height);//保存下当前位置与大小
this.Left = 0;//设置位置
this.Top = 0;
Rect rc = SystemParameters.WorkArea;//获取工作区大小
this.Width = rc.Width;
this.Height = rc.Height;
normalState = false;
}
/// <summary>
/// 还原
/// </summary>
private void WindowNormal(bool maxwindowDrag)
{
if (maxwindowDrag)
{
this.Left = 0;
this.Top = 0;
this.Width = rcnormal.Width;
this.Height = rcnormal.Height;
normalState = true;
this.BorderThickness = new Thickness(1);
if (Mouse.LeftButton == MouseButtonState.Pressed)
{
this.DragMove();
}
}
else
{
this.Left = rcnormal.Left;
this.Top = rcnormal.Top;
this.Width = rcnormal.Width;
this.Height = rcnormal.Height;
normalState = true;
this.BorderThickness = new Thickness(1);
}
}
private void Shutdown(object sender, MouseButtonEventArgs e)
{
if (MessageBox.Show("提醒", "您确定要退出吗?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
Application.Current.Shutdown();
}
}
private void MinimizWindow(object sender, MouseButtonEventArgs e)
{
this.WindowState = WindowState.Minimized;
}
private void ChangeWindowState(object sender, MouseButtonEventArgs e)
{
if (!normalState)
{
WindowNormal(false);
Mypoint = this.PointToScreen(new Point());
Mysize = new Size(this.Width, this.Height);
}
else
{
WindowMaximize();
Mypoint = this.PointToScreen(new Point());
Mysize = new Size(this.Width, this.Height);
}
}
private DateTime? LastMouseDownTimeInHeaderBar { get; set; }
private void DragWindow(object sender, MouseButtonEventArgs e)
{
if (LastMouseDownTimeInHeaderBar != null && (DateTime.Now - LastMouseDownTimeInHeaderBar) < TimeSpan.FromSeconds(0.3))
{
if (!normalState)
{
WindowNormal(false);
Mypoint = this.PointToScreen(new Point());
Mysize = new Size(this.Width, this.Height);
}
else
{
WindowMaximize();
Mypoint = this.PointToScreen(new Point());
Mysize = new Size(this.Width, this.Height);
}
return;
}
else
{
LastMouseDownTimeInHeaderBar = DateTime.Now;
}
if (e.LeftButton == MouseButtonState.Pressed)
{
if (normalState)//原大情况下是拖拽
{
this.DragMove();
Mypoint = this.PointToScreen(new Point());
Mysize = new Size(this.Width, this.Height);
}
else //最大化时先缩小 再拖拽
{
//p1 = Mouse.GetPosition(e.Source as FrameworkElement);
dragTimer.Interval = TimeSpan.FromMilliseconds(50);
dragTimer.Tick += DragTimer_Tick;
dragTimer.Start();
}
}
}
private void DragTimer_Tick(object sender, EventArgs e)
{
if (Mouse.LeftButton == MouseButtonState.Pressed)
{
WindowNormal(true);
Mypoint = this.PointToScreen(new Point());
Mysize = new Size(this.Width, this.Height);
}
dragTimer.Stop();
}
DispatcherTimer dragTimer = new DispatcherTimer();
#endregion
private void HideChildNode(object sender, MouseEventArgs e)
{
}
private void StackPanelShowScorBar(object sender, SizeChangedEventArgs e)
{
}
private void Border_MouseEnter(object sender, MouseEventArgs e)
{
}
private void Border_MouseLeave(object sender, MouseEventArgs e)
{
}
private void NailChildNodes(object sender, MouseButtonEventArgs e)
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
public Board board;
public FigureManager figureManager;
// Start is called before the first frame update
void Start()
{
board.Create();
figureManager.Setup(board);
}
}
|
namespace Session07.Es.CM.ApplicationServices.Customers.Dtoes
{
public class CustomerDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string CustomerId { get; set; }
public AddressDto Address { get; set; }
}
}
|
using EngageNet.Data;
using NUnit.Framework;
namespace EngageNet.Tests.Data
{
[TestFixture]
public class AddressTests
{
#region Setup/Teardown
[SetUp]
public void TestSetup()
{
_address = new Address();
}
#endregion
private Address _address;
[Test]
public void CanPopulateCountryProperty()
{
Assert.IsNull(_address.Country);
_address.AddProperty("country", "test");
Assert.AreEqual("test", _address.Country);
}
[Test]
public void CanPopulateFormattedProperty()
{
Assert.IsNull(_address.Formatted);
_address.AddProperty("formatted", "test");
Assert.AreEqual("test", _address.Formatted);
}
[Test]
public void CanPopulateLocalityProperty()
{
Assert.IsNull(_address.Locality);
_address.AddProperty("locality", "test");
Assert.AreEqual("test", _address.Locality);
}
[Test]
public void CanPopulatePostalCodeProperty()
{
Assert.IsNull(_address.PostalCode);
_address.AddProperty("postalCode", "test");
Assert.AreEqual("test", _address.PostalCode);
}
[Test]
public void CanPopulateRegionProperty()
{
Assert.IsNull(_address.Region);
_address.AddProperty("region", "test");
Assert.AreEqual("test", _address.Region);
}
[Test]
public void CanPopulateStreetAddressProperty()
{
Assert.IsNull(_address.StreetAddress);
_address.AddProperty("streetAddress", "test");
Assert.AreEqual("test", _address.StreetAddress);
}
}
} |
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Ask : Scenario {
/*void Start()
{
this.gameObject.transform.localScale = new Vector3 (0.1f, 0.01f);
}*/
public IEnumerator Anim(float finalSize, string text)
{
if (this.gameObject != null)
{
this.gameObject.transform.localScale = new Vector3 (0.1f, 0.01f);
while (Mathf.Abs(this.gameObject.transform.localScale.y) <= Mathf.Abs(finalSize))
{
this.gameObject.transform.localScale += new Vector3 (finalSize / Mathf.Abs (finalSize) * 0.1f, 0.1f, 0f);
yield return null;
}
GameObject dialog = GameObject.FindGameObjectWithTag("Top");
dialog.gameObject.GetComponent<Text>().text = text;
}
}
public override void Put ()
{
base.Put ();
sc.sortingLayerName = "Game";
sc.sortingOrder = 30;
this.tag = "Dog";
this.gameObject.transform.localScale = new Vector3 (0.1f, 0.01f);
this.imageSize = sc.bounds.size;
GameObject dialog = GameObject.FindGameObjectWithTag ("Top");
Instantiate (this, new Vector3 (Camera.main.transform.position.x, Camera.main.transform.position.y + Camara.delayCamY - 1.5f), Quaternion.identity);
}
}
|
using Newtonsoft.Json;
namespace ReceptiAPI.DTO
{
public class NamirnicaDTO
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "naziv")]
public string Naziv { get; set; }
[JsonProperty(PropertyName = "opis")]
public string Opis { get; set; }
[JsonProperty(PropertyName = "kategorija")]
public string Kategorija { get; set; }
[JsonProperty(PropertyName = "kalorije")]
public decimal Kalorije { get; set; }
[JsonProperty(PropertyName = "proteini")]
public decimal Proteini { get; set; }
[JsonProperty(PropertyName = "masti")]
public decimal Masti { get; set; }
[JsonProperty(PropertyName = "zasiceneMasti")]
public decimal ZasiceneMasti { get; set; }
[JsonProperty(PropertyName = "seceri")]
public decimal Seceri { get; set; }
[JsonProperty(PropertyName = "vlakna")]
public decimal Vlakna { get; set; }
}
}
|
using UnityEngine;
namespace Models
{
public class FieldModelDefault : FieldModel
{
private static int _fieldCtr = 1;
public FieldModelDefault()
{
var gs = GameModel.Instance.GameSettings;
Name = string.Format("Field {0}", _fieldCtr++);
Size = new Vector2Int(20, 20);
TargetHealth = gs.TargetHealth;
for (var i = 0; i < gs.NumberOfWaves; ++i)
{
Waves.Add(new WaveModelDefault());
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _5.DependencyInversionPrinciple.Repository
{
public interface ICustomerRepository
{
void SaveToDb(object objCustomer);
}
}
|
// Copyright (c) Erik Mavrinac, https://github.com/erikma. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
namespace OptimizedStrings
{
/// <summary>
/// Implements case sensitive and insensitive comparer logic for SpanStrings.
/// </summary>
public class SpanStringComparer :
IEqualityComparer<ISpanString>,
IEqualityComparer<SpanString1>,
IEqualityComparer<SpanString2>
{
private readonly bool _ignoreCase;
private SpanStringComparer(bool ignoreCase)
{
_ignoreCase = ignoreCase;
}
/// <summary>
/// Gets a SpanStringComparer instance that performs ordinal character comparisons.
/// </summary>
public static SpanStringComparer Ordinal { get; } = new SpanStringComparer(false);
/// <summary>
/// Gets a SpanStringComparer instance that performs case-insensitive ordinal character comparisons.
/// </summary>
public static SpanStringComparer OrdinalIgnoreCase { get; } = new SpanStringComparer(true);
/// <summary>
/// Compares two strings.
/// </summary>
/// <param name="a">The first string to compare.</param>
/// <param name="b">The second string to compare.</param>
/// <returns>True if the strings are equal.</returns>
public bool Equals(SpanString1 a, SpanString1 b)
{
return _ignoreCase ? SpanString1.EqualsIgnoreCase(a, b) : a.Equals(b);
}
/// <summary>
/// Compares two strings.
/// </summary>
/// <param name="a">The first string to compare.</param>
/// <param name="b">The second string to compare.</param>
/// <returns>True if the strings are equal.</returns>
public bool Equals(SpanString2 a, SpanString2 b)
{
return _ignoreCase ? SpanString2.EqualsIgnoreCase(a, b) : a.Equals(b);
}
/// <summary>
/// Compares two strings.
/// </summary>
/// <param name="a">The first string to compare.</param>
/// <param name="b">The second string to compare.</param>
/// <returns>True if the strings are equal.</returns>
public bool Equals(ISpanString a, ISpanString b)
{
// Find optimized comparison methods.
if (a is SpanString1 a1)
{
if (b is SpanString1 b1)
{
return _ignoreCase ? SpanString1.EqualsIgnoreCase(a1, b1) : SpanString1.Equals(a1, b1);
}
if (b is SpanString2 b2)
{
return _ignoreCase ? SpanString1.EqualsIgnoreCase(a1, b2) : SpanString1.Equals(a1, b2);
}
throw new ArgumentException($"Second param 'b' is an unknown SpanString type '{b.GetType().Name}', is this a bug?");
}
if (a is SpanString2 a2)
{
if (b is SpanString1 b1)
{
return _ignoreCase ? SpanString2.EqualsIgnoreCase(a2, b1) : SpanString2.Equals(a2, b1);
}
if (b is SpanString2 b2)
{
return _ignoreCase ? SpanString2.EqualsIgnoreCase(a2, b2) : SpanString2.Equals(a2, b2);
}
throw new ArgumentException($"Second param 'b' is an unknown SpanString type '{b.GetType().Name}', is this a bug?");
}
throw new ArgumentException($"First param 'a' is an unknown SpanString type '{a.GetType().Name}', is this a bug?");
}
/// <summary>
/// Gets a hash code for a SpanString. If strings A and B are such that A.Equals(B), then
/// they will return the same hash code.
/// </summary>
public int GetHashCode(ISpanString s)
{
if (!_ignoreCase)
{
return s.GetHashCode();
}
return s.GetHashCodeIgnoreCase();
}
/// <summary>
/// Gets a hash code for a SpanString. If strings A and B are such that A.Equals(B), then
/// they will return the same hash code.
/// </summary>
public int GetHashCode(SpanString1 s)
{
if (!_ignoreCase)
{
return s.GetHashCode();
}
return s.GetHashCodeIgnoreCase();
}
/// <summary>
/// Gets a hash code for a SpanString. If strings A and B are such that A.Equals(B), then
/// they will return the same hash code.
/// </summary>
public int GetHashCode(SpanString2 s)
{
if (!_ignoreCase)
{
return s.GetHashCode();
}
return s.GetHashCodeIgnoreCase();
}
internal static char ToUpperAscii(char c)
{
// Adapted from https://referencesource.microsoft.com/#mscorlib/system/string.cs EqualsIgnoreCaseAsciiHelper()
// TODO: We need to get the slow-path case-insensitive compare logic from
// .NET Framework's native code comnlsinfo.cpp InternalCompareStringOrdinalIgnoreCase()
if ((uint)((c | 0x20) - 'a') <= (uint)('z' - 'a'))
{
return (char)(c & ~0x20);
}
return c;
}
internal static int ToUpperAscii(int c)
{
// Adapted from https://referencesource.microsoft.com/#mscorlib/system/string.cs EqualsIgnoreCaseAsciiHelper()
// TODO: We need to get the slow-path case-insensitive compare logic from
// .NET Framework's native code comnlsinfo.cpp InternalCompareStringOrdinalIgnoreCase()
if ((uint)((c | 0x20) - 'a') <= (uint)('z' - 'a'))
{
return c & ~0x20;
}
return c;
}
internal static bool CharsEqualOrdinalIgnoreCase(char a, char b)
{
// Adapted from https://referencesource.microsoft.com/#mscorlib/system/string.cs EqualsIgnoreCaseAsciiHelper()
// TODO: We need to get the slow-path case-insensitive compare logic from
// .NET Framework's native code comnlsinfo.cpp InternalCompareStringOrdinalIgnoreCase()
// Ordinal equals or lowercase equals if the result ends up in the a-z range
if (a == b)
{
return true;
}
return (a | 0x20) == (b | 0x20) &&
(uint)((a | 0x20) - 'a') <= (uint)('z' - 'a');
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ISE.UILibrary;
using ISE.ClassLibrary;
using ISE.SM.Common.DTO;
using ISE.SM.Client.Common.Presenter;
using ISE.Framework.Utility.Utils;
namespace ISE.SM.Client.UCEntry
{
public partial class UCRoleEntry : IUserControl
{
public UCRoleEntry()
{
tmode = TransMode.NewRecord;
InitializeComponent();
LoadAppDomains();
}
TransMode tmode;
public RoleDto NewRoleDto { get; set; }
public DialogResult DialogResult { get; set; }
public UCRoleEntry(TransMode tmode, RoleDto role)
{
this.tmode = tmode;
InitializeComponent();
NewRoleDto = role;
LoadAppDomains();
if (tmode == TransMode.EditRecord || tmode == TransMode.ViewRecord)
{
NewRoleDto = role;
this.txtDisplayName.Text = role.CondidateRoleName;
this.txtGroupName.Text = role.RoleName;
this.chkEnabled.Checked = role.IsEnabled;
if (role.AppDomainId != null)
this.cmbDomain.SelectedValue = role.AppDomainId;
else
{
this.cmbDomain.SelectedIndex = -1;
}
if (tmode == TransMode.ViewRecord)
{
this.txtDisplayName.ReadOnly = true;
this.txtGroupName.ReadOnly = true;
this.chkEnabled.Enabled = false;
this.cmbDomain.Enabled = false;
}
}
}
public void LoadAppDomains()
{
AppDomainPresenter appDomainPresenter = new AppDomainPresenter();
var lst = appDomainPresenter.GetAppDomainList();
cmbDomain.DataSource = lst;
cmbDomain.DisplayMember = AssemblyReflector.GetMemberName((ApplicationDomainDto m) => m.Title);
cmbDomain.ValueMember = AssemblyReflector.GetMemberName((ApplicationDomainDto m) => m.ApplicationDomainId);
}
private void iTransToolBar1_SaveRecord(object sender, EventArgs e)
{
short enabled = 0;
if (chkEnabled.Checked)
{
enabled = 1;
}
if (tmode == TransMode.NewRecord)
{
RoleDto group = new RoleDto()
{
CondidateRoleName = txtDisplayName.Text,
Enabled = enabled,
RoleName = txtGroupName.Text,
};
if (this.cmbDomain.SelectedValue != null)
{
group.AppDomainId = (int)this.cmbDomain.SelectedValue;
}
NewRoleDto = group;
}
else if (tmode == TransMode.EditRecord)
{
if (NewRoleDto != null)
{
if (this.cmbDomain.SelectedValue != null)
{
NewRoleDto.AppDomainId = (int)this.cmbDomain.SelectedValue;
}
NewRoleDto.ApplicationDomainDto = (ApplicationDomainDto)cmbDomain.SelectedItem;
NewRoleDto.Enabled = enabled;
NewRoleDto.RoleName = txtGroupName.Text;
NewRoleDto.CondidateRoleName = txtDisplayName.Text;
}
}
DialogResult = System.Windows.Forms.DialogResult.OK;
this.ParentForm.Close();
}
private void iTransToolBar1_Close(object sender, EventArgs e)
{
this.ParentForm.Close();
}
private void iTransToolBar1_SaveAndNewRecord(object sender, EventArgs e)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TinhLuong.Models;
using TinhLuongBLL;
using TinhLuongINFO;
namespace TinhLuong.Controllers
{
public class TinhLuongBS_Ver1Controller : BaseController
{
// GET: TinhLuongBS_Ver1
[CheckCredential(RoleID = "TINH_LUONGBOSUNG")]
public ActionResult Index()
{
drpNam(DateTime.Now.Year.ToString());
drpThang(DateTime.Now.Month.ToString());
drpNam1(DateTime.Now.Year.ToString());
return View();
}
public void drpThang(string selected = null)
{
List<SelectListItem> listItems = new List<SelectListItem>();
listItems.Add(new SelectListItem
{
Text = "1",
Value = "1"
});
listItems.Add(new SelectListItem
{
Text = "2",
Value = "2",
});
listItems.Add(new SelectListItem
{
Text = "3",
Value = "3"
});
listItems.Add(new SelectListItem
{
Text = "4",
Value = "4"
});
listItems.Add(new SelectListItem
{
Text = "5",
Value = "5"
});
listItems.Add(new SelectListItem
{
Text = "6",
Value = "6"
});
listItems.Add(new SelectListItem
{
Text = "7",
Value = "7"
});
listItems.Add(new SelectListItem
{
Text = "8",
Value = "8"
});
listItems.Add(new SelectListItem
{
Text = "9",
Value = "9"
});
listItems.Add(new SelectListItem
{
Text = "10",
Value = "10"
});
listItems.Add(new SelectListItem
{
Text = "11",
Value = "11"
});
listItems.Add(new SelectListItem
{
Text = "12",
Value = "12"
});
ViewBag.drpThang = new SelectList(listItems, "Value", "Text", selected);
}
public void drpNam(string selected = null)
{
List<SelectListItem> listItems = new List<SelectListItem>();
listItems.Add(new SelectListItem
{
Text = (DateTime.Now.Year).ToString(),
Value = (DateTime.Now.Year).ToString()
});
listItems.Add(new SelectListItem
{
Text = (DateTime.Now.Year - 1).ToString(),
Value = (DateTime.Now.Year - 1).ToString()
});
ViewBag.drpNam = new SelectList(listItems, "Value", "Text", selected);
}
public void drpNam1(string selected = null)
{
List<SelectListItem> listItems = new List<SelectListItem>();
listItems.Add(new SelectListItem
{
Text = (DateTime.Now.Year).ToString(),
Value = (DateTime.Now.Year).ToString()
});
listItems.Add(new SelectListItem
{
Text = (DateTime.Now.Year - 1).ToString(),
Value = (DateTime.Now.Year - 1).ToString()
});
ViewBag.drpNam1 = new SelectList(listItems, "Value", "Text", selected);
}
[CheckCredential(RoleID = "TINH_LUONGBOSUNG")]
public ActionResult TinhLuong(decimal drpThang, decimal drpNam, string DienGiai, decimal drpNam1, DateTime NgayCK)
{
//Session.Add(SessionCommon.Thang, quy);
//Session.Add(SessionCommon.nam, nam);
string ngayck = NgayCK.Day+"/"+NgayCK.Month +"/" + NgayCK.Year;
var rs = new TinhLuongBoSungQuyBLL().TinhLuongBoSung(drpNam,DienGiai,ngayck,drpThang,drpNam1,Session[SessionCommon.Username].ToString());
if (rs)
{
setAlert("Tính toán dữ liệu thành công!", "success");
return Redirect("/TinhLuongBS_Ver1");
}
else
{
setAlert("Cập nhật thất bại", "error");
return Redirect("/TinhLuongBS_Ver1");
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace GreenValleyAuctionsSystems
{
public partial class Appraisal : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblValid.Visible = false;
String sqlQuery = "SELECT CUSTOMER.firstName, CUSTOMER.lastName, CUSTOMER.emailAddress, CUSTOMER.phoneNumber, " +
"CUSTOMER.streetAddress + ' ' + CUSTOMER.city + ', ' + CUSTOMER.state + ' ' + CUSTOMER.zipcode AS CustomerAddress, " +
"CUSTOMER.initialContact FROM dbo.CUSTOMER";
//sqlQuery += " WHERE CUSTOMER.customerID = SERVICETICKET.customerID AND SERVICETICKET.serviceID = SERVICE.serviceID AND SERVICE.serviceID = '" + Session["serviceID"].ToString() + "'";
//calls method to connect database and returns query results
DataSet customerDS = sqlConnection(sqlQuery);
//puts each attribute from query into respective variable
String fName = customerDS.Tables[0].Rows[0][0].ToString();
String lName = customerDS.Tables[0].Rows[0][1].ToString();
String email = customerDS.Tables[0].Rows[0][2].ToString();
String phone = customerDS.Tables[0].Rows[0][3].ToString();
String address = customerDS.Tables[0].Rows[0][4].ToString();
String contact = customerDS.Tables[0].Rows[0][5].ToString();
////displays customer information
//lblFirstName.Text = "First Name: " + fName;
//lblLastName.Text = "Last Name: " + lName;
//lblEmail.Text = "Email: " + email;
//lblPhone.Text = "Phone Number: " + phone;
//lblAddress.Text = "Address: " + address;
//lblInitalContact.Text = "Initial Contact: " + contact;
Session["CustEmail"] = email;
}
protected DataSet sqlConnection(String sqlQuery)
{
//creates connection object with the database
SqlConnection sqlConnect = new SqlConnection("Server=greenvalleyauctions.cn5mwe8nhtvg.us-east-1.rds.amazonaws.com;Database=Lab4;uid=DukeDevs;password=Capstone1!;Trusted_Connection=Yes;Integrated Security=false;");
//create sql command object and send query
SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlQuery, sqlConnect);
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnect;
sqlCommand.CommandType = CommandType.Text;
sqlCommand.CommandText = sqlQuery;
sqlConnect.Open();
//data set to hold the max id
DataSet inventoryDS = new DataSet();
sqlAdapter.Fill(inventoryDS);
return inventoryDS;
}
protected int getCustomerID()
{
String customerIDQuery = "Select customerID from CUSTOMER WHERE emailAddress = '" + Session["CustEmail"].ToString() + "'";
string custID = "";
int customerID;
SqlConnection sqlConnect1 = new SqlConnection(WebConfigurationManager.ConnectionStrings["Lab4"].ConnectionString);
SqlCommand getCustomerIDCommand = new SqlCommand();
getCustomerIDCommand.CommandType = CommandType.Text;
getCustomerIDCommand.CommandText = customerIDQuery;
getCustomerIDCommand.Connection = sqlConnect1;
sqlConnect1.Open();
SqlDataReader getCustomerIDReader = getCustomerIDCommand.ExecuteReader();
while (getCustomerIDReader.Read())
{
custID = getCustomerIDReader["customerID"].ToString();
}
customerID = Int32.Parse(custID);
//txtbxMoveDeadlineDate.Text = deadlineDate;
sqlConnect1.Close();
sqlConnect1.Dispose();
return customerID;
}
protected void CreateService()
{
int customerID = getCustomerID();
System.Data.SqlClient.SqlCommand cServ = new System.Data.SqlClient.SqlCommand();
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["Lab4"].ConnectionString);
con.Open();
cServ.Connection = con;
cServ.CommandText = "INSERT INTO SERVICE(serviceName, serviceStatus, customerID) VALUES (@ServiceName, @ServiceStatus, @CustomerID)";
cServ.Parameters.Add(new SqlParameter("@ServiceName", "Appraisal"));
cServ.Parameters.Add(new SqlParameter("@ServiceStatus", "New Service"));
cServ.Parameters.Add(new SqlParameter("@CustomerID", customerID));
cServ.ExecuteNonQuery();
con.Close();
}
protected int getServiceID()
{
String customerIDQuery = "Select MAX(serviceID) from Service";
string servID = "";
int serviceID;
SqlConnection sqlConnect1 = new SqlConnection(WebConfigurationManager.ConnectionStrings["Lab4"].ConnectionString);
SqlCommand getCustomerIDCommand = new SqlCommand();
getCustomerIDCommand.CommandType = CommandType.Text;
getCustomerIDCommand.CommandText = customerIDQuery;
getCustomerIDCommand.Connection = sqlConnect1;
sqlConnect1.Open();
SqlDataReader getServiceIDReader = getCustomerIDCommand.ExecuteReader();
while (getServiceIDReader.Read())
{
servID = getServiceIDReader[""].ToString();
}
serviceID = Int32.Parse(servID);
sqlConnect1.Close();
sqlConnect1.Dispose();
return serviceID;
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (textSize.Text != "" & textInv.Text != "" & typeList.Text != "" & date.Text != "")
{
CreateService();
int serviceID = getServiceID();
string size = HttpUtility.HtmlEncode(textSize.Text);
string inv = HttpUtility.HtmlEncode(textInv.Text);
System.Data.SqlClient.SqlCommand subApp = new System.Data.SqlClient.SqlCommand();
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["Lab4"].ConnectionString);
con.Open();
subApp.Connection = con;
subApp.CommandText = "INSERT INTO [dbo].[APPRAISAL] (purpose, deadline, size, inventory, serviceID) VALUES (@Purpose, @Deadline, @Size, @Inventory, @ServiceID)";
subApp.Parameters.Add(new SqlParameter("@Purpose", typeList.Text));
subApp.Parameters.Add(new SqlParameter("@Deadline", date.Text));
subApp.Parameters.Add(new SqlParameter("@Size", size));
subApp.Parameters.Add(new SqlParameter("@Inventory", inv));
subApp.Parameters.Add(new SqlParameter("@ServiceID", serviceID));
subApp.ExecuteNonQuery();
con.Close();
lblValid.ForeColor = System.Drawing.Color.Green;
lblValid.Font.Bold = true;
lblValid.Visible = true;
lblValid.Text = "Appraisal Submitted!";
}
else
{
lblValid.ForeColor = System.Drawing.Color.Red;
lblValid.Font.Bold = true;
lblValid.Visible = true;
lblValid.Text = "Please fill out all information.";
}
}
protected void EstateBut_CheckedChanged(object sender, EventArgs e)
{
}
protected void FamilyBut_CheckedChanged(object sender, EventArgs e)
{
}
protected void btnInitialContactForm_Click(object sender, EventArgs e)
{
Response.Redirect("NewCustomer.aspx");
}
protected void btnAuctionServiceOrder_Click(object sender, EventArgs e)
{
Response.Redirect("AuctionSchedulingForm.aspx");
}
protected void btnAuctionAssessmentForm_Click(object sender, EventArgs e)
{
//Change this when form is created
Response.Redirect("EmployeeDashboard.aspx");
}
protected void btnAppraisalServiceOrderForm_Click(object sender, EventArgs e)
{
//change this when form is created
Response.Redirect("Appraisal.aspx");
}
protected void btnMoveAssessmentForm_Click(object sender, EventArgs e)
{
Response.Redirect("MoveForm.aspx");
}
protected void btnMoveServiceOrder_Click(object sender, EventArgs e)
{
Response.Redirect("MoveSchedulingScreen.aspx");
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("CustomerFile.aspx");
}
protected void btnSubmitNote_Click(object sender, EventArgs e)
{
String employeeID = GetEmployeeID();
System.Data.SqlClient.SqlConnection sc = new SqlConnection(WebConfigurationManager.ConnectionStrings["Lab4"].ConnectionString.ToString());
sc.Open();
System.Data.SqlClient.SqlCommand addNote = new System.Data.SqlClient.SqlCommand();
addNote.Connection = sc;
// INSERT INTO Note TABLE
addNote.CommandText = "INSERT INTO dbo.EMPLOYEENOTE (noteTitle, noteBody, employeeID, serviceID) VALUES(@noteTitle, @noteBody, @employeeID, @serviceID)";
addNote.Parameters.Add(new SqlParameter("@noteTitle", HttpUtility.HtmlEncode(txtTitle.Text)));
addNote.Parameters.Add(new SqlParameter("@noteBody", HttpUtility.HtmlEncode(txtBody.Text)));
addNote.Parameters.Add(new SqlParameter("@employeeID", employeeID));
addNote.Parameters.Add(new SqlParameter("@serviceID", Session["serviceID"]));
addNote.ExecuteNonQuery();
sc.Close();
Response.Redirect("Appraisal.aspx");
}
//method to find the employee id
protected String GetEmployeeID()
{
try
{
String sqlQuery = "SELECT EMPLOYEE.employeeID FROM dbo.EMPLOYEE WHERE EMPLOYEE.emailAddress = '" + Session["Username"].ToString() + "'";
//will hold the ID from query
String employeeID = "";
DataTable employeeDS = sqlConnection2(sqlQuery);
employeeID = employeeDS.Rows[0][0].ToString();
int newIDNum = int.Parse(employeeID);
string newID = newIDNum.ToString();
return newID;
}
catch
{
return null;
}
}
protected DataTable sqlConnection2(String sqlQuery)
{
try
{
//creates connection object with the database
SqlConnection sqlConnect = new SqlConnection("Server=greenvalleyauctions.cn5mwe8nhtvg.us-east-1.rds.amazonaws.com;Database=Lab4;uid=DukeDevs;password=Capstone1!;Trusted_Connection=Yes;Integrated Security=false;");
//create sql command object and send query
SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlQuery, sqlConnect);
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnect;
sqlCommand.CommandType = CommandType.Text;
sqlCommand.CommandText = sqlQuery;
sqlConnect.Open();
//data set to hold the max id
DataTable inventoryDS = new DataTable();
sqlAdapter.Fill(inventoryDS);
return inventoryDS;
}
catch
{
return null;
}
}
protected void btnSubmitToDo_Click(object sender, EventArgs e)
{
String user = GetEmployeeID();
string taskTitle = HttpUtility.HtmlEncode(txtbxToDoItem.Text);
string taskBody = HttpUtility.HtmlEncode(txtbxToDoDescription.Text);
System.Data.SqlClient.SqlCommand saveNote = new System.Data.SqlClient.SqlCommand();
System.Data.SqlClient.SqlCommand getAuth = new System.Data.SqlClient.SqlCommand();
SqlConnection con2 = new SqlConnection(WebConfigurationManager.ConnectionStrings["Lab4"].ConnectionString);
SqlConnection con3 = new SqlConnection(WebConfigurationManager.ConnectionStrings["AUTH"].ConnectionString);
con3.Open();
con2.Open();
saveNote.Connection = con2;
saveNote.CommandText = "INSERT INTO [dbo].[TODO] (taskTitle, taskBody, startDate, endDate, urgency, employeeID, complete) VALUES(@TaskTitle, @TaskBody, GETDATE(), @EndDate, @Urgency, @EmployeeID, @Complete)";
saveNote.Parameters.Add(new SqlParameter("@TaskTitle", taskTitle));
saveNote.Parameters.Add(new SqlParameter("@TaskBody", taskBody));
//saveNote.Parameters.Add(new SqlParameter("@startDate", lblsDate.Text));
saveNote.Parameters.Add(new SqlParameter("@EndDate", todoDeadlineDate.Text));
saveNote.Parameters.Add(new SqlParameter("@Complete", HttpUtility.HtmlEncode('0')));
int status = 0;
if (rblUrgent.SelectedValue.Equals("Urgent"))
{
status = 0;
}
if (rblUrgent.SelectedValue.Equals("Very Urgent"))
{
status = 1;
}
saveNote.Parameters.Add(new SqlParameter("@Urgency", status));
saveNote.Parameters.Add(new SqlParameter("@EmployeeID", user));
saveNote.ExecuteNonQuery();
con2.Close();
Response.Redirect("EmployeeDashboard.aspx");
}
}
}
|
using System.Threading.Tasks;
using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Contexts;
using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Results.AllowSync;
using OrchardCore.ContentManagement;
namespace DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Items
{
public interface IContentItemGraphSyncer
{
int Priority { get; }
bool CanSync(ContentItem contentItem);
Task AllowSync(IGraphMergeItemSyncContext context, IAllowSync allowSync);
Task AddSyncComponents(IGraphMergeItemSyncContext context);
Task AllowDelete(IGraphDeleteItemSyncContext context, IAllowSync allowSync);
Task DeleteComponents(IGraphDeleteItemSyncContext context);
Task MutateOnClone(ICloneItemSyncContext context);
Task AddRelationship(IDescribeRelationshipsItemSyncContext context);
Task<(bool validated, string failureReason)> ValidateSyncComponent(IValidateAndRepairItemSyncContext context);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CellphoneAdStore
{
public partial class Site1 : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (Session["role"].Equals(" "))
{
LinkButton6.Visible = true; //admin login btton visibility
LinkButton3.Visible = false; //logout btton visibility
LinkButton11.Visible = false; //brand management btton visibility
LinkButton12.Visible = false; //model management visibility
LinkButton8.Visible = false; //addcell btton visibility
}
else if (Session["role"].Equals("admin"))
{
LinkButton6.Visible = false; //admin login btton visibility
LinkButton3.Visible = true; //logout btton visibility
LinkButton11.Visible = true; //brand management btton visibility
LinkButton12.Visible = true; //model management visibility
LinkButton8.Visible = true; //addcell btton visibility
}
}
catch(Exception ex)
{
}
}
protected void LinkButton6_Click(object sender, EventArgs e)
{
Response.Redirect("AdminLogin.aspx");
}
protected void LinkButton11_Click(object sender, EventArgs e)
{
Response.Redirect("phonebrand.aspx");
}
protected void LinkButton12_Click(object sender, EventArgs e)
{
Response.Redirect("phonemodel.aspx");
}
protected void LinkButton8_Click(object sender, EventArgs e)
{
Response.Redirect("cellphoneadd.aspx");
}
protected void LinkButton21_Click(object sender, EventArgs e)
{
Response.Redirect("AdminLogin.aspx");
}
protected void LinkButton22_Click(object sender, EventArgs e)
{
Response.Redirect("view_cellphones.aspx");
}
protected void LinkButton3_Click(object sender, EventArgs e)
{
Session["username"] = "";
Session["fullname"] = "";
Session["role"] = "";
Session["status"] = "";
LinkButton6.Visible = true; //admin login btton visibility
LinkButton3.Visible = false; //logout btton visibility
LinkButton11.Visible = false; //brand management btton visibility
LinkButton12.Visible = false; //model management visibility
LinkButton8.Visible = false; //addcell btton visibility
Response.Redirect("index.aspx");
}
protected void LinkButton99_Click(object sender, EventArgs e)
{
Response.Redirect("view_cellphones.aspx");
}
}
} |
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using CIPMSBC;
//added by sreevani for closed federations.
public partial class Enrollment_ClosedFedRedirection : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["FedId"] != null)
{
if (Session["FedId"].ToString() == "24")
{
pnlColumbusRedirect.Visible = true;
pnlPalmBeachRedirect.Visible = false;
pnlMiamiRedirect.Visible = false;
pnlIndianapolis.Visible = false;
}
else if (Session["FedId"].ToString() == "39")
{
pnlColumbusRedirect.Visible = false;
pnlPalmBeachRedirect.Visible = true;
pnlMiamiRedirect.Visible = false;
pnlIndianapolis.Visible = false;
btnNext.Visible = true;
btnPrevious.Visible = true;
pnlWashingtonRedirect.Visible = false;
btnSaveandExit.Visible = true;
}
else if (Session["FedId"].ToString() == "49")
{
pnlWashingtonRedirect.Visible = true;
pnlColumbusRedirect.Visible = false;
pnlPalmBeachRedirect.Visible = false;
pnlMiamiRedirect.Visible = false;
pnlIndianapolis.Visible = false;
btnNext.Visible = true;
btnPrevious.Visible = true;
btnSaveandExit.Visible = true;
}
else if (Session["FedId"].ToString() == "40")
{
pnlColumbusRedirect.Visible = false;
pnlPalmBeachRedirect.Visible = false;
pnlMiamiRedirect.Visible = true;
pnlIndianapolis.Visible = false;
}
else if (Session["FedId"].ToString() == "12")
{
pnlColumbusRedirect.Visible = false;
pnlPalmBeachRedirect.Visible = false;
pnlMiamiRedirect.Visible = false;
pnlIndianapolis.Visible = true;
}
}
}
}
//added by sreevani for redirecting to miip or pjl or NL page
protected void RedirectToNextFed()
{
CamperApplication CamperAppl = new CamperApplication();
if (Session["FJCID"] != null)
{
string strFJCID = Session["FJCID"].ToString();
int nextfederationid;
Redirection_Logic _objRedirectionLogic = new Redirection_Logic();
_objRedirectionLogic.GetNextFederationDetails(strFJCID);
nextfederationid = _objRedirectionLogic.NextFederationId;
CamperAppl.UpdateFederationId(strFJCID, nextfederationid.ToString());
Session["FedId"] = nextfederationid.ToString();
if (nextfederationid == 48 || nextfederationid == 63)
Response.Redirect(_objRedirectionLogic.NextFederationURL);
else
Response.Redirect("Step1_NL.aspx");
}
}
protected void clickherelink_Click(object sender, EventArgs e)
{
RedirectToNextFed();
}
protected void clickherelink1_Click(object sender, EventArgs e)
{
RedirectToNextFed();
}
protected void clickheremiami_Click(object sender, EventArgs e)
{
RedirectToNextFed();
}
protected void clickhereIndiana_Click(object sender, EventArgs e)
{
RedirectToNextFed();
}
protected void btnPrevious_Click(object sender, EventArgs e)
{
Response.Redirect("Step1.aspx");
}
protected void btnReturnAdmin_Click(object sender, EventArgs e)
{
string strRedirURL;
try
{
strRedirURL = ConfigurationManager.AppSettings["AdminRedirURL"].ToString();
Response.Redirect(strRedirURL);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
protected void btnSaveandExit_Click(object sender, EventArgs e)
{
try
{
string strRedirURL;
strRedirURL = Master.SaveandExitURL;
if (Master.IsCamperUser == "Yes")
{
General oGen = new General();
if (oGen.IsApplicationSubmitted(Session["FJCID"].ToString()))
{
Response.Redirect(strRedirURL);
}
else
{
string strScript = "<script language=javascript>openThis(); window.location='" + strRedirURL + "';</script>";
if (!ClientScript.IsStartupScriptRegistered("clientScript"))
{
ClientScript.RegisterStartupScript(Page.GetType(), "clientScript", strScript);
}
}
}
else
{
Response.Redirect(strRedirURL);
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
protected void btnNext_Click(object sender, EventArgs e)
{
RedirectToNextFed();
//string url = (string)Session["nxtUrl"];
//Response.Redirect(url);
}
}
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Repository.Model;
using Repository.Service;
using System;
using UrlShortener.Model;
namespace UrlShortener.Controllers
{
[ApiController]
[Route("[controller]")]
public class UriController : ControllerBase
{
private readonly UriService _uriService;
public UriController(UriService uriService)
{
_uriService = uriService;
}
[HttpGet]
public string Get(string uriName)
{
Uri uriResult;
UriResultModel result = new UriResultModel();
bool isValidUri = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult);
result.IsValid = isValidUri;
if (result.IsValid)
{
UriModel model = _uriService.GetByUri(uriResult.AbsoluteUri);
if (model == null)
{
string tempId = Helper.Generator.GetNextId();
while (_uriService.GetByShortUri(tempId) != null)
tempId = Helper.Generator.GetNextId();
model = _uriService.Create(uriResult.AbsoluteUri, tempId);
}
result.Url = model.ShortUri;
}
return JsonConvert.SerializeObject(result);
}
}
}
|
using NUnit.Framework;
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;
using ReqresTestTask.Models;
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace ReqresTestTask
{
public class HttpResponse
{
public int StatusCode { get; set; }
public string ResponseBody { get; set; }
}
public class ReqresTestSettings
{
public int TestUserId { get; set; }
public string TestUserEmail { get; set; }
public string TestUserFirstName { get; set; }
public string TestUserLastName { get; set; }
public string TestUserAvatarUrl { get; set; }
public string TestUserPassword { get; set; }
public string TestUserLoginToken { get; set; }
}
public class Tests
{
static readonly HttpClient Client = new HttpClient();
public ReqresTestSettings settings = new ReqresTestSettings();
[SetUp]
public void Setup()
{
settings = JsonConvert.DeserializeObject<ReqresTestSettings>(File.ReadAllText("ReqresTestSettings.json"));
}
[Test]
public void TestGetUserList()
{
try
{
Task<HttpResponse> resp = GetHttpResponse("https://reqres.in/api/users");
HttpResponse result = resp.Result;
DefaultContractResolver contractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
UserList userList = JsonConvert.DeserializeObject<UserList>(result.ResponseBody, new JsonSerializerSettings{
ContractResolver = contractResolver,
Formatting = Formatting.Indented
});
Assert.AreEqual(200, result.StatusCode);
Assert.Greater(userList.Data.Count, 0);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void TestGetPageUserList()
{
try
{
Task<HttpResponse> resp = GetHttpResponse("https://reqres.in/api/users?page=2");
HttpResponse result = resp.Result;
DefaultContractResolver contractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
UserList userList = JsonConvert.DeserializeObject<UserList>(result.ResponseBody, new JsonSerializerSettings
{
ContractResolver = contractResolver,
Formatting = Formatting.Indented
});
Assert.AreEqual(200, result.StatusCode);
Assert.AreEqual(2, userList.Page);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void TestEmptyGetPageUserList()
{
try
{
Task<HttpResponse> resp = GetHttpResponse("https://reqres.in/api/users?page=4");
HttpResponse result = resp.Result;
DefaultContractResolver contractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
UserList userList = JsonConvert.DeserializeObject<UserList>(result.ResponseBody, new JsonSerializerSettings
{
ContractResolver = contractResolver,
Formatting = Formatting.Indented
});
Assert.AreEqual(200, result.StatusCode);
Assert.Zero(userList.Data.Count);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void TestUserListPerPage()
{
try
{
Task<HttpResponse> resp = GetHttpResponse("https://reqres.in/api/users?per_page=2");
HttpResponse result = resp.Result;
DefaultContractResolver contractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
UserList userList = JsonConvert.DeserializeObject<UserList>(result.ResponseBody, new JsonSerializerSettings
{
ContractResolver = contractResolver,
Formatting = Formatting.Indented
});
Assert.AreEqual(200, result.StatusCode);
Assert.AreEqual(2, userList.Data.Count);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void TestEmailUserDataFromUserList()
{
try
{
Task<HttpResponse> resp = GetHttpResponse("https://reqres.in/api/users?page=2");
HttpResponse result = resp.Result;
DefaultContractResolver contractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
UserList userList = JsonConvert.DeserializeObject<UserList>(result.ResponseBody, new JsonSerializerSettings
{
ContractResolver = contractResolver,
Formatting = Formatting.Indented
});
//Тут вычисляется индекс записи с нужным пользователем из секции data на основе Id пользователя, параметров из ответа page и per_page
int userIndexOnPage = settings.TestUserId - (userList.PerPage * (userList.Page - 1)) - 1;
Assert.AreEqual(200, result.StatusCode);
Assert.AreEqual(settings.TestUserEmail, userList.Data[userIndexOnPage].Email);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void TestIdUserDataFromUserList()
{
try
{
Task<HttpResponse> resp = GetHttpResponse("https://reqres.in/api/users?page=2");
HttpResponse result = resp.Result;
DefaultContractResolver contractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
UserList userList = JsonConvert.DeserializeObject<UserList>(result.ResponseBody, new JsonSerializerSettings
{
ContractResolver = contractResolver,
Formatting = Formatting.Indented
});
//Тут вычисляется индекс записи с нужным пользователем из секции data на основе Id пользователя, параметров из ответа page и per_page
int userIndexOnPage = settings.TestUserId - (userList.PerPage * (userList.Page - 1)) - 1;
Assert.AreEqual(200, result.StatusCode);
Assert.AreEqual(settings.TestUserId, userList.Data[userIndexOnPage].Id);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void TestFirstNameUserDataFromUserList()
{
try
{
Task<HttpResponse> resp = GetHttpResponse("https://reqres.in/api/users?page=2");
HttpResponse result = resp.Result;
DefaultContractResolver contractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
UserList userList = JsonConvert.DeserializeObject<UserList>(result.ResponseBody, new JsonSerializerSettings
{
ContractResolver = contractResolver,
Formatting = Formatting.Indented
});
//Тут вычисляется индекс записи с нужным пользователем из секции data на основе Id пользователя, параметров из ответа page и per_page
int userIndexOnPage = settings.TestUserId - (userList.PerPage * (userList.Page - 1)) - 1;
Assert.AreEqual(200, result.StatusCode);
Assert.AreEqual(settings.TestUserFirstName, userList.Data[userIndexOnPage].FirstName);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void TestLastNameUserDataFromUserList()
{
try
{
Task<HttpResponse> resp = GetHttpResponse("https://reqres.in/api/users?page=2");
HttpResponse result = resp.Result;
DefaultContractResolver contractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
UserList userList = JsonConvert.DeserializeObject<UserList>(result.ResponseBody, new JsonSerializerSettings
{
ContractResolver = contractResolver,
Formatting = Formatting.Indented
});
//Тут вычисляется индекс записи с нужным пользователем из секции data на основе Id пользователя, параметров из ответа page и per_page
int userIndexOnPage = settings.TestUserId - (userList.PerPage * (userList.Page - 1)) - 1;
Assert.AreEqual(200, result.StatusCode);
Assert.AreEqual(settings.TestUserLastName, userList.Data[userIndexOnPage].LastName);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void TestAvatarNameUserDataFromUserList()
{
try
{
Task<HttpResponse> resp = GetHttpResponse("https://reqres.in/api/users?page=2");
HttpResponse result = resp.Result;
DefaultContractResolver contractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
UserList userList = JsonConvert.DeserializeObject<UserList>(result.ResponseBody, new JsonSerializerSettings
{
ContractResolver = contractResolver,
Formatting = Formatting.Indented
});
//Тут вычисляется индекс записи с нужным пользователем из секции data на основе Id пользователя, параметров из ответа page и per_page
int userIndexOnPage = settings.TestUserId - (userList.PerPage * (userList.Page - 1)) - 1;
Assert.AreEqual(200, result.StatusCode);
Assert.AreEqual(settings.TestUserAvatarUrl, userList.Data[userIndexOnPage].Avatar);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void TestSuccessfulLogin()
{
DefaultContractResolver contractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
UserLogin userLogin = new UserLogin();
userLogin.Email = settings.TestUserEmail;
userLogin.Password = settings.TestUserPassword;
string json = JsonConvert.SerializeObject(userLogin, new JsonSerializerSettings
{
ContractResolver = contractResolver,
Formatting = Formatting.Indented
});
Task<HttpResponse> resp = PostHttpResponse("https://reqres.in/api/login", json);
HttpResponse result = resp.Result;
LoginToken loginToken = JsonConvert.DeserializeObject<LoginToken>(result.ResponseBody, new JsonSerializerSettings
{
ContractResolver = contractResolver,
Formatting = Formatting.Indented
});
Assert.AreEqual(200, result.StatusCode);
Assert.AreEqual(settings.TestUserLoginToken, loginToken.Token);
}
[Test]
public void TestUnsuccessfulLoginWithoutEmail()
{
DefaultContractResolver contractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
UserLogin userLogin = new UserLogin();
userLogin.Email = "";
userLogin.Password = settings.TestUserPassword;
string json = JsonConvert.SerializeObject(userLogin, new JsonSerializerSettings
{
ContractResolver = contractResolver,
Formatting = Formatting.Indented
});
Task<HttpResponse> resp = PostHttpResponse("https://reqres.in/api/login", json);
HttpResponse result = resp.Result;
LoginError loginError = JsonConvert.DeserializeObject<LoginError>(result.ResponseBody, new JsonSerializerSettings
{
ContractResolver = contractResolver,
Formatting = Formatting.Indented
});
Assert.AreEqual(400, result.StatusCode);
Assert.AreEqual("Missing email or username", loginError.Error);
}
[Test]
public void TestUnsuccessfulLoginWithoutPassword()
{
DefaultContractResolver contractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
UserLogin userLogin = new UserLogin();
userLogin.Email = settings.TestUserEmail;
userLogin.Password = "";
string json = JsonConvert.SerializeObject(userLogin, new JsonSerializerSettings
{
ContractResolver = contractResolver,
Formatting = Formatting.Indented
});
Task<HttpResponse> resp = PostHttpResponse("https://reqres.in/api/login", json);
HttpResponse result = resp.Result;
LoginError loginError = JsonConvert.DeserializeObject<LoginError>(result.ResponseBody, new JsonSerializerSettings
{
ContractResolver = contractResolver,
Formatting = Formatting.Indented
});
Assert.AreEqual(400, result.StatusCode);
Assert.AreEqual("Missing password", loginError.Error);
}
[Test]
public void TestUnsuccessfulLoginWithUncorrectEmail()
{
DefaultContractResolver contractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
UserLogin userLogin = new UserLogin();
userLogin.Email = "111111";
userLogin.Password = settings.TestUserPassword;
string json = JsonConvert.SerializeObject(userLogin, new JsonSerializerSettings
{
ContractResolver = contractResolver,
Formatting = Formatting.Indented
});
Task<HttpResponse> resp = PostHttpResponse("https://reqres.in/api/login", json);
HttpResponse result = resp.Result;
LoginError loginError = JsonConvert.DeserializeObject<LoginError>(result.ResponseBody, new JsonSerializerSettings
{
ContractResolver = contractResolver,
Formatting = Formatting.Indented
});
Assert.AreEqual(400, result.StatusCode);
Assert.AreEqual("user not found", loginError.Error);
}
public async Task<HttpResponse> GetHttpResponse(string url)
{
HttpResponse result = new HttpResponse();
HttpResponseMessage response = await Client.GetAsync(url);
result.StatusCode = (int)response.StatusCode;
result.ResponseBody = await response.Content.ReadAsStringAsync();
return result;
}
public async Task<HttpResponse> PostHttpResponse(string url, string data)
{
HttpResponse result = new HttpResponse();
var stringContent = new StringContent(data, System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage response = await Client.PostAsync(url, stringContent);
result.StatusCode = (int)response.StatusCode;
result.ResponseBody = await response.Content.ReadAsStringAsync();
return result;
}
}
} |
using Alabo.Domains.Entities;
using MongoDB.Bson.Serialization.Attributes;
using System.ComponentModel.DataAnnotations.Schema;
namespace Alabo.Cloud.Cms.Votes.Domain.Entities
{
/// <summary>
/// 投票
/// </summary>
[BsonIgnoreExtraElements]
[Table("Market_Vote")]
public class Vote : AggregateMongodbUserRoot<Vote>
{
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
}
} |
using System.Collections.Generic;
namespace System.Web.Helpers {
internal interface IWebGridDataSource {
int TotalRowCount { get; }
IList<GenericWebGridRow> GetRows(SortInfo sortInfo, int pageIndex);
}
}
|
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.ViewManagement;
using Windows.ApplicationModel.Core;
using Inventory.Views;
using Inventory.ViewModels;
using Linphone.Model;
using Linphone;
using System.Collections.Generic;
using System.Diagnostics;
using Windows.ApplicationModel.Resources;
namespace Inventory.Services
{
public class LinphoneManagerService : CallControllerListener
{
private Dictionary<TransportType, string> EnumToTransport;
private Dictionary<string, TransportType> TransportToEnum;
public bool acceptCall { get; set; }
public LinphoneManagerService()
{
EnumToTransport = new Dictionary<TransportType, string>()
{
{ TransportType.Udp, ResourceLoader.GetForCurrentView().GetString("TransportUDP") },
{ TransportType.Tcp, ResourceLoader.GetForCurrentView().GetString("TransportTCP") },
{ TransportType.Tls, ResourceLoader.GetForCurrentView().GetString("TransportTLS") }
};
TransportToEnum = new Dictionary<string, TransportType>()
{
{ ResourceLoader.GetForCurrentView().GetString("TransportUDP"), TransportType.Udp },
{ ResourceLoader.GetForCurrentView().GetString("TransportTCP"), TransportType.Tcp },
{ ResourceLoader.GetForCurrentView().GetString("TransportTLS"), TransportType.Tls }
};
}
public String sipAddress { get; set; }
private static INavigationService _navigationService = null;
public Dictionary<String, String> DictSIP { get; set; }
public Dictionary<String, String> ChangesDictSIP { get; set; }
public static INavigationService NavigationService
{
get
{
return _navigationService;
}
}
private static LinphoneManagerService _instance = new LinphoneManagerService();
public static LinphoneManagerService Instance
{
get
{
return _instance;
}
}
public RegistrationState state { get; set; }
//private int unreadMessageCount;
//public int UnreadMessageCount
//{
// get
// {
// return unreadMessageCount;
// }
// set
// {
// unreadMessageCount = value;
// }
//}
private int missedCallCount;
public int MissedCallCount
{
get
{
return missedCallCount;
}
set
{
missedCallCount = value;
}
}
public int LinphoneManagerInit(CoreDispatcher dispatcher)
{
_navigationService = ServiceLocator.Current.GetService<INavigationService>();
SettingsManager.InstallConfigFile();
acceptCall = false;
LinphoneManager.Instance.InitLinphoneCore();
LinphoneManager.Instance.CallListener = this;
LinphoneManager.Instance.CoreDispatcher = dispatcher;
//LinphoneManager.Instance.RegistrationChanged += RegistrationChanged;
//LinphoneManager.Instance.MessageReceived += MessageReceived;
LinphoneManager.Instance.CallStateChangedEvent += CallStateChanged;
return 0;
}
//private void RegistrationChanged(ProxyConfig config, RegistrationState state, string message)
//{
// RefreshStatus();
//}
//public void RefreshStatus()
//{
// if (LinphoneManager.Instance.Core.DefaultProxyConfig == null)
// state = RegistrationState.None;
// else
// state = LinphoneManager.Instance.Core.DefaultProxyConfig.State;
//}
//private void MessageReceived(ChatRoom room, ChatMessage message)
//{
// UnreadMessageCount = LinphoneManager.Instance.GetUnreadMessageCount();
//}
public void CallStateChanged(Call call, CallState state)
{
MissedCallCount = LinphoneManager.Instance.Core.MissedCallsCount;
//if (call == null)
// return;
}
public void NewCallStarted(string callerNumber)
{
List<String> parameters = new List<String>();
parameters.Add(callerNumber);
//((CallControllerListener)Instance).NewCallStarted(callerNumber);
}
public void CallEnded(Call call)
{
//((CallControllerListener)Instance).CallEnded(call);
}
public void CallIncoming(Call call)
{
string phoneNumber = call.RemoteAddress.AsString();
string SIP_ = call.RemoteAddress.AsStringUriOnly();
phoneNumber = SIP_.Split(":")[1].Split("@")[0];
PhoneCall(phoneNumber);
}
public async void PhoneCall(string phoneNumber)
{
var ret = await NavigationService.CreateNewViewAsync<PhoneCallReceiveViewModel>(new PhoneCallArgs { PhoneNumber = phoneNumber });
}
public void MuteStateChanged(bool isMicMuted)
{
//((CallControllerListener)Instance).MuteStateChanged(isMicMuted);
}
public void PauseStateChanged(Call call, bool isCallPaused, bool isCallPausedByRemote)
{
//((CallControllerListener)Instance).PauseStateChanged(call, isCallPaused, isCallPausedByRemote);
}
public void CallUpdatedByRemote(Call call, bool isVideoAdded)
{
//((CallControllerListener)Instance).CallUpdatedByRemote(call, isVideoAdded);
}
#region Настройки учетной записи SIP SIP
/// <summary>
/// Загрузка настроек учетной записи SIP.
/// </summary>
#region Constants settings names
private const string UsernameKeyName = "Username";
private const string UserIdKeyName = "UserId";
private const string PasswordKeyName = "Password";
private const string DomainKeyName = "Domain";
private const string ProxyKeyName = "Proxy";
private const string OutboundProxyKeyName = "OutboundProxy";
private const string DisplayNameKeyName = "DisplayName";
private const string TransportKeyName = "Transport";
private const string ExpireKeyName = "Expire";
private const string AVPFKeyName = "AVPF";
private const string Ice = "ICE";
#endregion
public void Load()
{
DictSIP = new Dictionary<string, string>();
DictSIP.Add(UsernameKeyName,"");
DictSIP.Add(UserIdKeyName,"");
DictSIP.Add(PasswordKeyName,"");
DictSIP.Add(DisplayNameKeyName,"");
DictSIP.Add(DomainKeyName,"");
DictSIP.Add(ProxyKeyName,"");
DictSIP.Add(OutboundProxyKeyName, false.ToString());
DictSIP.Add(TransportKeyName,"UDP");
DictSIP.Add(ExpireKeyName,"");
DictSIP.Add(AVPFKeyName, false.ToString());
DictSIP.Add(Ice, false.ToString());
ProxyConfig cfg = LinphoneManager.Instance.Core.DefaultProxyConfig;
if (cfg != null)
{
Address address = cfg.IdentityAddress;
if (address != null)
{
Address proxyAddress = LinphoneManager.Instance.Core.CreateAddress(cfg.ServerAddr);
DictSIP[ProxyKeyName] = proxyAddress.AsStringUriOnly();
DictSIP[TransportKeyName] = EnumToTransport[proxyAddress.Transport];
DictSIP[UsernameKeyName] = address.Username;
DictSIP[DomainKeyName] = address.Domain;
DictSIP[OutboundProxyKeyName] = (cfg.Route != null && cfg.Route.Length > 0).ToString();
DictSIP[ExpireKeyName] = String.Format("{0}", cfg.Expires);
AuthInfo authInfo = LinphoneManager.Instance.Core.FindAuthInfo(address.Domain, address.Username, address.Domain);
if (authInfo != null)
{
DictSIP[PasswordKeyName] = authInfo.Passwd;
DictSIP[UserIdKeyName] = authInfo.Userid;
}
if (cfg.NatPolicy == null) cfg.NatPolicy = LinphoneManager.Instance.Core.CreateNatPolicy();
DictSIP[Ice] = cfg.NatPolicy.IceEnabled.ToString();
DictSIP[DisplayNameKeyName] = address.DisplayName;
DictSIP[AVPFKeyName] = (cfg.AvpfMode == AVPFMode.Enabled) ? true.ToString() : false.ToString();
}
}
ChangesDictSIP = new Dictionary<string, string>();
//ChangesDictSIP[UsernameKeyName] = "";
}
/// <summary>
/// Сохранение учетной записи SIP.
/// </summary>
public void Save()
{
bool AccountChanged = ValueChanged(UsernameKeyName) || ValueChanged(UserIdKeyName) || ValueChanged(PasswordKeyName) || ValueChanged(DomainKeyName)
|| ValueChanged(ProxyKeyName) || ValueChanged(OutboundProxyKeyName) || ValueChanged(DisplayNameKeyName) || ValueChanged(TransportKeyName) || ValueChanged(ExpireKeyName);
if (AccountChanged)
{
Core lc = LinphoneManager.Instance.Core;
ProxyConfig cfg = lc.DefaultProxyConfig;
if (cfg != null)
{
cfg.Edit();
cfg.RegisterEnabled = false;
cfg.Done();
//Wait for unregister to complete
int timeout = 2000;
Stopwatch stopwatch = Stopwatch.StartNew();
while (true)
{
if (stopwatch.ElapsedMilliseconds >= timeout || cfg.State == RegistrationState.Cleared || cfg.State == RegistrationState.None)
{
break;
}
LinphoneManager.Instance.Core.Iterate();
System.Threading.Tasks.Task.Delay(100);
}
}
String username = GetNew(UsernameKeyName);
String userid = GetNew(UserIdKeyName);
String password = GetNew(PasswordKeyName);
String domain = GetNew(DomainKeyName);
String proxy = GetNew(ProxyKeyName);
String displayname = GetNew(DisplayNameKeyName);
String transport = GetNew(TransportKeyName);
String expires = GetNew(ExpireKeyName);
bool avpf = Convert.ToBoolean(GetNew(AVPFKeyName));
bool ice = Convert.ToBoolean(GetNew(Ice));
bool outboundProxy = Convert.ToBoolean(GetNew(OutboundProxyKeyName));
lc.ClearAllAuthInfo();
lc.ClearProxyConfig();
if ((username != null) && (username.Length > 0) && (domain != null) && (domain.Length > 0))
{
cfg = lc.CreateProxyConfig();
cfg.Edit();
if (displayname != null && displayname.Length > 0)
{
cfg.IdentityAddress = Factory.Instance.CreateAddress("\"" + displayname + "\" " + "<sip:" + username + "@" + domain + ">");
}
else
{
cfg.IdentityAddress = Factory.Instance.CreateAddress("<sip:" + username + "@" + domain + ">");
}
if ((proxy == null) || (proxy.Length <= 0))
{
proxy = "sip:" + domain;
}
else
{
if (!proxy.StartsWith("sip:") && !proxy.StartsWith("<sip:")
&& !proxy.StartsWith("sips:") && !proxy.StartsWith("<sips:"))
{
proxy = "sip:" + proxy;
}
}
cfg.ServerAddr = proxy;
if (transport != null)
{
Address proxyAddr = LinphoneManager.Instance.Core.CreateAddress(proxy);
if (proxyAddr != null)
{
proxyAddr.Transport = TransportToEnum[transport];
cfg.ServerAddr = proxyAddr.AsStringUriOnly();
}
}
if (outboundProxy)
{
cfg.Route = cfg.ServerAddr;
}
if (cfg.NatPolicy == null)
cfg.NatPolicy = cfg.Core.CreateNatPolicy();
if (cfg.NatPolicy != null)
cfg.NatPolicy.IceEnabled = ice;
int result = 0;
int.TryParse(expires, out result);
if (result != 0)
{
cfg.Expires = result;
}
var auth = lc.CreateAuthInfo(username, userid, password, "", "", domain);
lc.AddAuthInfo(auth);
lc.CaptureDevice = "WASAPI: Microphone (High Definition Audio Device)";
lc.AddProxyConfig(cfg);
lc.DefaultProxyConfig = cfg;
//lc.CaptureDevice = "WASAPI: Microphone (High Definition Audio Device)";
//LinphoneManager.Instance.AddPushInformationsToContactParams();
cfg.AvpfMode = (avpf) ? AVPFMode.Enabled : AVPFMode.Disabled;
cfg.RegisterEnabled = true;
cfg.Done();
}
}
}
public void Delete()
{
ProxyConfig cfg = LinphoneManager.Instance.Core.DefaultProxyConfig;
if (cfg != null)
{
LinphoneManager.Instance.Core.ClearProxyConfig();
LinphoneManager.Instance.Core.ClearAllAuthInfo();
}
}
protected bool ValueChanged(String Key)
{
return DictSIP.ContainsKey(Key);
}
protected String GetNew(String Key)
{
if (ChangesDictSIP.ContainsKey(Key))
{
return ChangesDictSIP[Key];
}
else if (ChangesDictSIP.ContainsKey(Key))
{
return ChangesDictSIP[Key];
}
return null;
}
#endregion
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Modelo
{
public class Estudio
{
public static int FECHA = 0;
public static int MUESTREO_No = 1;
public static int PUNTO_MUESTREO = 2;
public static int PUNTO = 3;
public static int RIO = 4;
public static int COORDENADAS = 5;
public static int ICA_IDEAM = 6;
public static int OD = 7;
public static int PH = 8;
public static int DQO = 9;
public static int CE = 10;
public static int SST = 11;
public static String PANCE = "Pance";
public static String AGUACATAL = "Aguacatal";
public static String CALI = "Cali";
public static String CAÑAVERALEJO = "Canaveralejo";
public static String LILI = "Lili";
public static String MELENDEZ = "Melendez";
private Hashtable hash_Muestras;
private String[] lineas;
public Estudio()
{
Hash_Muestras = new Hashtable();
inicializar_Datos();
}
//Este metodo se encargara de leer los datos e introducirlos en la tabla hash
public void inicializar_Datos()
{
//Llenar hashTable de arrays
for (int i = 0; i <= 6; i++)
{
Hash_Muestras.Add(i, new ArrayList());
}
String line;
try
{
StreamReader sr = new StreamReader("..\\..\\..\\Modelo\\Datos\\Datos.csv");
line = "";
string[] datos = null;
while ((line = sr.ReadLine()) != null)
{
datos = line.Split(',');
if (!datos[0].Equals("Fecha"))
{
String fecha = datos[FECHA];
int muestraNumero = Int32.Parse(datos[MUESTREO_No]);
String puntoDeMuestreo = datos[PUNTO_MUESTREO];
String punto = datos[PUNTO];
String rio = datos[RIO];
String[] coordenadas = datos[COORDENADAS].Split(';');
double latitud = Double.Parse(coordenadas[0].Replace('.',','));
double longitud = Double.Parse(coordenadas[1].Replace('.', ','));
double ica_ideam = Convert.ToDouble(datos[ICA_IDEAM].Replace('.', ','));
double od = Convert.ToDouble(datos[OD].Replace('.', ','));
double ph = Convert.ToDouble(datos[PH].Replace('.', ','));
double dqo = Convert.ToDouble(datos[DQO].Replace('.', ','));
double ce = Convert.ToDouble(datos[CE].Replace('.', ','));
double sst = Convert.ToDouble(datos[SST].Remove(datos[SST].Length - 1).Replace('.', ','));
Muestra muestra = new Muestra(fecha, muestraNumero, puntoDeMuestreo, punto, rio, latitud, longitud, ica_ideam, od, ph, dqo, ce, sst);
if (muestra.Rio.Equals(AGUACATAL))
{
((ArrayList)Hash_Muestras[1]).Add(muestra);
}
if (muestra.Rio.Equals(CALI))
{
((ArrayList)Hash_Muestras[2]).Add(muestra);
}
if (muestra.Rio.Equals(CAÑAVERALEJO))
{
((ArrayList)Hash_Muestras[3]).Add(muestra);
}
if (muestra.Rio.Equals(LILI))
{
((ArrayList)Hash_Muestras[4]).Add(muestra);
}
if (muestra.Rio.Equals(MELENDEZ))
{
((ArrayList)Hash_Muestras[5]).Add(muestra);
}
if (muestra.Rio.Equals(PANCE))
{
((ArrayList)Hash_Muestras[6]).Add(muestra);
}
}
}
sr.Close();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
}
public Hashtable Hash_Muestras { get => hash_Muestras; set => hash_Muestras = value; }
public string[] Lineas { get => lineas; set => lineas = value; }
static void Main(string[] args)
{
Estudio e = new Estudio();
}
}
} |
using Capa_de_Negocios_ONG_SYS;
using System;
using System.Collections.Generic;
using System.Data;
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 ONG_SYS
{
/// <summary>
/// Interaction logic for FRM_Buscar_Producto.xaml
/// </summary>
public partial class FRM_Buscar_Producto : Window
{
public string idProducto = null;
public string nombreProducto = null;
CN_Productos objetoCN = new CN_Productos();
private Facturacion padre;
public FRM_Buscar_Producto(Facturacion parametro)
{
InitializeComponent();
padre = parametro;
}
public FRM_Buscar_Producto()
{
InitializeComponent();
}
private void MostrarProductos(string nombreProducto)
{
dgv_productos.SetBinding(ItemsControl.ItemsSourceProperty, new Binding { Source = objetoCN.buscarProductos(nombreProducto) });
}
private void dgv_productos_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataRowView rowView = dgv_productos.SelectedItem as DataRowView;
if (rowView != null)
{
nombreProducto = rowView[1].ToString();
idProducto = rowView[0].ToString();
padre.txt_producto.Text = nombreProducto;
padre.esProducto = true;
padre.Show();
this.Close();
}
}
private void btn_buscar_Click(object sender, RoutedEventArgs e)
{
MostrarProductos(txt_nombreProducto.Text);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for UserLogin
/// </summary>
public class UserLogin
{
public string UserName { get; set; }
public string Password { get; set; }
public string BranchID { get; set; }
public string FullName { get; set; }
public string PhoneNo { get; set; }
public UserLogin()
{
//
// TODO: Add constructor logic here
//
}
} |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Uniduino;
using RBF;
using System;
public class GloveController : MonoBehaviour {
//Arduino
private int[] m_bendPins = {1,0,3,2};
private int m_bendCalibratePin = 18;
private double[] m_bendValues;
private Arduino m_arduino;
//Calibration state
public enum CalibrationState{
AWAITING_CALIBRATION = 0,
CALIBRATING,
CALIBRATED
}
protected CalibrationState m_calibrationState = CalibrationState.AWAITING_CALIBRATION;
public CalibrationState GetCalibrationState(){ return m_calibrationState; }
private List<double[]> m_currentCalibrationSamples;
public int m_calibrationSamples = 60;
protected bool bIsCollectingSamples;
protected double[] m_calibrationAvg;
//RBF
private RBFCore m_rbf;
private string m_currentGesture;
private string m_lastGesture;
private string m_lastGestureDown;
private int m_currentGestureTimer = 0;
public string m_activeGesture;
private string m_activeGestureDown;
private bool m_isDirty = true;
//Gesture change speeds
private double[] m_lastGestureOutput;
private double[] m_gestureVelocity;
public double activeGestureVelocity;
private int m_calibratingGestureIndex;
public string[] m_gestures;
public bool m_toggleCalibration = false;
public bool m_toggleNextGestureCalibration = false;
public double m_sigma = 0.5;
public int m_gestureSwitchDelay = 0;
void Awake( )
{
m_arduino = GetComponent<Arduino>();
if(m_arduino == null)
throw new Exception("No arduino component found on glove!");
m_arduino.Setup(ConfigurePins);
m_rbf = new RBFCore(m_bendPins.Length, m_gestures.Length);
m_rbf.setSigma(m_sigma);
m_bendValues = new double[m_bendPins.Length];
m_gestureVelocity = new double[m_gestures.Length];
m_lastGestureOutput = new double[m_gestures.Length];
m_currentCalibrationSamples = new List<double[]>();
}
/*
* Set up pins
*/
protected void ConfigurePins( )
{
for(int i = 0; i < m_bendPins.Length; i++){
m_arduino.pinMode(m_bendPins[i], PinMode.ANALOG);
m_arduino.reportAnalog(m_bendPins[i], 1);
}
}
public void ToggleCalibration(){
m_toggleCalibration = true;
}
public void CalibrateNext(){
m_toggleNextGestureCalibration = true;
}
void Update ()
{
if(m_arduino.Connected){
for(int i = 0; i < m_bendValues.Length; i++)
m_bendValues[i] = (double)m_arduino.analogRead(m_bendPins[i]);
if(m_toggleCalibration){
m_toggleCalibration = false;
m_toggleNextGestureCalibration = true;
m_calibrationState = CalibrationState.CALIBRATING;
m_calibratingGestureIndex = 0;
Debug.Log("Glove calibration start:");
//Set first gesture that needs to be calibrated
m_activeGesture = m_gestures[m_calibratingGestureIndex];
Debug.Log("Calibrate " + m_gestures[m_calibratingGestureIndex]);
}
//Calibration
switch(m_calibrationState){
case CalibrationState.AWAITING_CALIBRATION:
if( Convert.ToBoolean( m_arduino.digitalRead(m_bendCalibratePin ) ) || Input.GetKeyDown(KeyCode.RightArrow) ){
m_calibrationState = CalibrationState.CALIBRATING;
}
break;
case CalibrationState.CALIBRATING:
if(m_toggleNextGestureCalibration){
//Start recording samples to calculate the averages per bend sensor.
if(m_currentCalibrationSamples.Count == 0){
bIsCollectingSamples = true;
}
if(bIsCollectingSamples){
if(m_currentCalibrationSamples.Count < m_calibrationSamples){
double[] sensorValues = m_bendValues.Clone() as Double[];
m_currentCalibrationSamples.Add(sensorValues);
//m_rbf.addTrainingPoint(sensorValues, BuildRBFGestureOuput(m_calibratingGestureIndex));
string vals = "";
int count = 0;
foreach(double n in sensorValues){
vals += n.ToString() + ", ";
count++;
}
}
else {
double[] m_calibrationTotal = new double[m_bendValues.Length];
m_calibrationAvg = new double[m_bendValues.Length];
foreach (double[] vals in m_currentCalibrationSamples)
{
for (int i = 0; i < vals.Length; i++)
{
m_calibrationTotal[i] += vals[i];
}
}
for (int i = 0; i < m_calibrationTotal.Length; i++)
{
m_calibrationAvg[i] = m_calibrationTotal[i] / m_calibrationSamples;
}
bIsCollectingSamples = false;
}
} else {
//Samples recorded, save into RBF engine.
m_toggleNextGestureCalibration = false;
m_rbf.addTrainingPoint(m_calibrationAvg, BuildRBFGestureOuput( m_calibratingGestureIndex));
m_currentCalibrationSamples.Clear();
m_calibratingGestureIndex++;
if(m_calibratingGestureIndex < m_gestures.Length){
m_activeGesture = m_gestures[m_calibratingGestureIndex];
Debug.Log("Calibrate " + m_gestures[m_calibratingGestureIndex]);
} else {
m_calibrationState = CalibrationState.CALIBRATED;
m_rbf.calculateWeights();
Debug.Log("Calibration complete!");
}
}
}
break;
case CalibrationState.CALIBRATED:
double[] gestureOutput = m_rbf.calculateOutput(m_bendValues);
//Calculate gesture change velocities
for(int i = 0; i < m_gestures.Length; i++){
m_gestureVelocity[i] = gestureOutput[i] - m_lastGestureOutput[i];
if(m_gestureVelocity[i] < 0) m_gestureVelocity[i] *= -1.0;
}
m_lastGestureOutput = gestureOutput;
double largestVal = 0.0;
int activeIndex = 0;
for(int i = 0; i < gestureOutput.Length; i++){
if(gestureOutput[i] > largestVal){
largestVal = gestureOutput[i];
activeIndex = i;
}
}
m_currentGesture = m_gestures[activeIndex];
//Delay the reported gesture change by a frame count to let the RBF settle
if(m_currentGesture != m_lastGesture)
m_currentGestureTimer = 0;
else
m_currentGestureTimer++;
if(m_currentGestureTimer > m_gestureSwitchDelay){
m_activeGesture = m_currentGesture;
if(m_activeGesture != m_lastGestureDown){
m_activeGestureDown = m_activeGesture;
activeGestureVelocity = m_gestureVelocity[activeIndex];
SetDirty();
//SetCollider(activeIndex);
} else {
m_activeGestureDown = "";
SetClean();
}
m_lastGestureDown = m_currentGesture;
}
m_lastGesture = m_currentGesture;
break;
}
}
}
/*
* Collider center/size for different gestures
*/
public void SetCollider(int gestureIndex){
SetCollider(m_gestures[gestureIndex]);
}
public void SetCollider(string gesture){
BoxCollider col = collider as BoxCollider;
switch(gesture){
case "IDLE_HAND":
col.center = new Vector3(0.0f, 0.01f, 0.06f);
col.size = new Vector3(0.11f, -0.03f, 0.11f);
break;
case "CLOSED_HAND":
col.center = new Vector3(0.0f, -0.02f, 0.0f);
col.size = new Vector3(0.11f, 0.05f, 0.08f);
break;
case "INDEX_POINT":
col.center = new Vector3(0.03f, -0.01f, 0.03f);
col.size = new Vector3(0.025f, 0.07f, 0.15f);
break;
case "INDEX_MIDDLE":
col.center = new Vector3(0.02f, 0.0f, 0.07f);
col.size = new Vector3(0.05f, 0.05f, 0.15f);
break;
case "THREE_SWIPE":
col.center = new Vector3(0.01f, 0.0f, 0.07f);
col.size = new Vector3(0.075f, 0.05f, 0.15f);
break;
case "PINKY":
col.center = new Vector3(-0.035f, 0.0f, 0.07f);
col.size = new Vector3(0.025f, 0.05f, 0.15f);
break;
case "ROCK_ON":
col.center = new Vector3(0.0f, 0.01f, 0.06f);
col.size = new Vector3(0.11f, -0.03f, 0.11f);
break;
}
}
/*
* Getters
*/
public string activeGesture{ get { return m_activeGesture; }}
public string[] gestureTypes{ get { return m_gestures; }}
public bool GetGestureDown(string gesture){
if(m_activeGestureDown == gesture && m_activeGestureDown != "")
return true;
return false;
}
public double[] GetRawGestures(){
return m_lastGestureOutput;
}
public string GetGestureName(int index){
if(index < m_gestures.Length)
return m_gestures[index];
return null;
}
/*
* GestureState notifiers
*/
private void SetDirty(){ m_isDirty = true; }
private void SetClean(){ m_isDirty = false; }
public bool IsGestureClean(){ return m_isDirty; }
/*
* Gets an array with the chosen gesture index set to 1.0. Used for finger RBF gesture matching
*/
protected double[] BuildRBFGestureOuput(int gestureIndex){
double[] calibrationArr = new double[m_gestures.Length];
calibrationArr[gestureIndex] = 1.0;
return calibrationArr;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Assistenza.BufDalsi.Web.Data;
using Assistenza.BufDalsi.Web.Models;
using Assistenza.BufDalsi.Web.Services;
using Microsoft.AspNetCore.Identity;
using Assistenza.BufDalsi.Data;
using Microsoft.AspNetCore.DataProtection;
using System.Globalization;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc.Razor;
namespace Assistenza.BufDalsi.Web
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
var cultureInfo = new CultureInfo("it-IT");
CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
services.AddSingleton<ITicketData>(new TicketData(Configuration.GetConnectionString("Awstick")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
var cultureInfo = new CultureInfo("it-IT");
CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/_Error");
//app.UseDeveloperExceptionPage();
//app.UseDatabaseErrorPage();
//app.UseBrowserLink();
}
app.UseStaticFiles();
app.UseIdentity();
// Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "ImpiantoDetails", // Route name
template: "{controller=Impianto}/{action=ImpiantoDetails}/{ipt_Id}/{clt_Id?}" // URL with parameters
); // Parameter default
});
await CreateRoles(app.ApplicationServices.GetRequiredService<RoleManager<ApplicationRole>>());
await ConfigureSiteAdmin(app.ApplicationServices.GetRequiredService<RoleManager<ApplicationRole>>(), app.ApplicationServices.GetRequiredService<UserManager<ApplicationUser>>());
}
//Creazione ruoli predefiniti al primo avvio dell'applicazione. In caso siano già presenti del DB non ne vengono creati altri
private async Task CreateRoles(RoleManager<ApplicationRole> roleManager)
{
var roles = new List<ApplicationRole>
{
// These are just the roles I made up. You can make your own!
new ApplicationRole {Id="1",
Name = "Admin",
Description = "Amministratore dell'applicazione"},
new ApplicationRole {Id="2",
Name = "User",
Description = "Cliente che possiede uno o più impianti"},
new ApplicationRole {Id="3",
Name="Operator",
Description="Operatore che si occupa di fare le manutenzioni"}
};
foreach (var role in roles)
{
if (await roleManager.RoleExistsAsync(role.Name)) continue;
var result = await roleManager.CreateAsync(role);
if (result.Succeeded) continue;
// If we get here, something went wrong.
throw new Exception($"Could not create '{role.Name}' role.");
}
}
//Creazione del Super user "Admin" con ruolo admin all'avvio dell'applicazione. Se l'utente esiste già non ne viene creato un altro
private async Task ConfigureSiteAdmin(RoleManager<ApplicationRole> roleManager, UserManager<ApplicationUser> userManager)
{
//TicketData m=new TicketData(Configuration.GetConnectionString("Awstick")); in caso sia necessario recuperare i clienti in base a ciò che ci manderà elmas
//m.GetClients();
if (await userManager.FindByNameAsync("Admin") != null)
return;
if (!await roleManager.RoleExistsAsync("Admin"))
throw new Exception($"The Admin role has not yet been created.");
var user = new ApplicationUser
{
Name = "Admin",
UserName = "Admin",
Email = "admin@admin.admin",
RoleId = "1"
};
await userManager.CreateAsync(user, "Password12345.");
await userManager.AddToRoleAsync(user, "Admin");
}
}
}
|
using System;
using System.Threading.Tasks;
using Tweetinvi.Core.Controllers;
using Tweetinvi.Core.Factories;
using Tweetinvi.Core.Helpers;
using Tweetinvi.Models;
using Tweetinvi.Models.DTO;
using Tweetinvi.Models.Entities;
namespace Tweetinvi.Logic
{
/// <summary>
/// Message that can be sent privately between Twitter users
/// </summary>
public class Message : IMessage
{
private readonly IUserFactory _userFactory;
private readonly IMessageController _messageController;
private IMessageDTO _messageDTO;
private readonly ITaskFactory _taskFactory;
private IUser _sender;
private IUser _receiver;
public Message(
IUserFactory userFactory,
IMessageController messageController,
IMessageDTO messageDTO,
ITaskFactory taskFactory)
{
_userFactory = userFactory;
_messageController = messageController;
_messageDTO = messageDTO;
_taskFactory = taskFactory;
}
// Properties
public IMessageDTO MessageDTO
{
get { return _messageDTO; }
set { _messageDTO = value; }
}
public long Id
{
get { return _messageDTO.Id; }
}
public DateTime CreatedAt
{
get { return _messageDTO.CreatedAt; }
}
public long SenderId
{
get { return _messageDTO.SenderId; }
}
public string SenderScreenName
{
get { return _messageDTO.SenderScreenName; }
}
public IUser Sender
{
get
{
if (_sender == null)
{
_sender = _userFactory.GenerateUserFromDTO(_messageDTO.Sender);
}
return _sender;
}
}
public long RecipientId
{
get { return _messageDTO.RecipientId; }
}
public string RecipientScreenName
{
get { return _messageDTO.RecipientScreenName; }
}
public IUser Recipient
{
get
{
if (_receiver == null)
{
_receiver = _userFactory.GenerateUserFromDTO(_messageDTO.Recipient);
}
return _receiver;
}
}
public IObjectEntities Entities
{
get { return _messageDTO.Entities; }
}
public string Text
{
get { return _messageDTO.Text; }
}
public bool IsMessagePublished
{
get { return _messageDTO.IsMessagePublished; }
}
public bool IsMessageDestroyed
{
get { return _messageDTO.IsMessageDestroyed; }
}
// Destroy
public bool Destroy()
{
return _messageController.DestroyMessage(_messageDTO);
}
// Set Recipient
public void SetRecipient(IUser recipient)
{
_messageDTO.Recipient = recipient != null ? recipient.UserDTO : null;
}
public bool Equals(IMessage other)
{
bool result =
Id == other.Id &&
Text == other.Text &&
Sender.Equals(other.Sender) &&
Recipient.Equals(other.Recipient);
return result;
}
#region Async
public async Task<bool> DestroyAsync()
{
return await _taskFactory.ExecuteTaskAsync(() => Destroy());
}
#endregion
public override string ToString()
{
return Text;
}
}
} |
using Improbable;
using Improbable.Core;
using Improbable.Unity.Visualizer;
using UnityEngine;
namespace Assets.Gamelogic.Pirates.Behaviours
{
// Add this MonoBehaviour on both client and server-side workers
public class TransformReceiver : MonoBehaviour
{
// Inject access to the entity's Position and Rotation components
[Require] private Position.Reader PositionReader;
[Require] private Rotation.Reader RotationReader;
void OnEnable()
{
// Initialize entity's gameobject transform from Position and Rotation component values
transform.position = PositionReader.Data.coords.ToUnityVector();
transform.rotation = Quaternion.Euler(0.0f, RotationReader.Data.rotation, 0.0f);
// Register callback for when component changes
PositionReader.ComponentUpdated.Add(OnPositionUpdated);
RotationReader.ComponentUpdated.Add(OnRotationUpdated);
}
void OnDisable()
{
// Deregister callback for when component changes
PositionReader.ComponentUpdated.Remove(OnPositionUpdated);
RotationReader.ComponentUpdated.Remove(OnRotationUpdated);
}
// Callback for whenever one or more property of the Position standard library component is updated
void OnPositionUpdated(Position.Update update)
{
/*
* Only update the transform if this component is on a worker which isn't authorative over the
* entity's Position standard library component.
* This synchronises the entity's local representation on the worker with that of the entity on
* whichever worker is authoritative over its Position and is responsible for its movement.
*/
if (!PositionReader.HasAuthority)
{
if (update.coords.HasValue)
{
transform.position = update.coords.Value.ToUnityVector();
}
}
}
// Callback for whenever one or more property of the Rotation component is updated
void OnRotationUpdated(Rotation.Update update)
{
/*
* Only update the transform if this component is on a worker which isn't authorative over the
* entity's Rotation component.
* This synchronises the entity's local representation on the worker with that of the entity on
* whichever worker is authoritative over its Rotation and is responsible for its movement.
*/
if (!RotationReader.HasAuthority)
{
if (update.rotation.HasValue)
{
transform.rotation = Quaternion.Euler(0.0f, update.rotation.Value, 0.0f);
}
}
}
}
}
|
using UnityEngine;
namespace View.Enemy
{
public class CommonEnemyView : MonoBehaviour, IView
{
public TextMesh Text;
public SpriteRenderer[] Sprites;
private void Awake()
{
Text.GetComponent<MeshRenderer>().sortingLayerName = "Items";
Text.GetComponent<MeshRenderer>().sortingOrder = 2;
}
public void ShowView(int damage, Vector2 worldPosition)
{
Sprites[UnityEngine.Random.Range(0, Sprites.Length)].gameObject.SetActive(true);
Text.text = damage.ToString();
gameObject.transform.position = worldPosition;
}
public void Destroy()
{
Destroy(this.gameObject);
}
}
}
|
using System.Collections.Generic;
using NHibernate;
using Profiling2.Domain.Prf.Persons;
using Profiling2.Domain.Scr;
using Profiling2.Domain.Scr.PersonEntity;
namespace Profiling2.Domain.Contracts.Queries
{
public interface IScreeningEntityQueries
{
/// <summary>
/// Searches all reasoning and commentary of the given screening entity using given search term.
///
/// Note that all reasoning and commentary are searched, not just the latest.
/// </summary>
/// <param name="term"></param>
/// <param name="screeningEntityId"></param>
/// <returns></returns>
IList<ScreeningRequestPersonEntity> SearchScreenings(string term, int screeningEntityId);
IList<ScreeningEntity> GetAllScreeningEntities(ISession session);
IList<ScreeningRequestPersonEntity> GetAllScreeningRequestPersonEntities(ISession session);
}
}
|
using System;
using System.Threading;
using System.Windows.Forms;
using FrameworkLibraries.Utils;
using FrameworkLibraries.AppLibs.QBDT;
using FrameworkLibraries.ActionLibs.WhiteAPI;
using Installer_Test.Lib;
using Installer_Test.Properties.Lib;
using TestStack.White.UIItems.WindowItems;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Installer_Test.Lib
{
public class SwitchToggle
{
public static string[] arrEdition;
public static string currEdition;
public static Property conf = Property.GetPropertyInstance();
public static string exe = conf.get("QBExePath");
public static void SwitchEdition(string SKU)
{
Logger.logMessage("Switch Edition - Started");
Logger.logMessage("-----------------------------------------------------------");
if (SKU == "Enterprise")
{
arrEdition = new string[] {"Enterprise Solutions General Business" , "Enterprise Solutions Contractor","Enterprise Solutions Manufacturing & Wholesale ", "Enterprise Solutions Nonprofit",
"Enterprise Solutions Professional Services", "Enterprise Solutions Retail"};
}
if (SKU == "Premier")
{
arrEdition = new string[] {"Premier Edition (General Business)" , "Premier Contractor Edition", "Premier Manufacturing & Wholesale Edition ", "Premier Nonprofit Edition",
"Premier Professional Services Edition", "Premier Retail Edition"};
}
for (int i = 1; i < arrEdition.Length; i++)
{
Perform_Switch(arrEdition[i], SKU);
Thread.Sleep(5000);
}
Perform_Switch(arrEdition[0], SKU);
Logger.logMessage("Switch Edition - Completed");
Logger.logMessage("-----------------------------------------------------------");
}
public static void Perform_Switch(string currEdition, string SKU)
{
TestStack.White.Application qbApp = null;
TestStack.White.UIItems.WindowItems.Window qbWindow = null;
//qbApp = FrameworkLibraries.AppLibs.QBDT.QuickBooks.Initialize(exe);
//qbWindow = FrameworkLibraries.AppLibs.QBDT.QuickBooks.PrepareBaseState(qbApp);
qbApp = QuickBooks.GetApp("QuickBooks");
qbWindow = QuickBooks.GetAppWindow(qbApp, "QuickBooks " + SKU);
if (qbWindow == null)
{
qbWindow = QuickBooks.GetAppWindow(qbApp, "QuickBooks: " + SKU);
}
// Close QuickBook pop-up windows
Install_Functions.CheckWindowsAndClose(SKU);
try
{
Actions.SelectMenu(qbApp, qbWindow, "Help", "Manage My License", "Change to a Different Industry Edition...");
Thread.Sleep(500);
Window editionWindow = Actions.GetChildWindow(qbWindow, "Select QuickBooks Industry-Specific Edition");
Actions.ClickElementByName(Actions.GetChildWindow(qbWindow, "Select QuickBooks Industry-Specific Edition"), currEdition);
Actions.ClickElementByName(Actions.GetChildWindow(qbWindow, "Select QuickBooks Industry-Specific Edition"), "Next >");
Actions.ClickElementByName(Actions.GetChildWindow(qbWindow, "Select QuickBooks Industry-Specific Edition"), "Finish");
Thread.Sleep(2000);
try
{
if (Actions.CheckDesktopWindowExists("QuickBooks " + SKU))
{
if (Actions.CheckWindowExists(Actions.GetDesktopWindow("QuickBooks " + SKU), "Automatic Backup") == true)
{
SendKeys.SendWait("%N");
}
}
// For Premier
if (Actions.CheckDesktopWindowExists("QuickBooks: " + SKU))
{
if (Actions.CheckWindowExists(Actions.GetDesktopWindow("QuickBooks: " + SKU), "Automatic Backup") == true)
{
SendKeys.SendWait("%N");
}
}
}
catch (Exception e)
{}
Install_Functions.Select_Edition(currEdition);
//qbApp = FrameworkLibraries.AppLibs.QBDT.QuickBooks.Initialize(exe);
//qbWindow = FrameworkLibraries.AppLibs.QBDT.QuickBooks.PrepareBaseState(qbApp);
qbApp = QuickBooks.GetApp("QuickBooks");
qbWindow = QuickBooks.GetAppWindow(qbApp, "QuickBooks " + SKU);
if (qbWindow == null)
{
qbWindow = QuickBooks.GetAppWindow(qbApp, "QuickBooks: " + SKU);
}
Actions.SelectMenu(qbApp, qbWindow, "Window", "Close All");
Install_Functions.Get_QuickBooks_Edition(qbApp, qbWindow);
Logger.logMessage("Switch Edition - Successful");
Logger.logMessage("-----------------------------------------------------------");
}
catch (Exception e)
{
Logger.logMessage("Switch Edition - Failed");
Logger.logMessage(e.Message);
Logger.logMessage("-----------------------------------------------------------");
}
}
public static void ToggleEdition(string SKU)
{
Logger.logMessage("Toggle Edition - Started");
Logger.logMessage("-----------------------------------------------------------");
if (SKU == "Enterprise")
{
arrEdition = new string[] {"Enterprise Solutions General Business" , "Enterprise Solutions Accountant - Home ","Enterprise Solutions Contractor", "Enterprise Solutions Manufacturing & Wholesale ",
"Enterprise Solutions Nonprofit", "Enterprise Solutions Professional Services", "Enterprise Solutions Retail"};
}
if (SKU == "Premier")
{
arrEdition = new string[] {"Premier Edition (General Business)" , "Premier Accountant Edition - Home ", "Premier Contractor Edition", "Premier Manufacturing & Wholesale Edition ",
"Premier Nonprofit Edition", "Premier Professional Services Edition", "Premier Retail Edition" , "QuickBooks Pro"};
}
for (int i = 2; i < arrEdition.Length; i++)
{
Perform_Toggle(arrEdition[i], SKU);
}
Perform_Toggle(arrEdition[0], SKU);
Perform_Toggle(arrEdition[1], SKU);
Logger.logMessage("Toggle Edition - Completed");
Logger.logMessage("-----------------------------------------------------------");
}
public static void Perform_Toggle(string currEdition, string SKU)
{
TestStack.White.Application qbApp = null;
TestStack.White.UIItems.WindowItems.Window qbWindow = null;
//qbApp = FrameworkLibraries.AppLibs.QBDT.QuickBooks.Initialize(exe);
//qbWindow = FrameworkLibraries.AppLibs.QBDT.QuickBooks.PrepareBaseState(qbApp);
qbApp = QuickBooks.GetApp("QuickBooks");
qbWindow = QuickBooks.GetAppWindow(qbApp, "QuickBooks " + SKU);
// Close QuickBook pop-up windows
Install_Functions.CheckWindowsAndClose(SKU);
try
{
Actions.SelectMenu(qbApp, qbWindow, "File", "Toggle to Another Edition... ");
Thread.Sleep(500);
Window editionWindow = Actions.GetChildWindow(qbWindow, "Select QuickBooks Industry-Specific Edition");
Thread.Sleep(1000);
Actions.ClickElementByName(Actions.GetChildWindow(qbWindow, "Select QuickBooks Industry-Specific Edition"), currEdition);
Thread.Sleep(1000);
Actions.ClickElementByName(Actions.GetChildWindow(qbWindow, "Select QuickBooks Industry-Specific Edition"), "Next >");
Thread.Sleep(1000);
Actions.ClickElementByName(Actions.GetChildWindow(qbWindow, "Select QuickBooks Industry-Specific Edition"), "Toggle");
Thread.Sleep(2000);
if (Actions.CheckWindowExists(Actions.GetDesktopWindow("QuickBooks"), "Automatic Backup") == true)
{
SendKeys.SendWait("%N");
}
Install_Functions.Select_Edition(currEdition); ///////////
Thread.Sleep(20000);
qbApp = QuickBooks.GetApp("QuickBooks");
qbWindow = QuickBooks.GetAppWindow(qbApp, "QuickBooks " + SKU);
Actions.SelectMenu(qbApp, qbWindow, "Window", "Close All");
Install_Functions.Get_QuickBooks_Edition(qbApp, qbWindow);
//QuickBooks.ResetQBWindows(qbApp, qbWindow, false);
Thread.Sleep(10000);
Logger.logMessage("Toggle Edition - Successful");
Logger.logMessage("-----------------------------------------------------------");
}
catch (Exception e)
{
Logger.logMessage("Toggle Edition - Failed");
Logger.logMessage(e.Message);
Logger.logMessage("-----------------------------------------------------------");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GUI.Helpers;
using Newtonsoft.Json.Linq;
namespace GUI.Models
{
/// <summary>
/// The different message types to the Broker
/// The values must reflect *exactly* the values defined in Broker\Task.h
/// </summary>
public enum MessageType : uint
{
GetOsInfo = 1,
HookDriver = 2,
UnhookDriver = 3,
GetDriverInfo = 4,
NumberOfDriver = 5,
NotifyEventHandle = 6, // don't use, todo remove
EnableMonitoring = 7,
DisableMonitoring = 8,
GetInterceptedIrps = 9,
ReplayIrp = 10,
StoreTestCase = 11,
EnumerateDrivers = 12,
EnableDriver = 13,
DisableDriver = 14,
GetNamesOfHookedDrivers = 15,
};
public class BrokerMessageHeader
{
public BrokerMessageHeader() { }
public Win32Error gle;
public bool is_success;
public MessageType type;
}
public class ReplayIrpMessage
{
public byte[] output_buffer;
public int output_buffer_length;
}
public class GetInterceptedIrps
{
public uint nb_irps;
public List<Irp> irps;
}
public class GetDriverListMessage
{
public List<String> drivers;
}
public class GetDriverInfo
{
public Driver driver;
}
public class GetOsInfoMessage
{
public uint version_major;
public uint version_minor;
public String version_build;
public uint cpu_arch;
public uint cpu_num;
public String username;
public String integrity;
public uint pid;
public uint version;
}
public class BrokerMessageBody
{
public BrokerMessageBody() { }
// used by requests (generic message)
public uint param_length;
public string param;
public GetDriverListMessage hooked_driver_list;
public GetDriverListMessage driver_list;
public GetDriverInfo driver_info;
public GetInterceptedIrps intercepted_irps;
public ReplayIrpMessage replay_irp;
public GetOsInfoMessage os_info;
}
public class BrokerMessage
{
public BrokerMessageHeader header;
public BrokerMessageBody body;
public BrokerMessage() { }
public BrokerMessage(MessageType type, byte[] args=null)
{
header = new BrokerMessageHeader();
header.type = type;
body = new BrokerMessageBody();
if(args == null)
{
body.param_length = 0;
body.param = "";
}
else
{
body.param_length = (uint)args.Length;
body.param = Utils.Base64Encode(args);
}
}
}
}
|
using System;
using System.IO;
using System.Linq;
using AppKit;
using Foundation;
using WpfApp4;
namespace MacOSApp1
{
public partial class ViewController : NSViewController
{
public ViewController(IntPtr handle) : base(handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
var browserDelegate = new FolderBrowserDelegate(_browser, Environment.GetLogicalDrives().Select(s=>new NSFolderViewModel(FolderViewModel.CreateDirectory(s))).ToList());
_browser.Delegate = browserDelegate;
_browser.MaxVisibleColumns = 3;
}
public override NSObject RepresentedObject
{
get
{
return base.RepresentedObject;
}
set
{
base.RepresentedObject = value;
// Update the view, if already loaded.
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Projeto_Carros.Models;
namespace Projeto_Carros.Services
{
public class CarrosServicesImpl : ICarrosServices
{
private ApplicationContext _applicationContext;
public CarrosServicesImpl(ApplicationContext applicationContext)
{
_applicationContext = applicationContext;
}
public Carros Create(Carros carros)
{
try
{
_applicationContext.Add(carros);
_applicationContext.SaveChanges();
}
catch (Exception ex)
{
throw ex;
}
return carros;
}
public IEnumerable<Carros> Lista()
{
return _applicationContext.Carros
.Include(d => d.Revisoes)
.ToList();
}
public Carros FindById(int Codigo)
{
return _applicationContext.Carros
.Include(i => i.Revisoes)
.SingleOrDefault(i => i.Codigo.Equals(Codigo));
}
public Carros Update(Carros carros)
{
if (!_applicationContext.Carros.Any(p => p.Codigo == carros.Codigo))
{
return new Carros();
}
var result = _applicationContext.Carros.SingleOrDefault(b => b.Codigo == carros.Codigo);
if (result != null)
{
try
{
_applicationContext.Entry(result).CurrentValues.SetValues(carros);
_applicationContext.SaveChanges();
}
catch (Exception ex)
{
throw ex;
}
}
return result;
}
public void Delete(int Codigo)
{
var result = _applicationContext.Carros.SingleOrDefault(p => p.Codigo.Equals(Codigo));
try
{
if (result != null)
{
_applicationContext.Carros.Remove(result);
_applicationContext.SaveChanges();
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace UnityTerraforming.GameAi
{
public class AvoidAgents : AgentBehaviour
{
public float ColisionRadius = 0.4f;
public float ScanRadius;
public float ScanTime = 0.5f;
private List<Agent> targets;
private void Start()
{
targets = new List<Agent>();
StartCoroutine("SearchTargets", ScanTime);
}
public IEnumerable SearchTargets(float timeToWait)
{
while (true)
{
SearchTargets();
yield return new WaitForSeconds(timeToWait);
}
}
private void SearchTargets()
{
Collider[] colliders = Physics.OverlapSphere(transform.position, ScanRadius);
foreach (Collider col in colliders)
{
Agent agent = col.GetComponent<Agent>();
if (agent != null)
{
targets.Add(agent);
}
}
}
public override Steering GetSteering()
{
Steering steering = new Steering();
float shortestTime = Mathf.Infinity;
Agent firstTarget = null;
float firstMinSeperaton = 0;
float firstDistance = 0;
Vector3 firstRelativePos = Vector3.zero;
Vector3 firstRelativeVel = Vector3.zero;
foreach (Agent t in targets)
{
Vector3 relativePos;
relativePos = t.transform.position - transform.position;
Vector3 relativeVel = t.Velocity - Agent.Velocity;
float relativeSpeed = relativeVel.magnitude;
float timeToCollision = Vector3.Dot(relativePos, relativeVel);
timeToCollision /= relativeSpeed * relativeSpeed * -1;
float distance = relativePos.magnitude;
float minSeperation = distance - relativeSpeed * timeToCollision;
if (minSeperation > 2 * ColisionRadius)
continue;
if (timeToCollision > 0 && timeToCollision < shortestTime)
{
shortestTime = timeToCollision;
firstTarget = t;
firstMinSeperaton = minSeperation;
firstRelativePos = relativePos;
firstRelativeVel = relativeVel;
}
}
if (firstTarget == null)
return steering;
if (firstMinSeperaton <= 0 || firstDistance < 2 * ColisionRadius)
firstRelativePos = firstTarget.transform.position;
else
firstRelativePos += firstRelativeVel * shortestTime;
firstRelativePos.Normalize();
steering.linear = -firstRelativePos * Agent.MaxAccel;
return steering;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UIInfoSuite
{
public interface LEEvents
{
event EventHandler OnXPChanged;
void raiseEvent();
}
}
|
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace ClassLibraryAandelen.basis
{
public class Notifyable : INotifyPropertyChanged
{
//event dat getriggert wordt wanneer er iets verandert
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// wordt gebruikt als je 1 property wilt laten weten dat er iets is verandert
/// </summary>
/// <param name="propertyName">property dat geupdatet worden, als deze leeg is wordt de callermembername</param>
protected virtual void OnPropertyChanged([CallerMemberName]String propertyName = "")
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
/// <summary>
/// wordt gebruikt als je meerdere properties wilt laten weten dat er iets is verandert
/// </summary>
/// <param name="props">array properties that are going to update</param>
public void NotifyProperties(params string[] props)
{
OnPropertyChanged();
if(props!=null) foreach (string item in props) OnPropertyChanged(item);
}
}
} |
namespace Sfa.Poc.ResultsAndCertification.CsvHelper.Web.Authentication.Interfaces
{
public interface ITokenService
{
string GetToken();
}
}
|
using NUnit.Framework;
namespace UnitTesting.GettingStarted.Tests
{
[TestFixture]
public class CalculatorTests
{
[Test]
public void Add_Always_ReturnsExpectedResult() //[subject]_[scenario]_[result] i.e GrantLoan_WhenCreditLessthan500_ReturnsFalse
{
var systemUnderTest = new Calculator();
Assert.That(systemUnderTest.Add(1, 3), Is.EqualTo(4));
}
[TestCase(1,2)]
[TestCase(0,9)]
[TestCase(100003, 349029)]
public void Add_Always_ReturnsExpectedResult_WithTestCaseExample(int lhs, int rhs)
{
var systemUnderTest = new Calculator();
var expectedValue = lhs + rhs;
Assert.That(systemUnderTest.Add(lhs, rhs), Is.EqualTo(expectedValue));
}
}
}
|
using System;
namespace Assets.Scripts.Models.Food
{
public class BottleWater : Food
{
public BottleWater()
{
LocalizationName = "bottle_water";
Description = "bottle_water_descr";
IconName = "bottle_water";
ThirstEffect = 40.0f;
}
public override void Use(GameManager gameManager, Action<int> changeAmount = null)
{
base.Use(gameManager, changeAmount);
gameManager.PlayerModel.ChangeThirst(ThirstEffect);
SoundManager.PlaySFX(WorldConsts.AudioConsts.PlayerDrink);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empresa.DesignPatterns.Vendas.Descontos
{
class DescontoParaMaisDe500Reais : Desconto
{
public Desconto Proximo { get; set;}
public DescontoParaMaisDe500Reais(Desconto proximo)
{
Proximo = proximo;
}
public double calcula(Orcamento orcamento)
{
if (orcamento.Valor > 500)
{
return orcamento.Valor * 0.07;
}
return Proximo.calcula(orcamento);
}
}
}
|
namespace Dg.KMS.Domain
{
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DFC.ServiceTaxonomy.JobProfiles.DataTransfer.Models.ServiceBus;
using DFC.ServiceTaxonomy.JobProfiles.DataTransfer.Models.ServiceBus.Configuration;
using DFC.ServiceTaxonomy.JobProfiles.DataTransfer.ServiceBus.Interfaces;
using Microsoft.Azure.ServiceBus;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace DFC.ServiceTaxonomy.JobProfiles.DataTransfer.ServiceBus
{
internal class ServiceBusMessageProcessor : IServiceBusMessageProcessor
{
private readonly ServiceBusSettings _serviceBusSettings;
private readonly ILogger<ServiceBusMessageProcessor> _logger;
public ServiceBusMessageProcessor(IConfiguration configuration, ILogger<ServiceBusMessageProcessor> logger)
{
_serviceBusSettings = configuration.GetSection("ServiceBusSettings").Get<ServiceBusSettings>();
_logger = logger;
}
public async Task SendJobProfileMessage(JobProfileMessage jpData, string contentType, string actionType)
{
_logger.LogInformation($" CREATED service bus message for OrchardCore event {actionType.ToUpper()} on JobProfile with Title -- {jpData.Title} and Jobprofile Id -- {jpData.JobProfileId}");
var topicName = (actionType == "Draft")
? _serviceBusSettings.ServiceBusTopicNameForDraft
: _serviceBusSettings.ServiceBusTopicName;
var topicClient = new TopicClient(_serviceBusSettings.ServiceBusConnectionString, topicName);
// Send Messages
var jsonData = JsonConvert.SerializeObject(jpData);
try
{
_logger.LogInformation($" SENDING service bus message for OrchardCore event {actionType.ToUpper()} on JobProfile with Title -- {jpData.Title} and with Jobprofile Id -- {jpData.JobProfileId} ");
// Message that send to the queue
var message = new Message(Encoding.UTF8.GetBytes(jsonData));
message.ContentType = "application/json";
message.Label = jpData.Title;
message.UserProperties.Add("Id", jpData.JobProfileId);
message.UserProperties.Add("ActionType", actionType);
message.UserProperties.Add("CType", contentType);
message.CorrelationId = Guid.NewGuid().ToString();
await topicClient.SendAsync(message);
_logger.LogInformation($" SENT service bus message for OrchardCore event {actionType.ToUpper()} on JobProfile with Title -- {jpData.Title} with Jobprofile Id -- {jpData.JobProfileId} and with Correlation Id -- {message.CorrelationId.ToString()}");
}
catch (Exception ex)
{
_logger.LogInformation($" FAILED service bus message for OrchardCore event {actionType.ToUpper()} on JobProfile with Title -- {jpData.Title} and with Jobprofile Id -- {jpData.JobProfileId} has an exception \n {ex.Message} ");
}
finally
{
await topicClient.CloseAsync();
}
}
public async Task SendOtherRelatedTypeMessages(IEnumerable<RelatedContentItem> relatedContentItems, string contentType, string actionType)
{
_logger.LogInformation($" CREATED service bus message for OrchardCore event {actionType.ToUpper()} on Item of Type -- {contentType.ToUpper()} with {relatedContentItems.Count().ToString()} message(s)");
var topicClient = new TopicClient(_serviceBusSettings.ServiceBusConnectionString, _serviceBusSettings.ServiceBusTopicName);
try
{
foreach (var relatedContentItem in relatedContentItems)
{
_logger.LogInformation($" SENDING service bus message for OrchardCore event {actionType.ToUpper()} on Item -- {relatedContentItem.Title} of Type -- {contentType} with Id -- {relatedContentItem.Id.ToString()} linked to Job Profile {relatedContentItem.JobProfileTitle} -- {relatedContentItem.JobProfileId.ToString()}");
// Send Messages
var jsonData = JsonConvert.SerializeObject(relatedContentItem);
// Message that send to the queue
var message = new Message(Encoding.UTF8.GetBytes(jsonData));
message.ContentType = "application/json";
message.Label = relatedContentItem.Title;
message.UserProperties.Add("Id", $"{relatedContentItem.JobProfileId}--{relatedContentItem.Id}");
message.UserProperties.Add("ActionType", actionType);
message.UserProperties.Add("CType", contentType);
message.CorrelationId = Guid.NewGuid().ToString();
await topicClient.SendAsync(message);
_logger.LogInformation($" SENT service bus message for OrchardCore event {actionType.ToUpper()} on Item -- {relatedContentItem.Title} of Type -- {contentType} with Id -- {relatedContentItem.Id.ToString()} linked to Job Profile {relatedContentItem.JobProfileTitle} -- {relatedContentItem.JobProfileId.ToString()} with Correlation Id -- {message.CorrelationId.ToString()}");
}
}
catch (Exception ex)
{
_logger.LogInformation($" FAILED service bus message for OrchardCore event {actionType.ToUpper()} on Item of Type -- {contentType} with {relatedContentItems.Count().ToString()} message(s) has an exception \n {ex.Message}");
}
finally
{
await topicClient.CloseAsync();
}
}
}
}
|
using System.Collections.Generic;
namespace LoneWolf.Migration.Code
{
public interface IGenerator
{
IEnumerable<string> Generate(IEnumerable<string> input);
}
}
|
using ISE.Framework.Common.CommonBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ISE.SM.Common.Message
{
[DataContract]
public class TokenValidationResult:BaseDto
{
public TokenValidationResult()
{
}
[DataMember]
public string Error { get; set; }
[DataMember]
public bool IsValid { get; set; }
public bool IsError { get { return !string.IsNullOrWhiteSpace(Error) || !IsValid; } }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using TeamleaderDotNet.Crm;
using TeamleaderDotNet.Utils;
namespace TeamleaderDotNet
{
public class TeamleaderCompaniesApi : TeamleaderApiBase
{
public TeamleaderCompaniesApi(string apiGroup, string apiSecret)
: base(apiGroup, apiSecret)
{
}
//TODO:
//Adding a company to TeamleaderApiBase
//Updating company information
//Searching TeamleaderApiBase companies
//Getting all possible business types for a country
/// <summary>
/// Adds a company to TeamleaderApiBase
/// </summary>
/// <returns>The TeamleaderApiBase ID of the newly created company</returns>
public int AddCompany(Company company, bool automerge_by_name, bool automerge_by_email, bool automerge_by_vat_code, string[] add_tag_by_string)
{
var fields = new List<KeyValuePair<string, string>>(company.ToArrayForApi());
fields.Add(new KeyValuePair<string, string>("automerge_by_name", automerge_by_name ? "1" : "0"));
fields.Add(new KeyValuePair<string, string>("automerge_by_email", automerge_by_email ? "1" : "0"));
fields.Add(new KeyValuePair<string, string>("automerge_by_vat_code", automerge_by_vat_code ? "1" : "0"));
if (add_tag_by_string != null && add_tag_by_string.Any())
fields.Add(new KeyValuePair<string, string>("add_tag_by_string", string.Join(",", add_tag_by_string)));
var companyId = DoCall<string>("addCompany.php", fields).Result;
return int.Parse(companyId);
}
/// <summary>
/// Fetches the information of a specific company
/// </summary>
/// <param name="id">The ID of the company</param>
/// <returns>The detailed information of the company</returns>
public Company GetCompany(int id)
{
return DoCall<Company>("getCompany.php", new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("company_id", id.ToString())
}).Result;
}
/// <summary>
/// Deletes a company
/// </summary>
/// <param name="id">The ID of the company</param>
public void DeleteCompany(int id)
{
var r = DoCall<Contact>("deleteCompany.php", new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("company_id", id.ToString())
}).Result;
}
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
public class CharacterMovingScript : MonoBehaviour {
public AudioSource audioSource;
public AudioClip jump;
public AudioClip fruit;
public AudioClip hurt;
public AudioClip win;
public GameObject character;
public GameObject endGameCanvas;
Vector2 v2;
private int coinScore = 0;
private Text coinText;
private Rigidbody2D rb;
public float firstJumpHeight;
public float secondJumpHeight;
private bool triedJump = false;
private bool onGround = true;
private int jumpCount = 0;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody2D> ();
coinText = GameObject.Find ("CoinText").GetComponent<Text> ();
}
// Update is called once per frame
void Update () {
v2 = new Vector2 (Time.deltaTime * 3f, 0);
character.transform.Translate (v2);
try{
if (Input.GetKeyDown("space") || Input.GetTouch(0).phase == TouchPhase.Began){
Debug.Log ("Spacebar pressed");
triedJump = true;
}
}
catch (ArgumentException){
}
}
void FixedUpdate(){
Jump ();
}
bool canDoubleJump(){
return jumpCount < 2;
}
void Jump(){
if (triedJump) {
if (onGround) {
rb.AddForce (Vector2.up * firstJumpHeight);
audioSource.clip = jump;
audioSource.Play ();
jumpCount++;
onGround = false;
} else if (canDoubleJump ()) {
audioSource.clip = jump;
audioSource.Play ();
rb.AddForce (Vector2.up * firstJumpHeight);
jumpCount++;
}
triedJump = false;
}
}
void OnCollisionEnter2D (Collision2D coll){
if (coll.gameObject.tag == "ground"){
onGround = true;
jumpCount = 0;
}
if (coll.gameObject.tag == "Fruit") {
audioSource.clip = fruit;
audioSource.Play ();
Destroy(coll.gameObject);
coinScore++;
updateCoinText();
}
if (coll.gameObject.tag == "DeathZone") {
BackgroundMusic.Pause();
audioSource.clip = hurt;
audioSource.Play ();
endGameScreen();
}
if (coll.gameObject.tag == "Finish") {
endGameScreen();
Coin.updateCoinScore("+", coinScore);
BackgroundMusic.Pause();
audioSource.clip = win;
audioSource.Play ();
}
}
private void updateCoinText() {
coinText.text = coinScore.ToString();
}
private void endGameScreen(){
Time.timeScale = 0f;
endGameCanvas.SetActive (true);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace WebAppMedOffices.Models
{
[NotMapped]
public class TurnoView : Turno
{
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
[Display(Name = "Fecha Desde")]
public DateTime FechaDesde { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
[Display(Name = "Fecha Hasta")]
public DateTime FechaHasta { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Library.Model;
namespace Library.Interfaces
{
public interface IPathStepRepository
{ // Not sure if this will ever be used... implementing it just in case though.
Task AddPathStep(PathStep pathStep);
Task<PathStep> GetPathStepByID(int id);
Task<IEnumerable<PathStep>> GetPathSteps();
Task UpdatePathStep(PathStep pathStep);
Task DeletePathStep(PathStep pathStep);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.