text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entidades
{
public enum Servicio
{
Comun,
SemiCama,
Ejecutivo,
}
public class PasajeMicro : Pasaje
{
public Servicio tipoServicio;
public PasajeMicro() { }
public PasajeMicro(string origen, string destino, Pasajero pasajero, float precio, DateTime fecha, Servicio tipoServicio)
: base(origen, destino, pasajero, precio, fecha)
{
this.tipoServicio = tipoServicio;
}
public override string Mostrar()
{
return String.Format("{0}\nPrecioFinal: {1}", base.Mostrar(), this.PrecioFinal);
}
public override float PrecioFinal
{
get
{
switch (this.tipoServicio)
{
case Servicio.SemiCama:
return Precio + ((Precio * 10) / 100);
case Servicio.Ejecutivo:
return Precio + ((Precio * 20) / 100);
}
return Precio;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shooting : MonoBehaviour {
public GameObject bullet;
public float timeLeftUntilSpawn = 0f;
public float startTime = 0f;
public float secondsBetweenSpawn = 0.5f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetMouseButton(0))
{
timeLeftUntilSpawn = Time.time - startTime;
if (timeLeftUntilSpawn >= secondsBetweenSpawn)
{
startTime = Time.time;
timeLeftUntilSpawn = 0;
Instantiate(bullet, transform.position, transform.rotation);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FershGreen.Models;
namespace FershGreen.Controllers
{
public class KnowleController : Controller
{
PrivateClinicEntities db = new PrivateClinicEntities();
// GET: Knowle
/// <summary>
/// 知识库界面
/// </summary>
/// <param name="pageIndex"></param>
/// <param name="pageCount"></param>
/// <param name="Name"></param>
/// <returns></returns>
public ActionResult Index(int pageIndex = 1, int pageCount =4, string Name = "")
{
//return View(db.KnowledgeBase.ToList());
int totalCount = db.KnowledgeBase.OrderBy(p => p.KnowID).Count();
//总页数
double totalPage = Math.Ceiling((double)totalCount / pageCount);
//获得用户集合 , 分页查询Skip()跳过指定数量的集合 Take() 从过滤后返回的集合中再从第一行取出指定的行数
List<KnowledgeBase> use = db.KnowledgeBase.OrderBy(p => p.KnowID).Where(p => Name == "" || p.KnowCommon.Contains(Name))
.Skip((pageIndex - 1) * pageCount).Take(pageCount).ToList();
ViewBag.pageIndex = pageIndex;
ViewBag.pageCount = pageCount;
ViewBag.totalCount = totalCount;
ViewBag.totalPage = totalPage;
ViewBag.Name = Name;
return View(use);
}
//删除
public ActionResult Delete(int? id)
{
var dele = db.KnowledgeBase.Find(id);
db.KnowledgeBase.Remove(dele);
db.SaveChanges();
return RedirectToAction("Index");
}
//添加
[HttpPost]
public ActionResult Create(KnowledgeBase Kno)
{
db.KnowledgeBase.Add(Kno);
db.SaveChanges();
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult Edit(KnowledgeBase Kno)
{
db.Entry(Kno).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
} |
using System;
class Alamprogramm{
static int Korruta(int arv1, int arv2){
return arv1*arv2;
}
public static void Main(string[] arg){
int a=4;
int b=6;
Console.WriteLine("{0} korda {1} on {2}", a, b, Korruta(a, b));
Console.WriteLine(Korruta(3, 5));
}
}
|
using UnityEngine;
using System.Collections;
using System;
public class Capture_ScoreManager : Photon.MonoBehaviour, IGame {
[SerializeField]
int teamsInGame;
[SerializeField]
int endGameScore;
public void OnGameSetup()
{
if(PhotonNetwork.isMasterClient)
{
InitializeGameScore();
}
}
public void OnGameStart()
{
}
public void OnRoundSetup()
{
}
public void OnRoundStart()
{
}
public void OnRoundEnd()
{
}
public void OnGameEnd()
{
}
void InitializeGameScore()
{
for (int team = 0; team < teamsInGame; team++)
PhotonNetwork.room.customProperties[RoomProperties.Score + team] = 0;
PhotonNetwork.room.SetCustomProperties(PhotonNetwork.room.customProperties);
}
public void Score(int team, int value = 1)
{
int currentScore = (int)PhotonNetwork.room.customProperties[RoomProperties.Score + team];
PhotonNetwork.room.customProperties[RoomProperties.Score + team] = currentScore + value;
PhotonNetwork.room.SetCustomProperties(PhotonNetwork.room.customProperties);
}
public bool HasGameEnded()
{
return GetWinnerTeam() >= 0;
}
public int GetWinnerTeam()
{
for (int team = 0; team < this.teamsInGame; team++)
{
int teamScore = (int)PhotonNetwork.room.customProperties[RoomProperties.Score + team];
if (teamScore >= this.endGameScore)
return team;
}
return -1;
}
}
|
using UnityEngine;
using System.Collections;
public class EnemyHunterCanon : Weapon
{
public EnemyHunterCanon(GameObject owner) : base(owner)
{
Stats = new WeaponStats
{
Damage = 10f,
RateOfFire = 0.3f,
Lifetime = 2f,
Speed = 2f,
PierceRate = 0f,
Projectiles = 1,
};
this.Projectile = GameManager.Instance.EnemyStandardBullet;
}
}
|
using ModelEF.Dao;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace TestUngDung.Areas.Admin.Controllers
{
public class HomeController : BaseController
{
public ActionResult Index()
{
var categr = new CategoryDao();
var modect = categr.quantitycategory();
ViewBag.countct = modect;
var qttpro = new ProductDao();
var d = qttpro.quantityproduct();
ViewBag.prd = d;
var acc = new UserAccountDao();
var modeacc = acc.getcountacc();
ViewBag.acccount = modeacc;
return View();
}
}
} |
using Data.Infrastructure;
using Entities.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Data.Mapping
{
public class UserMap : IdentityConfiguration<User>
{
public override void Configure(EntityTypeBuilder<User> builder)
{
builder.ToTable("User");
builder.HasOne(item => item.Territory)
.WithMany()
.HasForeignKey(item => item.TerritoryId)
.OnDelete(DeleteBehavior.SetNull);
}
}
} |
namespace Triton.Game.Mapping
{
using ns26;
using System;
[Attribute38("CardRewardCount")]
public class CardRewardCount : MonoBehaviour
{
public CardRewardCount(IntPtr address) : this(address, "CardRewardCount")
{
}
public CardRewardCount(IntPtr address, string className) : base(address, className)
{
}
public void Awake()
{
base.method_8("Awake", Array.Empty<object>());
}
public void Hide()
{
base.method_8("Hide", Array.Empty<object>());
}
public void SetCount(int count)
{
object[] objArray1 = new object[] { count };
base.method_8("SetCount", objArray1);
}
public void Show()
{
base.method_8("Show", Array.Empty<object>());
}
public UberText m_countText
{
get
{
return base.method_3<UberText>("m_countText");
}
}
public UberText m_multiplierText
{
get
{
return base.method_3<UberText>("m_multiplierText");
}
}
}
}
|
namespace _6.FilterStudentsByPhone
{
using System;
using System.Collections.Generic;
using System.Linq;
public class Startup
{
public static void Main(string[] args)
{
var input = Console.ReadLine();
var students = new List<string>();
while (!input.Equals("END"))
{
students.Add(input);
input = Console.ReadLine();
}
students.Select(s =>
{
var tokens = s.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
var FirstName = tokens[0];
var LastName = tokens[1];
var Phone = tokens[2];
return new {FirstName, LastName, Phone};
})
.Where(p => p.Phone.StartsWith("02") || p.Phone.StartsWith("+3592"))
.ToList()
.ForEach(c => Console.WriteLine($"{c.FirstName} {c.LastName}"));
}
}
}
|
using MISA.Core.Entities;
using MISA.Core.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MISA.Core.Services
{
public class CountryService : BaseService<Country>, ICountryService
{
IUnitOfWork _unitOfWork;
public CountryService(IUnitOfWork unitOfWork, IBaseRepository<Country> baseRepository) : base(unitOfWork,baseRepository)
{
_unitOfWork = unitOfWork;
}
public IEnumerable<Country> GetAllCountry()
{
return _unitOfWork.Country.GetEntities();
}
}
}
|
#if VRC_SDK_VRCSDK3
using UnityEngine;
using UnityEditor;
using UnityEditorInternal;
using System.Collections.Generic;
using VRC.SDK3.Avatars.Components;
using System;
using System.Linq;
public partial class AvatarDescriptorEditor3 : Editor
{
static string _eyeLookFoldoutPrefsKey = "VRCSDK3_AvatarDescriptorEditor3_EyeLookFoldout";
static string _eyeMovementFoldoutPrefsKey = "VRCSDK3_AvatarDescriptorEditor3_EyeLookFoldout_Movement";
static string _eyeTransformFoldoutPrefsKey = "VRCSDK3_AvatarDescriptorEditor3_EyeTransformFoldout";
static string _eyeRotationFoldoutPrefsKey = "VRCSDK3_AvatarDescriptorEditor3_EyeRotationFoldout";
static string _eyelidTransformFoldoutPrefsKey = "VRCSDK3_AvatarDescriptorEditor3_EyelidTransformFoldout";
static string _eyelidRotationFoldoutPrefsKey = "VRCSDK3_AvatarDescriptorEditor3_EyelidRotationFoldout";
static string _eyelidBlendshapesFoldoutPrefsKey = "VRCSDK3_AvatarDescriptorEditor3_EyeLookFoldout_EyelidBlendshapes";
static string _linkEyelidsDialog = "Link Left + Right for '{0}'?\n(using values of: {1})";
static string _activeProperty = null;
static Color _activeButtonColor = new Color(0.5f, 1, 0.5f, 1);
SkinnedMeshRenderer _currentEyelidsMesh;
string[] _eyelidBlendshapeNames;
static Texture _linkIcon;
static List<System.Action> activePropertyRestore = new List<System.Action>();
void InitEyeLook()
{
if (_linkIcon == null)
_linkIcon = Resources.Load<Texture>("EditorUI_Icons/EditorUI_Link");
EditorPrefs.SetBool(_eyeTransformFoldoutPrefsKey, true);
EditorPrefs.SetBool(_eyelidTransformFoldoutPrefsKey, true);
}
void DrawEyeLook()
{
if (Foldout(_eyeLookFoldoutPrefsKey, "Eye Look"))
{
SerializedProperty p = serializedObject.FindProperty("enableEyeLook");
bool toggle = GUILayout.Button(p.boolValue ? "Disable" : "Enable");
if (toggle)
p.boolValue = !p.boolValue;
if (p.boolValue)
{
var eyeSettings = serializedObject.FindProperty("customEyeLookSettings");
EditorGUILayout.BeginVertical();
DrawEyesGeneralBox(eyeSettings);
DrawEyesBox(eyeSettings);
DrawEyelidsBox(eyeSettings);
EditorGUILayout.EndVertical();
}
Separator();
}
}
static void DrawEyesGeneralBox(SerializedProperty eyeSettings)
{
BeginBox("General", true);
if (Foldout(_eyeMovementFoldoutPrefsKey, "Eye Movements"))
{
var eyeMovement = eyeSettings.FindPropertyRelative("eyeMovement");
var confidence = eyeMovement.FindPropertyRelative("confidence");
var excitement = eyeMovement.FindPropertyRelative("excitement");
EyeLookMovementSlider(excitement, "Calm", "Excited");
EyeLookMovementSlider(confidence, "Shy", "Confident");
}
EndBox();
}
void DrawEyesBox(SerializedProperty eyeSettings)
{
BeginBox("Eyes", true);
var leftEye = eyeSettings.FindPropertyRelative("leftEye");
var rightEye = eyeSettings.FindPropertyRelative("rightEye");
if (Foldout(_eyeTransformFoldoutPrefsKey, "Transforms", true))
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(leftEye, new GUIContent("Left Eye Bone"));
EditorGUILayout.PropertyField(rightEye, new GUIContent("Right Eye Bone"));
if(EditorGUI.EndChangeCheck())
SetActiveProperty(null); //Disable active property, maintains proper preview/undo state
}
Separator();
EditorGUI.BeginDisabledGroup(leftEye.objectReferenceValue == null || rightEye.objectReferenceValue == null);
if (Foldout(_eyeRotationFoldoutPrefsKey, "Rotation States"))
{
var eyesLookingStraight = eyeSettings.FindPropertyRelative("eyesLookingStraight");
var eyesLookingUp = eyeSettings.FindPropertyRelative("eyesLookingUp");
var eyesLookingDown = eyeSettings.FindPropertyRelative("eyesLookingDown");
var eyesLookingLeft = eyeSettings.FindPropertyRelative("eyesLookingLeft");
var eyesLookingRight = eyeSettings.FindPropertyRelative("eyesLookingRight");
RotationFieldEyeLook(eyesLookingStraight, leftEye, rightEye, "Looking Straight");
RotationFieldEyeLook(eyesLookingUp, leftEye, rightEye, "Looking Up", () => { BeginEyesUpDown(true); });
RotationFieldEyeLook(eyesLookingDown, leftEye, rightEye, "Looking Down", () => { BeginEyesUpDown(false); });
RotationFieldEyeLook(eyesLookingLeft, leftEye, rightEye, "Looking Left");
RotationFieldEyeLook(eyesLookingRight, leftEye, rightEye, "Looking Right");
}
EditorGUI.EndDisabledGroup();
EndBox();
}
void RotationFieldEyeLook(SerializedProperty property, SerializedProperty leftEyeBone, SerializedProperty rightEyeBone, string label, System.Action onSetActive=null)
{
RotationField(property, leftEyeBone, rightEyeBone, label, isActive: IsActiveProperty(property), SetActive: SetActive);
void SetActive()
{
//Set
SetActiveProperty(property);
//Check for transforms
if (((Transform)leftEyeBone.objectReferenceValue) == null || ((Transform)rightEyeBone.objectReferenceValue) == null)
return;
//Record
RecordEyeRotations(property, leftEyeBone, rightEyeBone);
//Other
onSetActive?.Invoke();
}
}
void DrawEyelidsBox(SerializedProperty eyeSettings)
{
BeginBox("Eyelids", true);
DrawEyelidType(eyeSettings);
if (avatarDescriptor.customEyeLookSettings.eyelidType == VRCAvatarDescriptor.EyelidType.Blendshapes)
{
DrawEyelidBlendshapeDropdowns(eyeSettings);
}
else if (avatarDescriptor.customEyeLookSettings.eyelidType == VRCAvatarDescriptor.EyelidType.Bones)
{
DrawEyelidBoneRotations(eyeSettings);
_currentEyelidsMesh = null;
}
else
{
_currentEyelidsMesh = null;
}
EndBox();
}
void DrawEyelidType(SerializedProperty eyeSettings)
{
EditorGUI.BeginChangeCheck();
var eyelidType = eyeSettings.FindPropertyRelative("eyelidType");
EditorGUILayout.PropertyField(eyelidType);
if (EditorGUI.EndChangeCheck())
{
if (eyelidType.enumValueIndex == (int)VRCAvatarDescriptor.EyelidType.Blendshapes)
EditorPrefs.SetBool(_eyelidBlendshapesFoldoutPrefsKey, true);
}
}
void DrawEyelidBoneRotations(SerializedProperty eyeSettings)
{
Separator();
var upperLeftEyelid = eyeSettings.FindPropertyRelative("upperLeftEyelid");
var upperRightEyelid = eyeSettings.FindPropertyRelative("upperRightEyelid");
var lowerLeftEyelid = eyeSettings.FindPropertyRelative("lowerLeftEyelid");
var lowerRightEyelid = eyeSettings.FindPropertyRelative("lowerRightEyelid");
if (Foldout(_eyelidTransformFoldoutPrefsKey, "Transforms", true))
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(upperLeftEyelid);
EditorGUILayout.PropertyField(upperRightEyelid);
EditorGUILayout.PropertyField(lowerLeftEyelid);
EditorGUILayout.PropertyField(lowerRightEyelid);
if (EditorGUI.EndChangeCheck())
SetActiveProperty(null); //Disable active property, maintains proper preview/undo state
}
Separator();
if (Foldout(_eyelidRotationFoldoutPrefsKey, "Rotation States"))
{
var eyelidsDefault = eyeSettings.FindPropertyRelative("eyelidsDefault");
var eyelidsClosed = eyeSettings.FindPropertyRelative("eyelidsClosed");
var eyelidsLookingUp = eyeSettings.FindPropertyRelative("eyelidsLookingUp");
var eyelidsLookingDown = eyeSettings.FindPropertyRelative("eyelidsLookingDown");
GUILayout.BeginHorizontal();
GUILayout.Space(16);
GUILayout.BeginVertical();
RotationFieldEyelids(eyelidsDefault, upperLeftEyelid, upperRightEyelid, lowerLeftEyelid, lowerRightEyelid, "Default");
RotationFieldEyelids(eyelidsClosed, upperLeftEyelid, upperRightEyelid, lowerLeftEyelid, lowerRightEyelid, "Closed");
RotationFieldEyelids(eyelidsLookingUp, upperLeftEyelid, upperRightEyelid, lowerLeftEyelid, lowerRightEyelid, "Looking Up", () => { BeginEyesUpDown(true); } );
RotationFieldEyelids(eyelidsLookingDown, upperLeftEyelid, upperRightEyelid, lowerLeftEyelid, lowerRightEyelid, "Looking Down", () => { BeginEyesUpDown(false); });
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
}
void RotationFieldEyelids(SerializedProperty property,
SerializedProperty upperLeftBone, SerializedProperty upperRightBone,
SerializedProperty lowerLeftBone, SerializedProperty lowerRightBone,
string label = null,
System.Action onSetActive=null)
{
var upperProperty = property.FindPropertyRelative("upper");
var lowerProperty = property.FindPropertyRelative("lower");
GUILayout.BeginHorizontal();
if (EditorGUILayout.PropertyField(property, new GUIContent(label), GUILayout.MinWidth(100)))
{
Button();
GUILayout.EndHorizontal();
GUILayout.BeginVertical();
RotationField(upperProperty, upperLeftBone, upperRightBone, "Upper Eyelids", showButton:false, isActive:IsActiveProperty(property), SetActive:SetActive);
RotationField(lowerProperty, lowerLeftBone, lowerRightBone, "Lower Eyelids", showButton:false, isActive:IsActiveProperty(property), SetActive:SetActive);
GUILayout.EndVertical();
}
else
{
Button();
GUILayout.EndHorizontal();
}
void SetActive()
{
SetActiveProperty(property);
//Record
RecordEyeRotations(upperProperty, upperLeftBone, upperRightBone);
RecordEyeRotations(lowerProperty, lowerLeftBone, lowerRightBone);
//Other
onSetActive?.Invoke();
}
void Button()
{
bool isActiveProperty = IsActiveProperty(property);
GUI.backgroundColor = isActiveProperty ? _activeButtonColor : Color.white;
if (GUILayout.Button(isActiveProperty ? "Return" : "Preview", EditorStyles.miniButton, GUILayout.MaxWidth(PreviewButtonWidth), GUILayout.Height(PreviewButtonHeight)))
{
if(isActiveProperty)
{
SetActiveProperty(null);
}
else
{
SetActive();
}
}
GUI.backgroundColor = Color.white;
}
}
void DrawEyelidBlendshapeDropdowns(SerializedProperty eyeSettings)
{
Separator();
var eyelidsMeshProp = eyeSettings.FindPropertyRelative("eyelidsSkinnedMesh");
eyelidsMeshProp.objectReferenceValue = (SkinnedMeshRenderer)EditorGUILayout.ObjectField("Eyelids Mesh", eyelidsMeshProp.objectReferenceValue, typeof(SkinnedMeshRenderer), true);
if (eyelidsMeshProp.objectReferenceValue == null)
{
_eyelidBlendshapeNames = null;
return;
}
if (_currentEyelidsMesh == null)
{
_currentEyelidsMesh = (SkinnedMeshRenderer)eyelidsMeshProp.objectReferenceValue;
_eyelidBlendshapeNames = GetBlendShapeNames(_currentEyelidsMesh);
}
var eyelidsBlendshapes = eyeSettings.FindPropertyRelative("eyelidsBlendshapes");
if (Foldout(_eyelidBlendshapesFoldoutPrefsKey, "Blendshape States"))
{
if (eyelidsBlendshapes.arraySize != 3)
eyelidsBlendshapes.arraySize = 3;
int[] indices = new int[] { eyelidsBlendshapes.GetArrayElementAtIndex(0).intValue,
eyelidsBlendshapes.GetArrayElementAtIndex(1).intValue,
eyelidsBlendshapes.GetArrayElementAtIndex(2).intValue};
PreviewBlendshapeField("Blink", 0, eyelidsBlendshapes.GetArrayElementAtIndex(0));
PreviewBlendshapeField("Looking Up", 1, eyelidsBlendshapes.GetArrayElementAtIndex(1), () => { BeginEyesUpDown(true); });
PreviewBlendshapeField("Looking Down", 2, eyelidsBlendshapes.GetArrayElementAtIndex(2), () => { BeginEyesUpDown(false); });
}
}
/*static float NormalizedDegAngle ( float degrees )
{
int factor = (int) (degrees/360);
degrees -= factor * 360;
if ( degrees > 180 )
return degrees - 360;
if ( degrees < -180 )
return degrees + 360;
return degrees;
}
static Vector3 NormalizedEulers(Vector3 eulers)
{
Vector3 normEulers;
normEulers.x = NormalizedDegAngle(eulers.x);
normEulers.y = NormalizedDegAngle(eulers.y);
normEulers.z = NormalizedDegAngle(eulers.z);
return normEulers;
}*/
static int PreviewButtonWidth = 55;
static int PreviewButtonHeight = 24;
static void RecordEyeRotations(SerializedProperty property, SerializedProperty leftEyeBone, SerializedProperty rightEyeBone)
{
//Record restore point
var transformL = (Transform)leftEyeBone.objectReferenceValue;
var transformR = (Transform)rightEyeBone.objectReferenceValue;
var prevRotationL = transformL != null ? transformL.localRotation : Quaternion.identity;
var prevRotationR = transformR != null ? transformR.localRotation : Quaternion.identity;
System.Action restore = () =>
{
if (transformL != null)
transformL.localRotation = prevRotationL;
if (transformR != null)
transformR.localRotation = prevRotationR;
};
activePropertyRestore.Add(restore);
//Set to value
var leftRotation = property.FindPropertyRelative("left");
var rightRotation = property.FindPropertyRelative("right");
if(transformL != null)
transformL.localRotation = leftRotation.quaternionValue;
if (transformR != null)
transformR.localRotation = rightRotation.quaternionValue;
}
void BeginEyesUpDown(bool isUp)
{
var eyeSettings = serializedObject.FindProperty("customEyeLookSettings");
//Record - Eye Up
{
var eyesLooking = eyeSettings.FindPropertyRelative(isUp ? "eyesLookingUp" : "eyesLookingDown");
var leftEye = eyeSettings.FindPropertyRelative("leftEye");
var rightEye = eyeSettings.FindPropertyRelative("rightEye");
RecordEyeRotations(eyesLooking, leftEye, rightEye);
}
//Record - Eyelid Up Bones
if (avatarDescriptor.customEyeLookSettings.eyelidType == VRCAvatarDescriptor.EyelidType.Bones)
{
var upperLeftEyelid = eyeSettings.FindPropertyRelative("upperLeftEyelid");
var upperRightEyelid = eyeSettings.FindPropertyRelative("upperRightEyelid");
var lowerLeftEyelid = eyeSettings.FindPropertyRelative("lowerLeftEyelid");
var lowerRightEyelid = eyeSettings.FindPropertyRelative("lowerRightEyelid");
var eyelidsLooking = eyeSettings.FindPropertyRelative(isUp ? "eyelidsLookingUp" : "eyelidsLookingDown");
var upperProperty = eyelidsLooking.FindPropertyRelative("upper");
var lowerProperty = eyelidsLooking.FindPropertyRelative("lower");
RecordEyeRotations(upperProperty, upperLeftEyelid, upperRightEyelid);
RecordEyeRotations(lowerProperty, lowerLeftEyelid, lowerRightEyelid);
}
//Record - Eyelid Blendshapes
if (avatarDescriptor.customEyeLookSettings.eyelidType == VRCAvatarDescriptor.EyelidType.Blendshapes)
{
var eyelidsBlendshapes = eyeSettings.FindPropertyRelative("eyelidsBlendshapes");
var blendshapeIndex = eyelidsBlendshapes.GetArrayElementAtIndex(isUp ? 1 : 2);
RecordBlendShape(blendshapeIndex.intValue);
}
}
static Vector3 EditorQuaternionToVector3(Quaternion value)
{
var result = value.eulerAngles;
//Fix the axis flipping
if(Mathf.Approximately(value.eulerAngles.y, 180) && Mathf.Approximately(value.eulerAngles.z, 180))
{
if (result.x < 90.0f)
result.x = 90f + (90f - result.x);
else
result.x = 270f + (270f - result.x);
result.y = 0;
result.z = 0;
}
//Represent angle as -180 to 180
if (result.x > 180.0f)
result.x = -(360f-result.x);
if (result.y > 180.0f)
result.y = -(360f - result.y);
if (result.z > 180.0f)
result.z = -(360f - result.z);
//Prevent small number in editor, they arn't nessecary here
if (result.x < 0.001f && result.x > -0.001f)
result.x = 0f;
if (result.y < 0.001f && result.y > -0.001f)
result.y = 0f;
if (result.z < 0.001f && result.z > -0.001f)
result.z = 0f;
//Return
return result;
}
static bool RotationField(SerializedProperty property, SerializedProperty leftEyeBone, SerializedProperty rightEyeBone, string label = null, bool showButton = true, bool isActive=false, System.Action SetActive=null)
{
bool dirty = false;
EditorGUI.BeginChangeCheck();
GUILayout.BeginHorizontal();
var leftRotation = property.FindPropertyRelative("left");
var rightRotation = property.FindPropertyRelative("right");
var linked = property.FindPropertyRelative("linked");
GUILayout.BeginVertical();
label = string.IsNullOrEmpty(label) ? property.displayName : label;
if (GUILayout.Button(label, EditorStyles.label))
dirty = true;
if (linked.boolValue)
{
GUILayout.BeginHorizontal();
{
//Link button
GUI.color = GUI.skin.label.normal.textColor;
if (GUILayout.Button(new GUIContent(_linkIcon), GUI.skin.label, GUILayout.MaxWidth(16)))
linked.boolValue = false;
GUI.color = Color.white;
var testA1 = Quaternion.Euler(new Vector3(20, 0, 0)).eulerAngles;
var testA2 = Quaternion.Euler(new Vector3(45, 0, 0)).eulerAngles;
var testA3 = Quaternion.Euler(new Vector3(90, 0, 0)).eulerAngles;
var testA4 = Quaternion.Euler(new Vector3(95, 0, 0)).eulerAngles;
var testA5 = Quaternion.Euler(new Vector3(120, 0, 0)).eulerAngles;
var testB1 = EditorQuaternionToVector3(Quaternion.Euler(new Vector3(20, 0, 0)));
var testB2 = EditorQuaternionToVector3(Quaternion.Euler(new Vector3(45, 0, 0)));
var testB3 = EditorQuaternionToVector3(Quaternion.Euler(new Vector3(90, 0, 0)));
var testB4 = EditorQuaternionToVector3(Quaternion.Euler(new Vector3(95, 0, 0)));
var testB5 = EditorQuaternionToVector3(Quaternion.Euler(new Vector3(120, 0, 0)));
//Values
//leftRotation.quaternionValue = EditorGUILayout.Vector3Field(GUIContent.none, QuaternionToVector3(leftRotation.quaternionValue), GUILayout.MinWidth(100)));
leftRotation.quaternionValue = Quaternion.Euler( EditorGUILayout.Vector3Field(GUIContent.none, EditorQuaternionToVector3(leftRotation.quaternionValue), GUILayout.MinWidth(100)) );
rightRotation.quaternionValue = leftRotation.quaternionValue;
}
GUILayout.EndHorizontal();
}
else
{
GUIStyle style = new GUIStyle(EditorStyles.boldLabel);
style.contentOffset = new Vector2(0, -4);
GUILayout.BeginHorizontal();
if (GUILayout.Button("L", style, GUILayout.MaxHeight(16)))
{
string message = string.Format(_linkEyelidsDialog, label, "L");
if ((rightRotation.quaternionValue == leftRotation.quaternionValue)
|| EditorUtility.DisplayDialog("Collapse?", message, "Yes", "No"))
{
linked.boolValue = true;
rightRotation.quaternionValue = leftRotation.quaternionValue;
}
}
leftRotation.quaternionValue = Quaternion.Euler(EditorGUILayout.Vector3Field(GUIContent.none, EditorQuaternionToVector3(leftRotation.quaternionValue), GUILayout.MinWidth(100)));
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
if (GUILayout.Button("R", style, GUILayout.MaxHeight(16)))
{
string message = string.Format(_linkEyelidsDialog, label, "R");
if ((leftRotation.quaternionValue == rightRotation.quaternionValue)
|| (EditorUtility.DisplayDialog("Collapse?", message, "Yes", "No")))
{
linked.boolValue = true;
leftRotation.quaternionValue = rightRotation.quaternionValue;
}
}
rightRotation.quaternionValue = Quaternion.Euler(EditorGUILayout.Vector3Field(GUIContent.none, EditorQuaternionToVector3(rightRotation.quaternionValue), GUILayout.MinWidth(100)));
GUILayout.EndHorizontal();
}
GUILayout.EndVertical();
GUILayout.FlexibleSpace();
GUILayout.BeginVertical();
bool changed = EditorGUI.EndChangeCheck();
//Edit button
if (showButton)
{
GUI.backgroundColor = (isActive ? _activeButtonColor : Color.white);
GUILayout.BeginVertical();
GUILayout.Space(linked.boolValue ? 4 : 20);
if (GUILayout.Button(isActive ? "Return" : "Preview", EditorStyles.miniButton, GUILayout.Width(PreviewButtonWidth), GUILayout.Height(PreviewButtonHeight)))
{
if (isActive)
{
SetActiveProperty(null);
isActive = false;
}
else
{
SetActive();
isActive = true;
}
dirty = _repaint = true;
}
GUILayout.EndVertical();
GUI.backgroundColor = Color.white;
}
GUILayout.EndVertical();
GUILayout.EndHorizontal();
//Mark active if changed
if(changed)
{
//Set active if not already
if (!isActive)
{
SetActive();
isActive = true;
}
//Mark dirty
dirty = _repaint = true;
}
//Update values, always update if active not only on change.
//We do this because the user may change values with a control-z/undo operation
if (isActive)
{
//Left
var leftEyeTransform = (Transform)leftEyeBone.objectReferenceValue;
if (leftEyeTransform != null)
leftEyeTransform.localRotation = leftRotation.quaternionValue;
//Right
var rightEyeTransform = (Transform)rightEyeBone.objectReferenceValue;
if (rightEyeTransform != null)
rightEyeTransform.localRotation = rightRotation.quaternionValue;
}
//Return
return dirty;
}
void PreviewBlendshapeField(string label, int buttonIndex, SerializedProperty blendShapeIndex, System.Action onSetActive=null)
{
if (_eyelidBlendshapeNames == null)
return;
bool setActive = false;
GUILayout.BeginHorizontal();
{
//Dropdown
EditorGUI.BeginChangeCheck();
blendShapeIndex.intValue = EditorGUILayout.Popup(label, blendShapeIndex.intValue + 1, _eyelidBlendshapeNames) - 1;
if (EditorGUI.EndChangeCheck())
{
SetActiveProperty(null);
setActive = true;
}
//Preview
bool isActiveProperty = IsActiveProperty(blendShapeIndex);
GUI.backgroundColor = isActiveProperty ? _activeButtonColor : Color.white;
if (GUILayout.Button(isActiveProperty ? "Return" : "Preview", EditorStyles.miniButton, GUILayout.MaxWidth(PreviewButtonWidth)) || setActive)
{
if (isActiveProperty)
{
SetActiveProperty(null);
}
else
{
onSetActive?.Invoke();
SetActiveProperty(blendShapeIndex);
//Record
RecordBlendShape(blendShapeIndex.intValue);
//Other
onSetActive?.Invoke();
}
}
GUI.backgroundColor = Color.white;
}
GUILayout.EndHorizontal();
}
void RecordBlendShape(int index, float newWeight = 100.0f)
{
//Validate
if (avatarDescriptor.customEyeLookSettings.eyelidsSkinnedMesh == null || index < 0 || index >= avatarDescriptor.customEyeLookSettings.eyelidsSkinnedMesh.sharedMesh.blendShapeCount)
return;
//Record old position
int oldIndex = index;
float oldWeight = avatarDescriptor.customEyeLookSettings.eyelidsSkinnedMesh.GetBlendShapeWeight(index);
System.Action restore = () =>
{
avatarDescriptor.customEyeLookSettings.eyelidsSkinnedMesh.SetBlendShapeWeight(oldIndex, oldWeight);
};
activePropertyRestore.Add(restore);
//Set new weight
avatarDescriptor.customEyeLookSettings.eyelidsSkinnedMesh.SetBlendShapeWeight(index, newWeight);
}
void ResetBlendshapes(int[] indices)
{
for (int v = 0; v < indices.Length; v++)
{
if (indices[v] < 0) continue;
avatarDescriptor.customEyeLookSettings.eyelidsSkinnedMesh.SetBlendShapeWeight(indices[v], 0);
}
}
static void EyeLookMovementSlider(SerializedProperty property, string minLabel, string maxLabel)
{
GUIStyle style = new GUIStyle(EditorStyles.miniLabel);
style.alignment = TextAnchor.MiddleRight;
style.padding.left = 10;
style.padding.right = 10;
GUILayout.BeginHorizontal();
GUILayout.Label(GUIContent.none);
Rect r = GUILayoutUtility.GetLastRect();
// left word
float leftLabelWidth = r.width * 0.2f;
float rightLabelWidth = r.width * 0.3f;
float sliderWidth = r.width * 0.5f;
r.width = leftLabelWidth;
GUI.Label(r, minLabel, style);
r.x += r.width;
// slider
r.width = sliderWidth;
property.floatValue = GUI.HorizontalSlider(r, property.floatValue, 0f, 1f);
property.floatValue = Mathf.Round(property.floatValue * 10) * 0.1f;
r.x += r.width;
// right word
r.width = rightLabelWidth;
style.alignment = TextAnchor.MiddleLeft;
GUI.Label(r, maxLabel, style);
GUILayout.EndHorizontal();
}
static bool IsActiveProperty(SerializedProperty property)
{
return (_activeProperty != null) && _activeProperty.Equals(property.propertyPath, System.StringComparison.Ordinal);
}
static void SetActiveProperty(SerializedProperty property)
{
if (_activeProperty == property?.propertyPath)
return;
//Set
_activeProperty = (property?.propertyPath);
//Restore previous state
activePropertyRestore.Reverse(); //Iterate from last to first
foreach (var restore in activePropertyRestore)
restore();
activePropertyRestore.Clear();
//Redraw
_repaint = true;
}
public static string[] GetBlendShapeNames(SkinnedMeshRenderer skinnedMeshRenderer)
{
if (!skinnedMeshRenderer)
return null;
string[] names = new string[skinnedMeshRenderer.sharedMesh.blendShapeCount+1];
names[0] = "-none-";
for (int v = 0; v < skinnedMeshRenderer.sharedMesh.blendShapeCount; v++)
{
names[v+1] = skinnedMeshRenderer.sharedMesh.GetBlendShapeName(v);
}
return names;
}
void DrawSceneViewpoint()
{
var viewPosition = serializedObject.FindProperty("ViewPosition");
if(IsActiveProperty(viewPosition))
{
viewPosition.vector3Value = Handles.PositionHandle(viewPosition.vector3Value, Quaternion.identity);
}
}
void DrawSceneEyeLook()
{
var eyeSettings = serializedObject.FindProperty("customEyeLookSettings");
var leftEye = eyeSettings.FindPropertyRelative("leftEye");
var rightEye = eyeSettings.FindPropertyRelative("rightEye");
//Eye Rotation State
DrawSceneEyes(eyeSettings.FindPropertyRelative("eyesLookingStraight"), leftEye, rightEye);
DrawSceneEyes(eyeSettings.FindPropertyRelative("eyesLookingUp"), leftEye, rightEye);
DrawSceneEyes(eyeSettings.FindPropertyRelative("eyesLookingDown"), leftEye, rightEye);
DrawSceneEyes(eyeSettings.FindPropertyRelative("eyesLookingLeft"), leftEye, rightEye);
DrawSceneEyes(eyeSettings.FindPropertyRelative("eyesLookingRight"), leftEye, rightEye);
//Eyelid Rotation States
if(avatarDescriptor.customEyeLookSettings.eyelidType == VRCAvatarDescriptor.EyelidType.Bones)
{
var upperLeftEyelid = eyeSettings.FindPropertyRelative("upperLeftEyelid");
var upperRightEyelid = eyeSettings.FindPropertyRelative("upperRightEyelid");
var lowerLeftEyelid = eyeSettings.FindPropertyRelative("lowerLeftEyelid");
var lowerRightEyelid = eyeSettings.FindPropertyRelative("lowerRightEyelid");
DrawSceneEyelids(eyeSettings.FindPropertyRelative("eyelidsDefault"), upperLeftEyelid, upperRightEyelid, lowerLeftEyelid, lowerRightEyelid);
DrawSceneEyelids(eyeSettings.FindPropertyRelative("eyelidsClosed"), upperLeftEyelid, upperRightEyelid, lowerLeftEyelid, lowerRightEyelid);
DrawSceneEyelids(eyeSettings.FindPropertyRelative("eyelidsLookingUp"), upperLeftEyelid, upperRightEyelid, lowerLeftEyelid, lowerRightEyelid);
DrawSceneEyelids(eyeSettings.FindPropertyRelative("eyelidsLookingDown"), upperLeftEyelid, upperRightEyelid, lowerLeftEyelid, lowerRightEyelid);
}
}
void DrawSceneEyes(SerializedProperty property, SerializedProperty leftEye, SerializedProperty rightEye, bool checkActive=true)
{
if (checkActive && !IsActiveProperty(property))
return;
var leftRotation = property.FindPropertyRelative("left");
var rightRotation = property.FindPropertyRelative("right");
var linked = property.FindPropertyRelative("linked").boolValue;
bool changeL = DrawRotationHandles(leftEye, leftRotation);
bool changeR = DrawRotationHandles(rightEye, rightRotation);
if(linked)
{
if(changeL)
{
var rotation = leftRotation.quaternionValue;
(rightEye.objectReferenceValue as Transform).localRotation = rotation;
rightRotation.quaternionValue = rotation;
}
else if (changeR)
{
var rotation = rightRotation.quaternionValue;
(leftEye.objectReferenceValue as Transform).localRotation = rotation;
leftRotation.quaternionValue = rotation;
}
}
}
void DrawSceneEyelids(SerializedProperty property, SerializedProperty upperLeftEyelid, SerializedProperty upperRightEyelid, SerializedProperty lowerLeftEyelid, SerializedProperty lowerRightEyelid)
{
if (!IsActiveProperty(property))
return;
var upperProperty = property.FindPropertyRelative("upper");
var lowerProperty = property.FindPropertyRelative("lower");
DrawSceneEyes(upperProperty, upperLeftEyelid, upperRightEyelid, false);
DrawSceneEyes(lowerProperty, lowerLeftEyelid, lowerRightEyelid, false);
}
bool DrawRotationHandles(SerializedProperty transformProperty, SerializedProperty rotationProperty)
{
var transform = transformProperty.objectReferenceValue as Transform;
if (transform == null)
return false;
Handles.matrix = Matrix4x4.TRS(transform.position, transform.parent.rotation, Vector3.one);
transform.localRotation = rotationProperty.quaternionValue;
var result = Handles.RotationHandle(transform.localRotation, Vector3.zero);
if (result != transform.localRotation)
{
transform.localRotation = result;
rotationProperty.quaternionValue = result;
return true;
}
Handles.matrix = Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one);
Handles.color = new Color(1, 1, 1, 0.5f);
Handles.DrawWireDisc(Vector3.zero, Vector3.forward, 0.01f);
return false;
}
}
#endif
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectEuler
{
public class LongestCollatzSequence : ISolution
{
public void Run()
{
var longestSequences = Enumerable.Range(1, 999999).AsParallel().Select(Sequence).OrderByDescending(x => x.Count()).ToList();
var longestSequence = longestSequences.First();
Result = String.Join(" --> ", longestSequence.Select(x => x.ToString()));
}
public object Result { get; private set; }
static long Next(long number)
{
return number % 2L == 0L ? number / 2L : 3L * number + 1L;
}
static IEnumerable<long> Sequence(int start)
{
var number = (long)start;
while (number != 1L)
{
yield return number;
number = Next(number);
}
yield return 1L;
}
}
}
|
namespace CriticalPath.Web.Models
{
public class ImageUploadViewModel
{
public ImageUploadViewModel()
{
UploadUrl = AppSettings.Urls.ImageUpload;
ThumbFolderUrl = AppSettings.Urls.ThumbImages;
ImageFolderUrl = AppSettings.Urls.ProductImages;
}
public ImageUploadViewModel(string propertyName)
: this()
{
PropertyName = propertyName;
}
public ImageUploadViewModel(string propertyName, string imageName)
: this(propertyName)
{
ImageName = imageName;
}
public int Id { get; set; }
public string PropertyName { get; set; }
public string ImageFolderUrl { get; set; }
public string ImageName { get; set; }
public bool MultiUpload { get; set; }
public string ThumbFolderUrl { get; set; }
public string UploadUrl { get; set; }
}
} |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CoinTable.Models
{
[JsonObject]
public class Coin
{
[JsonProperty("id")]
public int id { get; set; }
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("symbol")]
public string symbol { get; set; }
[JsonProperty("logo")]
public string logo { get; set; }
[JsonProperty("price")]
public double price { get; set; }
[JsonProperty("percent_change_1h")]
public double percent_change_1h { get; set; }
[JsonProperty("percent_change_24h")]
public double percent_change_24h { get; set; }
[JsonProperty("market_cap")]
public int market_cap { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace JJTrailerStore.Areas.Admin.Models
{
public class Category
{
//general
public Guid ID { get; set; }
public string Name { get; set; }
[UIHint("Redactor")]
[DataType(DataType.Html)]
[AllowHtml]
public string Description { get; set; }
public string MetaTagDescription { get; set; }
public string MetaTagKeywords { get; set; }
//data
public Guid? CategoryImageID { get; set; }
public Guid? CategoryID { get; set; }
public bool Status { get; set; }
}
} |
using System;
using Whale.Shared.Models.User;
namespace Whale.Shared.Models.Group.GroupUser
{
public class GroupUserDTO
{
public Guid Id { get; set; }
public Guid UserId { get; set; }
public UserDTO User { get; set; }
public Guid GroupId { get; set; }
public GroupDTO Group { get; set; }
}
}
|
namespace EP.CrudModalDDD.Domain.Commands.Results
{
public class CidadeCommandResult : ICommandResult
{
public CidadeCommandResult()
{
}
}
} |
namespace kelvinho_airlines.Entities.CrewMembers
{
public class Officer : TechnicalCrewMember
{
public Officer(string name) : base(name)
{
IncompatibleCrewMemberTypes.Add(typeof(Prisoner));
IncompatibleCrewMemberTypes.Add(typeof(FlightServiceChief));
}
}
} |
using SQLite;
using System;
using uwpEvernote.Interfaces;
namespace uwpEvernote.Model {
public class Note: Notify {
private int _id;
[PrimaryKey, AutoIncrement]
public int Id {
get { return _id; }
set {
if (value != _id) {
_id = value;
OnPropertyChanged("id");
}
}
}
private int _notebookId;
[Indexed]
public int NotebookId {
get { return _notebookId; }
set {
if (value != _notebookId) {
_notebookId = value;
OnPropertyChanged("notebookId");
}
}
}
private string _title;
public string Title {
get { return _title; }
set {
if (value != _title) {
_title = value;
OnPropertyChanged("title");
}
}
}
private DateTime _cratedTime;
public DateTime CratedTime {
get { return _cratedTime; }
set {
if (value != _cratedTime) {
_cratedTime = value;
OnPropertyChanged("cratedTime");
}
}
}
private DateTime _updatedTime;
public DateTime UpdatedTime {
get { return _updatedTime; }
set {
if (value != _updatedTime) {
_updatedTime = value;
OnPropertyChanged("updatedTime");
}
}
}
private string _filePath;
public string FilePath {
get { return _filePath; }
set {
if (value != _filePath) {
_filePath = value;
OnPropertyChanged("filePath");
}
}
}
}
}
|
using Panoptes.Model.Serialization.Packets;
using QuantConnect;
using QuantConnect.Orders;
using QuantConnect.Statistics;
using System;
using System.Collections.Generic;
using BacktestResultParameters = QuantConnect.Packets.BacktestResultParameters;
using LiveResultParameters = QuantConnect.Packets.LiveResultParameters;
namespace Panoptes.Model
{
public sealed class ResultConverter : IResultConverter
{
/* QuantConnect results are either BacktestResult or LiveResult.
* They have common properties as well as specific properties.
* However, the QC libary has no base class for them. For this tool, we do need a baseclass
* This baseclass is 'Result' which remembers the actual result type, and has all possible fields to show in the UI
*/
public QCResult FromBacktestResult(BacktestResult backtestResult)
{
return new QCResult
{
ResultType = ResultType.Backtest,
Charts = new Dictionary<string, Charting.ChartDefinition>(backtestResult.Charts.MapToChartDefinitionDictionary()),
Orders = new Dictionary<int, Order>(backtestResult.Orders ?? new Dictionary<int, Order>()),
ProfitLoss = new Dictionary<DateTime, decimal>(backtestResult.ProfitLoss ?? new Dictionary<DateTime, decimal>()),
Statistics = new Dictionary<string, string>(backtestResult.Statistics ?? new Dictionary<string, string>()),
RuntimeStatistics = new Dictionary<string, string>(backtestResult.RuntimeStatistics ?? new Dictionary<string, string>()),
//ServerStatistics = new Dictionary<string, string>(backtestResult.ServerStatistics ?? new Dictionary<string, string>()), // No server stats in backtest?
RollingWindow = new Dictionary<string, AlgorithmPerformance>(backtestResult.RollingWindow ?? new Dictionary<string, AlgorithmPerformance>()),
OrderEvents = backtestResult.OrderEvents,
};
}
public QCResult FromLiveResult(LiveResult liveResult)
{
return new QCResult
{
ResultType = ResultType.Live,
Charts = new Dictionary<string, Charting.ChartDefinition>(liveResult.Charts.MapToChartDefinitionDictionary() ?? new Dictionary<string, Charting.ChartDefinition>()),
Orders = new Dictionary<int, Order>(liveResult.Orders ?? new Dictionary<int, Order>()),
ProfitLoss = new Dictionary<DateTime, decimal>(liveResult.ProfitLoss ?? new Dictionary<DateTime, decimal>()),
Statistics = new Dictionary<string, string>(liveResult.Statistics ?? new Dictionary<string, string>()),
RuntimeStatistics = new Dictionary<string, string>(liveResult.RuntimeStatistics ?? new Dictionary<string, string>()),
ServerStatistics = new Dictionary<string, string>(liveResult.ServerStatistics ?? new Dictionary<string, string>()),
OrderEvents = liveResult.OrderEvents,
Holdings = new Dictionary<string, Holding>(liveResult.Holdings ?? new Dictionary<string, Holding>()),
Cash = liveResult.Cash,
AccountCurrency = liveResult.AccountCurrency,
AccountCurrencySymbol = liveResult.AccountCurrencySymbol
};
}
public BacktestResult ToBacktestResult(QCResult result)
{
if (result == null) throw new ArgumentNullException(nameof(result));
if (result.ResultType != ResultType.Backtest) throw new ArgumentException("Result is not of type Backtest", nameof(result));
// Total performance is always null in the original data holder
var backtestResultParameters = new BacktestResultParameters(result.Charts.MapToChartDictionary(), result.Orders, result.ProfitLoss, result.Statistics, result.RuntimeStatistics, result.RollingWindow, null, null);
return new BacktestResult(backtestResultParameters);
}
public LiveResult ToLiveResult(QCResult result)
{
if (result == null) throw new ArgumentNullException(nameof(result));
if (result.ResultType != ResultType.Live) throw new ArgumentException("Result is not of type Live", nameof(result));
var liveResultParameters = new LiveResultParameters(result.Charts.MapToChartDictionary(),
result.Orders, result.ProfitLoss, result.Holdings,
null, result.Statistics, result.RuntimeStatistics, // result.CashBook
null, result.ServerStatistics);
return new LiveResult(liveResultParameters);
}
}
}
|
using InterfaceClasseAbstr.Modelo.Contratos;
using InterfaceClasseAbstr.Modelo.Enums;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
namespace InterfaceClasseAbstr.Modelo.Entidades
{
abstract class Forma : IForma
{
public Cor Cor { get; set; }
public abstract double Area();
}
}
|
namespace HangMan
{
public interface IWordGenerator
{
string GetWord();
}
}
|
using Nop.Core.Domain.Blogs;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Forums;
using Nop.Core.Domain.Messages;
using Nop.Core.Domain.News;
using Nop.Core.Domain.Orders;
using Nop.Core.Domain.Shipping;
using Nop.Core.Domain.Stores;
using Nop.Core.Domain.Vendors;
namespace ToSic.Nop.Plugins.RazorMessageService
{
/// <summary>
/// Model used to generate DummyMessage
/// </summary>
/// <remarks>Must be public so it can be accessed by RazorEngine!</remarks>
public class DummyMessageModel
{
public Store Store { get; set; } = new Store();
public BlogComment BlogComment { get; set; } = new BlogComment();
public Customer Customer { get; set; } = new Customer();
public BackInStockSubscription BackInStockSubscription { get; set; } = new BackInStockSubscription();
public OrderNote OrderNote { get; set; } = new OrderNote();
public Order Order { get; set; } = new Order();
public PrivateMessage PrivateMessage { get; set; } = new PrivateMessage();
public ForumPost ForumPost { get; set; } = new ForumPost();
public ForumTopic ForumTopic { get; set; } = new ForumTopic();
public Forum Forum { get; set; } = new Forum();
public GiftCard GiftCard { get; set; } = new GiftCard();
public ReturnRequest ReturnRequest { get; set; } = new ReturnRequest();
public OrderItem OrderItem { get; set; } = new OrderItem();
public NewsComment NewsComment { get; set; } = new NewsComment();
public NewsLetterSubscription Subscription { get; set; } = new NewsLetterSubscription();
public string VatName { get; set; } = string.Empty;
public string VatAddress { get; set; } = string.Empty;
public Vendor Vendor { get; set; } = new Vendor();
public decimal RefundedAmount { get; set; } = 0m;
public ProductReview ProductReview { get; set; } = new ProductReview();
public Product Product { get; set; } = new Product();
public RecurringPayment RecurringPayment { get; set; } = new RecurringPayment();
public string PersonalMessage { get; set; } = string.Empty;
public string CustomerEmail { get; set; } = string.Empty;
public Shipment Shipment { get; set; } = new Shipment();
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AudioStateChangeEnabler : MonoBehaviour
{
[SerializeField] private AudioSource _AudioSource;
[SerializeField] private SOSwitchState _SwitchStateRef;
private void OnEnable()
{
_SwitchStateRef.Instance.Value.SwitchStatesEvent += StatesSwitched;
}
private void StatesSwitched()
{
if (_SwitchStateRef.Instance.Value.IsInDriveState % 2 == 0)
{
_AudioSource.Play();
}
else
{
_AudioSource.Stop();
}
}
}
|
using MediatR;
using OmniSharp.Extensions.JsonRpc;
using OmniSharp.Extensions.JsonRpc.Generation;
using OmniSharp.Extensions.LanguageServer.Protocol.Client;
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
using OmniSharp.Extensions.LanguageServer.Protocol.Serialization;
using OmniSharp.Extensions.LanguageServer.Protocol.Server;
// ReSharper disable once CheckNamespace
namespace OmniSharp.Extensions.LanguageServer.Protocol
{
namespace Models
{
[Serial]
[Method(WindowNames.WorkDoneProgressCreate, Direction.ServerToClient)]
[GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Window"), GenerateHandlerMethods,
GenerateRequestMethods(typeof(IWindowLanguageServer), typeof(ILanguageServer))]
public partial record WorkDoneProgressCreateParams : IRequest
{
/// <summary>
/// The token to be used to report progress.
/// </summary>
public ProgressToken? Token { get; init; }
}
[Serial]
[Method(WindowNames.WorkDoneProgressCancel, Direction.ClientToServer)]
[GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Window"), GenerateHandlerMethods,
GenerateRequestMethods(typeof(IWindowLanguageClient), typeof(ILanguageClient))]
public partial record WorkDoneProgressCancelParams : IRequest
{
/// <summary>
/// The token to be used to report progress.
/// </summary>
public ProgressToken? Token { get; init; }
}
public interface IWorkDoneProgressParams
{
/// <summary>
/// An optional token that a server can use to report work done progress.
/// </summary>
[Optional]
ProgressToken? WorkDoneToken { get; init; }
}
public interface IWorkDoneProgressOptions
{
[Optional] bool WorkDoneProgress { get; set; }
}
public abstract record WorkDoneProgress
{
public WorkDoneProgress(WorkDoneProgressKind kind) => Kind = kind;
public WorkDoneProgressKind Kind { get; }
/// <summary>
/// Optional, a final message indicating to for example indicate the outcome
/// of the operation.
/// </summary>
[Optional]
public string? Message { get; init; }
}
[StringEnum]
public readonly partial struct WorkDoneProgressKind
{
public static WorkDoneProgressKind Begin { get; } = new WorkDoneProgressKind("begin");
public static WorkDoneProgressKind End { get; } = new WorkDoneProgressKind("end");
public static WorkDoneProgressKind Report { get; } = new WorkDoneProgressKind("report");
}
/// <summary>
/// To start progress reporting a `$/progress` notification with the following payload must be sent
/// </summary>
public record WorkDoneProgressBegin : WorkDoneProgress
{
public WorkDoneProgressBegin() : base(WorkDoneProgressKind.Begin)
{
}
/// <summary>
/// Mandatory title of the progress operation. Used to briefly inform about
/// the kind of operation being performed.
///
/// Examples: "Indexing" or "Linking dependencies".
/// </summary>
public string Title { get; init; } = null!;
/// <summary>
/// Controls if a cancel button should show to allow the user to cancel the
/// long running operation. Clients that don't support cancellation are allowed
/// to ignore the setting.
/// </summary>
[Optional]
public bool Cancellable { get; init; }
/// <summary>
/// Optional progress percentage to display (value 100 is considered 100%).
/// If not provided infinite progress is assumed and clients are allowed
/// to ignore the `percentage` value in subsequent in report notifications.
///
/// The value should be steadily rising. Clients are free to ignore values
/// that are not following this rule.
/// </summary>
/// <remarks>
/// <see cref="uint"/> in the LSP spec
/// </remarks>
[Optional]
public int? Percentage { get; init; }
}
/// <summary>
/// Signaling the end of a progress reporting is done using the following payload
/// </summary>
public record WorkDoneProgressEnd : WorkDoneProgress
{
public WorkDoneProgressEnd() : base(WorkDoneProgressKind.End)
{
}
}
public record WorkDoneProgressOptions : IWorkDoneProgressOptions
{
[Optional] public bool WorkDoneProgress { get; set; }
}
/// <summary>
/// Reporting progress is done using the following payload
/// </summary>
public record WorkDoneProgressReport : WorkDoneProgress
{
public WorkDoneProgressReport() : base(WorkDoneProgressKind.Report)
{
}
/// <summary>
/// Controls enablement state of a cancel button. This property is only valid if a cancel
/// button got requested in the `WorkDoneProgressStart` payload.
///
/// Clients that don't support cancellation or don't support control the button's
/// enablement state are allowed to ignore the setting.
/// </summary>
[Optional]
public bool Cancellable { get; set; }
/// <summary>
/// Optional progress percentage to display (value 100 is considered 100%).
/// If not provided infinite progress is assumed and clients are allowed
/// to ignore the `percentage` value in subsequent in report notifications.
///
/// The value should be steadily rising. Clients are free to ignore values
/// that are not following this rule.
/// </summary>
/// <remarks>
/// <see cref="uint"/> in the LSP spec
/// </remarks>
[Optional]
public int? Percentage { get; set; }
}
}
namespace Window
{
public static partial class WorkDoneProgressExtensions
{
public static void SendWorkDoneProgressCancel(this IWindowLanguageClient mediator, IWorkDoneProgressParams @params) =>
mediator.SendNotification(WindowNames.WorkDoneProgressCancel, new WorkDoneProgressCancelParams { Token = @params.WorkDoneToken });
public static void SendWorkDoneProgressCancel(this IWindowLanguageClient mediator, ProgressToken token) =>
mediator.SendNotification(WindowNames.WorkDoneProgressCancel, new WorkDoneProgressCancelParams { Token = token });
}
}
}
|
using UnityEngine;
public class BlockController : MonoBehaviour {
private const string PlayerTag = "Player";
[SerializeField]
private Color _defaultColor;
[SerializeField]
private Color _touchedColor;
[SerializeField]
private SpriteRenderer _renderer;
[SerializeField]
private ParticleSystem _touchedVfx;
private bool _touched;
private bool _scaleOut;
private Vector3 _scaleStart;
private float _scaleTimer = 0.0f;
private float _scaleTime = 0.2f;
private void Awake() {
_renderer.color = _defaultColor;
_touchedVfx.Stop();
}
private void OnCollisionEnter2D(Collision2D col) {
if (!_touched && col.gameObject.tag != PlayerTag) return;
_touched = true;
_renderer.color = _touchedColor;
_touchedVfx.Play();
}
private void OnCollisionExit2D(Collision2D col) {
if (_scaleOut) return;
if (col.gameObject.tag != PlayerTag) return;
ScaleOut();
}
private void Update() {
UpdateScale();
}
private void UpdateScale() {
if (!_scaleOut) return;
if (_scaleTimer > _scaleTime) {
_scaleOut = false;
Destroy(gameObject);
return;
}
var lerp = Mathf.Clamp01(_scaleTimer / _scaleTime);
transform.localScale = Vector3.Lerp(_scaleStart, Vector3.zero, lerp);
_scaleTimer += Time.deltaTime;
}
private void ScaleOut() {
_scaleOut = true;
_scaleTimer = 0.0f;
_scaleStart = transform.localScale;
}
}
|
using System;
namespace GumballMachine
{
class Program
{
static void Main(string[] args)
{
Dispenser disp = new Dispenser(55);//creates dispenser with max amount
do
{
Console.Clear();
Console.WriteLine("[--------- Gumball Machine ---------]");
Console.WriteLine("Get some gum: press any key\n");
Console.ReadKey();
Console.WriteLine(disp.DispenseGumball(55));//max amount of being filled up
Console.ReadKey();
} while (true);
}
}
}
|
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;
namespace Clinica_Dental
{
/// <summary>
/// Lógica de interacción para menuPrincipal2.xaml
/// </summary>
public partial class menuPrincipal2 : Window
{
DispatcherTimer Timer;
double panelWidth;
bool hidden;
public menuPrincipal2()
{
InitializeComponent();
Timer = new DispatcherTimer();
Timer.Interval = new TimeSpan(0, 0, 0, 0, 10);
panelWidth = SidePanel.Width;
}
private void Timer_Tick(object sender, EventArgs e)
{
if (hidden)
{
SidePanel.Width += 1;
if (SidePanel.Width >= panelWidth)
{
Timer.Stop();
hidden = false;
}
}
else
{
SidePanel.Width -= 1;
if (SidePanel.Width <= 30)
{
Timer.Stop();
hidden = true;
}
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Timer.Start();
Close();
}
private void PanelHeader_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
DragMove();
}
}
private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int index = ListaView.SelectedIndex;
switch (index)
{
case 0:
GridPrincipal2.Children.Clear();
GridPrincipal2.Children.Add(new ListaCitas());
break;
case 1:
GridPrincipal2.Children.Clear();
GridPrincipal2.Children.Add(new pacienteU());
break;
default:
break;
}
}
}
}
|
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using SGDE.Domain.Entities;
namespace SGDE.DataEFCoreSQL.Configurations
{
public class CompanyDataConfiguration
{
public CompanyDataConfiguration(EntityTypeBuilder<CompanyData> entity)
{
entity.ToTable("CompanyData");
entity.HasKey(x => x.Id);
entity.Property(x => x.Id).ValueGeneratedOnAdd();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OOP4
{
public class ProductionQueue
{
private Queue<IDetail> details;
private int maxDetailsCount;
public ProductionQueue(int maxDetailsCount)
{
details = new Queue<IDetail>();
this.maxDetailsCount = maxDetailsCount;
}
public delegate void CountOfDetailsHandler(string message);
public event CountOfDetailsHandler OutOfDetails;
public event CountOfDetailsHandler QueueIsFull;
public IDetail DequeueDetail()
{
if (details.Count == 0)
{
OutOfDetails("Деталей нет");
}
return details.Dequeue();
}
public void LoadQueue(List<IDetail> alldetails)
{
for (int i = 0; i < maxDetailsCount; i++)
{
EnqueueDetail(alldetails[0]);
alldetails.RemoveAt(0);
}
}
private void EnqueueDetail(IDetail detail)
{
if (details.Count >= maxDetailsCount)
{
QueueIsFull("Очередь заполнена");
return;
}
details.Enqueue(detail);
}
public Queue<IDetail> Details { get => details;}
public int MaxDetailsCount { get => maxDetailsCount; set => maxDetailsCount = value; }
}
}
|
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Threading.Tasks;
namespace HelpdeskDAL
{
public class DepartmentDAO
{
readonly IRepository<Department> repository;
public DepartmentDAO()
{
repository = new HelpdeskRepository<Department>();
}
public async Task<List<Department>> GetAll()
{
List<Department> allDepartments;
try
{
allDepartments = await repository.GetAll();
}
catch (Exception ex)
{
Debug.WriteLine("Problem in " + GetType().Name + " " + MethodBase.GetCurrentMethod().Name + " " + ex.Message);
throw;
}
return allDepartments;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using System.Threading.Tasks;
using Tasks.Services.Domain;
using System.Web.Mvc;
using Tasks.Services.Domain.Models;
namespace Tasks.Web.SignalR
{
public class TasksHub : Hub
{
public async Task TaskCreated(TaskModel model)
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<TasksHub>();
if (hubContext != null)
{
model.IsLoginUserTask = false;
await hubContext.Clients.AllExcept(Context.ConnectionId).sendCreatedTaskToClients(model);
}
}
public async Task TaskUpdated(TaskModel model)
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<TasksHub>();
if (hubContext != null)
{
await hubContext.Clients.AllExcept(Context.ConnectionId).sendUpdatedTaskToClients(model);
}
}
}
} |
using UnityEngine;
[RequireComponent(typeof(AudioController))]
public class AudioSettings : MonoBehaviour {
[SerializeField] float m_Music = 1f;
[SerializeField] float m_Sound = 1f;
float Music { get { return m_Music; } set { } }
float Sound { get { return m_Sound; } set { } }
void Start()
{
AudioController.SetVolume(Music, Sound);
}
void Update()
{
AudioController.ManualUpdate(TimeManager.TimeDeltaTime, TimeManager.UnscaledDeltaTime);
}
void OnEnable()
{
AudioController.Change += OnChangeAudio;
}
void OnDisable()
{
AudioController.Change -= OnChangeAudio;
}
void OnChangeAudio()
{
Sound = AudioController.SoundVolume;
Music = AudioController.MusicVolume;
}
}
|
// -----------------------------------------------------------------------
// <copyright file="StreamingTests.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root
// for license information.
// </copyright>
// -----------------------------------------------------------------------
using System.Collections.Generic;
using System.Linq;
using Mlos.Streaming;
using Xunit;
namespace Mlos.NetCore.UnitTest
{
public class StreamingTests
{
[Fact]
public void MinOnBuffer()
{
var collection = Enumerable.Range(0, 100);
var collectionStream = new StreamableSource<int>();
var results = new List<int>();
// #TODO, build expression tree and optimize
// Expression<Action<Streamable<int>>> expression = collectionStream =>
//
// Build a pipeline from the collection stream.
//
collectionStream
.Buffer(5)
.Min()
.Consume(r =>
results.Add(r));
collectionStream.Publish(collection);
var expected = Enumerable.Range(0, 20).Select(r => r * 5);
// #TODO obtain results from the collectionStream
//
collectionStream.Inspect();
Assert.Equal(expected, results);
}
[Fact]
public void CardinalityOfStream()
{
var collection = Enumerable.Range(0, 1000);
var collectionStream = new StreamableSource<int>();
var results = new List<int>();
// #TODO, build expression tree and optimize
// Expression<Action<Streamable<int>>> expression = collectionStream =>
//
// Build a pipeline from the collection stream.
//
collectionStream
.CardinalityEstimate(_ => _, 0.1);
collectionStream.Publish(collection);
// var expected = Enumerable.Range(0, 20).Select(r => r * 5);
// #TODO obtain results from the collectionStream
//
collectionStream.Inspect();
// Assert.Equal(expected, results);
}
}
}
|
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace LuyenTriNho.Codes
{
public class Constants
{
#region List number image
public static string[] YellowNumber = new string[] { "Images/Numbers/ZeroYellow.png", "Images/Numbers/OneYellow.png", "Images/Numbers/TwoYellow.png", "Images/Numbers/ThreeYellow.png", "Images/Numbers/FourYellow.png", "Images/Numbers/FiveYellow.png", "Images/Numbers/SixYellow.png", "Images/Numbers/SevenYellow.png", "Images/Numbers/EightYellow.png", "Images/Numbers/NineYellow.png" };
public static string[] BoldYellowNumber = new string[] { "Images/Numbers/ZeroBYellow.png", "Images/Numbers/OneBYellow.png", "Images/Numbers/TwoBYellow.png", "Images/Numbers/ThreeBYellow.png", "Images/Numbers/FourBYellow.png", "Images/Numbers/FiveBYellow.png", "Images/Numbers/SixBYellow.png", "Images/Numbers/SevenBYellow.png", "Images/Numbers/EightBYellow.png", "Images/Numbers/NineBYellow.png" };
public static string[] GreenNumber = new string[] { "Images/Numbers/ZeroGreen.png", "Images/Numbers/OneGreen.png", "Images/Numbers/TwoGreen.png", "Images/Numbers/ThreeGreen.png", "Images/Numbers/FourGreen.png", "Images/Numbers/FiveGreen.png", "Images/Numbers/SixGreen.png", "Images/Numbers/SevenGreen.png", "Images/Numbers/EightGreen.png", "Images/Numbers/NineGreen.png" };
public static string[] PinkNumber = new string[] { "Images/Numbers/ZeroPink.png", "Images/Numbers/OnePink.png", "Images/Numbers/TwoPink.png", "Images/Numbers/ThreePink.png", "Images/Numbers/FourPink.png", "Images/Numbers/FivePink.png", "Images/Numbers/SixPink.png", "Images/Numbers/SevenPink.png", "Images/Numbers/EightPink.png", "Images/Numbers/NinePink.png" };
#endregion
#region Diem thuong khi LevelUp
public static int PointLevelUp1 = 500;
public static int PointLevelUp2 = 1000;
public static int PointLevelUp3 = 2000;
public static int PointLevelUp4 = 5000;
public static int PointLevelUp5 = 10000;
public static int PointLevelUp6 = 20000;
public static int PointLevelUp7 = 40000;
#endregion
#region Thời gian theo từng Level
public static int TimeLineLevel1 = 50;
public static int TimeLineLevel2 = 50;
public static int TimeLineLevel3 = 40;
public static int TimeLineLevel4 = 30;
public static int TimeLineLevel5 = 20;
public static int TimeLineLevel6 = 10;
public static int TimeLineLevel7 = 10;
#endregion
#region Số chữ số tương ứng với mỗi Level
public static int QuestionNumLevel1 = 1;
public static int QuestionNumLevel2 = 2;
public static int QuestionNumLevel3 = 3;
public static int QuestionNumLevel4 = 5;
public static int QuestionNumLevel5 = 5;
public static int QuestionNumLevel6 = 6;
public static int QuestionNumLevel7 = 7;
#endregion
//Thời gian để xem sau mỗi câu hỏi
public static int TimeSecondToWatch = 2;
public static int MaximumLevel = 7;
#region Thời gian xem hướng dẫn mỗi Level
public static int TimeWatchGuideLevel1 = 2;
public static int TimeWatchGuideLevel2 = 3;
public static int TimeWatchGuideLevel3 = 4;
public static int TimeWatchGuideLevel4 = 4;
public static int TimeWatchGuideLevel5 = 4;
public static int TimeWatchGuideLevel6 = 4;
public static int TimeWatchGuideLevel7 = 4;
#endregion
}
}
|
using FluentValidation;
namespace DDDSouthWest.Domain.Features.Account.Admin.ManageTalks.AddNewTalk
{
public class AddNewTalkValidator : AbstractValidator<AddNewTalk.Command>
{
public AddNewTalkValidator()
{
RuleFor(x => x.TalkTitle).NotEmpty();
RuleFor(x => x.TalkSummary).NotEmpty();
RuleFor(x => x.TalkBodyMarkdown).NotEmpty().WithMessage("'Talk Abstract' must not be empty");
}
}
} |
namespace Triton.Game.Mapping
{
using ns26;
using System;
using Triton.Game.Mono;
[Attribute38("UnopenedPackStack")]
public class UnopenedPackStack : MonoClass
{
public UnopenedPackStack(IntPtr address) : this(address, "UnopenedPackStack")
{
}
public UnopenedPackStack(IntPtr address, string className) : base(address, className)
{
}
public UberText m_AmountText
{
get
{
return base.method_3<UberText>("m_AmountText");
}
}
public GameObject m_RootObject
{
get
{
return base.method_3<GameObject>("m_RootObject");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Calculadora
{
class Operacion
{
//Declaramos res globalmente para que las operacion tenga una variable para el resultado
double res;
//Hacemos sus respectivos metodos de cada operacion
public double Suma(Valores V)
{
res = V.ValorA + V.ValorB;
return res;
}
public double Resta(Valores V)
{
res = V.ValorA - V.ValorB;
return res;
}
public double Multiplicar(Valores V)
{
res = V.ValorA * V.ValorB;
return res;
}
public double Division(Valores V)
{
res = V.ValorA / V.ValorB;
return res;
}
}
}
|
namespace Codelet.AspNetCore.Mvc.Cqrs
{
using System;
using Codelet.Cqrs;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
/// <summary>
/// Helpers for generation URLs for queries, commands and view models.
/// </summary>
[HtmlTargetElement("a", Attributes = "cqrs-get")]
[HtmlTargetElement("form", Attributes = "cqrs-*")]
public class CqrsUrlTagHelpers
: TagHelper
{
/// <summary>
/// Initializes a new instance of the <see cref="CqrsUrlTagHelpers" /> class.
/// </summary>
/// <param name="urlHelperFactory">The URL helper factory.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="urlHelperFactory" /> == <c>null</c>.</exception>
public CqrsUrlTagHelpers(IUrlHelperFactory urlHelperFactory)
=> this.UrlHelperFactory = urlHelperFactory ?? throw new ArgumentNullException(nameof(urlHelperFactory));
/// <summary>
/// Gets or sets the <see cref="ViewContext" /> for the current request.
/// </summary>
[HtmlAttributeNotBound]
[ViewContext]
public ViewContext ViewContext { get; set; }
/// <summary>
/// Gets or sets the GET route object.
/// </summary>
[HtmlAttributeName("cqrs-get")]
public Maybe<object> Get { get; set; }
/// <summary>
/// Gets or sets the POST route object.
/// </summary>
//[HtmlAttributeName("cqrs-post")]
//public Maybe<Command> Post { get; set; }
private IUrlHelperFactory UrlHelperFactory { get; }
/// <inheritdoc />
public override void Process(TagHelperContext context, TagHelperOutput output)
{
base.Process(context, output);
var urlHelper = this.UrlHelperFactory.GetUrlHelper(this.ViewContext);
Apply(context, output, this.Get, urlHelper.Get, "get");
//Apply(context, output, this.Post, urlHelper.Post, "post");
}
private static void Apply<T>(
TagHelperContext context,
TagHelperOutput output,
Maybe<T> attribute,
Func<T, Uri> urlGenerator,
string method)
{
if (!attribute.HasValue)
{
return;
}
var isForm = context.TagName.Equals("form", StringComparison.InvariantCultureIgnoreCase);
var attributeName = isForm ? "action" : "href";
output.Attributes.RemoveAll(attributeName);
output.Attributes.Add(attributeName, urlGenerator(attribute.Value));
if (isForm)
{
output.Attributes.RemoveAll("method");
output.Attributes.Add("method", method);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SnakeLista
{
public class Punto
{
/// <summary>
/// Coordenadas del punto
/// </summary>
private int x, y;
/// <summary>
/// Letra a mostrar
/// </summary>
private string s;
/// <summary>
/// Tamaño de la serpiente
/// </summary>
public int nsnake = 5;
public Punto()
{
}
public int X { get { return x; } set { x = value; } }
public int Y { get { return y; } set { y = value; } }
public string S { get { return s; } set { s = value; } }
/// <summary>
/// Constructor
/// </summary>
/// <param name="x">X incial</param>
/// <param name="y">Y inicial</param>
/// <param name="s">Letra a mostrar</param>
public Punto(int x, int y, string s)
{
this.x = x;
this.y = y;
this.s = s;
Mostrar(s);
}
/// <summary>
/// Metodo que se encarga de crear la lista de puntos dandole yo unos valores
/// </summary>
/// <returns></returns>
public List<Punto> CrearLista()
{
//Utilizando la clase randomizer para generar un punto aleatorio donde aparecera la serpiente
Random rnd = new Random();
int newX = rnd.Next(10, 30);
int newY = rnd.Next(11, 19);
Punto p1 = new Punto();
List<Punto> ListaPuntos = new List<Punto>();
//new Punto(newX, newY + 5, "°"),
//new Punto(newX, newY + 4, "°"),ddd
//new Punto(newX, newY + 3, "°"),
//new Punto(newX, newY + 2, "°"),
//new Punto(newX, newY + 1, "°"),
//new Punto(newX, newY + 0, "°"),
//};
for (int i = nsnake + 1; i > 0; i--)
{
p1 = new Punto(newX, newY + i, "°");
ListaPuntos.Add(p1);
}
return ListaPuntos;
}
public void GenerarArroba(List<Punto> a, List<Punto> p, bool borrar = true)
{
Random rnd = new Random();
int newX2 = 0;
int newY2 = 0;
bool j = false;
do
{
newX2 = rnd.Next(2, Display.anchura - 1);
newY2 = rnd.Next(Display.max + 1, Display.max + 15);
foreach (var f in p)
{
if (newX2 == f.X || newY2 == f.Y)
{
newX2 = rnd.Next(2, Display.anchura - 1);
newY2 = rnd.Next(Display.max + 1, Display.max + 15);
j = true;
break;
}
}
} while (j == false);
if (borrar)
{
//Borra el punto
a[0].Borrar();
a[0].Mostrar("°");
}
//Genera un punto random
a[0].MoverPunto(a[0], newX2, newY2);
}
public List<Punto> CrearArrobas()
{
//Utilizando la clase randomizer para generar un punto aleatorio donde aparecera la serpiente
Random rnd = new Random();
List<Punto> ListaArrobas = new List<Punto> {
new Punto(5, 20, "@"),
};
return ListaArrobas;
}
/// <summary>
/// Metodo que mueve el punto
/// </summary>
/// <param name="p">Lista de puntos</param>
/// <param name="newX">Nuevo X donde estara el punto</param>
/// <param name="newY">Nueva Y donde estara el punto</param>
public void Mover(int newX, int newY)
{
this.x = newX;
this.y = newY;
this.s = "°";
Mostrar("°");
}
public void MoverPunto(Punto p, int newX, int newY)
{
this.x = newX;
this.y = newY;
this.s = "*";
Mostrar("@");
}
/// <summary>
/// Cambia los valores de los puntos por el siguiente,
/// asi se consigue hacer efecto de serpiente, este metodo se llama cuando se han mostrado los
/// valores anteriores
/// </summary>
/// <param name="p"></param>
public void Remap(List<Punto> p)
{
for (int i = p.Count - 1; i > 0; i--)
{
p[i].y = p[i - 1].y;
p[i].x = p[i - 1].x;
}
}
/// <summary>
/// Muestra el punto
/// </summary>
/// <param name="p">Lista de puntos</param>
/// <param name="s"></param>
public void Mostrar(string s)
{
Console.SetCursorPosition(this.x, this.y);
Console.Write(s);
}
public void Borrar()
{
Console.SetCursorPosition(this.x, this.y);
Console.Write(" ");
}
}
}
|
using LuaInterface;
using RO;
using SLua;
using System;
using UnityEngine;
public class Lua_RO_GameObjPool : LuaObject
{
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int constructor(IntPtr l)
{
int result;
try
{
GameObjPool o = new GameObjPool();
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, o);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int Add(IntPtr l)
{
int result;
try
{
GameObjPool gameObjPool = (GameObjPool)LuaObject.checkSelf(l);
GameObject go;
LuaObject.checkType<GameObject>(l, 2, out go);
string name;
LuaObject.checkType(l, 3, out name);
string poolName;
LuaObject.checkType(l, 4, out poolName);
GameObject o = gameObjPool.Add(go, name, poolName);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, o);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int AddEx(IntPtr l)
{
int result;
try
{
GameObjPool gameObjPool = (GameObjPool)LuaObject.checkSelf(l);
GameObject go;
LuaObject.checkType<GameObject>(l, 2, out go);
string name;
LuaObject.checkType(l, 3, out name);
string poolName;
LuaObject.checkType(l, 4, out poolName);
bool ignoreActive;
LuaObject.checkType(l, 5, out ignoreActive);
GameObject o = gameObjPool.AddEx(go, name, poolName, ignoreActive);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, o);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int RAdd(IntPtr l)
{
int result;
try
{
GameObjPool gameObjPool = (GameObjPool)LuaObject.checkSelf(l);
GameObject go;
LuaObject.checkType<GameObject>(l, 2, out go);
ResourceID name;
LuaObject.checkType<ResourceID>(l, 3, out name);
string poolName;
LuaObject.checkType(l, 4, out poolName);
GameObject o = gameObjPool.RAdd(go, name, poolName);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, o);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int RAddEx(IntPtr l)
{
int result;
try
{
GameObjPool gameObjPool = (GameObjPool)LuaObject.checkSelf(l);
GameObject go;
LuaObject.checkType<GameObject>(l, 2, out go);
ResourceID name;
LuaObject.checkType<ResourceID>(l, 3, out name);
string poolName;
LuaObject.checkType(l, 4, out poolName);
bool ignoreActive;
LuaObject.checkType(l, 5, out ignoreActive);
GameObject o = gameObjPool.RAddEx(go, name, poolName, ignoreActive);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, o);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int Get(IntPtr l)
{
int result;
try
{
GameObjPool gameObjPool = (GameObjPool)LuaObject.checkSelf(l);
string name;
LuaObject.checkType(l, 2, out name);
string poolName;
LuaObject.checkType(l, 3, out poolName);
GameObject parent;
LuaObject.checkType<GameObject>(l, 4, out parent);
GameObject o = gameObjPool.Get(name, poolName, parent);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, o);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int GetEx(IntPtr l)
{
int result;
try
{
GameObjPool gameObjPool = (GameObjPool)LuaObject.checkSelf(l);
string name;
LuaObject.checkType(l, 2, out name);
string poolName;
LuaObject.checkType(l, 3, out poolName);
GameObject parent;
LuaObject.checkType<GameObject>(l, 4, out parent);
bool ignoreActive;
LuaObject.checkType(l, 5, out ignoreActive);
GameObject ex = gameObjPool.GetEx(name, poolName, parent, ignoreActive);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, ex);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int RGet(IntPtr l)
{
int result;
try
{
GameObjPool gameObjPool = (GameObjPool)LuaObject.checkSelf(l);
ResourceID name;
LuaObject.checkType<ResourceID>(l, 2, out name);
string poolName;
LuaObject.checkType(l, 3, out poolName);
GameObject parent;
LuaObject.checkType<GameObject>(l, 4, out parent);
GameObject o = gameObjPool.RGet(name, poolName, parent);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, o);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int RGetEx(IntPtr l)
{
int result;
try
{
GameObjPool gameObjPool = (GameObjPool)LuaObject.checkSelf(l);
ResourceID name;
LuaObject.checkType<ResourceID>(l, 2, out name);
string poolName;
LuaObject.checkType(l, 3, out poolName);
GameObject parent;
LuaObject.checkType<GameObject>(l, 4, out parent);
bool ignoreActive;
LuaObject.checkType(l, 5, out ignoreActive);
GameObject o = gameObjPool.RGetEx(name, poolName, parent, ignoreActive);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, o);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int ClearPool(IntPtr l)
{
int result;
try
{
GameObjPool gameObjPool = (GameObjPool)LuaObject.checkSelf(l);
string poolName;
LuaObject.checkType(l, 2, out poolName);
gameObjPool.ClearPool(poolName);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int ClearPoolEx(IntPtr l)
{
int result;
try
{
GameObjPool gameObjPool = (GameObjPool)LuaObject.checkSelf(l);
string poolName;
LuaObject.checkType(l, 2, out poolName);
bool ignoreActive;
LuaObject.checkType(l, 3, out ignoreActive);
gameObjPool.ClearPoolEx(poolName, ignoreActive);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int ClearAll(IntPtr l)
{
int result;
try
{
GameObjPool gameObjPool = (GameObjPool)LuaObject.checkSelf(l);
gameObjPool.ClearAll();
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_OnPoolNoGet(IntPtr l)
{
int result;
try
{
GameObjPool gameObjPool = (GameObjPool)LuaObject.checkSelf(l);
Func<ResourceID, string, GameObject> func;
int num = LuaDelegation.checkDelegate(l, 2, out func);
if (num == 0)
{
gameObjPool.OnPoolNoGet = func;
}
else if (num == 1)
{
GameObjPool expr_30 = gameObjPool;
expr_30.OnPoolNoGet = (Func<ResourceID, string, GameObject>)Delegate.Combine(expr_30.OnPoolNoGet, func);
}
else if (num == 2)
{
GameObjPool expr_53 = gameObjPool;
expr_53.OnPoolNoGet = (Func<ResourceID, string, GameObject>)Delegate.Remove(expr_53.OnPoolNoGet, func);
}
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_Instance(IntPtr l)
{
int result;
try
{
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, GameObjPool.Instance);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_monoGameObject(IntPtr l)
{
int result;
try
{
GameObjPool gameObjPool = (GameObjPool)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, gameObjPool.monoGameObject);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
public static void reg(IntPtr l)
{
LuaObject.getTypeTable(l, "RO.GameObjPool");
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_GameObjPool.Add));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_GameObjPool.AddEx));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_GameObjPool.RAdd));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_GameObjPool.RAddEx));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_GameObjPool.Get));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_GameObjPool.GetEx));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_GameObjPool.RGet));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_GameObjPool.RGetEx));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_GameObjPool.ClearPool));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_GameObjPool.ClearPoolEx));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_GameObjPool.ClearAll));
LuaObject.addMember(l, "OnPoolNoGet", null, new LuaCSFunction(Lua_RO_GameObjPool.set_OnPoolNoGet), true);
LuaObject.addMember(l, "Instance", new LuaCSFunction(Lua_RO_GameObjPool.get_Instance), null, false);
LuaObject.addMember(l, "monoGameObject", new LuaCSFunction(Lua_RO_GameObjPool.get_monoGameObject), null, true);
LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_RO_GameObjPool.constructor), typeof(GameObjPool), typeof(SingleTonGO<GameObjPool>));
}
}
|
using SözTabani.Contexts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SözTabani
{
public partial class KisiDetay : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadKisiDetay();
}
}
private void LoadKisiDetay()
{
if (Request.QueryString["kid"] != null)
{
int id = int.Parse(Request.QueryString["kid"].ToString());
using (SozTabaniContext context = new SozTabaniContext())
{
var entity = (from i in context.Kisiler
where i.kisi_id == id
select i).FirstOrDefault();
if (entity != null)
{
txtkisi.Text = entity.kisi_adsoyad;
txtkisibilgi.Text = entity.kisi_bilgi;
}
}
}
else
{
Response.Redirect("/kisiliste");
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
string kname = txtkisi.Text.Trim();
string kbilgi = txtkisibilgi.Text.Trim();
using (SozTabaniContext context = new SozTabaniContext())
{
int k_id = int.Parse(Request.QueryString["kid"].ToString());
var entity = (from i in context.Kisiler
where i.kisi_id == k_id
select i).FirstOrDefault();
if (string.IsNullOrEmpty(kname))
{
Error.Text = "Boş Bırakılamaz !";
return;
}
if (string.IsNullOrEmpty(kbilgi))
{
Error.Text = "Boş Bırakılamaz !";
return;
}
if (entity != null)
{
entity.kisi_adsoyad = kname;
entity.kisi_bilgi = kbilgi;
context.SaveChanges();
Error.Text = "Kişi Güncellendi..";
//Response.Redirect("KisiListe.aspx");
}
}
}
}
} |
using PDV.DAO.Atributos;
namespace PDV.DAO.Entidades.NFe
{
public class ProdutoNFe
{
[CampoTabela("IDPRODUTONFE")]
public decimal IDProdutoNFe { get; set; } = -1;
[CampoTabela("SEQUENCIA")]
public int Sequencia { get; set; }
[CampoTabela("FRETE")]
public decimal Frete { get; set; }
[CampoTabela("OUTRASDESPESAS")]
public decimal OutrasDespesas { get; set; }
[CampoTabela("QUANTIDADE")]
public decimal Quantidade { get; set; }
[CampoTabela("VALORUNITARIO")]
public decimal ValorUnitario { get; set; }
[CampoTabela("DESCONTO")]
public decimal Desconto { get; set; }
[CampoTabela("IDPRODUTO")]
public decimal IDProduto { get; set; }
[CampoTabela("IDCFOP")]
public decimal IDCFOP { get; set; }
[CampoTabela("IDNFE")]
public decimal IDNFe { get; set; }
[CampoTabela("SEGURO")]
public decimal Seguro { get; set; }
[CampoTabela("IDINTEGRACAOFISCAL")]
public decimal IDIntegracaoFiscal { get; set; }
public decimal ValorTotal { get; set; }
public decimal TotalFinanceiro { get; set; }
[CampoTabela("IDUNIDADEDEMEDIDA")]
public decimal IDUnidadeDeMedida { get; set; }
public ProdutoNFe() { }
}
}
|
//
// Copyright (c) .NET Foundation. 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;
using System.Configuration;
using System.Data;
using DotNetNuke.Common;
using PetaPoco;
namespace DotNetNuke.Data.PetaPoco
{
[CLSCompliant(false)]
public class PetaPocoDataContext : IDataContext
{
#region Private Members
private readonly Database _database;
private readonly IMapper _mapper;
#endregion
#region Constructors
public PetaPocoDataContext()
: this(ConfigurationManager.ConnectionStrings[0].Name, String.Empty)
{
}
public PetaPocoDataContext(string connectionStringName)
: this(connectionStringName, String.Empty, new Dictionary<Type, IMapper>())
{
}
public PetaPocoDataContext(string connectionStringName, string tablePrefix)
: this(connectionStringName, tablePrefix, new Dictionary<Type, IMapper>())
{
}
public PetaPocoDataContext(string connectionStringName, string tablePrefix, Dictionary<Type, IMapper> mappers)
{
Requires.NotNullOrEmpty("connectionStringName", connectionStringName);
_database = new Database(connectionStringName);
_mapper = new PetaPocoMapper(tablePrefix);
TablePrefix = tablePrefix;
FluentMappers = mappers;
}
#endregion
public Dictionary<Type, IMapper> FluentMappers { get; private set; }
public string TablePrefix { get; private set; }
#region Implementation of IDataContext
public void BeginTransaction()
{
_database.BeginTransaction();
}
public void Commit()
{
_database.CompleteTransaction();
}
public bool EnableAutoSelect
{
get { return _database.EnableAutoSelect; }
set { _database.EnableAutoSelect = value; }
}
public void Execute(CommandType type, string sql, params object[] args)
{
if (type == CommandType.StoredProcedure)
{
sql = DataUtil.GenerateExecuteStoredProcedureSql(sql, args);
}
_database.Execute(DataUtil.ReplaceTokens(sql), args);
}
public IEnumerable<T> ExecuteQuery<T>(CommandType type, string sql, params object[] args)
{
PetaPocoMapper.SetMapper<T>(_mapper);
if (type == CommandType.StoredProcedure)
{
sql = DataUtil.GenerateExecuteStoredProcedureSql(sql, args);
}
return _database.Fetch<T>(DataUtil.ReplaceTokens(sql), args);
}
public T ExecuteScalar<T>(CommandType type, string sql, params object[] args)
{
if (type == CommandType.StoredProcedure)
{
sql = DataUtil.GenerateExecuteStoredProcedureSql(sql, args);
}
return _database.ExecuteScalar<T>(DataUtil.ReplaceTokens(sql), args);
}
public T ExecuteSingleOrDefault<T>(CommandType type, string sql, params object[] args)
{
PetaPocoMapper.SetMapper<T>(_mapper);
if (type == CommandType.StoredProcedure)
{
sql = DataUtil.GenerateExecuteStoredProcedureSql(sql, args);
}
return _database.SingleOrDefault<T>(DataUtil.ReplaceTokens(sql), args);
}
public IRepository<T> GetRepository<T>() where T : class
{
PetaPocoRepository<T> rep = null;
//Determine whether to use a Fluent Mapper
if (FluentMappers.ContainsKey(typeof (T)))
{
var fluentMapper = FluentMappers[typeof(T)] as FluentMapper<T>;
if (fluentMapper != null)
{
rep = new PetaPocoRepository<T>(_database, fluentMapper);
rep.Initialize(fluentMapper.CacheKey, fluentMapper.CacheTimeOut, fluentMapper.CachePriority, fluentMapper.Scope);
}
}
else
{
rep = new PetaPocoRepository<T>(_database, _mapper);
}
return rep;
}
public void RollbackTransaction()
{
_database.AbortTransaction();
}
#endregion
#region Implementation of IDisposable
public void Dispose()
{
_database.Dispose();
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Qiniu.Http;
using Qiniu.IO;
using Qiniu.Util;
using Zhouli.Common;
using Zhouli.FileService.Models;
namespace Zhouli.FileService.Controllers
{
/// <summary>
/// 文件下载
/// </summary>
[Route("[controller]")]
[ApiController]
public class FileController : ControllerBase
{
private IOptionsSnapshot<CustomConfiguration> _configuration;
/// <summary>
/// FileController
/// </summary>
/// <param name="configuration"></param>
public FileController(IOptionsSnapshot<CustomConfiguration> configuration)
{
_configuration = configuration;
}
/// <summary>
/// 测试
/// </summary>
/// <returns></returns>
[HttpGet]
public IActionResult Get()
{
return Ok("哈哈");
}
/// <summary>
/// 文件访问,返回文件流
/// </summary>
/// <param name="fileKey"></param>
/// <param name="environment"></param>
/// <returns></returns>
[HttpGet("{fileKey}")]
public async Task<FileResult> Download([FromServices]IHostingEnvironment environment, string fileKey)
{
byte[] byteData = null;
//解析fileKey
Mac mac = new Mac(_configuration.Value.AccessKey, _configuration.Value.SecretKey);
string rawUrl = $"{_configuration.Value.Bucket.@private.Split(',')[0]}";
// 设置下载链接有效期3600秒
int expireInSeconds = 3600;
string accUrl = DownloadManager.CreateSignedUrl(mac, rawUrl, expireInSeconds);
// 接下来可以使用accUrl来下载文件
HttpResult result = await DownloadManager.DownloadAsync(accUrl, null);
byteData = result.Data;
return File(byteData, "application/octet-stream", Path.GetFileName(fileKey));
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Validation
{
public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CheckInterests();
}
protected void RadioButtonListGender_SelectedIndexChanged(object sender, EventArgs e)
{
CheckInterests();
}
public void CheckInterests()
{
if (this.RadioButtonListGender.SelectedIndex == 0)
{
this.PanelMale.Visible = true;
this.PanelFemale.Visible = false;
}
else
{
this.PanelMale.Visible = false;
this.PanelFemale.Visible = true;
}
}
}
} |
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LoginTest
{
public class BaseTest
{
public IWebDriver Driver { get; set; }
public BaseTest()
{
InitializeTest();
}
public void InitializeTest()
{
Driver = new ChromeDriver();
// Driver=new FirefoxDriver();
}
public void IrAtari()
{
try
{
/*Brain
Driver.Navigate().GoToUrl("http://191.232.161.185/#/login");
*/
/*Sandbox*/
Driver.Navigate().GoToUrl("http://sandbox.entregacreativa.com/#/login");
}
catch (Exception)
{
Console.Write("Tiempo de carga superado");
}
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class EnemySpawner : MonoBehaviour
{
public GameObject enemyPrefab;
public Sprite[] enemySprites;
public int currentEnemyIndex = -1;
public float width;
public float height;
public float moveSpeed;
public float spawnDelay = 0.5f;
private bool isMovingLeft = true;
private float camSizeY;
// Use this for initialization
void Start ()
{
enemySprites = Resources.LoadAll<Sprite> ("Enemies");
camSizeY = Camera.main.orthographicSize * Camera.main.aspect;
SpawnEnemy ();
}
void SetNextEnemySprite ()
{
if (currentEnemyIndex < enemySprites.Length - 1)
currentEnemyIndex++;
enemyPrefab.GetComponent<SpriteRenderer> ().sprite = enemySprites [currentEnemyIndex];
}
void SpawnEnemy ()
{
SetNextEnemySprite ();
foreach (Transform childPositionGameObject in transform) {
GameObject enemy = Instantiate (enemyPrefab, childPositionGameObject.transform.position, Quaternion.identity) as GameObject;
enemy.transform.parent = childPositionGameObject.transform;
}
}
void SpawnEnemyUntilFull ()
{
if (!ScoreKeeper.isGameOver) {
Transform spawnablePositionGameObject = NextAvailablePosition ();
if (spawnablePositionGameObject) {
GameObject enemy = Instantiate (
enemyPrefab, spawnablePositionGameObject.position, Quaternion.identity
) as GameObject;
spawnablePositionGameObject.GetComponent<Position> ().isRestricted = true;
enemy.transform.parent = spawnablePositionGameObject;
if (NextAvailablePosition ())
Invoke ("SpawnEnemyUntilFull", spawnDelay);
}
}
}
void OnDrawGizmos ()
{
Gizmos.DrawWireCube (this.transform.position, new Vector3 (width, height));
}
// Update is called once per frame
void Update ()
{
if (!ScoreKeeper.isGameOver) {
if (isMovingLeft) {
if ((this.transform.position.x - width / 2f) <= -camSizeY)
isMovingLeft = false;
this.transform.position += Vector3.left * moveSpeed * Time.deltaTime;
} else {
if ((this.transform.position.x + width / 2f) >= camSizeY)
isMovingLeft = true;
this.transform.position += Vector3.right * moveSpeed * Time.deltaTime;
}
if (AllMembersDead ())
SpawnEnemyUntilFull ();
}
}
bool AllMembersDead ()
{
foreach (Transform childPositionGameObject in transform) {
if (childPositionGameObject.childCount > 0)
return false;
}
ResetPositionAvailability ();
return true;
}
void ResetPositionAvailability ()
{
SetNextEnemySprite ();
foreach (Transform childPositionGameObject in transform) {
childPositionGameObject.GetComponent<Position> ().isRestricted = false;
}
}
Transform NextAvailablePosition ()
{
foreach (Transform childPositionGameObject in transform) {
if (childPositionGameObject.childCount == 0 &&
!childPositionGameObject.GetComponent<Position> ().isRestricted)
return childPositionGameObject;
}
return null;
}
}
|
using Android.App;
using Android.Widget;
using Android.Graphics;
using Xamarin.Forms.Platform.Android;
using MCCForms;
using MCCForms.Droid;
[assembly: Xamarin.Forms.ExportRenderer (typeof(LabelBoldFont), typeof(LabelBoldFontCustomRenderer))]
namespace MCCForms.Droid
{
public class LabelBoldFontCustomRenderer : LabelRenderer
{
Typeface _typeFaceBold = Typeface.CreateFromAsset (Application.Context.Assets, "RijksoverheidSansTextTT-Bold_2_0.ttf");
protected override void OnElementPropertyChanged (object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged (sender, e);
var nativeTextView = (TextView)Control;
nativeTextView.SetTypeface (_typeFaceBold, TypefaceStyle.Normal);
}
}
} |
using Microsoft.EntityFrameworkCore;
using ServiceHost.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ServiceHost.Repository
{
public class AccountRepository : BaseRepository<Account>, IAccountRepository
{
public AccountRepository(ServiceHostContext context) : base(context)
{
}
public async Task<Account> GetAccountAsync(string accountId)
{
var guid = new Guid(accountId);
var account = await Task.Run(() => context.Account.Include(x => x.Owner).Include(x => x.Currency).Where(x => x.Id == guid).FirstOrDefault<Account>());
return account;
}
public async Task<IEnumerable<Account>> GetAccountsAsync()
{
var accounts = await Task.Run(() => context.Account.Include(x => x.Owner).Include(x => x.Currency));
return accounts;
}
public async Task<IEnumerable<Account>> GetAccountsAsync(ApplicationUser owner)
{
var accounts = await context.Account.Include(x => x.Owner).Include(x => x.Currency).Where(x => x.Owner == owner).ToListAsync<Account>();
return accounts;
}
public async Task<Account> GetAccountAsync(ApplicationUser owner, string iBan)
{
var account = await context.Account.Include(x => x.Owner).Include(x => x.Currency).Where(x => x.Owner == owner && x.IBAN == iBan).FirstOrDefaultAsync<Account>();
return account;
}
public async Task<Account> GetAccountByIbanAsync(string iBan)
{
var account = await context.Account.Include(x => x.Owner).Include(x => x.Currency).Where(x => x.IBAN == iBan).FirstOrDefaultAsync();
return account;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mojio.Events
{
/// <summary>
///
/// </summary>
[CollectionNameAttribute(typeof(Event))]
public class FenceEvent : TripEvent
{
}
}
|
using LuaInterface;
using RO;
using SLua;
using System;
public class Lua_RO_ROFileUtils : LuaObject
{
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int FileExists_s(IntPtr l)
{
int result;
try
{
string path;
LuaObject.checkType(l, 1, out path);
bool b = ROFileUtils.FileExists(path);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, b);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int FileDelete_s(IntPtr l)
{
int result;
try
{
string file;
LuaObject.checkType(l, 1, out file);
ROFileUtils.FileDelete(file);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int ReadAllText_s(IntPtr l)
{
int result;
try
{
string path;
LuaObject.checkType(l, 1, out path);
string s = ROFileUtils.ReadAllText(path);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, s);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int DirectoryExists_s(IntPtr l)
{
int result;
try
{
string path;
LuaObject.checkType(l, 1, out path);
bool b = ROFileUtils.DirectoryExists(path);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, b);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int DirectoryDelete_s(IntPtr l)
{
int result;
try
{
string file;
LuaObject.checkType(l, 1, out file);
bool recursive;
LuaObject.checkType(l, 2, out recursive);
ROFileUtils.DirectoryDelete(file, recursive);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
public static void reg(IntPtr l)
{
LuaObject.getTypeTable(l, "RO.ROFileUtils");
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_ROFileUtils.FileExists_s));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_ROFileUtils.FileDelete_s));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_ROFileUtils.ReadAllText_s));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_ROFileUtils.DirectoryExists_s));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_ROFileUtils.DirectoryDelete_s));
LuaObject.createTypeMetatable(l, null, typeof(ROFileUtils));
}
}
|
using System;
using System.ServiceModel;
using Microsoft.ComplexEventProcessing;
using Microsoft.ComplexEventProcessing.Linq;
using Microsoft.ComplexEventProcessing.ManagementService;
using System.Reactive;
using System.Reactive.Linq;
using System.Windows;
using SiDualMode;
using SiDualMode.Base;
using SiDualMode.InputAdapter.YahooFinanceAdapter;
using SiDualMode.OutputAdapter.WpfAdapter;
namespace ComplexStreamSI_Client.Model {
public class SIViewModel : DependencyObject {
public SIViewModel() {
using (Server cepServer = Server.Connect(new EndpointAddress(@"http://localhost/StreamInsight/MyInstance"))) {
var cepApplication = cepServer.Applications["DualMode"];
var cepSource = cepApplication.GetStreamable<StreamInputEvent<YahooDataEvent>>("DualModeSource");
var mySink = cepApplication.GetObserver<StreamOutputEvent<YahooDataEvent>>("PointSink");
var sinkConfig = new WpfOutputConfig() {
};
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AlgorithmQuestions
{
public class BigInter
{
public static void test(string x, string y, string operate)
{
int xLen = x.Length;
int yLen = y.Length;
string tempX = x;
string tempY = y;
if (xLen > yLen)
{
tempY = y.PadLeft(xLen, ' ');
}
else
{
tempX = x.PadRight(yLen, ' ');
}
Console.WriteLine(" " + tempX);
Console.WriteLine(operate + tempY);
//Console.WriteLine("-------------------------------------------------------------------------------------------");
if (operate == "+")
{
Console.WriteLine("=" + Add(x, y));
}
}
// +
public static string Add(string x, string y)
{
string returnValue = string.Empty;
if (x.StartsWith("-") && y.StartsWith("-"))
{
return "-" + Add(x.TrimStart('-'), y.TrimEnd('-'));
}
else if (x.StartsWith("-") && !y.StartsWith("-"))
{
return Subtract(y, x.TrimStart('-'));
}
else if (!x.StartsWith("-") && y.StartsWith("-"))
{
return Subtract(x, y.TrimStart('-'));
}
int xLen = x.Length;
int yLen = y.Length;
if (xLen > yLen)
{
y = y.PadLeft(xLen, '0');
yLen = xLen;
}
else
{
x = x.PadLeft(yLen, '0');
xLen = yLen;
}
int[] sums = new int[xLen + 1];
for (int i = xLen - 1; i >= 0; i--)
{
int temsum = int.Parse(x[i].ToString()) + int.Parse(y[i].ToString()) + sums[i + 1];
if (temsum >= 10)
{
sums[i + 1] = temsum - 10;
sums[i] = 1;
}
else
{
sums[i + 1] = temsum;
}
}
returnValue = string.Concat(sums);
if (sums[0] == 0)
{
returnValue = returnValue.Remove(0, 1);
}
return returnValue;
}
// -
public static string Subtract(string x, string y)
{
string returnValue = string.Empty;
return returnValue;
}
// *
public static string Multiply(string x, string y)
{
string returnValue = string.Empty;
return returnValue;
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GamepadInput;
public class StrikerController : MonoBehaviour
{
public KeyCode[] StrikerKeyboardInputs;
public Striker[] Strikers;
public PlayerShip PlayerShip;
private float gamepadTriggerSensitivity = 0.5f;
private bool leftTriggerUp;
private bool rightTriggerUp;
public void Update()
{
GetInputs();
}
private void GetInputs()
{
if (PlayerShip.PlayerInfo.IsKeyboardAndMouse)
{
TriggerKeyboardAndMouse();
}
else
{
TriggerGamepad();
}
}
private void TriggerKeyboardAndMouse()
{
for (int i = 0; i < Strikers.Length; i++)
{
if (Strikers[0].StrikerState == StrikerState.Default && (Input.GetKeyDown(StrikerKeyboardInputs[i]) || Input.GetMouseButtonDown(i)))
{
Strikers[i].MoveBlade();
}
else if (Strikers[0].StrikerState == StrikerState.Default && (Input.GetKeyUp(StrikerKeyboardInputs[i]) || Input.GetMouseButtonUp(i)))
{
Strikers[i].StopBlade();
}
}
}
private void TriggerGamepad()
{
float leftTrigger = GamePad.GetTrigger(GamePad.Trigger.LeftTrigger, PlayerShip.PlayerInfo.GamepadIndex);
float rightTrigger = GamePad.GetTrigger(GamePad.Trigger.RightTrigger, PlayerShip.PlayerInfo.GamepadIndex);
if (Strikers[0].StrikerState == StrikerState.Default)
{
TryUseStriker(GamePad.Trigger.LeftTrigger, Strikers[0], ref leftTriggerUp);
}
else
{
Strikers[0].StopBlade();
}
if(Strikers[0].StrikerState == StrikerState.Default)
{
TryUseStriker(GamePad.Trigger.RightTrigger, Strikers[1], ref rightTriggerUp);
}
else
{
Strikers[1].StopBlade();
}
}
private void TryUseStriker(GamePad.Trigger trigger, Striker striker, ref bool triggerState)
{
float axis = GamePad.GetTrigger(trigger, PlayerShip.PlayerInfo.GamepadIndex);
if(!triggerState)
{
if(axis >= gamepadTriggerSensitivity)
{
triggerState = true;
striker.MoveBlade();
}
}
else
{
if (axis < gamepadTriggerSensitivity)
{
triggerState = false;
striker.StopBlade();
}
}
}
public void OnDodge()
{
for (int i = 0; i < Strikers.Length; i++)
{
Strikers[i].SetStrikerDown();
}
}
public void SetStrikersToDefault()
{
for (int i = 0; i < Strikers.Length; i++)
{
Strikers[i].SetStrikerToDefaultState();
}
}
} |
using System;
using System.Dynamic;
using System.Reflection.Emit;
using System.Security.Authentication.ExtendedProtection.Configuration;
using System.Threading;
namespace ClearSight.RendererAbstract
{
/// <summary>
/// Base class for all objects that are created and managed by the device.
/// </summary>
public abstract class DeviceChild<TDescriptor> : DeviceChildBase
where TDescriptor : struct
{
/// <summary>
/// The descriptor, set by Device.Create
/// </summary>
public TDescriptor Desc { get; private set; }
protected DeviceChild(ref TDescriptor desc, Device device, string label) : base(device, label)
{
Desc = desc;
}
}
public abstract class DeviceChildBase : IDisposable
{
/// <summary>
/// Device from which this DeviceChild was created. Set by Device.Create
/// </summary>
public Device Device { get; private set; }
/// <summary>
/// Device child label, useful for debugging.
/// </summary>
public string Label { get; private set; }
protected DeviceChildBase(Device device, string label)
{
Device = device;
Label = label;
}
#region State
/// <summary>
/// The creation state a device child can have.
/// </summary>
public enum State
{
/// <summary>
/// Either there was an error during load, or the resource was already disposed and is waiting for garbage collection to pick it up.
/// </summary>
Invalid,
/// <summary>
/// Resource is ready to use.
/// </summary>
Normal,
/// <summary>
/// The resource was already disposed, but is currently locked.
/// Since only loaded resources can be locked, this also means that the resource is loaded.
/// </summary>
WaitingForUnlockToDispose,
}
public State CurrentState { get; private set; } = State.Invalid;
#endregion
/// <summary>
/// Called by the device, after setting Desc.
/// </summary>
internal void Create()
{
ClearSight.Core.Assert.Debug(CurrentState == State.Invalid, "It is only possible to create device children if their are uninitialized.");
ClearSight.Core.Assert.Debug(!InUse, "It is not possible to create device children that are in use.");
CreateImpl();
CurrentState = State.Normal;
}
protected abstract void CreateImpl();
/// <summary>
/// Destroys the resource. Called by Dispose or RemoveRef if the device child is no longer in use.
/// </summary>
internal virtual void Destroy()
{
ClearSight.Core.Assert.Debug(CurrentState == State.Normal, "It is only possible to destroy intact device children.");
ClearSight.Core.Assert.Debug(!InUse, "It is not possible to destroy device children that are in use.");
DestroyImpl();
CurrentState = State.Invalid;
}
protected abstract void DestroyImpl();
#region Locking
/// <summary>
/// Determines if the resource has a ref count bigger than zero and cannot be destroyed immediately.
/// </summary>
public bool InUse => usageCount > 0;
/// <summary>
/// Number of active locks.
/// </summary>
private int usageCount = 0;
/// <summary>Increases usage counter (threadsafe).</summary>
/// <remarks>
/// Locks the resource against delection. InUse will defer their destruction until all locks are lifted.
/// Only resources in the Loaded or WaitingForUnlockToDispose state can be (un)locked
/// </remarks>
/// <see cref="RemoveRef"/>
public void AddRef()
{
lock (this)
{
ClearSight.Core.Assert.Always(CurrentState == State.Normal, "It is only possible to lock intact device children.");
ClearSight.Core.Assert.Debug(usageCount >= 0, "Invalid lock count!");
++usageCount;
}
}
/// <summary>Decreases usage counter (threadsafe).</summary>
/// <remarks>
/// If the InUse is now false and the resource was waiting for dispose, dispose will be called again.
/// Only resources in the Loaded or WaitingForUnlockToDispose state can be (un)locked.
/// </remarks>
/// <see cref="AddRef"/>
public void RemoveRef()
{
lock (this)
{
ClearSight.Core.Assert.Always(CurrentState == State.Normal, "It is only possible to unlock intact device children.");
ClearSight.Core.Assert.Debug(usageCount > 0, "Invalid lock count!");
--usageCount;
if (CurrentState == State.WaitingForUnlockToDispose && !InUse)
{
((IDisposable) this).Dispose();
}
}
}
#endregion
/// <summary>
/// Destroys the resource. If the resource is locked, it will be destroyed when all locks are lifted.
/// Calls unload.
/// </summary>
public void Dispose()
{
ClearSight.Core.Assert.Debug(CurrentState == State.Normal, "It is only possible to destroy intact device children.");
lock (this)
{
if (InUse)
{
CurrentState = State.WaitingForUnlockToDispose;
}
else
{
Destroy();
GC.SuppressFinalize(this);
}
}
}
~DeviceChildBase()
{
ClearSight.Core.Assert.Debug(CurrentState == State.Invalid, "DeviceChild was not disposed explicitely!");
ClearSight.Core.Assert.Debug(!InUse, "DeviceChild is still in use during finalization!");
}
}
}
|
using System.Collections.Generic;
using System.Linq;
public class CarManager
{
private Dictionary<int, Car> cars;
private Dictionary<int, Race> races;
private Garage garage;
public CarManager()
{
this.cars = new Dictionary<int, Car>();
this.races = new Dictionary<int, Race>();
this.garage = new Garage();
}
public void Register(int id, string type, string brand, string model, int yearOfProduction, int horsepower, int acceleration, int suspension, int durability)
{
if (type.Equals("Performance"))
{
Car car = new PerformanceCar(brand, model, yearOfProduction, horsepower, acceleration, suspension, durability);
this.cars.Add(id, car);
}
else if (type.Equals("Show"))
{
Car car = new ShowCar(brand, model, yearOfProduction, horsepower, acceleration, suspension, durability);
this.cars.Add(id, car);
}
}
public string Check(int id)
{
return cars[id].ToString();
}
public void Open(int id, string type, int lenght, string route, int prizePool)
{
if (type.Equals("Casual"))
{
Race race = new CasualRace(lenght, route, prizePool);
this.races.Add(id, race);
}
else if (type.Equals("Drag"))
{
Race race = new DragRace(lenght, route, prizePool);
this.races.Add(id, race);
}
else if (type.Equals("Drift"))
{
Race race = new DriftRace(lenght, route, prizePool);
this.races.Add(id, race);
}
}
public void Open(int id, string type, int lenght, string route, int prizePool, int bonus)
{
if (type.Equals("TimeLimit"))
{
Race race = new TimeLimitRace(lenght, route, prizePool, bonus);
this.races.Add(id, race);
}
else if (type.Equals("Circuit"))
{
Race race = new CircuitRace(lenght, route, prizePool, bonus);
this.races.Add(id, race);
}
}
public void Participate(int carId, int raceId)
{
if (!garage.ParkedCars.Contains(carId))
{
this.races[raceId].Participants.Add(carId, cars[carId]);
}
}
public string Start(int id)
{
if (races[id].StartRace() == null)
{
return "Cannot start the race with zero participants.";
}
var race = races[id].StartRace();
races.Remove(id);
return race;
}
public void Park(int id)
{
foreach (var race in races.Values)
{
if (race.Participants.ContainsKey(id))
{
return;
}
}
this.garage.ParkedCars.Add(id);
}
public void Unpark(int id)
{
garage.ParkedCars.Remove(id);
}
public void Tune(int tuneIndex, string addOn)
{
foreach (var carGarage in garage.ParkedCars)
{
var car = cars[carGarage];
car.Tune(tuneIndex, addOn);
}
}
}
|
using UnityEngine;
using System.Collections;
public class GUICameraS : MonoBehaviour {
public GameObject CONFIG;
private MainGame MGame;
private GameObject MENUS;
private GameObject SPAWN;
// Use this for initialization
void Start () {
MGame = CONFIG.GetComponent<MainGame>();
MENUS = transform.Find("MENUS").gameObject;
if(MENUS!=null)
SPAWN = MENUS.transform.Find ("SPAWN").gameObject;
}
// Update is called once per frame
void Update () {
//RESETS STUFF
if(GetComponent<Camera>().enabled && RenderSettings.fog)
{
RenderSettings.fog=false;
Cursor.visible = true;
}
else if(!GetComponent<Camera>().enabled && !RenderSettings.fog)
{
RenderSettings.fog=true;
Cursor.visible = false;
}
//GUIs
if(GetComponent<Camera>().enabled)
{
switch(MGame.GUIScreen)
{
case "Spawn":
disableAllExcept("Spawn");
spawnLocation();
if(!SPAWN.GetComponent<GUI_BASIC_SCREEN>().enabled)
SPAWN.GetComponent<GUI_BASIC_SCREEN>().enabled=true;
break;
}
}
else
{
disableAllExcept("");
}
}
//GUI FUNCTIONS
void closeActualMenu()
{
MGame.GUIOpen=false;
MGame.GUIScreen="none";
}
void disableAllExcept(string except)
{
if(except!="Spawn")
SPAWN.GetComponent<GUI_BASIC_SCREEN>().enabled=false;
}
//SCREENS/MENUS
void spawnLocation()
{
//BUTTONS
if (Input.GetButtonDown("Fire1")) {
Ray ray = GetComponent<Camera>().ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray, out hit))
{
switch(hit.transform.gameObject.name)
{
case "GUI_Spawn_BTN_A":
MGame.jogador.transform.position = CONFIG.transform.Find("SpawnPoints").gameObject.transform.Find("Bootcamp").gameObject.transform.position;
closeActualMenu();
break;
case "GUI_Spawn_BTN_B":
MGame.jogador.transform.position = CONFIG.transform.Find("SpawnPoints").gameObject.transform.Find("Desert").gameObject.transform.position;
closeActualMenu();
break;
case "GUI_Spawn_BTN_C":
MGame.jogador.transform.position = CONFIG.transform.Find("SpawnPoints").gameObject.transform.Find("Forest").gameObject.transform.position;
closeActualMenu();
break;
case "GUI_Spawn_BTN_D":
MGame.jogador.transform.position = CONFIG.transform.Find("SpawnPoints").gameObject.transform.Find("City").gameObject.transform.position;
closeActualMenu();
break;
}
}
}
}
}
|
using Course.Commands;
using Course.Context;
using Course.Model;
using Course.View;
using NLog;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace Course.ViewModel
{
class AllMaterialViewModel
{
Logger logger = LogManager.GetCurrentClassLogger();
RelayCommand filterMaterialsCommand;
RelayCommand showMaterialCommand;
RelayCommand showVictimCommand;
RelayCommand deleteMaterialCommand;
ApplicationContext db;
private Employee selectedEmployee = new Employee() { LastName = " " };
private string selectedDecision;
private Material selectedMaterial;
private Victim selectedVictim;
private ObservableCollection<Material> materials;
private ObservableCollection<Employee> employees;
public List<string> DecisionList { get; set; }
public DateTime StartData { get; set; }
public DateTime FinishData { get; set; }
public string SelectedDecision
{
get
{
if (selectedDecision == " ")
return null;
else
return selectedDecision;
}
set
{
selectedDecision = value;
OnPropertyChanged("SelectedDecision");
}
}
public ObservableCollection<Material> Materials
{
get { return materials; }
set
{
materials = value;
OnPropertyChanged("Materials");
}
}
public ObservableCollection<Employee> Employees
{
get { return employees; }
set
{
employees = value;
}
}
public Employee SelectedEmployee
{
//get { return selectedEmployee; }
get
{
if (selectedEmployee.LastName == " ")
return null;
else
return selectedEmployee;
}
set
{
selectedEmployee = value;
}
}
public Material SelectedMaterial
{
get { return selectedMaterial; }
set
{
selectedMaterial = value;
}
}
public Victim SelectedVictim
{
get { return selectedVictim; }
set
{
selectedVictim = value;
OnPropertyChanged("SelectedVictim");
}
}
public AllMaterialViewModel(ApplicationContext db)
{
this.db = db;
Materials = new ObservableCollection<Material>();
Employees = new ObservableCollection<Employee>();
try
{
db.Materials.ToList().Where(x => x.ExecutedOrNotExecuted != true).ToList().ForEach(x => Materials.Add(x));
Employees.Add(new Employee() { LastName = " " });
db.Employees.ToList().ForEach(x => Employees.Add(x));
}
catch (Exception ex)
{
logger.Error(ex, "Ошибка загрузки БД в конструкторе ");
}
DecisionList = new List<string> {" ", "Отказано в ВУД", "ВУД(факт)", "ВУД(лицо)", "Передано по территориальности",
"Передано в др. службу", "Списано в дело" };
StartData = DateTime.Today;
FinishData = DateTime.Today;
}
public RelayCommand FilterMaterialsCommand
{
get
{
return filterMaterialsCommand ??
(filterMaterialsCommand = new RelayCommand((o) =>
{
Materials.Clear();
try
{
if (SelectedEmployee != null && SelectedDecision != null)
{
//Materials.Where(x => x.Employees.FirstOrDefault().EmployeeId == SelectedEmployee.EmployeeId);
db.Materials.Where(x => x.DateOfRegistration >= StartData
&& x.DateOfRegistration <= FinishData
&& x.Employees.FirstOrDefault().EmployeeId == SelectedEmployee.EmployeeId
&& x.Decision == SelectedDecision)
.ToList().ForEach(x => Materials.Add(x));
}
else if (SelectedEmployee == null && SelectedDecision != null)
{
db.Materials.Where(x => x.DateOfRegistration >= StartData
&& x.DateOfRegistration <= FinishData
&& x.Decision == SelectedDecision)
.ToList().ForEach(x => Materials.Add(x));
}
else if (SelectedEmployee != null && SelectedDecision == null)
{
db.Materials.Where(x => x.DateOfRegistration >= StartData
&& x.DateOfRegistration <= FinishData
&& x.Employees.FirstOrDefault().EmployeeId == SelectedEmployee.EmployeeId)
.ToList().ForEach(x => Materials.Add(x));
}
else
{
db.Materials.Where(x => x.DateOfRegistration >= StartData
&& x.DateOfRegistration <= FinishData).ToList().ForEach(x => Materials.Add(x));
}
}
catch (Exception ex)
{
logger.Error(ex, "Ошибка при фильрации данных из БД");
}
}
));
}
}
public RelayCommand ShowMaterialCommand
{
get
{
return showMaterialCommand ??
(showMaterialCommand = new RelayCommand((o) =>
{
LookMaterialWindow lookMaterialWindow = new LookMaterialWindow();
lookMaterialWindow.DataContext = SelectedMaterial;
lookMaterialWindow.ShowDialog();
}, (o => SelectedMaterial != null)
));
}
}
public RelayCommand ShowVictimCommand
{
get
{
return showVictimCommand ??
(showVictimCommand = new RelayCommand((o) =>
{
try
{
SelectedVictim = db.Victims.FirstOrDefault(x => x.Materials.FirstOrDefault().MaterialId == SelectedMaterial.MaterialId);
}
catch (Exception ex)
{
logger.Error(ex, "Ошибка c БД в ShowVictimCommand");
}
LookVictimWindow lookVictimWindow = new LookVictimWindow(null, db, SelectedVictim);
lookVictimWindow.ShowDialog();
}, (o => SelectedMaterial != null)
));
}
}
public RelayCommand DeleteMaterialCommand
{
get
{
return deleteMaterialCommand ??
(deleteMaterialCommand = new RelayCommand((o) =>
{
var result = MessageBox.Show("Удалить материал?", "", MessageBoxButton.YesNo, MessageBoxImage.Information);
if (result == MessageBoxResult.Yes)
{
try
{
db.Materials.Remove(db.Materials.Where(x => x.MaterialId == SelectedMaterial.MaterialId).First());
db.SaveChanges();
logger.Info("Материал ЕК№" + SelectedMaterial.NumberEK + " удален из БД");
}
catch (Exception ex)
{
logger.Error(ex, "Ошибка c удалением материала в БД ");
}
materials.Remove(SelectedMaterial);
}
}, (o => SelectedMaterial != null)
));
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string prop = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ChatSignalR.Chat;
using ChatSignalR.Data;
using ChatSignalR.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace ChatSignalR
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer("Data Source=.;Initial Catalog = ChatSignalR ;Integrated Security = SSPI;"));
services.AddIdentity<AppUser, IdentityRole>().AddDefaultTokenProviders().AddEntityFrameworkStores<ApplicationDbContext>();
services.AddSignalR();
services.AddSingleton<ChatClientManager>();
services.AddMvc();
services.AddAuthentication();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseStaticFiles();
app.UseSignalR(option =>
{
option.MapHub<ChatHub>("/chatHub");
});
app.UseMvc(routes =>
{
routes.MapRoute(name: "default", template: "{controller=Chat}/{action=Index}/{id?}");
});
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DvdApplication.Repositories;
namespace JobApplication.Models
{
public class FakeJobDatabase : IJobRepository
{
private static List<Job> _jobs = new List<Job>();
public List<Job> GetAll()
{
return _jobs;
}
public void Add(Job job)
{
if (_jobs.Any())
job.JobId = _jobs.Max(c => c.JobId) + 1; // Adding one to the maximum # of jobs currently in collection
else
job.JobId = 1;
_jobs.Add(job);
}
public void Delete(int id)
{
_jobs.RemoveAll(c => c.JobId == id);
}
public void Edit(Job job)
{
Delete(job.JobId);
_jobs.Add(job);
}
public Job GetById(int id)
{
return _jobs.First(c => c.JobId == id);
}
}
} |
using System.Text.Json.Serialization;
namespace PlatformRacing3.Server.Game.Communication.Messages.Incoming.Json;
internal sealed class JsonCoinsIncomingMessage : JsonPacket
{
[JsonPropertyName("coins")]
public uint Coins { get; set; }
} |
using AutoMapper;
using AutoMapper.Extensions.ExpressionMapping;
using Contoso.AutoMapperProfiles;
using Contoso.BSL.AutoMapperProfiles;
using Contoso.Common.Utils;
using Contoso.Contexts;
using Contoso.Data.Entities;
using Contoso.Domain.Entities;
using Contoso.Parameters.Expansions;
using Contoso.Parameters.Expressions;
using Contoso.Repositories;
using Contoso.Stores;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Xunit;
namespace Contoso.Bsl.Flow.Integration.Tests
{
public class PersistenceOperationsTest
{
public PersistenceOperationsTest()
{
Initialize();
}
#region Fields
private IServiceProvider serviceProvider;
private static readonly string parameterName = "$it";
#endregion Fields
#region Tests
[Fact]
public void Add_A_Single_Entity()
{
//arrange
var bodyParameter = new EqualsBinaryOperatorParameters
(
new MemberSelectorOperatorParameters("FullName", new ParameterOperatorParameters(parameterName)),
new ConstantOperatorParameters("Roger Milla")
);
//act
DoTest<StudentModel, Student>
(
bodyParameter,
null,
new SelectExpandDefinitionParameters
{
ExpandedItems = new List<SelectExpandItemParameters>
{
new SelectExpandItemParameters { MemberName = "Enrollments" }
}
},
parameterName,
(StudentModel studentModel, ISchoolRepository repository) =>
{
PersistenceOperations<StudentModel, Student>.Save
(
repository,
new StudentModel
{
EntityState = LogicBuilder.Domain.EntityStateType.Added,
EnrollmentDate = new DateTime(2021, 2, 8),
Enrollments = new List<EnrollmentModel>
{
new EnrollmentModel { CourseID = 1050, Grade = Domain.Entities.Grade.A },
new EnrollmentModel { CourseID = 4022, Grade = Domain.Entities.Grade.A },
new EnrollmentModel { CourseID = 4041, Grade = Domain.Entities.Grade.A }
},
FirstName = "Roger",
LastName = "Milla"
}
);
},
returnValue =>
{
Assert.Equal(new DateTime(2021, 2, 8), returnValue.EnrollmentDate);
Assert.Empty(returnValue.Enrollments);
},
"$it => ($it.FullName == \"Roger Milla\")"
);
}
[Fact]
public void Add_An_Object_Graph()
{
//arrange
var bodyParameter = new EqualsBinaryOperatorParameters
(
new MemberSelectorOperatorParameters("FullName", new ParameterOperatorParameters(parameterName)),
new ConstantOperatorParameters("Roger Milla")
);
//act
DoTest<StudentModel, Student>
(
bodyParameter,
null,
new SelectExpandDefinitionParameters
{
ExpandedItems = new List<SelectExpandItemParameters>
{
new SelectExpandItemParameters { MemberName = "Enrollments" }
}
},
parameterName,
(StudentModel studentModel, ISchoolRepository repository) =>
{
PersistenceOperations<StudentModel, Student>.SaveGraph
(
repository,
new StudentModel
{
EntityState = LogicBuilder.Domain.EntityStateType.Added,
EnrollmentDate = new DateTime(2021, 2, 8),
Enrollments = new List<EnrollmentModel>
{
new EnrollmentModel { CourseID = 1050, Grade = Domain.Entities.Grade.A },
new EnrollmentModel { CourseID = 4022, Grade = Domain.Entities.Grade.A },
new EnrollmentModel { CourseID = 4041, Grade = Domain.Entities.Grade.A }
},
FirstName = "Roger",
LastName = "Milla"
}
);
},
returnValue =>
{
Assert.Equal(new DateTime(2021, 2, 8), returnValue.EnrollmentDate);
Assert.Equal(3, returnValue.Enrollments.Count());
},
"$it => ($it.FullName == \"Roger Milla\")"
);
}
[Fact]
public void Delete_A_Single_Entity_Using_Save()
{
//arrange
var bodyParameter = new EqualsBinaryOperatorParameters
(
new MemberSelectorOperatorParameters("FullName", new ParameterOperatorParameters(parameterName)),
new ConstantOperatorParameters("Carson Alexander")
);
//act
DoTest<StudentModel, Student>
(
bodyParameter,
null,
null,
parameterName,
(StudentModel studentModel, ISchoolRepository repository) =>
{
studentModel.EntityState = LogicBuilder.Domain.EntityStateType.Deleted;
PersistenceOperations<StudentModel, Student>.Save(repository, studentModel);
},
returnValue =>
{
Assert.Null(returnValue);
},
"$it => ($it.FullName == \"Carson Alexander\")"
);
}
[Fact]
public void Delete_A_Single_Entity_Using_Delete()
{
//arrange
var bodyParameter = new EqualsBinaryOperatorParameters
(
new MemberSelectorOperatorParameters("FullName", new ParameterOperatorParameters(parameterName)),
new ConstantOperatorParameters("Carson Alexander")
);
//act
DoTest<StudentModel, Student>
(
bodyParameter,
null,
null,
parameterName,
(StudentModel studentModel, ISchoolRepository repository) =>
{
IExpressionParameter expressionParameter = GetFilterParameter<StudentModel>(bodyParameter, parameterName);
Expression<Func<StudentModel, bool>> expression = ProjectionOperations<StudentModel, Student>.GetFilter
(
serviceProvider.GetRequiredService<IMapper>().MapToOperator(expressionParameter)
);
PersistenceOperations<StudentModel, Student>.Delete(repository, expression);
},
returnValue =>
{
Assert.Null(returnValue);
},
"$it => ($it.FullName == \"Carson Alexander\")"
);
}
[Fact]
public void Update_A_Single_Entity()
{
//arrange
var bodyParameter = new EqualsBinaryOperatorParameters
(
new MemberSelectorOperatorParameters("FullName", new ParameterOperatorParameters(parameterName)),
new ConstantOperatorParameters("Carson Alexander")
);
//act
DoTest<StudentModel, Student>
(
bodyParameter,
null,
null,
parameterName,
(StudentModel studentModel, ISchoolRepository repository) =>
{
studentModel.EnrollmentDate = new DateTime(2021, 2, 8);
studentModel.EntityState = LogicBuilder.Domain.EntityStateType.Modified;
PersistenceOperations<StudentModel, Student>.Save(repository, studentModel);
},
returnValue =>
{
Assert.Equal(new DateTime(2021, 2, 8), returnValue.EnrollmentDate);
},
"$it => ($it.FullName == \"Carson Alexander\")"
);
}
[Fact]
public void Add_An_Entry_To_A_Child_Collection()
{
//arrange
var bodyParameter = new EqualsBinaryOperatorParameters
(
new MemberSelectorOperatorParameters("FullName", new ParameterOperatorParameters(parameterName)),
new ConstantOperatorParameters("Carson Alexander")
);
//act
DoTest<StudentModel, Student>
(
bodyParameter,
null,
new SelectExpandDefinitionParameters
{
ExpandedItems = new List<SelectExpandItemParameters>
{
new SelectExpandItemParameters { MemberName = "Enrollments" }
}
},
parameterName,
(StudentModel studentModel, ISchoolRepository repository) =>
{
studentModel.EnrollmentDate = new DateTime(2021, 2, 8);
studentModel.Enrollments.Add
(
new EnrollmentModel
{
CourseID = 3141,
Grade = Domain.Entities.Grade.B,
EntityState = LogicBuilder.Domain.EntityStateType.Added
}
);
studentModel.EntityState = LogicBuilder.Domain.EntityStateType.Modified;
PersistenceOperations<StudentModel, Student>.SaveGraph(repository, studentModel);
},
returnValue =>
{
Assert.Equal(new DateTime(2021, 2, 8), returnValue.EnrollmentDate);
Assert.Equal(Domain.Entities.Grade.B, returnValue.Enrollments.Single(e => e.CourseID == 3141).Grade);
Assert.Equal(4, returnValue.Enrollments.Count());
},
"$it => ($it.FullName == \"Carson Alexander\")"
);
}
[Fact]
public void Update_An_Entry_In_A_Child_Collection()
{
//arrange
var bodyParameter = new EqualsBinaryOperatorParameters
(
new MemberSelectorOperatorParameters("FullName", new ParameterOperatorParameters(parameterName)),
new ConstantOperatorParameters("Carson Alexander")
);
//act
DoTest<StudentModel, Student>
(
bodyParameter,
null,
new SelectExpandDefinitionParameters
{
ExpandedItems = new List<SelectExpandItemParameters>
{
new SelectExpandItemParameters { MemberName = "Enrollments" }
}
},
parameterName,
(StudentModel studentModel, ISchoolRepository repository) =>
{
studentModel.EnrollmentDate = new DateTime(2021, 2, 8);
var enrollment = studentModel.Enrollments.Single(e => e.CourseID == 1050);
enrollment.Grade = Domain.Entities.Grade.B;
studentModel.EntityState = LogicBuilder.Domain.EntityStateType.Modified;
enrollment.EntityState = LogicBuilder.Domain.EntityStateType.Modified;
PersistenceOperations<StudentModel, Student>.SaveGraph(repository, studentModel);
},
returnValue =>
{
Assert.Equal(new DateTime(2021, 2, 8), returnValue.EnrollmentDate);
Assert.Equal(Domain.Entities.Grade.B, returnValue.Enrollments.Single(e => e.CourseID == 1050).Grade);
Assert.Equal(3, returnValue.Enrollments.Count());
},
"$it => ($it.FullName == \"Carson Alexander\")"
);
}
[Fact]
public void Delete_An_Entry_From_A_Child_Collection()
{
//arrange
var bodyParameter = new EqualsBinaryOperatorParameters
(
new MemberSelectorOperatorParameters("FullName", new ParameterOperatorParameters(parameterName)),
new ConstantOperatorParameters("Carson Alexander")
);
//act
DoTest<StudentModel, Student>
(
bodyParameter,
null,
new SelectExpandDefinitionParameters
{
ExpandedItems = new List<SelectExpandItemParameters>
{
new SelectExpandItemParameters { MemberName = "Enrollments" }
}
},
parameterName,
(StudentModel studentModel, ISchoolRepository repository) =>
{
studentModel.EnrollmentDate = new DateTime(2021, 2, 8);
var enrollment = studentModel.Enrollments.Single(e => e.CourseID == 1050);
enrollment.Grade = Domain.Entities.Grade.B;
studentModel.EntityState = LogicBuilder.Domain.EntityStateType.Modified;
enrollment.EntityState = LogicBuilder.Domain.EntityStateType.Deleted;
PersistenceOperations<StudentModel, Student>.SaveGraph(repository, studentModel);
},
returnValue =>
{
Assert.Equal(new DateTime(2021, 2, 8), returnValue.EnrollmentDate);
Assert.Null(returnValue.Enrollments.SingleOrDefault(e => e.CourseID == 1050));
Assert.Equal(2, returnValue.Enrollments.Count());
},
"$it => ($it.FullName == \"Carson Alexander\")"
);
}
#endregion Tests
#region Helpers
private IExpressionParameter GetFilterParameter<T>(IExpressionParameter selectorBody, string parameterName = "$it")
=> new FilterLambdaOperatorParameters
(
selectorBody,
typeof(T),
parameterName
);
void DoTest<TModel, TData>(IExpressionParameter bodyParameter,
IExpressionParameter queryFunc,
SelectExpandDefinitionParameters expansion,
string parameterName,
Action<TModel, ISchoolRepository> update,
Action<TModel> assert,
string expectedExpressionString) where TModel : LogicBuilder.Domain.BaseModel where TData : LogicBuilder.Data.BaseData
{
//arrange
IMapper mapper = serviceProvider.GetRequiredService<IMapper>();
ISchoolRepository repository = serviceProvider.GetRequiredService<ISchoolRepository>();
IExpressionParameter expressionParameter = GetFilterParameter<TModel>(bodyParameter, parameterName);
TestExpressionString();
TestReturnValue();
void TestReturnValue()
{
//act
TModel returnValue = ProjectionOperations<TModel, TData>.Get
(
repository,
mapper,
expressionParameter,
queryFunc,
expansion
);
update(returnValue, repository);
returnValue = ProjectionOperations<TModel, TData>.Get
(
repository,
mapper,
expressionParameter,
queryFunc,
expansion
);
//assert
assert(returnValue);
}
void TestExpressionString()
{
//act
Expression<Func<TModel, bool>> expression = ProjectionOperations<TModel, TData>.GetFilter
(
mapper.MapToOperator(expressionParameter)
);
//assert
if (!string.IsNullOrEmpty(expectedExpressionString))
{
AssertFilterStringIsCorrect(expression, expectedExpressionString);
}
}
}
private void AssertFilterStringIsCorrect(Expression expression, string expected)
{
AssertStringIsCorrect(ExpressionStringBuilder.ToString(expression));
void AssertStringIsCorrect(string resultExpression)
=> Assert.True
(
expected == resultExpression,
$"Expected expression '{expected}' but the deserializer produced '{resultExpression}'"
);
}
static MapperConfiguration MapperConfiguration;
private void Initialize()
{
if (MapperConfiguration == null)
{
MapperConfiguration = new MapperConfiguration(cfg =>
{
cfg.AddExpressionMapping();
cfg.AddProfile<ParameterToDescriptorMappingProfile>();
cfg.AddProfile<DescriptorToOperatorMappingProfile>();
cfg.AddProfile<SchoolProfile>();
cfg.AddProfile<ExpansionParameterToDescriptorMappingProfile>();
cfg.AddProfile<ExpansionDescriptorToOperatorMappingProfile>();
});
}
MapperConfiguration.AssertConfigurationIsValid();
serviceProvider = new ServiceCollection()
.AddDbContext<SchoolContext>
(
options => options.UseSqlServer
(
@"Server=(localdb)\mssqllocaldb;Database=SchoolContext4;ConnectRetryCount=0"
),
ServiceLifetime.Transient
)
.AddTransient<ISchoolStore, SchoolStore>()
.AddTransient<ISchoolRepository, SchoolRepository>()
.AddSingleton<AutoMapper.IConfigurationProvider>
(
MapperConfiguration
)
.AddTransient<IMapper>(sp => new Mapper(sp.GetRequiredService<AutoMapper.IConfigurationProvider>(), sp.GetService))
.BuildServiceProvider();
SchoolContext context = serviceProvider.GetRequiredService<SchoolContext>();
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
DatabaseSeeder.Seed_Database(serviceProvider.GetRequiredService<ISchoolRepository>()).Wait();
}
#endregion Helpers
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using System.Collections;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
using AARMEmail;
public partial class StatusUpdate : System.Web.UI.Page
{
string obj_Authenticated;
PlaceHolder maPlaceHolder;
UserControl obj_Tabs;
UserControl obj_LoginCtrl;
UserControl obj_WelcomCtrl;
UserControl obj_Navi;
UserControl obj_Navihome;
AarmsUser obj_Class = new AarmsUser();
DataTable dt = new DataTable();
int Mode;
string connStr = ConfigurationManager.ConnectionStrings["BizCon"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ChkAuthentication();
Binddata(0);
}
}
public void Binddata(int mode)
{
DataSet ds = new DataSet();
if (mode == 0)
{
ds = obj_Class.DisplayAppointDetails(Convert.ToDateTime("01/Jan/2012"), mode);
}
else
{
ds = obj_Class.DisplayAppointDetails(Convert.ToDateTime(txtappdate.Text), mode);
}
GridStatus.DataSource = ds;
GridStatus.DataBind();
}
protected void ButShow_Click(object sender, EventArgs e)
{
try
{
if (txtappdate.Text == "")
{
Session["Mode"] = 0;
}
else
{
Session["Mode"] = 1;
}
DateTime dtt = new DateTime();
dtt = Convert.ToDateTime(txtappdate.Text);
txtappdate.Text = dtt.ToString("dd-MMM-yyyy");
Binddata(Convert.ToInt32(Session["Mode"].ToString()));
}
catch (Exception ex)
{
}
}
public void ChkAuthentication()
{
obj_LoginCtrl = null;
obj_WelcomCtrl = null;
obj_Navi = null;
obj_Navihome = null;
if (Session["Authenticated"] == null)
{
Session["Authenticated"] = "0";
}
else
{
obj_Authenticated = Session["Authenticated"].ToString();
}
maPlaceHolder = (PlaceHolder)Master.FindControl("P1");
if (maPlaceHolder != null)
{
obj_Tabs = (UserControl)maPlaceHolder.FindControl("loginheader1");
if (obj_Tabs != null)
{
obj_LoginCtrl = (UserControl)obj_Tabs.FindControl("login1");
obj_WelcomCtrl = (UserControl)obj_Tabs.FindControl("welcome1");
// obj_Navi = (UserControl)obj_Tabs.FindControl("Navii");
//obj_Navihome = (UserControl)obj_Tabs.FindControl("Navihome1");
if (obj_LoginCtrl != null & obj_WelcomCtrl != null)
{
if (obj_Authenticated == "1")
{
SetVisualON();
}
else
{
SetVisualOFF();
}
}
}
else
{
}
}
else
{
}
}
public void SetVisualON()
{
obj_LoginCtrl.Visible = false;
obj_WelcomCtrl.Visible = true;
lblwelcome.Text = "Welcome Nanda";
//obj_Navi.Visible = true;
//obj_Navihome.Visible = true;
}
public void SetVisualOFF()
{
obj_LoginCtrl.Visible = true;
obj_WelcomCtrl.Visible = false;
// obj_Navi.Visible = true;
//obj_Navihome.Visible = false;
}
protected void GridStatus_RowEditing(object sender, GridViewEditEventArgs e)
{
if (txtappdate.Text == "")
{
Session["Mode"] = 0;
}
else
{
Session["Mode"] = 1;
}
GridStatus.EditIndex = e.NewEditIndex;
Binddata(Convert.ToInt32(Session["Mode"].ToString()));
}
protected void GridStatus_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridStatus.EditIndex = -1;
Binddata(Convert.ToInt32(Session["Mode"].ToString()));
}
protected void GridStatus_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int res = 0;
try
{
int index = GridStatus.EditIndex;
GridViewRow row = GridStatus.Rows[index];
TextBox txtcontactperson = (TextBox)row.FindControl("txtcontactperson");
TextBox txtMobileNumber = (TextBox)row.FindControl("txtMobileNumber");
TextBox txtEmailId = (TextBox)row.FindControl("txtEmailId");
TextBox txtDept = (TextBox)row.FindControl("txtDept");
TextBox txtenterby = (TextBox)row.FindControl("txtenterby");
TextBox txtAppdate = (TextBox)row.FindControl("txtAppdate");
TextBox txtMetBy = (TextBox)row.FindControl("txtMetBy");
TextBox txtTripplan = (TextBox)row.FindControl("txtTripplan");
DropDownList ddlaction = (DropDownList)row.FindControl("ddlaction");
TextBox txtRemarks = (TextBox)row.FindControl("txtRemarks");
Label lblActivityID = (Label)row.FindControl("lblActivityID");
int resp = obj_Class.Bizconnect_UpdateStatus(txtcontactperson.Text, txtMobileNumber.Text,txtEmailId.Text ,txtDept.Text, txtenterby.Text , Convert.ToDateTime(txtAppdate.Text),txtMetBy.Text,txtTripplan.Text,ddlaction.Text,txtRemarks.Text,Convert.ToInt32(lblActivityID.Text));
if(resp==1)
{
GridStatus.EditIndex = -1;
Binddata(Convert.ToInt32(Session["Mode"].ToString()));
ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('Update Successfully');</script>");
}
}
catch (Exception ex)
{
}
}
protected void LinkLogout_Click(object sender, EventArgs e)
{
Session["UserID"] = 0;
Session.Abandon();
Response.Redirect("Index.aspx");
}
protected void btnexport_Click(object sender, EventArgs e)
{
ExportGrid(GridStatus, "Report.xls");
}
public static void ExportGrid(GridView oGrid, string exportFile)
{
//Clear the response, and set the content type and mark as attachment
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"" + exportFile + "\"");
//Clear the character set
HttpContext.Current.Response.Charset = "";
//Create a string and Html writer needed for output
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
//Clear the controls from the pased grid
ClearControls(oGrid);
//Show grid lines
oGrid.GridLines = GridLines.Both;
//Color header
oGrid.HeaderStyle.BackColor = System.Drawing.Color.LightGray;
//Render the grid to the writer
oGrid.RenderControl(oHtmlTextWriter);
//Write out the response (file), then end the response
HttpContext.Current.Response.Write(oStringWriter.ToString());
HttpContext.Current.Response.End();
}
private static void ClearControls(Control control)
{
//Recursively loop through the controls, calling this method
for (int i = control.Controls.Count - 1; i >= 0; i--)
{
ClearControls(control.Controls[i]);
}
//If we have a control that is anything other than a table cell
if (!(control is TableCell))
{
if (control.GetType().GetProperty("SelectedItem") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
try
{
literal.Text = (string)control.GetType().GetProperty("SelectedItem").GetValue(control, null);
}
catch
{
}
control.Parent.Controls.Remove(control);
}
else
if (control.GetType().GetProperty("Text") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
literal.Text = (string)control.GetType().GetProperty("Text").GetValue(control, null);
control.Parent.Controls.Remove(control);
}
}
return;
}
public override void VerifyRenderingInServerForm(Control control)
{
}
protected void GridStatus_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
//int index = GridStatus.EditIndex;
//GridViewRow row = GridStatus.Rows[index];
string id = GridStatus.DataKeys[e.RowIndex].Value.ToString();
SqlConnection conn = new SqlConnection();
conn.ConnectionString = connStr;
conn.Open();
SqlCommand cmd = new SqlCommand();
//Label lblActivityID = (Label)GridStatus.FindControl("lblActivityID");
string qry = "delete from Bizconnect_AARMSDailyActivity where ActivityID='" + id + "'";
cmd = new SqlCommand(qry, conn);
cmd.ExecuteNonQuery();
conn.Close();
//GridStatus.EditIndex = -1;
ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('Status Removed Successfully');</script>");
Binddata(0);
}
catch (Exception ex)
{
}
}
public string MailBody()
{
string Body = "";
StreamReader streamReader;
streamReader = File.OpenText(Server.MapPath(@"Documents\AARMSCampaign.html"));
string contents = streamReader.ReadToEnd();
streamReader.Close();
Body = contents;
return Body;
}
protected void btn_Sendmail_Click(object sender, EventArgs e)
{
EmailTo_ClientForConfirm();
}
public void EmailTo_ClientForConfirm()
{
try
{
foreach (GridViewRow gvrow in GridStatus.Rows)
{
CheckBox chk_ID = (CheckBox)gvrow.FindControl("chk_ID");
if (chk_ID.Checked)
{
Label Emailid = (Label)gvrow.FindControl("lblEmailID");
string obj_Body = "";
string body = "";
obj_Body = MailBody();
string Attachment = Server.MapPath(@"Excel/END-TOENDQUESTIONNAIRE.xlsx");
string fromgetemailid = "introduction@scmbizconnect.com";
string fromgetpwd = "introduction";
// string obj_Message = "<pre>" + "<font size=4>" + mailcontent + "<br/>Best Regards,<br/>Bid2sky Team.<br/></pre></font>";
//string mailcontent = " Dear Customer,<br/>";
//mailcontent = mailcontent + "<br/> One client has created a " + " project in our Bid2sky portal. The details of RFQ are given in the below Table.<br/>";
body = body + "<br/><br/>\n\n" + obj_Body + "\r\n\n";
AARMEmail.EmailControl Email = new EmailControl();
int obj_resp = Email.SendEmail(Emailid.Text, fromgetemailid, fromgetpwd, "satish@aarmsvaluechain.com", "", "satish@aarmsvaluechain.com", "", "SCM SOLUTIONS - DOMESTIC TRANSPORTATION SOLUTIONS", body.ToString().Trim(), System.Web.Mail.MailFormat.Html, System.Web.Mail.MailPriority.High, "smtp.gmail.com", "465", "2", "1", true, Attachment);
//int obj_resp = Email.SendEmail("", fromgetemailid, fromgetpwd, Emailid.Text, "", "", "", "Bid2sky new RFQ Posted", body.ToString().Trim(), System.Web.Mail.MailFormat.Html, System.Web.Mail.MailPriority.High, "mail.aarmsvaluechain.com", "25", "2", "1", false, "Excel/END-TO END QUESTIONNAIRE.xlsx");
//int obj_resp = Email.SendEmail("", fromgetemailid, fromgetpwd, "krishna.irki@gmail.com,krishnasai.rk@gmail.com", "", "", "", "Bid2sky new RFQ Posted", body.ToString().Trim(), System.Web.Mail.MailFormat.Html, System.Web.Mail.MailPriority.High, "smtp.gmail.com", "465", "2", "1", true, Attachment);
ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('Mails has been sent successfully');</script>");
}
}
}
catch (Exception ex)
{
}
}
protected void btn_Search_Click(object sender, EventArgs e)
{
Mode = ddl_Search.SelectedIndex == 1 ? 1 : ddl_Search.SelectedIndex == 2 ? 2 : ddl_Search.SelectedIndex == 3 ? 3 : 0;
if (Mode != 0)
{
if (txt_Search.Text != "")
{
dt = obj_Class.Search_DisplayAppointDetails(txt_Search.Text, Mode);
if (dt.Rows.Count > 0)
{
GridStatus.DataSource = dt;
GridStatus.DataBind();
}
else
{
GridStatus.DataSource = null;
GridStatus.DataBind();
}
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('Please enter text to search');</script>");
}
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('Please select any one option to search');</script>");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//Task 2
namespace GetMaxNumber
{
class GetMaxNumber
{
static void Main(string[] args)
{
Console.WriteLine("Input numbers: ");
int n1 = int.Parse(Console.ReadLine());
int n2 = int.Parse(Console.ReadLine());
int n3 = int.Parse(Console.ReadLine());
int biggestNum = Math.Max(n3, GetMaxNum(n1, n2));
Console.WriteLine("The biggest number is: {0}", biggestNum);
}
static int GetMaxNum(int n1, int n2)
{
return Math.Max(n1, n2);
}
}
}
|
using Lab13_2_dev_build.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using Dapper.Contrib.Extensions;
using MySql.Data.MySqlClient;
namespace Lab13_2_dev_build.Controllers
{
public class ProductController : Controller
{
//index view shows only names and prices
//in index make a link around each product name. have the link go to the detail action, passing that object's id.
//changed index to product index. was that ok? or should i have make a new productIndex action?
public IActionResult Index()
{
MySqlConnection db = new MySqlConnection("Server=localhost;Database=coffeeshop;Uid=root;Password=abc123");
List<Product> prodlist = db.GetAll<Product>().ToList();
return View(prodlist);
//how do i also get prices?
}
//clicking on a product name take you to a description page
//detail action/view
public IActionResult Detail(int pr)
{
MySqlConnection db = new MySqlConnection("Server=localhost;Database=coffeeshop;Uid=root;Password=abc123");
Product prod = db.Get<Product>(pr);
return View(prod);
}
}
}
|
using GlobalDevelopment.SocialNetworks.Facebook;
using GlobalDevelopment.SocialNetworks.LinkedIn;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GlobalDevelopment.SocialNetworks
{
public class SocialNetworks
{
public FacebookM FacebookSession { get; set; }
public LinkedInM LinkedinSession { get; set; }
public void CreateFacebookSession(string appID, string appSecret, string returnUrl)
{
FacebookSession = new FacebookM(appID, appSecret, returnUrl);
}
public void CreateLinkedinSession(string appID, string appSecret, string returnUrl)
{
LinkedinSession = new LinkedInM(appID, appSecret, returnUrl);
}
}
} |
using System;
using System.ComponentModel;
namespace TableTopCrucible.Core.Models.Sources
{
public interface ISaveFileProgression : INotifyPropertyChanged
{
ITaskProgressionInfo DirectoryTaskState { get; }
ITaskProgressionInfo FileTaskState { get; }
ITaskProgressionInfo LinkTaskState { get; }
ITaskProgressionInfo ItemTaskState { get; }
ITaskProgressionInfo MainTaskProgression { get; }
TaskProgressionState SubTaskProgression { get; }
IObservable<TaskProgressionState> SubTaskProgressionChanges { get; }
}
} |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="UserAuthentication.cs" company="CGI">
// Copyright (c) CGI. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using CGI.Reflex.Core.Utilities;
using NHibernate.Criterion;
namespace CGI.Reflex.Core.Entities
{
/// <summary>
/// This entity holds user authentication information when Forms Authentication is used in web, for example.
/// </summary>
public class UserAuthentication : BaseEntity
{
public const int MaxFailedAttemptPassword = 3;
#pragma warning disable 649
private string _passwordDigest;
private DateTime? _lastPasswordChangedAt;
private string _singleAccessToken;
private DateTime? _singleAccessTokenValidUntil;
#pragma warning restore 649
[Required]
public virtual User User { get; set; }
[StringLength(256)]
public virtual string PasswordDigest { get { return _passwordDigest; } }
public virtual DateTime? LastPasswordChangedAt { get { return _lastPasswordChangedAt; } }
public virtual DateTime? LastLoginDate { get; set; }
public virtual int FailedPasswordAttemptCount { get; set; }
[StringLength(128)]
public virtual string SingleAccessToken { get { return _singleAccessToken; } }
public virtual DateTime? SingleAccessTokenValidUntil { get { return _singleAccessTokenValidUntil; } }
public static UserAuthentication Authenticate(string nameOrEmail, string password)
{
var userAuth = References.NHSession.QueryOver<UserAuthentication>()
.JoinQueryOver(a => a.User)
.Where(
Restrictions.Or(
Restrictions.InsensitiveLike(Projections.Property<User>(u => u.UserName), nameOrEmail, MatchMode.Exact),
Restrictions.InsensitiveLike(Projections.Property<User>(u => u.Email), nameOrEmail, MatchMode.Exact)))
.SingleOrDefault();
if (userAuth == null)
return null;
if (userAuth.User.IsLockedOut)
return null;
if (!userAuth.VerifyPassword(password))
{
userAuth.FailedPasswordAttemptCount++;
if (userAuth.FailedPasswordAttemptCount > MaxFailedAttemptPassword)
userAuth.User.IsLockedOut = true;
return null;
}
userAuth.LastLoginDate = DateTime.Now;
userAuth.FailedPasswordAttemptCount = 0;
userAuth.ClearSingleAccessToken();
return userAuth;
}
public virtual void SetPassword(string clearPassword)
{
_passwordDigest = Encryption.Hash(clearPassword);
FailedPasswordAttemptCount = 0;
_lastPasswordChangedAt = DateTime.Now;
_singleAccessToken = string.Empty;
}
public virtual void ClearPassword()
{
_passwordDigest = string.Empty;
_lastPasswordChangedAt = DateTime.Now;
_singleAccessToken = string.Empty;
}
public virtual bool VerifyPassword(string clearPassword)
{
if (string.IsNullOrEmpty(_passwordDigest))
return false;
return _passwordDigest.Equals(Encryption.Hash(clearPassword), StringComparison.InvariantCulture);
}
public virtual string GenerateSingleAccessToken(TimeSpan validity)
{
return GenerateSingleAccessToken(DateTime.Now.Add(validity));
}
public virtual string GenerateSingleAccessToken(DateTime validity)
{
_singleAccessToken = Encryption.GenerateRandomToken(128);
_singleAccessTokenValidUntil = validity;
return _singleAccessToken;
}
public virtual void ClearSingleAccessToken()
{
_singleAccessToken = string.Empty;
_singleAccessTokenValidUntil = null;
}
}
}
|
using System;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using VehicleManagement.Application.Common.Interfaces;
using VehicleManagement.Domain.Entities;
namespace VehicleManagement.Application.Commands.Brands
{
public static class DeleteBrand
{
public record Command(Guid Id) : IRequest<int>;
public class Handler : IRequestHandler<Command, int>
{
private readonly IBrandRepository _repository;
public Handler(IBrandRepository repository)
{
_repository = repository;
}
public async Task<int> Handle(Command request, CancellationToken cancellationToken)
{
var brand = await _repository.FindById(request.Id);
if (brand is null)
return 0;
await _repository.Remove(brand);
return 1;
}
}
}
} |
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
namespace NMoSql.Helpers
{
public class Over : Helper, IQueryHelper
{
private readonly HelperManager<IQueryHelper> _queryHelpers;
public Over(HelperManager<IQueryHelper> queryHelpers)
{
_queryHelpers = queryHelpers ?? throw new ArgumentNullException(nameof(queryHelpers));
}
public string Fn(JToken over, IList<object> values, Query query) => ((IQueryHelper)this).Fn(over, values, query);
string IQueryHelper.Fn(JToken value, IList<object> values, Query query)
{
if (value.IsNull())
return string.Empty;
if (value.Type != JTokenType.Object)
throw new InvalidOperationException($"Invalid type '{value.Type}' for query helper 'over'. Expects '{JTokenType.Object}'");
Func<JToken, IList<object>, Query, string> order = _queryHelpers.Get("order").Fn;
Func<JToken, IList<object>, Query, string> partition = _queryHelpers.Get("partition").Fn;
string clause = string.Empty;
if (value["partition"].Truthy())
clause = partition(value["partition"], values, query);
if (value["order"].Truthy())
clause = (clause.Length > 0 ? clause + " " : string.Empty) + order(value["order"], values, query);
return "over (" + clause.Trim() + ")";
}
}
}
|
using System.Threading.Tasks;
using Akka.Actor;
using akka_microservices_proj.Actors.Provider;
using akka_microservices_proj.Domain;
using akka_microservices_proj.Messages;
using Microsoft.AspNetCore.Mvc;
namespace akka_microservices_proj.Commands
{
public interface IGetBasketFromCustomerCommand
{
Task<IActionResult> ExecuteAsync(GetBasketMessage msg);
}
public class GetBasketFromCustomerCommand : IGetBasketFromCustomerCommand
{
private readonly IActorRef _basketActor;
public GetBasketFromCustomerCommand(ActorProvider actorProvider)
{
_basketActor = actorProvider.GetBasketActor();
}
public async Task<IActionResult> ExecuteAsync(GetBasketMessage msg)
{
if (msg.CustomerId > 0)
{
var result = await _basketActor.Ask<Basket>(msg);
if (result != null)
return new OkObjectResult(result);
}
return new BadRequestObjectResult("No Customer given.");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
public partial class Admin_Pro_Process : System.Web.UI.Page
{
public decimal pId = 0; decimal flag = -1;
PDTech.OA.BLL.VIEW_PRO_STEP_TYPE vBll = new PDTech.OA.BLL.VIEW_PRO_STEP_TYPE();
public string t_rand = "";
const string Symol = "/images/nextIcon.png";
protected void Page_Load(object sender, EventArgs e)
{
t_rand = DateTime.Now.ToString("yyyyMMddHHmmssff");
if (Request.QueryString["pId"] != null)
{
pId = decimal.Parse(Request.QueryString["pId"].ToString());
hidPid.Value = Request.QueryString["pId"].ToString();
//flag = decimal.Parse(Request.QueryString["flag"].ToString());
//hidFlag.Value = Request.QueryString["flag"].ToString();
//if (flag == 0)
//{
// hidTid.Value = Request.QueryString["tId"].ToString();
// hidArId.Value = Request.QueryString["ArId"].ToString();
//}
}
if (Request.QueryString["Isedit"] != null)
{
hidisedit.Value = Request.QueryString["Isedit"].ToString();
}
if (Request.QueryString["ArId"] != null)
{
hidarchid.Value = Request.QueryString["ArId"].ToString();
}
if (Request.QueryString["tId"] != null)
{
hidtaskid.Value = Request.QueryString["tId"].ToString();
}
if (!IsPostBack)
{
BindData();
}
}
/// <summary>
/// 绑定项目步骤
/// </summary>
public void BindData()
{
if (string.IsNullOrEmpty(hidarchid.Value))
{
PDTech.OA.BLL.VIEW_PROJECT_STEP_USER vapbll = new PDTech.OA.BLL.VIEW_PROJECT_STEP_USER();
PDTech.OA.Model.VIEW_PROJECT_STEP_USER vpsu = new PDTech.OA.Model.VIEW_PROJECT_STEP_USER();
vpsu.PROJECT_ID = pId;
vpsu = vapbll.get_paging_project_info(vpsu);
hidarchid.Value = vpsu.ARCHIVE_ID.ToString();
if (string.IsNullOrEmpty(hidtaskid.Value) || hidtaskid.Value=="0")
{
hidtaskid.Value = vpsu.ARCHIVE_TASK_ID.ToString();
}
}
PDTech.OA.BLL.RISK_POINT_INFO rpiBll = new PDTech.OA.BLL.RISK_POINT_INFO();
IList<PDTech.OA.Model.RISK_POINT_INFO> allRiskPoint = rpiBll.GetAllRiskPointInfo();
IList<PDTech.OA.Model.VIEW_PRO_STEP_TYPE> vList = vBll.get_viewStepAndType(new PDTech.OA.Model.VIEW_PRO_STEP_TYPE() { PROJECT_ID = pId });
StringBuilder sb = new StringBuilder();
for (int i = 0; i < vList.Count; i++)
{
string p_state = "";
if (vList[i].P_STEP_STATUS == 9)
{
p_state = "1";
}
else
{
p_state = "0";
}
string state = "";
switch (vList[i].STEP_STATUS.ToString())
{
case "0":
state = "未开始";
sb.Append("<tr class='HandCss' >");
sb.Append("<td onclick=\"showStepDetail('" + vList[i].URL + "','" + vList[i].PROJECT_STEP_ID + "','" + p_state + "','" + vList[i].P_STEP_NAME + "')\">" + vList[i].STEP_NAME + "</td>");
break;
case "1":
state = "进行中";
sb.Append("<tr class='green HandCss' title='负责人:" + vList[i].FULL_NAME + ",开始时间:" + vList[i].START_TIME + ",结束时间:" + vList[i].END_TIME + "' >");
sb.Append("<td onclick=\"showStepDetail('" + vList[i].URL + "','" + vList[i].PROJECT_STEP_ID + "','" + p_state + "','" + vList[i].P_STEP_NAME + "')\">" + vList[i].STEP_NAME + "</td>");
break;
case "9":
if (vList[i].START_FLAG != "1")
{
state = "已完成";
sb.Append("<tr class='Orange HandCss' title='负责人:" + vList[i].FULL_NAME + ",开始时间:" + vList[i].START_TIME + ",结束时间:" + vList[i].END_TIME + "' >");
sb.Append("<td onclick=\"showStepDetail('" + vList[i].URL + "','" + vList[i].PROJECT_STEP_ID + "','" + p_state + "','" + vList[i].P_STEP_NAME + "')\">" + vList[i].STEP_NAME + "</td>");
}
else
{
state = "已完成";
sb.Append("<tr class='Orange HandCss' title='负责人:" + vList[i].FULL_NAME + ",开始时间:" + vList[i].START_TIME + ",结束时间:" + vList[i].END_TIME + "'>");
sb.Append("<td>" + vList[i].STEP_NAME + "</td>");
}
break;
}
#region 获取步骤对应的风险点
sb.Append(" <td > ");
PDTech.OA.Model.RISK_POINT_INFO step_risk_point = null;
if (allRiskPoint != null)
{
step_risk_point = allRiskPoint.Where(r => r.STEP_TYPE == "SW_PROJECT_STEP" && r.STEP_ID == vList[i].STEP_ID.Value).FirstOrDefault();
}
if (step_risk_point != null)
{
string risk_title = "风险点:" + step_risk_point.RISK_POINT + "\n\n防范措施:" + step_risk_point.RISK_RESOLVE + "";
string risk_icon = "";
//配置提示样式
switch (step_risk_point.RISK_LEVEL.Value.ToString())
{
case "1":
risk_icon = "<b class='text-danger pull-right' style='font-size: 18px; '><span class='glyphicon glyphicon-star'></span><span class='glyphicon glyphicon-star'></span><span class='glyphicon glyphicon-star'></span></b>";
break;
case "2":
risk_icon = "<b class='text-danger pull-right' style='font-size: 18px;'><span class='glyphicon glyphicon-star'></span><span class='glyphicon glyphicon-star'></span></b>";
break;
case "3":
risk_icon = "<b class='text-danger pull-right' style='font-size: 18px; '><span class='glyphicon glyphicon-star'></span></b>";
break;
}
sb.Append(" <span class=\"AttitudeBtn\"; title=\"" + risk_title + "\">" + risk_icon + "</span>");
}
sb.Append(" </td>");
#endregion
sb.Append("<td>" + vList[i].DEPARTMENT_NAME + "</td>");
sb.Append("<td>" +AidHelp.ShortTime(vList[i].START_TIME) + "</td>");
sb.Append("<td>" + AidHelp.ShortTime(vList[i].END_TIME) + "</td>");
string date;
if (vList[i].LIMIT_TIME == null || string.IsNullOrEmpty(vList[i].LIMIT_TIME.ToString()))
{
date = "";
}
else
{
date = vList[i].LIMIT_TIME.Value.ToString("yyyy-MM-dd");
}
sb.Append("<td>" + date + "</td>");
sb.Append("<td>" + state + "</td>");
if (vList[i].RISK_HANDLE_ARCHIVE_ID == null)
{
sb.Append("<td style=\"color:#0000ed;\" onclick=\"editRisk('33','" + vList[i].PROJECT_ID + "','" + vList[i].PROJECT_STEP_ID + "')\"><a href='javascript:void(0);'>生成风险处置单</a></td>");
}
else
{
sb.Append("<td style=\"color:#0000ed;\" onclick=\"selrisk('" + vList[i].RISK_HANDLE_ARCHIVE_ID + "')\"><a href='javascript:void(0);'>查看风险处置单</a></td>");
}
sb.Append("</tr>");
if (i != vList.Count -1)
{
sb.Append("<tr>");
sb.Append("<td colspan='8'><img src='" + Symol + "' alt='下一步' style='height:20px;'/></td>");
sb.Append("</tr>");
}
}
ShowScript.Text = sb.ToString();
}
} |
#! "netcoreapp2.1"
#r "_bin/FlipLeaf.Engine.dll"
#r "_bin/Markdig.dll"
#load "FlipLeaf.Scripting.csx"
using FlipLeaf;
using FlipLeaf.Core;
using FlipLeaf.Core.Text;
using static FlipLeafGenerator;
Sources.Add("content", s => new FlipLeaf.Core.Inputs.FileInputSource(s.InputDirectory) { Exclude = new[] { "README.md" } });
Sources.Add("static", s => new FlipLeaf.Core.Inputs.FileInputSource(s.GetFullRootPath("_static")));
Pipelines.Add("content", site =>
{
var parser = new FlipLeaf.Core.Text.MarkdigSpecifics.MarkdigParser();
parser.Use(new FlipLeaf.Core.Text.MarkdigSpecifics.WikiLinkExtension() { Extension = ".md" });
parser.Use(new FlipLeaf.Core.Text.MarkdigSpecifics.CustomLinkInlineRendererExtension(site));
return new FlipLeaf.Core.Pipelines.TextTransformPipeline(
i => i.Extension == ".md",
// read
new FlipLeaf.Core.Text.ReadContentMiddleware(),
// prepare
new FlipLeaf.Core.Text.ITextMiddleware[] {
new FlipLeaf.Core.Text.YamlHeaderMiddleware(new FlipLeaf.Core.Text.YamlParser())
},
// transform
new FlipLeaf.Core.Text.ITextMiddleware[] {
new FlipLeaf.Core.Text.YamlHeaderMiddleware(new FlipLeaf.Core.Text.YamlParser()),
new FlipLeaf.Core.Text.LiquidMiddleware(new FlipLeaf.Core.Text.FluidLiquid.FluidParser(site)),
new FlipLeaf.Core.Text.MarkdownMiddleware(parser)
},
// write
new FlipLeaf.Core.Text.WriteContentMiddleware() { Extension = ".html" }
);
});
Pipelines.Add("static", s => new FlipLeaf.Core.Pipelines.CopyPipeline());
await Generate(Args.ToArray());
|
namespace Plus.Communication.Packets.Outgoing.Rooms.Furni.LoveLocks
{
internal class LoveLockDialogueMessageComposer : MessageComposer
{
public int ItemId { get; }
public LoveLockDialogueMessageComposer(int itemId)
: base(ServerPacketHeader.LoveLockDialogueMessageComposer)
{
ItemId = itemId;
}
public override void Compose(ServerPacket packet)
{
packet.WriteInteger(ItemId);
packet.WriteBoolean(true);
}
}
} |
using System.Windows;
namespace HandyControl.Tools.Extension
{
public static class ValueExtension
{
public static Thickness Add(this Thickness a, Thickness b) => new Thickness(a.Left + b.Left, a.Top + b.Top, a.Right + b.Right, a.Bottom + b.Bottom);
}
} |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Loggly.Responses;
namespace Loggly
{
public interface ILogglyClient
{
Task<LogResponse> Log(LogglyEvent logglyEvent);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace Sunny.Robot
{
public class RobotCommand
{
private RobotCommandType _commandType = RobotCommandType.no;
public string Name { get; set; }
public string Description { get; set; }
public string Remarkes { get; set; }
public bool Enabled { get; set; }
public string Tool { get; set; }
[XmlIgnore]
public string ParametersString { get; set; }
[XmlIgnore]
public RobotCommandType CommandType
{
get
{
if (_commandType == RobotCommandType.no)
{
if (!string.IsNullOrEmpty(Name))
{
Enum.TryParse<RobotCommandType>(Name, out _commandType);
}
}
return _commandType;
}
set
{
_commandType = value;
}
}
}
public enum RobotCommandType
{
no,
sr,
cl,
hp,
ls,
}
}
|
using System.Collections.Generic;
using System.Linq;
using Plus.Communication.Packets.Outgoing.Rooms.Settings;
using Plus.HabboHotel.GameClients;
using Plus.HabboHotel.Rooms;
namespace Plus.Communication.Packets.Incoming.Rooms.Settings
{
internal class ToggleMuteToolEvent : IPacketEvent
{
public void Parse(GameClient session, ClientPacket packet)
{
if (!session.GetHabbo().InRoom)
return;
Room room = session.GetHabbo().CurrentRoom;
if (room == null || !room.CheckRights(session, true))
return;
room.RoomMuted = !room.RoomMuted;
List<RoomUser> roomUsers = room.GetRoomUserManager().GetRoomUsers();
foreach (RoomUser roomUser in roomUsers.ToList())
{
if (roomUser == null || roomUser.GetClient() == null)
continue;
roomUser.GetClient()
.SendWhisper(room.RoomMuted ? "This room has been muted" : "This room has been unmuted");
}
room.SendPacket(new RoomMuteSettingsComposer(room.RoomMuted));
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SoundManager : Singleton<SoundManager>
{
public AudioSource[] audiosources;
public PitchVolumeAudio plantGrowStartSound; //0
public PitchVolumeAudio plantGrowEndSound; //1
public PitchVolumeAudio dashSound; //2
public PitchVolumeAudio jumpSound; //3
public PitchVolumeAudio filetSound; //4
public PitchVolumeAudio jumpingLeafSound; //5
public PitchVolumeAudio doubleJumpSound; //6
public PitchVolumeAudio feedingSound; //7
void Start()
{
for (int i = 0; i < audiosources.Length; i++)
{
audiosources[i].loop = false;
}
}
public void PlaySound(int sound)
{
switch(sound)
{
case 0:
plantGrowStartSound.Play(GetAudioSourceAvailable());
break;
case 1:
plantGrowEndSound.Play(GetAudioSourceAvailable());
break;
case 2:
dashSound.Play(GetAudioSourceAvailable());
break;
case 3:
jumpSound.Play(GetAudioSourceAvailable());
break;
case 4:
filetSound.Play(GetAudioSourceAvailable());
break;
case 5:
jumpingLeafSound.Play(GetAudioSourceAvailable());
break;
case 6:
doubleJumpSound.Play(GetAudioSourceAvailable());
break;
case 7:
feedingSound.Play(GetAudioSourceAvailable());
break;
}
}
public void GetAudioSourceAvailable(AudioClip clip)
{
for (int i = 0; i < audiosources.Length; i++)
{
if (!audiosources[i].isPlaying)
{
audiosources[i].loop = false;
audiosources[i].clip = clip;
audiosources[i].Play();
return;
}
}
}
public AudioSource GetAudioSourceAvailable()
{
for (int i = 0; i < audiosources.Length; i++)
{
if (!audiosources[i].isPlaying)
{
return audiosources[i];
}
}
return null;
}
}
|
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;
using Microsoft.Azure.Documents;
namespace ResourceTagging
{
public static class Tagging
{
[FunctionName(nameof(GetResourceGroup))]
public static async Task<IActionResult> GetResourceGroup([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequest req, ILogger log)
{
Regex rx = new Regex("resourceGroups\\/(.+)\\/providers");
log.LogInformation("C# HTTP trigger function processed a request.");
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
string id = (string)data["id"];
return new OkObjectResult(rx.Match(id).Groups[1].Value);
}
[FunctionName(nameof(CheckTags))]
public static async Task<IActionResult> CheckTags(
[HttpTrigger(AuthorizationLevel.Function, "post")]TagRequest req,
[CosmosDB("ignite", "tags", Id = "{ResourceGroup}", ConnectionStringSetting = "CosmosDBConnectionString")] Document doc,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
JObject cosmosTags = doc.GetPropertyValue<JObject>("tags");
log.LogInformation("Exected tags: " + cosmosTags.ToString());
log.LogInformation("Actual tags: " + req.Tags.ToString());
bool equal = true;
foreach(var tag in cosmosTags)
{
if (!(req.Tags.ContainsKey(tag.Key) && ((string)req.Tags.GetValue(tag.Key)).Equals((string)tag.Value)))
{
equal = false;
}
}
return new OkObjectResult(
new {
isEqual = equal,
expected = cosmosTags,
actual = req.Tags
});
}
public class TagRequest
{
public string ResourceGroup { get; set; }
public JObject Tags { get; set; }
}
}
}
|
namespace IsLeapYear
{
using System;
public class IsLeapYear
{
/// <summary>
/// Write a program that reads a year from the console and checks whether it is a leap.
/// Use DateTime.
/// </summary>
public static void Main(string[] args)
{
Console.WriteLine("Please, enter year:");
int year = int.Parse(Console.ReadLine());
Console.WriteLine("{0}: {1}", year, DateTime.IsLeapYear(year) ? "leap" : "not leap");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
static class A
{
public static bool IsTrue(this bool value) { return true == value; }
}
class Program
{
static void Main(string[] args)
{
var address = "brno";
var oldAddress = address;
Console.WriteLine(address);
Console.WriteLine(oldAddress);
DoSomething(address);
Console.WriteLine(address);
Console.WriteLine(oldAddress);
bool aa = false;
if (aa.IsTrue())
{
}
var obj = new { Id = 1, Name = "sadfasdf" };
//obj.Id = 4;
Console.WriteLine(obj.Id);
IShape[] shapes = new IShape[] { new Square(), new Rectangle() };
foreach (var shape in shapes)
{
shape.Draw();
}
var a = new MyClass(10);
foreach (var i in a.CountFrom(5))
{
Console.WriteLine(i);
}
Console.ReadLine();
}
private static void DoSomething(string address)
{
address = "Brno";
}
}
class MyClass
{
int limit = 0;
public MyClass(int limit) { this.limit = limit; }
public IEnumerable<int> CountFrom(int start)
{
for (int i = start; i <= limit; i++)
{
yield return i;
}
//yield return -1;
//yield return -2;
//yield return -3;
}
}
interface IShape
{
void Draw();
}
class Rectangle : IShape
{
public void Draw()
{
Console.WriteLine("Rectangle");
}
}
class Square : Rectangle
{
public void Draw()
{
Console.WriteLine("Square");
}
}
class Entry<K, V>
{
private readonly K key;
private readonly V value;
public Entry(K k, V v)
{
key = k;
value = v;
}
}
}
|
using Calcifer.Engine.Graphics;
using OpenTK.Graphics.OpenGL;
namespace Calcifer.Engine.Scenegraph
{
public class MaterialNode: SceneNode
{
protected Material Material { get; private set; }
public MaterialNode(SceneNode parent, Material material) : base(parent)
{
Material = material;
}
public override void AcceptPass(RenderPass pass)
{
pass.Visit(this);
}
public override void BeginRender()
{
GL.Material(MaterialFace.Front, MaterialParameter.Diffuse, Material.Diffuse);
GL.Material(MaterialFace.Front, MaterialParameter.Specular, Material.Specular);
GL.Material(MaterialFace.Front, MaterialParameter.Ambient, Material.Ambient);
GL.Material(MaterialFace.Front, MaterialParameter.Shininess, Material.Shininess);
if (Material.DiffuseMap != null)
{
GL.ActiveTexture(TextureUnit.Texture0);
Material.DiffuseMap.Bind();
}
if (Material.SpecularMap != null)
{
GL.ActiveTexture(TextureUnit.Texture1);
Material.SpecularMap.Bind();
}
if (Material.NormalMap != null)
{
GL.ActiveTexture(TextureUnit.Texture6);
Material.NormalMap.Bind();
}
}
public override void EndRender()
{
Material.DiffuseMap.Unbind();
}
}
}
|
using System;
namespace InterfaceExtensibility
{
public class DbMigrator
{
private readonly ILogger _logger;
public DbMigrator(ILogger logger)
{
this._logger = logger;
}
public void Migrate()
{
_logger.LogInfo($"Db migration started {DateTime.Now}");
_logger.LogInfo($"Db migration finished {DateTime.Now}");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Observer
{
class ConcreteObserver : Observer
{
public void Update(object obj)
{
Console.WriteLine("Observer Recived:" + obj);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Grisaia.Extensions;
namespace Grisaia.Asmodean {
partial class Hg3 {
#region Extract
private static Hg3 Extract(Stream stream, string fileName, string directory, bool saveFrames, bool expand) {
BinaryReader reader = new BinaryReader(stream);
HG3HDR hdr = reader.ReadUnmanaged<HG3HDR>();
if (hdr.Signature != "HG-3")
throw new UnexpectedFileTypeException(fileName, "HG-3");
//int backtrack = Marshal.SizeOf<HG3TAG>() - 1;
List<KeyValuePair<HG3STDINFO, List<long>>> imageOffsets = new List<KeyValuePair<HG3STDINFO, List<long>>>();
for (int i = 0; ; i++) {
// NEW-NEW METHOD: We now know the next offset ahead
// of time from the HG3OFFSET we're going to read.
// Usually skips 0 bytes, otherwise usually 1-7 bytes.
long startPosition = stream.Position;
HG3OFFSET offset = reader.ReadUnmanaged<HG3OFFSET>();
HG3TAG tag = reader.ReadUnmanaged<HG3TAG>();
if (!HG3STDINFO.HasTagSignature(tag.Signature))
throw new Exception("Expected \"stdinfo\" tag!");
// NEW METHOD: Keep searching for the next stdinfo
// This way we don't miss any images
/*int offset = 0;
while (!tag.Signature.StartsWith("stdinfo")) {
if (stream.IsEndOfStream())
break;
stream.Position -= backtrack;
tag = reader.ReadStruct<HG3TAG>();
offset++;
}
if (stream.IsEndOfStream())
break;*/
// OLD METHOD: Missed entries in a few files
//if (!tag.signature.StartsWith(StdInfoSignature))
// break;
HG3STDINFO stdInfo = reader.ReadUnmanaged<HG3STDINFO>();
List<long> frameOffsets = new List<long>();
imageOffsets.Add(new KeyValuePair<HG3STDINFO, List<long>>(stdInfo, frameOffsets));
while (tag.OffsetNext != 0) {
tag = reader.ReadUnmanaged<HG3TAG>();
string signature = tag.Signature;
if (HG3IMG.HasTagSignature(signature)) { // "img####"
frameOffsets.Add(stream.Position);
// Skip this tag
stream.Position += tag.Length;
}
/*else if (HG3ATS.HasTagSignature(signature)) { // "ats####"
// Skip this tag
stream.Position += tag.Length;
}
else if (HG3CPTYPE.HasTagSignature(signature)) { // "cptype"
// Skip this tag
stream.Position += tag.Length;
}
else if (HG3IMG_AL.HasTagSignature(signature)) { // "img_al"
// Skip this tag
stream.Position += tag.Length;
}
else if (HG3IMG_JPG.HasTagSignature(signature)) { // "img_jpg"
// Skip this tag
stream.Position += tag.Length;
}
else if (HG3IMGMODE.HasTagSignature(signature)) { // "imgmode"
// Skip this tag
stream.Position += tag.Length;
}*/
else {
// Skip this unknown tag
stream.Position += tag.Length;
}
}
if (offset.OffsetNext == 0)
break; // End of stream
stream.Position = startPosition + offset.OffsetNext;
}
HG3STDINFO[] stdInfos = imageOffsets.Select(p => p.Key).ToArray();
long[][] allFrameOffsets = imageOffsets.Select(p => p.Value.ToArray()).ToArray();
Hg3 hg3 = new Hg3(Path.GetFileName(fileName), hdr, stdInfos, allFrameOffsets, saveFrames && expand);
// Save any frames after we've located them all.
// This way we truely know if something is an animation.
if (saveFrames) {
for (int imgIndex = 0; imgIndex < hg3.Count; imgIndex++) {
HG3STDINFO stdInfo = stdInfos[imgIndex];
Hg3Image hg3Image = hg3.Images[imgIndex];
for (int frmIndex = 0; frmIndex < hg3Image.FrameCount; frmIndex++) {
stream.Position = hg3Image.FrameOffsets[frmIndex];
HG3IMG imghdr = reader.ReadUnmanaged<HG3IMG>();
string pngFile = hg3.GetFrameFilePath(directory, imgIndex, frmIndex);
ExtractBitmap(reader, stdInfo, imghdr, expand, pngFile);
}
}
}
return hg3;
}
#endregion
#region ExtractBitmap
/// <summary>
/// Extracts the bitmap from the HG-3 file.
/// </summary>
/// <param name="reader">The binary reader for the file.</param>
/// <param name="std">The HG3STDINFO containing image dimensions, etc.</param>
/// <param name="img">The image header used to process the image.</param>
/// <param name="expand">True if the image should be expanded to its full size.</param>
/// <param name="pngFile">The path to the PNG file to save to.</param>
private static void ExtractBitmap(BinaryReader reader, HG3STDINFO std, HG3IMG img, bool expand, string pngFile) {
int depthBytes = (std.DepthBits + 7) / 8;
int stride = (std.Width * depthBytes + 3) / 4 * 4;
byte[] bufferTmp = reader.ReadBytes(img.DataLength);
byte[] cmdBufferTmp = reader.ReadBytes(img.CmdLength);
byte[] rgbaBuffer;
// Perform heavy processing that's faster in native code
ProcessImageNative(
bufferTmp,
img.DataLength,
img.OriginalDataLength,
cmdBufferTmp,
img.CmdLength,
img.OriginalCmdLength,
out IntPtr pRgbaBuffer,
out int rgbaLength,
std.Width,
std.Height,
depthBytes);
try {
// Vertically flip the buffer so its in the correct setup to load into Bitmap
rgbaBuffer = new byte[rgbaLength];
for (int y = 0; y < std.Height; y++) {
int src = y * stride;
int dst = (std.Height - (y + 1)) * stride;
Marshal.Copy(pRgbaBuffer + src, rgbaBuffer, dst, stride);
}
} finally {
Marshal.FreeHGlobal(pRgbaBuffer);
}
WriteBitmap(rgbaBuffer, std, expand, pngFile);
}
/// <summary>
/// Writes the bitmap buffer to <paramref name="pngFile"/> and optional performs expansion if
/// <paramref name="expand"/> is true.
/// </summary>
/// <param name="buffer">The buffer to the image bits.</param>
/// <param name="std">The HG3STDINFO containing image dimensions, etc.</param>
/// <param name="expand">True if the image should be expanded to its full size.</param>
/// <param name="pngFile">The path to the PNG file to save to.</param>
private static void WriteBitmap(byte[] buffer, HG3STDINFO std, bool expand, string pngFile) {
GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
try {
IntPtr scan0 = handle.AddrOfPinnedObject();
int depthBytes = (std.DepthBits + 7) / 8;
int stride = (std.Width * depthBytes + 3) / 4 * 4;
PixelFormat format;
switch (std.DepthBits) {
case 32: format = PixelFormat.Format32bppArgb; break;
case 24: format = PixelFormat.Format24bppRgb; break;
default: throw new Exception($"Unsupported depth bits {std.DepthBits}!");
}
// Do expansion here, and up to 32 bits if not 32 bits already.
if (expand) {
using (var bitmap = new Bitmap(std.Width, std.Height, stride, format, scan0))
using (var bitmap32 = new Bitmap(std.TotalWidth, std.TotalHeight, PixelFormat.Format32bppArgb))
using (Graphics g = Graphics.FromImage(bitmap32)) {
g.DrawImageUnscaled(bitmap, std.OffsetX, std.OffsetY);
bitmap32.Save(pngFile, ImageFormat.Png);
}
}
else {
using (var bitmap = new Bitmap(std.Width, std.Height, stride, format, scan0))
bitmap.Save(pngFile, ImageFormat.Png);
}
} finally {
// Thing to note that gave me headaches earlier:
// Once this handle is freed, the bitmap loaded from
// scan0 will be invalidated after garbage collection.
handle.Free();
}
}
#endregion
}
}
|
using PDV.DAO.Atributos;
using System;
namespace PDV.DAO.Entidades.Estoque.Suprimentos
{
public class ContatoClienteFornecedor
{
[CampoTabela("IDCONTATOCLIENTEFORNECEDOR")]
public decimal IDContatoClienteFornecedor { get; set; } = -1;
[CampoTabela("IDFORNECEDOR")]
public decimal? IDFornecedor { get; set; }
[CampoTabela("IDCLIENTE")]
public decimal? IDCliente { get; set; }
[CampoTabela("NOME")]
public string Nome { get; set; }
[CampoTabela("CARGO")]
public string Cargo { get; set; }
[CampoTabela("EMAIL")]
public string Email { get; set; }
[CampoTabela("TELEFONE1")]
public string Telefone1 { get; set; }
[CampoTabela("TELEFONE2")]
public string Telefone2 { get; set; }
[CampoTabela("SEXO")]
public decimal Sexo { get; set; }
public ContatoClienteFornecedor() { }
}
}
|
namespace Abstraction
{
using System;
public abstract class AbstractShape : IShape
{
public abstract double CalculatePerimeter();
public abstract double CalculateSurface();
protected void ValidateDoubleValue(double value, string valueName)
{
if (value < 0 || value == 0)
{
throw new ArgumentOutOfRangeException(" " + valueName
+ " cannot be zero, or negative !");
}
}
}
}
|
using Infrastructure;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
using System;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using Web.Models;
using Web.ViewModels;
namespace Web.Controllers
{
public class HomeController : Controller
{
private readonly IStringLocalizer<HomeController> localizer;
public HomeController(IStringLocalizer<HomeController> localizer)
{
this.localizer = localizer;
}
public IActionResult Index()
{
var strings = localizer.GetAllStrings();
Response.Cookies
.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(
new RequestCulture(CultureInfo.CurrentCulture)
)
);
var repository = new ProductRepository();
var products = repository.Get();
return View(products.OrderBy(product => product.Name,
StringComparer.OrdinalIgnoreCase));
}
[HttpPost]
public IActionResult Add(ProductViewModel model)
{
if(!ModelState.IsValid)
{
var errors = ModelState.Values
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage);
return BadRequest(errors);
}
return Ok();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;
using System.Windows.Forms;
namespace MetroWeb
{
/// <summary>
/// Interaction logic for UserControlWebBrowserWindow.xaml
/// </summary>
public partial class UserControlWebBrowserWindow : System.Windows.Controls.UserControl
{
TabItem myTabItem;
public bool IsLoading;
public UserControlWebBrowserWindow(TabItem TabItem)
{
myTabItem = TabItem;
InitializeComponent();
}
void _browser_DownloadComplete(object sender, EventArgs e)
{
IsLoading = false;
Utils.EndLoad(myTabItem);
}
private void WebBrowser_StartNewWindow(object sender, ExtendedWebBrowser2.BrowserExtendedNavigatingEventArgs e)
{
if ((e.NavigationContext & ExtendedWebBrowser2.UrlContext.UserFirstInited)
== ExtendedWebBrowser2.UrlContext.UserFirstInited &&
(e.NavigationContext & ExtendedWebBrowser2.UrlContext.UserInited)
== ExtendedWebBrowser2.UrlContext.UserInited)
Utils.myMainWindow.AddTab(e.Url);
e.Cancel = true;
}
private void WebBrowser_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)
{
Utils.UpdateProgress(e.CurrentProgress, myTabItem);
}
private void WebBrowser_CanGoBackChanged(object sender, EventArgs e)
{
Utils.CanGoBackChanged(WebBrowser.CanGoBack, myTabItem);
}
private void WebBrowser_CanGoForwardChanged(object sender, EventArgs e)
{
Utils.CanGoForwardChanged(WebBrowser.CanGoForward, myTabItem);
}
private void WebBrowser_Downloading(object sender, EventArgs e)
{
IsLoading = true;
Utils.StartLoad(myTabItem);
}
private void WebBrowser_DocumentTitleChanged(object sender, EventArgs e)
{
Utils.UpdateTitle(this.WebBrowser.DocumentTitle, myTabItem);
}
private void WebBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
Utils.UpdateAddressBox(this.WebBrowser.Document.Url, myTabItem);
}
}
}
|
using System.Runtime.Serialization;
using System.ServiceModel;
namespace WcfMathServiceInterface
{
[ServiceContract]
public interface IMathService
{
[OperationContract]
CompositeType Add(int a, int b);
[OperationContract]
CompositeType Substract(int a, int b);
}
[DataContract]
public class CompositeType
{
[DataMember]
public int Result { get; set; }
[DataMember]
public bool IsFirstBigger { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
using HeladacWeb.Services;
namespace HeladacWeb.Models
{
public class Credential
{
public string _id = Guid.NewGuid().ToString();
public string id
{
get
{
return _id;
}
set
{
_id = value;
}
}
public string credentialId { get; set; }
[ForeignKey("credentialId")]
public HelmUser credentialUser_DB { get; set; }
public string helmUserId { get; set; }
[ForeignKey("helmUserId")]
public HelmUser helmUser_DB { get; set; }
public string heladacUserId { get; set; }
[ForeignKey("heladacUserId")]
public HelmUser heladacUser_DB { get; set; }
[NotMapped]
public CredentialServiceType credentialService { get; set; } = CredentialServiceType.none;
public string credentialService_DB
{
get
{
return credentialService.ToString().ToLower();
}
set
{
if (string.IsNullOrEmpty(value) || string.IsNullOrWhiteSpace(value))
{
credentialService = CredentialServiceType.none;
}
else
{
credentialService = Utility.ParseEnum<CredentialServiceType>(value);
}
}
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations.Schema;
namespace API.Entities
{
[Table("Places")]
public class Place
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string OpenTime { get; set; }
public string CloseTime { get; set; }
public string Theme { get; set; }
public string Subtheme { get; set; }
public double Rating { get; set; }
public int NumberOfGrades { get; set; }
public bool Promotion { get; set; }
public string ExpectedTimeSpent { get; set; }
public City City { get; set; }
public int CityId { get; set; }
}
} |
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Collections.Generic;
using System.Security.Claims;
using System.Web.Http;
using WepApiUserRegistrationAngular.Models;
namespace WepApiUserRegistrationAngular.Controllers
{
public class AccountController : ApiController
{
[Route("api/User/Register")]
[HttpPost]
[AllowAnonymous]
public IdentityResult Register(AccountModel model)
{
var userStore = new UserStore<ApplicationUser>(new ApplicationDbContext());
var manager = new UserManager<ApplicationUser>(userStore);
var user = new ApplicationUser { UserName = model.UserName, Email = model.Email };
user.FirstName = model.FirstName;
user.LastName = model.LastName;
manager.PasswordValidator = new PasswordValidator { RequiredLength = 3 };
IdentityResult result = manager.Create(user, model.Password);
return result;
}
[HttpGet]
[Route("api/GetUserClaims")]
public AccountModel GetUserClaims()
{
var identityClass = (ClaimsIdentity)User.Identity;
IEnumerable<Claim> claims = identityClass.Claims;
AccountModel model = new AccountModel()
{
UserName = identityClass.FindFirst("Username").Value,
Email = identityClass.FindFirst("Email").Value,
FirstName = identityClass.FindFirst("FirstName").Value,
LastName = identityClass.FindFirst("LastName").Value,
LoggedOn = identityClass.FindFirst("LoggedOn").Value,
};
return model;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine;
public class DelayFua : MonoBehaviour
{
public GameObject texto;
public float tiempo;
public GameObject jugador;
public GameObject Tiempo;
public GameObject Este;
private void Start()
{
AuidoScript.instance.Mute("Marcha");
}
void Update()
{
if (tiempo > 0)
{
tiempo -= Time.deltaTime * 1;
}
if (tiempo <= 0)
{
texto.SetActive(false);
jugador.SetActive(true);
Tiempo.GetComponent<LimiteDeTiempoFua>().enabled = true;
Este.SetActive(false);
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace Cubecraft.Net.Protocol
{
public delegate void HttpCallBack(bool isSuccess, string result);
internal delegate void LoginCallBack(ProtocolHandler.LoginResult result, SessionToken session);
class ProtocolHandler
{
public static bool MinecraftServiceLookup(ref string domain, ref ushort port)
{
if (!String.IsNullOrEmpty(domain) && domain.Any(c => char.IsLetter(c)))
{
try
{
Console.WriteLine("Resolving {0}...", domain);
Heijden.DNS.Response response = new Heijden.DNS.Resolver().Query("_minecraft._tcp." + domain, Heijden.DNS.QType.SRV);
Heijden.DNS.RecordSRV[] srvRecords = response.RecordsSRV;
if (srvRecords != null && srvRecords.Any())
{
//Order SRV records by priority and weight, then randomly
Heijden.DNS.RecordSRV result = srvRecords
.OrderBy(record => record.PRIORITY)
.ThenByDescending(record => record.WEIGHT)
.ThenBy(record => Guid.NewGuid())
.First();
string target = result.TARGET.Trim('.');
UnityEngine.Debug.Log(String.Format("§8Found server {0}:{1} for domain {2}", target, result.PORT, domain));
domain = target;
port = result.PORT;
return true;
}
}
catch (Exception e)
{
UnityEngine.Debug.Log(String.Format("Failed to perform SRV lookup for {0}\n{1}: {2}", domain, e.GetType().FullName, e.Message));
}
}
return false;
}
public enum LoginResult { OtherError, ServiceUnavailable, SSLError, Success, WrongPassword, AccountMigrated, NotPremium, LoginRequired, InvalidToken, InvalidResponse, NullError };
public static void GetLogin(string user, string pass, LoginCallBack call)
{
Global.clientID = Guid.NewGuid().ToString().Replace("-", "");
SessionToken session = new SessionToken();
try
{
string json_request = "{\"agent\": { \"name\": \"Minecraft\", \"version\": 1 }, \"username\": \"" + JsonEncode(user) + "\", \"password\": \"" + JsonEncode(pass) + "\", \"clientToken\": \"" + JsonEncode(Global.clientID) + "\" }";
DoHTTPSPost("https://authserver.mojang.com/authenticate", json_request, (bool isSuccess, string result) =>
{
if (isSuccess)
{
if (result.Contains("availableProfiles\":[]}"))
{
call(LoginResult.NotPremium, session);
}
else
{
session = JsonUtility.FromJson<SessionToken>(result);
if (!string.IsNullOrEmpty(session.accessToken))
{
call(LoginResult.Success, session);
}
}
}
});
}
catch(Exception e)
{
UnityEngine.Debug.Log(e.Message);
}
call(LoginResult.InvalidResponse, session);
}
private async static void DoHTTPSPost(string url, string data, HttpCallBack call)
{
UnityEngine.Debug.Log("Post to " + url);
HttpWebRequest request;
if(url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) =>
{
return true;
});
}
request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
try
{
byte[] postData = Encoding.UTF8.GetBytes(data);
request.ContentLength = postData.Length;
var writer = request.GetRequestStream();
writer.Write(postData, 0, postData.Length);
writer.Close();
HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse;
using(StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string result = reader.ReadToEnd();
response.Close();
call(true, result);
}
}
catch (Exception e)
{
call(false, e.Message);
}
}
private static string JsonEncode(string text)
{
StringBuilder result = new StringBuilder();
foreach (char c in text)
{
if ((c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z'))
{
result.Append(c);
}
else
{
result.AppendFormat(@"\u{0:x4}", (int)c);
}
}
return result.ToString();
}
}
}
|
using System.Collections.Generic;
using Student.Model;
using System.Linq;
namespace Student.Service.interfaces
{
public interface IEntityService<T> where T : BaseEntity<int>
{
T Create(T entity);
void Delete(T entity);
void Update(T entity);
T FindById(int Id);
IQueryable<T> GetAll();
}
}
|
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using IdentityProvider.Model.ViewModel;
using IdentityServer3.Core;
using IdentityServer3.Core.Extensions;
using IdentityServer3.Core.Models;
using IdentityServer3.Core.Services;
namespace IdentityProvider.Services
{
public class LoginUserService : IUserService
{
private readonly ICredentialProvider credentialProvider;
private readonly IIdentityService identityService;
public LoginUserService(ICredentialProvider credentialProvider, IIdentityService identityService)
{
this.credentialProvider = credentialProvider;
this.identityService = identityService;
}
public async Task AuthenticateLocalAsync(LocalAuthenticationContext context)
{
var username = context.UserName;
var password = context.Password;
context.AuthenticateResult = null;
var credential = new CredentialInputModel
{
Username = username,
Password = password
};
var result = await credentialProvider.ValidateAsync(credential);
if (!result.IsValid)
{
return;
}
var identityId = result.IdentityId;
var identity = await identityService.GetIdentityAsync(identityId);
if (identity == null)
{
context.AuthenticateResult = new AuthenticateResult("Invalid identity");
return;
}
context.AuthenticateResult = new AuthenticateResult(identityId.ToString(), identity.Alias);
}
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
var subject = context.Subject.GetSubjectId();
var identity = await identityService.GetIdentityAsync(new Guid(subject));
if (identity == null)
{
context.IssuedClaims = null;
return;
}
var userClaims = new List<Claim>
{
new Claim(Constants.ClaimTypes.Subject, subject),
new Claim(Constants.ClaimTypes.PreferredUserName, identity.Alias),
new Claim(Constants.ClaimTypes.Name, $"{identity.FirstName} {identity.LastName}"),
new Claim(Constants.ClaimTypes.GivenName, identity.FirstName),
new Claim(Constants.ClaimTypes.FamilyName, identity.LastName),
new Claim(Constants.ClaimTypes.MiddleName, identity.MiddleName ?? string.Empty),
new Claim(Constants.ClaimTypes.Email, identity.Email)
};
context.IssuedClaims = userClaims;
}
public Task PreAuthenticateAsync(PreAuthenticationContext context)
{
return Task.FromResult(0);
}
public Task IsActiveAsync(IsActiveContext context)
{
context.IsActive = true;
return Task.FromResult(0);
}
public Task AuthenticateExternalAsync(ExternalAuthenticationContext context)
{
return Task.FromResult(0);
}
public Task PostAuthenticateAsync(PostAuthenticationContext context)
{
return Task.FromResult(0);
}
public Task SignOutAsync(SignOutContext context)
{
return Task.FromResult(0);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.