text stringlengths 13 6.01M |
|---|
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.IO;
class MainClass {
//Methods
public static void Main (string[] args) {
//Objects to initialize
Random random = new Random();
//Variables
List<string> inven = new List<string>();
inven.Add("earth");
inven.Add("fire");
inven.Add("air");
inven.Add("water");
SortedList<string, string> combosAndRecipes = new SortedList<string, string>();
//Initializing the main variable that stores all of the unlockable items and their correspoding recipes
string[] combosAndRecipesArray = new [] {
"fire+fire", "energy", "land+land", "continent", "solarsystem+solarsystem", "galaxy", "aminoacids+energy", "life",
"earth+earth", "dirt", "continent+continent", "globe", "galaxy+galaxy", "*universe*", "life+dirt", "plant",
"earth+energy", "earthquake", "globe+atmosphere", "planet", "sun+pressure", "*blackhole*", "plant+fire", "ash",
"water+earth", "mud", "water+water", "ocean", "wind+wind", "*tornado*", "ash+pressure", "coal",
"water+dirt", "mud", "dust+dust", "minerals", "clay+fire", "brick", "coal+pressure", "diamond",
"mud+fire", "clay", "fire+planet", "sun", "brick+brick", "wall", "plant+dirt", "tree",
"energy+air", "wind", "sun+cloud", "sky", "wall+wall", "home", "tree+human", "wood",
"wind+earth", "dust", "ocean+minerals", "aminoacids", "home+home", "village", "wood+human", "tool",
"fire+water", "steam", "aminoacids+sun", "life", "village+village" + "city", "rock+human", "tool",
"water+air", "mist", "water+land", "river", "city+city", "metropolis", "wood+wood", "home",
"steam+air", "cloud", "water+continent", "ocean", "metropolis+metropolis", "population", "tool+fish", "*sushi*",
"fire+air", "pressure", "energy+cloud", "storm", "rock+water", "sand", "tool+bird", "*fried chicken*",
"earth+air", "dust", "storm+energy", "lightning", "life+land", "animal", "tool+planet", "rocket ship",
"dirt+dirt", "land", "cloud+water", "rain", "animal+clay", "human", "rain+rock", "dust",
"air+air", "atmosphere", "lava+water", "rock", "aniaml+fire", "*phoenix*", "rain+earth", "mud",
"earthquake+earth", "mountain", "wind+rock", "dust", "aniaml+water", "fish", "lava+air", "obsidian",
"earth+fire", "lava", "water+dust", "cloud", "animal+air", "bird", "diamond+wood", "diamond pickaxe",
"lava+mountain", "volcano", "planet+sun", "solar system", "human+human", "family",
"volcano+pressure", "eruption", "planet+planet", "solar system", "family+brick", "home",
"diamondpickaxe+obsidian", "*nether portal*", "ocean+energy", "*hurricane*", "ocean+wind", "hurricane",
"continent+energy", "earthquake", "fire+wood", "fire", "lava+wood", "fire", "planet+plant", "earth","earth+rock","*moon*",
"river+animal", "frog", "frog+tool", "*frog legs*", "sand+sand", "beach", "beech+tree", "*palm tree*",
"sand+fire", "glass", "glass+glass", "glasses", "glass+earth", "*terrarium*", "glass+water", "*aquarium*",
"rock+tool", "metal", "metal+glass", "microscope", "microscope+life", "bacteria", "bacteria+animal", "disease",
"bacteria+human", "disease", "disease+human", "death", "disease+animal", "death", "death+rock", "tomstone",
};
//A collection of the actual recipes, but in an array to help add these objects into combosAndRecipes SortedList
//Converting the array to the SortedList
string prevKey = "";
string prevValue = "";
bool hasPrevKey = false;
bool hasPrevValue = false;
foreach(string recipeItem in combosAndRecipesArray) {
if (recipeItem.Contains("+")) {
prevKey = recipeItem;
hasPrevKey = true;
} else {
prevValue = recipeItem;
hasPrevValue = true;
}
if (hasPrevKey && hasPrevValue) {
combosAndRecipes.Add(prevKey, prevValue);
hasPrevKey = false;
hasPrevValue = false;
}
}
int numRepeats = 0;
IList<string> allValue = combosAndRecipes.Values;
numRepeats = allValue.Count() - allValue.Distinct().Count();
bool running = true;
bool runIntro = true;
//Variables containing arrays of possible inputs
string[] possExitCodes = new string[5] {"exit", "leave", "quit", "q", "e"};
//Possible input codes for quiting the game
string[] possInvenCodes = new string[4] {"inventory", "inven", "backpack", "i"};
//Possible input codes for accessing the inventory menu
string[] possCraftCodes = new string[3] {"c", "crafting", "craft"};
//Possible input codes for accessing the crafting menu
string[] possHelpCodes = new string[2] {"help", "h"};
//Possible input codes for accessing the help menu
string[] possShortCutCodes = new string[3] {"shortcuts", "s", "shorts"};
//Possible input codes for accessing the shortcuts menu
string[] possHintCodes = new [] {"hint", "stuck", "idea"};
//Possible input codes for accessing the hint menu
//Varaibles contataing arrays of possible repsonses
string[] possUIRps = new string[4]
{"Um, I don't know that", "Error Error. Cannot compute input", "Ha! Try again!", "Uh... nice try!"};
//Possible repsonses if player inputed unknown input
//Last minute clean up before player starts playing
Console.Clear();
//Conducting the into to the game
Console.WriteLine("Welcome to the wonderful game of crafting! \nWould you like to know how to play? (Y / N)");
while (runIntro) {
Console.Write(">> ");
string input = Console.ReadLine().ToLower();
input = input.Replace(">> ", "");
if (input == "n") {
runIntro = false;
Console.WriteLine("Okay! Good luck, and have fun!\n");
} else if (input == "y") {
Console.WriteLine("As you may already know, this is a game where you combine two items together to craft, or discover, another item. This new item can possibly be an ingredient for another crafting recipe. \nIf an item has an astrisk (*) by their name, that means that it isn't an ingredient for another recipe. \n\nYou can access different menus that provide different information. For instance, type \"inven\" (without the quotes), and you can see the items you have discovered. The menu you will spend most of you time with will be the crafting menu, you can access it by typing \"craft\". If you have any questions, just type \"help\" to see the full list of possible inputs. \nIf you ever get stuck, don't worry! Type \"hint\" to access the hint menu.\nPress the ENTER key to begin.");
Console.ReadLine();
Console.WriteLine("Good luck, and have fun!\n");
runIntro = false;
} else {
Console.WriteLine("(Y / N)");
}
}
//Main loop for the game
while (running)
{
Console.WriteLine("What would you like to do? Type \"help\" if you ever need it (without the quotes).");
Console.Write(">> ");
string input = Console.ReadLine().ToLower().Replace(">> ", "").Replace(" ", "");
if (possExitCodes.Contains(input)) {
running = false;
break;
} else if (possCraftCodes.Contains(input)) { //The Crating Center
Console.WriteLine("Give two ingredients you want to craft with:\n");
Console.Write("Ingredient 1: ");
string firstIngredientInput = Console.ReadLine().ToLower().Replace("Ingredient 1: ", "").Replace(" ", "");
Console.Write("Ingredient 2: ");
string secondIngredientInput = Console.ReadLine().ToLower().Replace("Ingredient 2: ", "").Replace(" ", "");
Console.WriteLine("");
bool hasIngredOne = false;
bool hasIngredTwo = false;
string[] tempInven = inven.ToArray();
foreach(string invenItem in tempInven) {
tempInven[Array.IndexOf(tempInven, invenItem)] = tempInven[Array.IndexOf(tempInven, invenItem)].Replace(" ", "");
}
if (tempInven.Contains(firstIngredientInput)) {
hasIngredOne = true;
} else {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("You don't have " + firstIngredientInput);
Console.ResetColor();
}
if (tempInven.Contains(secondIngredientInput)) {
hasIngredTwo = true;
} else {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("You don't have " + secondIngredientInput);
Console.ResetColor();
}
if (hasIngredOne && hasIngredTwo) {
string combinedIngredOne = firstIngredientInput + "+" + secondIngredientInput;
string combinedIngredTwo = secondIngredientInput + "+" + firstIngredientInput;
if (combosAndRecipes.ContainsKey(combinedIngredOne) || combosAndRecipes.ContainsKey(combinedIngredTwo)) {
string trueIngredCombo;
if (combosAndRecipes.ContainsKey(combinedIngredOne)) {
trueIngredCombo = combinedIngredOne;
} else {
trueIngredCombo = combinedIngredTwo;
}
if (inven.Contains(combosAndRecipes[trueIngredCombo])) {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("You have already discovered " + combosAndRecipes[trueIngredCombo].ToUpper());
Console.ResetColor();
} else {
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("You have discovered " + combosAndRecipes[trueIngredCombo].ToUpper() + "!");
inven.Add(combosAndRecipes[trueIngredCombo]);
Console.ResetColor();
Console.Write("\nPress ENTER to continue");
Console.ReadLine();
}
} else {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Unknown combination");
Console.ResetColor();
}
}
} else if (possInvenCodes.Contains(input)) { //The Inventory Center
Console.WriteLine("Welcome to the inventory menu. You have:\n");
if (inven.Count == 0) {
Console.WriteLine("Nothing...:\\n");
} else {
Console.ForegroundColor = ConsoleColor.Yellow;
foreach(string invenItem in inven) {
Console.Write("[" + invenItem.ToUpper() + "] ");
}
Console.ResetColor();
}
Console.WriteLine("\n\n** You have discovered " + inven.Count + "/" + (combosAndRecipes.Count + 4 - numRepeats) + " of all items **");
Console.Write("\nPress ENTER to continue");
Console.ReadLine();
} else if (possHelpCodes.Contains(input)) { //The Help Center
Console.WriteLine("Welcome to the help center! Here, you can find specific inputs, and their following effects.");
Console.WriteLine("\nINPUT\t\t\tEFFECT\n\ncraft\t\t\tOpens the crafting menu\ninventory\t\tOpens the crafting menu, where most of the game takes place\nhelp\t\t\tOpens this help menu\nclear\t\t\tClears the screen of previous inputs (NOT UNDOABLE!)\nshortcuts\t\tOpens the shortcuts menu\nexit\t\t\tQuits the game (please don't leave me alone D;)\nhint\t\t\tOpens the hint menu whenever you get stuck.");
Console.Write("\nPress ENTER to continue");
Console.ReadLine();
} else if (possShortCutCodes.Contains(input)) { //Shortcut center
Console.WriteLine("Welcome to the help center! Here, you can find variations of specific inputs.");
Console.WriteLine("\nINPUT\t\t\tSHORTCUT\n\ncraft\t\t\tc, crafting\ninventory\t\ti, inven, backback\nhelp\t\t\th\nshortcuts\t\ts, shorts\nhint\t\t\tstuck, idea");
} else if (input == "clear") {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Are you sure? (Y / N)");
Console.Write(">> ");
input = Console.ReadLine().ToLower().Replace(">> ", "").Replace(" ", "");
if (input == "y") {
Console.Clear();
}
Console.ResetColor();
} else if (possHintCodes.Contains(input)) { //The Hint Center
Console.WriteLine("Welcome to the hint center! Whenever you get stuck, just come here!");
IList<string> allPossItems = combosAndRecipes.Values;
string[] invenArray = inven.ToArray();
string hint;
do {
hint = allPossItems[random.Next(allPossItems.Count)];
} while (invenArray.Contains(hint));
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("\nTry to get the item: " + hint.ToUpper());
Console.ResetColor();
Console.Write("\nPress ENTER to continue");
Console.ReadLine();
} else {
Console.ForegroundColor = ConsoleColor.Red;
int randInt = random.Next(possUIRps.Length);
Console.WriteLine(possUIRps[randInt]);
Console.ResetColor();
}
Console.Write("\n");
}
Console.WriteLine("Successfully shut down");
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class next : MonoBehaviour {
public Image prev;
public GameObject player;
public Image cur;
public GameObject sphere, cube;
// Use this for initialization
void Start () {
/* this.GetComponent<Renderer> ().material.color = player.GetComponent<Renderer> ().material.color;
//this.gameObject.transform.position = new Vector3(-100, 30, player.transform.position.z + 200);
this.GetComponent<MeshFilter>().mesh = player.GetComponent<MeshFilter>().mesh;
this.gameObject.transform.position = new Vector3(-100, 30, player.transform.position.z + 200);*/
setPlayer ();
setPlayerHit (player);
}
// Update is called once per frame
void Update () {
//this.GetComponent<Renderer>().material.color = current.GetComponent<Renderer>().material.color;
// print ("col type is : " + this.GetComponent<MeshFilter> ().mesh + " " + this.GetComponent<MeshFilter> ().mesh.vertices[1]);
// print ("this type is: " + col.GetComponent<MeshFilter> ().mesh + " " + col.GetComponent<MeshFilter> ().mesh.vertices[1]);
//this.GetComponent<MeshFilter>().mesh = player.GetComponent<MeshFilter>().mesh;
}
private int getShape(GameObject go) {
if (go.GetComponent<MeshFilter> ().mesh.vertices [0] == sphere.GetComponent<MeshFilter> ().sharedMesh.vertices [0])
return 0;
else if (go.GetComponent<MeshFilter> ().mesh.vertices [0] == cube.GetComponent<MeshFilter> ().sharedMesh.vertices [0])
return 1;
else
return 2;
}
public void setPlayer() {
prev.color = player.GetComponent<Renderer> ().material.color;
//this.gameObject.transform.position = new Vector3(-100, 30, player.transform.position.z + 200);
//this.GetComponent<MeshFilter>().mesh = player.GetComponent<MeshFilter>().mesh;
//this.gameObject.transform.position = new Vector3(-100, 30, player.transform.position.z + 200);
switch(getShape(player)) {
case 0: prev.sprite = Resources.Load<Sprite>("Sphere");
break;
case 1: prev.sprite = Resources.Load<Sprite>("Cube");
break;
case 2: prev.sprite = Resources.Load<Sprite>("Cylinder");
break;
}
}
public void setPlayerHit(GameObject hit) {
cur.color = hit.GetComponent<Renderer> ().material.color;
//playerhitshow.GetComponent<MeshFilter>().mesh = hit.GetComponent<MeshFilter>().mesh;
//playerhitshow.color = hit.GetComponent<Renderer> ().material.color;
//playerhitshow.gameObject.transform.position = new Vector3(100, 30, player.transform.position.z + 200);
switch(getShape(hit)) {
case 0: cur.sprite = Resources.Load<Sprite>("Sphere");
break;
case 1: cur.sprite = Resources.Load<Sprite>("Cube");
break;
case 2: cur.sprite = Resources.Load<Sprite>("Cylinder");
break;
}
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.DependencyInjection;
[assembly: DesignTimeProviderServices("Microsoft.EntityFrameworkCore.Cosmos.Design.Internal.CosmosDesignTimeServices")]
namespace Microsoft.EntityFrameworkCore.Cosmos.Design.Internal
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public class CosmosDesignTimeServices : IDesignTimeServices
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual void ConfigureDesignTimeServices(IServiceCollection serviceCollection)
{
serviceCollection.AddEntityFrameworkCosmos();
new EntityFrameworkDesignServicesBuilder(serviceCollection)
.TryAddCoreServices();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using System.Web.Mvc;
namespace MeraAdda.Models
{
public class Review //: IValidatableObject
{
public virtual int ID { get; set; }
public virtual CityPlace CityPlace { get; set; }
[Required]
[Range(1, 10)]
[Display(Name = "Rating")]
public virtual int Rating { get; set; }
[Required]
[DataType(DataType.MultilineText)]
[AllowHtml]
[Display(Name = "Comments or Checks")]
public virtual string Body { get; set; }
[Required]
[DataType(DataType.Date)]
[DisplayName("Visit Date")]
public virtual DateTime VisitDate { get; set; }
//public IEnumerable<ValidationResult>
// Validate(ValidationContext validationContext)
//{
// // custom validations ...
// return Enumerable.Empty<ValidationResult>();
//}
}
} |
using System;
using System.Text.RegularExpressions;
namespace Sample.Domain.V6
{
public class Email
{
private string emailString;
public Email(string emailString)
{
EmailString = emailString.ToLower();
}
public Email(Email email)
{
EmailString = email.EmailString.ToLower();
}
private string EmailString
{
get { return emailString.ToLower(); }
set
{
if(string.IsNullOrEmpty(value))
throw new Exception("Email can not be empty string");
if (!ValidateEmail(value))
throw new ArgumentException("Email is invalid.");
emailString = value.ToLower();
}
}
private static bool ValidateEmail(string value)
{
var emailRegex = new Regex(@"[\w-]+(\.?[\w-])*\@[\w-]+(\.[\w-]+)+", RegexOptions.IgnoreCase);
return emailRegex.IsMatch(value);
}
public override string ToString()
{
return EmailString;
}
public static implicit operator string(Email email)
{
if (email == null)
return null;
return email.EmailString;
}
public static implicit operator Email(string email)
{
if (string.IsNullOrEmpty(email))
return null;
return new Email(email.ToLower());
}
public static bool IsValid(string email)
{
return ValidateEmail(email);
}
}
} |
// ===== Enhanced Editor - https://github.com/LucasJoestar/EnhancedEditor ===== //
//
// Notes:
//
// ============================================================================ //
using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
namespace EnhancedEditor.Editor {
/// <summary>
/// <see cref="ResetOnExitPlayModeAttribute"/>-related manager class.
/// </summary>
[InitializeOnLoad]
internal static class ResetOnExitPlayModeManager {
#region Serialization Wrappers
[Serializable]
private class JsonWrapper {
public List<ObjectWrapper> Objects = new List<ObjectWrapper>();
}
[Serializable]
private class ObjectWrapper {
public string GUID = string.Empty;
public string Json = string.Empty;
// -----------------------
public ObjectWrapper(Object _object) {
GUID = EnhancedEditorUtility.GetAssetGUID(_object);
Json = EditorJsonUtility.ToJson(_object);
}
}
#endregion
#region Play Mode State Changed
private const string MainKey = "ResetOnExitPlayMode_MainKey";
// -----------------------
static ResetOnExitPlayModeManager() {
EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
// Restore values.
if (!EditorApplication.isPlayingOrWillChangePlaymode) {
DeserializeObjects();
}
}
private static void OnPlayModeStateChanged(PlayModeStateChange _mode) {
switch (_mode) {
// Reset values when entering edit mode.
case PlayModeStateChange.EnteredEditMode:
DeserializeObjects();
break;
// Save values before entering Play mode.
case PlayModeStateChange.ExitingEditMode:
SerializeObjects();
break;
default:
break;
}
}
private static void SerializeObjects() {
JsonWrapper _json = new JsonWrapper();
foreach (Type _type in GetObjectTypes())
foreach (ScriptableObject _object in LoadObjects(_type)) {
ObjectWrapper _wrapper = new ObjectWrapper(_object);
_json.Objects.Add(_wrapper);
}
// Register values to be restored outside Play mode.
EditorPrefs.SetString(MainKey, EditorJsonUtility.ToJson(_json));
}
private static void DeserializeObjects() {
// Get values to restore.
string _json = EditorPrefs.GetString(MainKey, string.Empty);
if (string.IsNullOrEmpty(_json)) {
return;
}
JsonWrapper _wrapper = new JsonWrapper();
EditorJsonUtility.FromJsonOverwrite(_json, _wrapper);
foreach (var _obj in _wrapper.Objects) {
string _path = AssetDatabase.GUIDToAssetPath(_obj.GUID);
// If an object can't be found, skip it.
if (string.IsNullOrEmpty(_path)) {
continue;
}
Object _asset = AssetDatabase.LoadMainAssetAtPath(_path);
EditorJsonUtility.FromJsonOverwrite(_obj.Json, _asset);
}
// Reset Prefs value to indicate there is nothing to be restored.
EditorPrefs.SetString(MainKey, string.Empty);
}
#endregion
#region Utility
private static readonly List<Type> resetTypes = new List<Type>();
private static readonly List<Object> buffer = new List<Object>();
// -----------------------
private static List<Type> GetObjectTypes() {
Type _scriptableType = typeof(ScriptableObject);
resetTypes.Clear();
#if UNITY_2019_2_OR_NEWER
foreach (var _type in TypeCache.GetTypesWithAttribute<ResetOnExitPlayModeAttribute>()) {
if (_type.IsSubclassOf(_scriptableType)) {
resetTypes.Add(_type);
}
}
#else
foreach (Assembly _assembly in AppDomain.CurrentDomain.GetAssemblies()) {
foreach (Type _type in _assembly.GetTypes()) {
if (_type.IsSubclassOf(_scriptableType) && (_type.GetCustomAttribute<ResetOnExitPlayModeAttribute>(true) != null)) {
resetTypes.Add(_type);
}
}
}
#endif
return resetTypes;
}
private static List<Object> LoadObjects(Type _type) {
buffer.Clear();
buffer.AddRange(EnhancedEditorUtility.LoadAssets(_type));
return buffer;
}
#endregion
}
}
|
using MetroFramework;
using MetroFramework.Forms;
using PDV.CONTROLER.Funcoes;
using PDV.DAO.Entidades.Estoque.Suprimentos;
using PDV.UTIL;
using PDV.VIEW.App_Context;
using PDV.VIEW.Forms.Cadastro;
using PDV.VIEW.Forms.Cadastro.Parametros;
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
namespace PDV.VIEW.Forms.Consultas.Parametros
{
public partial class FCO_MotivoCancelamento : DevExpress.XtraEditors.XtraForm
{
private string NOME_TELA = "CONSULTA MOTIVO DE CANCELAMENTO";
public FCO_MotivoCancelamento()
{
InitializeComponent();
Carregar();
}
private void Carregar()
{
gridControl1.DataSource = FuncoesMotivoCancelamento.GetMotivos("");
gridView1.OptionsBehavior.Editable = false;
gridView1.OptionsSelection.EnableAppearanceFocusedCell = false;
gridView1.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;
gridView1.BestFitColumns();
AjustaHeaderTextGrid();
}
private void AjustaHeaderTextGrid()
{
gridView1.Columns[0].Visible = false;
gridView1.Columns[1].Caption = "NOME";
gridView1.Columns[2].Caption = "ATIVO";
}
private void ovBTN_Pesquisar_Click(object sender, EventArgs e)
{
Carregar();
}
private void ovBTN_Novo_Click(object sender, EventArgs e)
{
new FCA_MotivoCancelamento(new MotivoCancelamento()).ShowDialog(this);
Carregar();
}
private void ovBTN_Editar_Click(object sender, EventArgs e)
{
decimal IDMotivoCancelamento = decimal.Parse(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "idmotivocancelamento").ToString());
new FCA_MotivoCancelamento(FuncoesMotivoCancelamento.GetMotivo(IDMotivoCancelamento)).ShowDialog(this);
Carregar();
editamonitormetroButton4.Enabled = false;
}
private void ovBTN_Excluir_Click(object sender, EventArgs e)
{
if (MessageBox.Show(this, "Deseja remover o Motivo de Cancelamento selecionado?", NOME_TELA, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
{
decimal IDMotivoCancelamento = decimal.Parse(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "idmotivocancelamento").ToString());
try
{
if (!FuncoesMotivoCancelamento.Remover(IDMotivoCancelamento))
throw new Exception("Não foi possível remover o Motivo de Cancelamento.");
}
catch (Exception Ex)
{
MessageBox.Show(this, Ex.Message, NOME_TELA, MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
Carregar();
}
}
private void FCO_Ncm_Load(object sender, EventArgs e)
{
Carregar();
}
private void gridControl1_Click(object sender, EventArgs e)
{
editamonitormetroButton4.Enabled = true;
}
private void gridControl1_DoubleClick(object sender, EventArgs e)
{
decimal IDMotivoCancelamento = decimal.Parse(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "idmotivocancelamento").ToString());
new FCA_MotivoCancelamento(FuncoesMotivoCancelamento.GetMotivo(IDMotivoCancelamento)).ShowDialog(this);
Carregar();
editamonitormetroButton4.Enabled = false;
}
private void imprimriMetroButton_Click(object sender, EventArgs e)
{
gridView1.ShowPrintPreview();
}
private void atualizarMetroButton_Click(object sender, EventArgs e)
{
Carregar();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Xml;
namespace C1ILDGen
{
public partial class frmAppConfig : Form
{
public frmAppConfig()
{
InitializeComponent();
}
private void frmAppConfig_Load(object sender, EventArgs e)
{
LoadConfigData();
}
private void LoadConfigData()
{
dgAppConfig.Rows.Clear();
foreach (string key in ConfigurationManager.AppSettings)
{
string value = ConfigurationManager.AppSettings[key];
dgAppConfig.Rows.Add(key, value);
}
}
private void btnAddNew_Click(object sender, EventArgs e)
{
try
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Add(txtKey.Text, txtValue.Text);
config.Save();
ConfigurationManager.RefreshSection("appSettings");
LoadConfigData();
MessageBox.Show("New Config Entry Added Succesfully.", "Config");
txtKey.Text = "";
txtValue.Text = "";
}
catch
{
MessageBox.Show("Failed To Add New Config Entry.", "Config");
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
int RowNr = 0;
foreach (XmlElement element in xmlDoc.DocumentElement)
{
if (element.Name.Equals("appSettings"))
{
foreach (XmlNode node in element.ChildNodes)
{
if(node.NodeType != XmlNodeType.Comment)
{
if (node.Attributes[0].Value.Equals(dgAppConfig.Rows[RowNr].Cells[0].Value.ToString()))
{
if (dgAppConfig.Rows[RowNr].Cells[1].Value != null)
node.Attributes[1].Value = dgAppConfig.Rows[RowNr].Cells[1].Value.ToString();
else
node.Attributes[1].Value = "";
}
RowNr++;
}
}
}
}
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
ConfigurationManager.RefreshSection("appSettings");
MessageBox.Show("Config Data Updated Succesfully.", "Config");
}
private void lblClose_Click(object sender, EventArgs e)
{
this.Hide();
}
}
}
|
using System;
using System.Collections.Generic;
namespace TravelAgency
{
public interface ITourSchedule
{
void CreateTour(string name, DateTime dateTime, int seats);
List<Tour> GetToursFor(DateTime dateTime);
}
} |
using System;
using System.Linq;
using System.Reflection;
using System.Text;
public class Spy
{
public string StealFieldInfo(string investigatedClass, params string[] fields)
{
var getClass = Type.GetType(investigatedClass);
var classFields = getClass.GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public |
BindingFlags.NonPublic);
var sb = new StringBuilder();
var classIstance = Activator.CreateInstance(getClass, new object[] { });
sb.AppendLine($"Class under investigation: {investigatedClass}");
foreach (var fied in classFields.Where(f => fields.Contains(f.Name)))
{
sb.AppendLine($"{fied.Name} = {fied.GetValue(classIstance)}");
}
return sb.ToString().Trim();
}
public string AnalyzeAcessModifiers(string className)
{
var getClass = Type.GetType(className);
var getClassFields = getClass.GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public);
var getPublicMethod = getClass.GetMethods(BindingFlags.Instance | BindingFlags.Public);
var getNonPublickMethod = getClass.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic);
var sb = new StringBuilder();
foreach (var field in getClassFields)
{
sb.AppendLine($"{field.Name} must be private!");
}
foreach (var method in getNonPublickMethod.Where(g => g.Name.StartsWith("get")))
{
sb.AppendLine($"{method.Name} have to be public!");
}
foreach (var method in getPublicMethod.Where(g => g.Name.StartsWith("set")))
{
sb.AppendLine($"{method.Name} have to be private!");
}
return sb.ToString().Trim();
}
public string RevealPrivateMethods(string investigatedClass)
{
var getClass = Type.GetType(investigatedClass);
var getMethods = getClass.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic);
var sb = new StringBuilder();
sb.AppendLine($"All Private Methods of Class: {investigatedClass}");
sb.AppendLine($"Base Class: {getClass.BaseType.Name}");
foreach (var method in getMethods)
{
sb.AppendLine($"{method.Name}");
}
return sb.ToString().Trim();
}
public string CollectGettersAndSetters(string investigatedClass)
{
var getClass = Type.GetType(investigatedClass);
var getMethods = getClass.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
var sb = new StringBuilder();
foreach (var method in getMethods.Where(f => f.Name.StartsWith("get")))
{
sb.AppendLine($"{method.Name} will return {method.ReturnType}");
}
foreach (var method in getMethods.Where(f => f.Name.StartsWith("set")))
{
sb.AppendLine($"{method.Name} will set field of {method.GetParameters().First().ParameterType}");
}
return sb.ToString().Trim();
}
} |
using CORE2;
using System;
using System.Collections.Generic;
using System.Text;
namespace Accounts.Service.Contract.Services
{
public class GroupAccountsDocumentService : DocumentService
{
public GroupAccountsDocumentService(DocumentServiceSettings settings) : base(settings) { }
}
}
|
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
namespace Microsoft.PowerShell.EditorServices.Services.PowerShellContext
{
/// <summary>
/// Enumerates the possible execution results that can occur after
/// executing a command or script.
/// </summary>
public enum ExecutionStatus
{
/// <summary>
/// Indicates that execution has not yet started.
/// </summary>
Pending,
/// <summary>
/// Indicates that the command is executing.
/// </summary>
Running,
/// <summary>
/// Indicates that execution has failed.
/// </summary>
Failed,
/// <summary>
/// Indicates that execution was aborted by the user.
/// </summary>
Aborted,
/// <summary>
/// Indicates that execution completed successfully.
/// </summary>
Completed
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class QuestionScript : MonoBehaviour
{
public Text questionText;
public string newQuestion;
public GameObject rightAnswer;
public GameObject[] wrongAnswers;
public void RightAnswer()
{
PlayerStats playerStats = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerStats>();
playerStats.playerHP++;
playerStats.keyFragments++;
Destroy(rightAnswer);
for(int i = 0; i < wrongAnswers.Length; i++)
{
Destroy(wrongAnswers[i]);
}
questionText.text = newQuestion;
}
public void WrongAnswer()
{
PlayerStats playerStats = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerStats>();
playerStats.playerHP--;
}
}
|
using System;
using System.Collections.Generic;
namespace Binocle
{
public static class ListExt
{
public static void shuffle<T>(this IList<T> list)
{
var n = list.Count;
while (n > 1)
{
n--;
int k = UnityEngine.Random.Range(0, n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
/// <summary>
/// returns false if the item is already in the List and true if it was successfully added.
/// </summary>
/// <returns>The if not present.</returns>
/// <param name="list">List.</param>
/// <param name="item">Item.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public static bool addIfNotPresent<T>(this IList<T> list, T item)
{
if (list.Contains(item))
return false;
list.Add(item);
return true;
}
/// <summary>
/// gets a random item from the list. Does not empty check the list!
/// </summary>
/// <returns>The item.</returns>
/// <param name="list">List.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public static T randomItem<T>(this IList<T> list)
{
return list[UnityEngine.Random.Range(0, list.Count)];
}
}
}
|
using Poker.Enums;
using System;
using System.Collections.Generic;
using System.Text;
namespace Poker
{
public class PlayingCard
{
public Rank Rank { get; set; }
public Suit Suit { get; set; }
}
}
|
// Copyright (C) 2016 Kazuhiro Fujieda <fujieda@users.osdn.me>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using KancolleSniffer.Forms;
using KancolleSniffer.Model;
namespace KancolleSniffer.View.ListWindow
{
public class AntiAirPanel : Panel, IPanelResize
{
private const int LineHeight = 16;
private readonly List<AntiAirLabels> _labelList = new List<AntiAirLabels>();
private readonly List<Record> _table = new List<Record>();
private class AntiAirLabels : ShipLabels
{
public Label Rate { get; set; }
public Label Diff { get; set; }
protected override Control[] AddedControls => new Control[] {Rate, Diff};
}
public void Update(Sniffer sniffer)
{
CreateTable(sniffer);
SuspendLayout();
CreateLabels();
ResizeLabels();
SetRecords();
ResumeLayout();
}
private class Record
{
public string Fleet { get; set; }
public string Ship { get; set; }
public int Id { get; set; }
public string Rate { get; set; }
public string Diff { get; set; }
public Record()
{
Fleet = Ship = Rate = Diff = "";
}
}
private void CreateTable(Sniffer sniffer)
{
_table.Clear();
var fn = new[] {"第一艦隊", "第二艦隊", "第三艦隊", "第四艦隊"};
foreach (var fleet in sniffer.Fleets)
{
var ships = fleet.ActualShips;
var rawForFleet = ships.Sum(ship => ship.EffectiveAntiAirForFleet);
var forFleet = new[] {1.0, 1.2, 1.6}.Select(r => (int)(rawForFleet * r) * 2 / 1.3).ToArray();
_table.Add(new Record
{
Fleet = fn[fleet.Number] + " 防空" + string.Join("/", forFleet.Select(x => x.ToString("f1")))
});
foreach (var ship in ships)
{
_table.Add(CreateShipRecord(ship));
_table.Add(CreateAntiAirRecord(forFleet, ship));
}
}
}
private Record CreateShipRecord(ShipStatus ship)
{
var param = " Lv" + ship.Level +
" 加重" + ship.EffectiveAntiAirForShip.ToString("d") +
AntiAirPropellantBarrageChance(ship);
var name = ship.Name;
var realWidth = Scaler.ScaleWidth(ListForm.PanelWidth - 10);
return new Record
{
Ship = StringTruncator.Truncate(name, param, realWidth, GetFont(name)) + param,
Id = ship.Id
};
}
private Record CreateAntiAirRecord(double[] forFleet, ShipStatus ship)
{
var rate = ship.EffectiveAntiAirForShip / 4.0;
var diff = forFleet.Select(x => (x + ship.EffectiveAntiAirForShip) / 10.0);
return new Record
{
Rate = "割合" + rate.ToString("f1") + "% ",
Diff = "固定" + string.Join("/", diff.Select(d => d.ToString("f1")))
};
}
private static Font GetFont(string name)
{
return ShipLabel.Name.StartWithLetter(name)
? ShipLabel.Name.LatinFont
: ShipLabel.Name.BaseFont;
}
private static string AntiAirPropellantBarrageChance(ShipStatus ship)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (ship.AntiAirPropellantBarrageChance == 0)
return "";
var chance = ship.AntiAirPropellantBarrageChance;
return " 弾幕" + (chance < 100 ? chance.ToString("f1") : ((int)chance).ToString());
}
private void CreateLabels()
{
for (var i = _labelList.Count; i < _table.Count; i++)
CreateLabels(i);
}
private void CreateLabels(int i)
{
var y = 1 + LineHeight * i;
var labels = new AntiAirLabels
{
Fleet = new ShipLabel.Fleet(new Point(1, 3)),
Name = new ShipLabel.Name(new Point(10, 3), ShipNameWidth.Max),
Rate = new Label {Location = new Point(35, 3), AutoSize = true},
Diff = new Label {Location = new Point(100, 3), AutoSize = true},
BackPanel = new Panel
{
Location = new Point(0, y),
Size = new Size(ListForm.PanelWidth, LineHeight),
}
};
_labelList.Add(labels);
labels.Arrange(this, CustomColors.ColumnColors.BrightFirst(i));
labels.Scale();
labels.Move(AutoScrollPosition);
}
public void ApplyResize()
{
SuspendLayout();
ResizeLabels();
ResumeLayout();
}
private void ResizeLabels()
{
var width = Width - SystemInformation.VerticalScrollBarWidth - 2;
foreach (var labels in _labelList)
labels.BackPanel.Width = width;
}
private void SetRecords()
{
for (var i = 0; i < _table.Count; i++)
SetRecord(i);
for (var i = _table.Count; i < _labelList.Count; i++)
_labelList[i].BackPanel.Visible = false;
}
private void SetRecord(int i)
{
var lbp = _labelList[i].BackPanel;
var column = _table[i];
var labels = _labelList[i];
labels.Fleet.Text = column.Fleet;
labels.Name.SetName(column.Ship);
labels.Rate.Text = column.Rate;
labels.Diff.Text = column.Diff;
lbp.Visible = true;
}
public void ShowShip(int id)
{
var i = _table.FindIndex(e => e.Id == id);
if (i == -1)
return;
var y = Scaler.ScaleHeight(LineHeight * i);
AutoScrollPosition = new Point(0, y);
}
}
} |
using FactoryMethod.Entities.Personagens;
namespace FactoryMethod
{
public class IPersonagemFactory
{
public IPersonagem EscolherPersonagem(string personagem)
{
switch (personagem)
{
case "1": return new LiuKang();
case "2": return new SubZero();
case "3": return new Scorpion();
default: return null;
}
}
}
}
|
using VeraControl.Model.UpnpDevices.Base;
namespace VeraControl.Model.UpnpDevices
{
public class BinaryLight1 : UpnpDeviceBase
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExcelHelper.Infrastruction
{
public struct Sheet
{
string _name;
string _sheetId;
string _rid;
public Sheet(string name, string sheetId, string rid)
{
_name = name;
_sheetId = sheetId;
_rid = rid;
}
}
}
|
using Ramazan.UdemyBlogWebSite.Entities.Concreate;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Ramazan.UdemyBlogWebSite.DataAccess.Interfaces
{
public interface IBlogDal : IGenericDal<Blog>
{
Task<List<Blog>> GetAllByCategoryIdAsync(int categoryId);
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.IO;
/*
* Downloaded (and modified) from Unity Wiki:
* http://wiki.unity3d.com/index.php?title=ImprovedFileBrowser
*
* Script for the browse button on the main menu
* When pressed, opens the file browser and writes the resulting
* path into the file path input field
*/
public class BrowseButton : MonoBehaviour {
public InputField field, fieldMng;
public GUISkin skin;
public Texture2D directoryImage, fileImage;
public Selectable singleDatabaseToggle, launchButton, browseButton, browseButtonMng, cameraOptionButton;
public Slider sliderFrames;
private FileBrowser fileBrowser;
//Called every frame. Calls the file browser's on GUI if it is not null (meaning it's open)
void OnGUI () {
if (fileBrowser != null) {
//Disable controls while browser is open to prevent clicking through browser
launchButton.interactable = false;
singleDatabaseToggle.interactable = false;
GetComponent<Button>().interactable = false;
field.interactable = false;
sliderFrames.interactable = false;
browseButton.interactable = false;
browseButtonMng.interactable = false;
fieldMng.interactable = false;
cameraOptionButton.interactable = false;
GUI.skin = skin;
fileBrowser.OnGUI();
}
}
//Called when the file browser finishes.
//Writes the path into the input field if a file was selected
protected void FileSelectedCallback(string filename) {
//Re enable controls
launchButton.interactable = true;
singleDatabaseToggle.interactable = true;
GetComponent<Button>().interactable = true;
field.interactable = true;
sliderFrames.interactable = true;
browseButton.interactable = true;
browseButtonMng.interactable = true;
fieldMng.interactable = true;
cameraOptionButton.interactable = true;
fileBrowser = null;
if(filename != null) {
field.text = filename;
}
}
//Called when the button is pressed
//Opens the file browser
public void OnPressed() {
fileBrowser = new FileBrowser(
new Rect(Screen.width/2-250, Screen.height/2-200, 500, 400),
"Choose .json file",
FileSelectedCallback
);
if(File.Exists(field.text)) {
fileBrowser.CurrentDirectory = field.text.Substring(0,field.text.LastIndexOf(Path.DirectorySeparatorChar)+1);
}
fileBrowser.SelectionPattern = "*.json";
fileBrowser.DirectoryImage = directoryImage;
fileBrowser.FileImage = fileImage;
}
}
|
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Threading;
namespace Sample.View
{
class Program
{
static void Main(string[] args)
{
var thread = new Thread(ListenToJobViewUpdates);
thread.Start();
}
private static void ListenToJobViewUpdates()
{
using (var pipeStream = new NamedPipeServerStream("EventSourcingSample"))
{
pipeStream.WaitForConnection();
using (var sr = new StreamReader(pipeStream))
{
Console.WriteLine("JobView Updated:");
string message;
while ((message = sr.ReadLine()) != null)
{
Console.WriteLine(message);
}
}
}
ListenToJobViewUpdates();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PESWeb.Profiles.Interface;
using Pes.Core;
namespace PESWeb.Profiles.Presenter
{
public class StatusUpdatesPresenter
{
private IStatusUpdates _view;
private Int32 _accountIDToShow;
public StatusUpdatesPresenter()
{
}
public void Init(IStatusUpdates view, Int32 AccountIDToShow)
{
_view = view;
_accountIDToShow = AccountIDToShow;
ShowStatusUpdates();
}
private void ShowStatusUpdates()
{
_view.ShowUpdates(StatusUpdate.GetStatusUpdatesByAccountID(_accountIDToShow));
}
}
}
|
using Zhouli.DbEntity.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace Zhouli.DAL.Interface
{
public interface ISysRoleDAL : IBaseDAL<SysRole>
{
/// <summary>
/// 设置角色的权限集合
/// </summary>
/// <returns></returns>
//List<SysRole> SetRolePowerList(List<SysRole> sysRoles);
/// <summary>
/// 为角色添加功能菜单
/// </summary>
/// <param name="roleId"></param>
/// <param name="menuDtos"></param>
/// <returns></returns>
bool AddRoleMenu(string roleId, List<SysMenu> menus);
}
}
|
namespace iQuest.VendingMachine.UseCases.Interfaces
{
internal interface IUseCase
{
void Execute();
}
} |
using BlockChain.utils;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using WebSocketSharp;
using WebSocketSharp.Server;
namespace BlockChain
{
public class BlockChainServer : WebSocketBehavior
{
private WebSocketServer wss = null;
private BlockChain blockChain;
private string ipAddress;
private string port;
public BlockChainServer(BlockChain blockChain, string ipAddress, string port)
{
this.blockChain = blockChain;
this.ipAddress = ipAddress;
this.port = port;
}
public void Start()
{
wss = new WebSocketServer($"ws://" + ipAddress + ":" + port + "");
wss.AddWebSocketService<BlockChainServer>("/Blockchain", () => new BlockChainServer(blockChain, ipAddress, port));
wss.Start();
// wss.Log.Output = (_, __) => { };
}
protected override void OnMessage(MessageEventArgs e)
{
if(NetworkUtils.SplitPacket(e.Data, 0).Equals("packet_connect"))
{
blockChain.blockChainClient.Connect(NetworkUtils.SplitPacket(e.Data, 1), NetworkUtils.SplitPacket(e.Data, 2));
Send("You are successfully connected to " + ipAddress + ":" + port);
}
if (NetworkUtils.SplitPacket(e.Data, 0).Equals("packet_block"))
{
bool blockAdded = blockChain.AddForeignBlock(JsonConvert.DeserializeObject<Block>(NetworkUtils.SplitPacket(e.Data, 1)));
Send("packet_block" + NetworkUtils.packetSeparator + blockAdded + NetworkUtils.packetSeparator + "ws://" + ipAddress + ":" + port + "/Blockchain");
}
if (NetworkUtils.SplitPacket(e.Data, 0).Equals("packet_verification"))
{
bool isBlockChainValid = blockChain.CompareBlocks(JsonConvert.DeserializeObject<List<Block>>(NetworkUtils.SplitPacket(e.Data, 1)));
Send("packet_verification" + NetworkUtils.packetSeparator + isBlockChainValid + NetworkUtils.packetSeparator + "ws://" + ipAddress + ":" + port + "/Blockchain");
}
if (NetworkUtils.SplitPacket(e.Data, 0).Equals("packet_chainrequest"))
{
Send("packet_chain" + NetworkUtils.packetSeparator + JsonConvert.SerializeObject(blockChain.GetAllBlocks()));
}
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Assets.Scripts.GameLogic.EnemySystem;
using UnityEngine.UI;
public class SpawnEnemyScript : MonoBehaviour
{
public GameObject m_waveTextBox;
public FieldScript m_FieldSystem;
public LifeAndMoneyScript m_LifeAndMoney;
private GameObject m_EndTile;
public TilePos m_SpawnPos;
public List<IWave> m_Waves = new List<IWave>();
public GameObject m_firstEnemy;
public GameObject m_secondEnemy;
private List<TilePos> m_ToProcess = new List<TilePos>();
private List<TilePos> m_AlreadyChecked = new List<TilePos>();
private int nextBossWave = 0;
public int m_WaveDifficultyPoints = 100;
public int m_WavesStored = 5;
public int m_CurrentWaveIndex = 0;
public int m_BossWave =2;
[Range(0.01f, 1.00f)]
public float m_Difficulty = 0.05f;
public Enemies m_Enemies;
public int m_WaveDelayBetween = 5;
public int m_BossDelayBetween = 15;
public float m_CurrentDelayBetween = 0.0f;
private bool updated = true;
// Use this for initialization
void Start()
{
nextBossWave = m_BossWave-1;
for (int i = 0; i < m_WavesStored; i++)
{
m_Waves.Add(CreateNewWave(i));
}
}
// Update is called once per frame
void Update()
{
if (m_Waves.Count > 0) {
//hole alle GameObjekte von den Wellen
m_waveTextBox.GetComponent<Text>().text = "Current Wave: " + (m_CurrentWaveIndex+1);
if (m_CurrentDelayBetween <= 0.0f)
{
if (!updated) {
m_CurrentWaveIndex++;
updated = true;
}
GameObject[] gos = m_Waves[0].Update();
if (gos != null)
{
m_SpawnPos = GetSpawn();//Spawnpunkt holen
if (m_SpawnPos == null) return;
m_FieldSystem.LevelFinished(m_SpawnPos.y);
foreach (GameObject go in gos)
{
SpawnEnemyOn(go, m_SpawnPos);//Alle GameObjekte Spawnen
}
if (m_Waves[0].Clear())
{//Wenn Welle fertig
m_Waves.RemoveAt(0);
m_Waves.Add(CreateNewWave(m_CurrentWaveIndex + m_WavesStored));
if ((m_CurrentWaveIndex + 1) % m_BossWave == 0)
{
m_CurrentDelayBetween = m_BossDelayBetween ;
}
else
{
m_CurrentDelayBetween = m_WaveDelayBetween;
}
updated = false;
}
}
}
else
{
if (m_CurrentWaveIndex+(updated?0:1) == 0)
{
m_waveTextBox.GetComponent<Text>().text += "\n" + "First Wave in " + (int)m_CurrentDelayBetween;
}
else
{
m_waveTextBox.GetComponent<Text>().text += "\n" + "Next Wave in " + (int)m_CurrentDelayBetween;
}
m_CurrentDelayBetween -= Time.deltaTime;
}
}
}
private IWave CreateNewWave(int difficulty,float usedWavePoints = 0,GameObject enemy = null)
{
if (difficulty == nextBossWave)
{
nextBossWave += m_BossWave;
return CreateBossWave(difficulty);
}
float multiplier = 1.0f + difficulty * m_Difficulty;
float wavePoints = m_WaveDifficultyPoints * multiplier;
if (usedWavePoints != 0)
{
wavePoints = usedWavePoints * multiplier;
}
if (Random.Range(0f,1f)<0.9f || enemy!=null)
{
if (enemy == null)
{
enemy = m_Enemies.GetRandomEnemy();
}
enemy.transform.SetParent(this.transform);
EnemyScript es = enemy.GetComponent<EnemyScript>();
es.IncreaseDifficulty(difficulty);
es.SetLifeAndMoneySystem(m_LifeAndMoney);
if (es == null) throw new System.Exception("ERROR : No EnemyScript");
int count = (int)(wavePoints / es.m_WavePoints) + 1;
float delay = Random.Range(1f/ es.m_Speed, 2f / es.m_Speed);
Wave w = new Wave(count,enemy,delay);
return w;
}
else
{
GameObject[] enemies = m_Enemies.GetRandomEnemies(2);
WaveGroup wg = new WaveGroup();
for (int i = 0; i < 2; i++)
{
wg.m_Waves.Add(CreateNewWave(difficulty, usedWavePoints / 2.0f, enemies[i]));
}
return wg;
}
}
private IWave CreateBossWave(int difficulty)
{
float multiplier = 1.0f + difficulty * m_Difficulty;
float wavePoints = m_WaveDifficultyPoints * multiplier;
bool minions = Random.Range(0.0f, 1.0f) > 0.8f;
if (minions)
{
wavePoints /= 2;
}
GameObject boss = m_Enemies.GetRandomBoss();
boss.transform.SetParent(this.transform);
EnemyScript es = boss.GetComponent<EnemyScript>();
es.IncreaseDifficulty((int)(difficulty*wavePoints/es.m_WavePoints));
es.SetLifeAndMoneySystem(m_LifeAndMoney);
if (es == null) throw new System.Exception("ERROR : No EnemyScript");
Wave bossW = new Wave(1, boss, 0.0f);
if (minions)
{
WaveGroup wg = new WaveGroup();
wg.m_Waves.Add(bossW);
wg.m_Waves.Add(CreateNewWave(difficulty, wavePoints));
return wg;
}
else
{
return bossW;
}
}
public TilePos GetSpawn()
{
m_EndTile = GameObject.FindObjectOfType<EndPoint>().gameObject;
if (m_EndTile == null)
return null;
m_ToProcess = processTiles(m_FieldSystem.m_LevelWidth/2,0);
//endtile hinzufügen
GameObject first = m_FieldSystem.GetTileFrom(m_FieldSystem.m_LevelWidth / 2,0);
PathTileScript firstScript = first.GetComponent<PathTileScript>();
firstScript.m_ParentDirection.Add(PathTileScript.NORTH);
firstScript.m_ParentObject.Add(m_EndTile);
if (m_ToProcess.Count == 0)
return null;
return m_ToProcess[0];
}
private void SpawnEnemyOn(GameObject go, TilePos spawnPos)
{
//if (spawnPos == null) return;
GameObject spawn = m_FieldSystem.GetTileFrom(spawnPos.x, spawnPos.y);
PathTileScript pathScript = spawn.GetComponent<PathTileScript>();
GameObject copy = GameObject.Instantiate(go);
copy.transform.parent = this.transform;
PathMoveScript pathMove = copy.GetComponent<PathMoveScript>();
if (pathMove == null)
return;
pathMove.m_CurrentObject = spawn;
pathMove.m_CurrentIndex = 1;
if (pathScript.m_north && m_FieldSystem.GetTileFrom(spawnPos.x, spawnPos.y + 1) == null)
{
copy.transform.position = pathScript.m_PathNorth[0].transform.position;
pathMove.m_CurrentList = pathScript.m_PathNorth;
}
if (pathScript.m_south && m_FieldSystem.GetTileFrom(spawnPos.x, spawnPos.y - 1) == null)
{
copy.transform.position = pathScript.m_PathSouth[0].transform.position;
pathMove.m_CurrentList = pathScript.m_PathSouth;
}
if (pathScript.m_east && m_FieldSystem.GetTileFrom(spawnPos.x + 1, spawnPos.y) == null)
{
copy.transform.position = pathScript.m_PathEast[0].transform.position;
pathMove.m_CurrentList = pathScript.m_PathEast;
}
if (pathScript.m_west && m_FieldSystem.GetTileFrom(spawnPos.x - 1, spawnPos.y) == null)
{
copy.transform.position = pathScript.m_PathWest[0].transform.position;
pathMove.m_CurrentList = pathScript.m_PathWest;
}
pathMove.m_rotationToNext = pathMove.m_CurrentList[pathMove.m_CurrentIndex].transform.position - pathMove.transform.position;
pathMove.m_rotationPos = pathMove.transform.position;
float rotate = Vector3.Angle(Vector3.back, pathMove.m_rotationToNext);
Vector3 cross = Vector3.Cross(Vector3.back, pathMove.m_rotationToNext);
if (cross.y < 0) rotate = -rotate;
if (rotate != 0.0f)
{
pathMove.transform.Rotate(Vector3.up, rotate);
}
}
private List<TilePos> processTiles(int x, int y)
{
PathTileScript[] scripts = GameObject.FindObjectsOfType<PathTileScript>();
foreach (PathTileScript script in scripts)
{
script.m_ParentObject.Clear();
script.m_ParentDirection.Clear();
}
m_AlreadyChecked.Clear();
List<TilePos> list = new List<TilePos>();
List<TilePos> spawnPos = new List<TilePos>();
list.Add(new TilePos(x, y));
while (list.Count > 0)
{
TilePos pos = list[0];
m_AlreadyChecked.Add(pos);
list.RemoveAt(0);
GameObject objToCheck = m_FieldSystem.GetTileFrom(pos.x, pos.y);
PathTileScript pathScript = objToCheck.GetComponent<PathTileScript>();
if (pathScript == null)
continue;
if (pathScript.m_north)
{
if (m_FieldSystem.GetTileFrom(pos.x, pos.y + 1) == null)
{
spawnPos.Add(pos);
}
else
{
TilePos newPos = new TilePos(pos.x, pos.y + 1);
if (!m_AlreadyChecked.Contains(newPos))
{
GameObject tile = m_FieldSystem.GetTileFrom(newPos.x, newPos.y);
PathTileScript script = tile.GetComponent<PathTileScript>();
script.m_ParentObject.Add(objToCheck);
script.m_ParentDirection.Add(PathTileScript.NORTH);
list.Add(newPos);
}
}
}
if (pathScript.m_south)
{
if (pos.y != 0 && pos.x != m_FieldSystem.m_LevelWidth / 2)
{
if (m_FieldSystem.GetTileFrom(pos.x, pos.y - 1) == null)
{
spawnPos.Add(pos);
}
else
{
TilePos newPos = new TilePos(pos.x, pos.y - 1);
if (!m_AlreadyChecked.Contains(newPos))
{
GameObject tile = m_FieldSystem.GetTileFrom(newPos.x, newPos.y);
PathTileScript script = tile.GetComponent<PathTileScript>();
script.m_ParentObject.Add(objToCheck);
script.m_ParentDirection.Add(PathTileScript.SOUTH);
list.Add(newPos);
}
}
}
}
if (pathScript.m_east)
{
if (m_FieldSystem.GetTileFrom(pos.x + 1, pos.y) == null)
{
spawnPos.Add(pos);
}
else
{
TilePos newPos = new TilePos(pos.x + 1, pos.y);
if (!m_AlreadyChecked.Contains(newPos))
{
GameObject tile = m_FieldSystem.GetTileFrom(newPos.x, newPos.y);
PathTileScript script = tile.GetComponent<PathTileScript>();
script.m_ParentObject.Add(objToCheck);
script.m_ParentDirection.Add(PathTileScript.EAST);
list.Add(newPos);
}
}
}
if (pathScript.m_west)
{
if (m_FieldSystem.GetTileFrom(pos.x - 1, pos.y) == null)
{
spawnPos.Add(pos);
}
else
{
TilePos newPos = new TilePos(pos.x - 1, pos.y);
if (!m_AlreadyChecked.Contains(newPos))
{
GameObject tile = m_FieldSystem.GetTileFrom(newPos.x, newPos.y);
PathTileScript script = tile.GetComponent<PathTileScript>();
script.m_ParentObject.Add(objToCheck);
script.m_ParentDirection.Add(PathTileScript.WEST);
list.Add(newPos);
}
}
}
}
return spawnPos;
}
public int getCurrentWaveIndex()
{
return m_CurrentWaveIndex;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace bt.Admin
{
public partial class Ncc : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
getData();
}
}
public void getData()
{
banhang2Entities db = new banhang2Entities();
List<ncc> obj = db.ncc.ToList();
dgvNcc.DataSource = obj;
dgvNcc.DataBind();
}
protected void btnXoa_Command(object sender, CommandEventArgs e)
{
int mancc = Convert.ToInt32(e.CommandArgument);
banhang2Entities db = new banhang2Entities();
ncc obj = db.ncc.FirstOrDefault(x => x.mancc == mancc);
if(obj!=null)
{
db.ncc.Remove(obj);
db.SaveChanges();
getData();
}
}
}
} |
// Copyright (c) 2008 Josh Cooley
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
namespace Tivo.Hme
{
/// <summary>
/// Provides data for the <see cref="Application.ResourceStateChanged"/> event.
/// </summary>
public class ResourceStateChangedArgs : EventArgs
{
private IHmeResource _resource;
private ResourceStatus _status;
private Dictionary<string, string> _resourceInfo;
/// <summary>
/// The key for the <see cref="ResourceInfo"/> dictionary containing speed data.
/// </summary>
public const string Speed = "speed";
/// <summary>
/// The key for the <see cref="ResourceInfo"/> dictionary containing position data.
/// </summary>
public const string Position = "pos";
/// <summary>
/// Creates a <see cref="ResourceStateChangedArgs"/>.
/// </summary>
/// <param name="resource">The resource that changed state.</param>
/// <param name="status">The status of the resource.</param>
/// <param name="info">A collection of name/value pairs defining additional resource information.</param>
public ResourceStateChangedArgs(IHmeResource resource, ResourceStatus status, Dictionary<string, string> info)
{
_resource = resource;
_status = status;
_resourceInfo = info;
}
/// <summary>
/// The resource that is changing state.
/// </summary>
public IHmeResource Resource
{
get { return _resource; }
}
/// <summary>
/// <see cref="ResourceStatus"/> value for the resource.
/// </summary>
public ResourceStatus Status
{
get { return _status; }
}
/// <summary>
/// A collection of name/value pairs defining additional resource information.
/// </summary>
public Dictionary<string, string> ResourceInfo
{
get { return _resourceInfo; }
}
}
/// <summary>
/// Specifies the type of resource error encountered by the application
/// </summary>
public enum ResourceErrorCode
{
/// <summary>
/// Indicates the error is not known
/// </summary>
Unknown = 0,
/// <summary>
/// A data format error.
/// </summary>
BadDataFormat = 1,
/// <summary>
/// A bad magic number given the content type.
/// </summary>
BadMagicNumber = 2,
/// <summary>
/// The version of media is not supported
/// </summary>
MediaVersionNotSupported = 3,
/// <summary>
/// Connection was lost unexpectedly.
/// </summary>
ConnectionLost = 4,
/// <summary>
/// Connection timed-out.
/// </summary>
ConnectionTimeout = 5,
/// <summary>
/// Connection failed.
/// </summary>
ConnectionFailed = 6,
/// <summary>
/// Specified host name was not found.
/// </summary>
HostNotFound = 7,
/// <summary>
/// The version of media is incompatible.
/// </summary>
IncompatibleMediaVersion = 8,
/// <summary>
/// Media type is not supported.
/// </summary>
MediaTypeNotSupported = 9,
/// <summary>
/// A bad argument was specified.
/// </summary>
BadArgument = 20,
/// <summary>
/// The state is invalid.
/// </summary>
BadState = 21
}
/// <summary>
/// Provides data for the <see cref="Application.ResourceErrorOccurred"/> event.
/// </summary>
public class ResourceErrorArgs : EventArgs
{
private IHmeResource _resource;
private ResourceErrorCode _code;
private string _text;
/// <summary>
/// Creates a <see cref="ResourceErrorArgs"/>.
/// </summary>
/// <param name="resource">The resource with an error.</param>
/// <param name="code">The code for the error.</param>
/// <param name="text">A textual representation of the error.</param>
public ResourceErrorArgs(IHmeResource resource, ResourceErrorCode code, string text)
{
_resource = resource;
_code = code;
_text = text;
}
/// <summary>
/// The resource with an error.
/// </summary>
public IHmeResource Resource
{
get { return _resource; }
}
/// <summary>
/// An <see cref="ResourceErrorCode"/> value that represents the error.
/// </summary>
public ResourceErrorCode Code
{
get { return _code; }
set { _code = value; }
}
/// <summary>
/// A textual representation of the error.
/// </summary>
public string Text
{
get { return _text; }
set { _text = value; }
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class defaultCamMove : MonoBehaviour
{
public GameObject targe;
public GameObject rel;
public CameraSwitch cam;
public KeyCode forward, left, right, back;
public Vector3 direction;
public float mainSpeed = 100.0f; //regular speed
public float horiBound; //horizontal camera movement boundaries
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (cam.camVal == 1)
{
direction = GetBaseInput();
// Debug.Log("This is the original direction " + direction + "THis is the Y position !!!!!::!!!!!! " + transform.position.y);
direction = direction * mainSpeed;
// Debug.Log("This is the direction after multiplied by mainSpeed " + direction + "THis is the Y position !!!!!::!!!!!! " + transform.position.y);
direction = direction * Time.deltaTime;
// Debug.Log("This is the direction multiplied by time.deltatime " + direction + "THis is the Y position !!!!!::!!!!!! " + transform.position.y);
Vector3 dirt = new Vector3(direction.x, 0, direction.z);
targe.transform.Translate(dirt, rel.transform);
Vector3 clampPos = transform.position;
clampPos.x = Mathf.Clamp(clampPos.x, -horiBound, horiBound);
clampPos.z = Mathf.Clamp(clampPos.z, -horiBound, horiBound);
targe.transform.position = clampPos;
Debug.Log("THis is the Vector3 dirt !!!!!::!!!!!! " + dirt);
}
}
private Vector3 GetBaseInput()
{ //returns the basic values, if it's 0 than it's not active.
Vector3 p_Velocity = new Vector3(0,0,0);
if (Input.GetKey(forward))
{
p_Velocity += new Vector3(0, 0, 1);
Debug.Log("Forward");
}
if (Input.GetKey(back))
{
p_Velocity += new Vector3(0, 0, -1);
Debug.Log("back");
}
if (Input.GetKey(left))
{
p_Velocity += new Vector3(-1, 0, 0);
Debug.Log("left");
}
if (Input.GetKey(right))
{
p_Velocity += new Vector3(1, 0, 0);
Debug.Log("right");
}
return p_Velocity;
}
}
|
// -----------------------------------------------------------------------
// <copyright file="Streamable.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;
namespace Mlos.Streaming
{
/// <summary>
/// Interface for 'Push' type streams.
/// </summary>
/// <remarks>
/// Interface does not provide subscribe methods to register the observer.
/// This is implemented in base abstract Streamable class.
/// </remarks>
internal interface IStreamable
{
/// <summary>
/// Returns a stream observer.
/// </summary>
/// <returns></returns>
IStreamObserver GetStreamObserver();
}
/// <summary>
/// Base abstract class for 'Push' type streams.
/// </summary>
/// <typeparam name="T">Type of the element in the stream.</typeparam>
public abstract class Streamable<T> : IStreamable
{
private Action<T> publish;
public void Publish(T value)
{
publish?.Invoke(value);
}
public void Subscribe(IStreamObserver<T> observer)
{
publish = observer.Observed;
}
public void Subscribe(Action<T> onObserved)
{
publish = onObserved;
}
IStreamObserver IStreamable.GetStreamObserver()
{
return publish?.Target as IStreamObserver;
}
public void Inspect()
{
IStreamObserver streamObserver = publish.Target as IStreamObserver;
while (streamObserver != null)
{
string result = streamObserver.Inspect();
IStreamable streamable = streamObserver as IStreamable;
if (streamable == null)
{
// Last element in the chain.
//
return;
}
// Follow the chain.
//
streamObserver = streamable.GetStreamObserver();
}
}
}
/// <summary>
/// Base abstract class for 'Push' type streams.
/// </summary>
/// <typeparam name="T1">First type of the element in the stream.</typeparam>
/// <typeparam name="T2">Second type of the element in the stream.</typeparam>
public abstract class Streamable<T1, T2> : IStreamable
{
private Action<T1, T2> publish;
public void Publish(T1 value1, T2 value2)
{
publish?.Invoke(value1, value2);
}
public void Subscribe(IStreamObserver<T1, T2> observer)
{
publish = observer.Observed;
}
public void Subscribe(Action<T1, T2> onObserved)
{
publish = onObserved;
}
IStreamObserver IStreamable.GetStreamObserver()
{
return publish.Target as IStreamObserver;
}
}
}
|
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
namespace GomokuEngine
{
public class ABMove : BoardSquare
{
//public int square;
readonly Player _player;
public BothPlayerEvaluation moveType;
public int value;
public TTEvaluationType valueType;
public int examinedMoves;
public int depthLeft;
public Player vctPlayer;
public TimeSpan time;
// int boardSize;
/*
public ABMove()
{
}*/
public ABMove(int boardSize, int index, Player player) : base(boardSize, index)
{
// _boardSize = boardSize;
// _index = index;
_player = player;
}
/*
public ABMove(int square, Player player, int boardSize, TimeSpan time)
{
this.square = square;
this.player = player;
this.boardSize = boardSize;
this.time = time;
}
public ABMove(int square, Player player, int boardSize)
{
this.square = square;
this.player = player;
this.boardSize = boardSize;
}*/
// public override string ToString()
// {
// Conversions conversions = new Conversions(boardSize);
// return conversions.Complete(square);
// }
public string[] ToStringArray(int index)
{
string s1 = EvaluationConstants.Score2Text(value);
string s2;
switch (valueType)
{
case TTEvaluationType.LowerBound:
s2 = ">= " + s1;
break;
case TTEvaluationType.UpperBound:
s2 = "<= " + s1;
break;
default:
s2 = s1;
break;
}
string[] str = { Convert.ToString(index), this.ToString() + " (" + Index.ToString() + ")", time.TotalSeconds.ToString(),
moveType.ToString(), s2, vctPlayer.ToString(), examinedMoves.ToString(), depthLeft.ToString(),
};
return str;
}
// public int Row
// {
// get
// {
// Conversions conversions = new Conversions(boardSize);
// return conversions.Index2Row(square);
// }
// }
//
// public int Column
// {
// get
// {
// Conversions conversions = new Conversions(boardSize);
// return conversions.Index2Column(square);
// }
// }
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using Console = Colorful.Console;
using BetterConsoleTables;
namespace footbal_manager
{
public static class ConsoleHandler
{
private static readonly string defaultTitle = "FOOTBAL MANAGER";
// public methods
public static string Welcome()
{
string[] descriptionLines = { "Welcome to Footbal Manager!", "Select your option:" };
string[] options = { "[1] New Game", "[2] About" };
int optionSelected = OptionChoice(false, descriptionLines, options);
return options[optionSelected];
}
public static CoachModel CreateCoach()
{
Console.Clear();
string[] descriptionLines = { "Hello coach!", "Before you continue, please insert your information" };
var options = new List<string>();
options.Add("[1] Name: ");
//coach properties
CoachSpeciality speciality = CoachSpeciality.DefaultNone;
var nameInput = (name: "", done: false);
var ageInput = (ageString: "", done: false);
var specialityInput = (speciality: speciality, done: false);
bool allInfoDone = false;
Console.CursorVisible = false;
do
{
Console.Clear();
OptionMenuTableUnicodeAlt(descriptionLines, options.ToArray());
ConsoleKey input = Console.ReadKey(true).Key;
// update table options
if (input == ConsoleKey.Enter)
{
// age
if (!nameInput.done && nameInput.name.Length > 2)
{
options.Add("[2] Age: ");
nameInput.done = true;
}
// speciality
else if (!ageInput.done && ageInput.ageString.Length > 1)
{
options.Add("[3] Speciality: ");
ageInput.done = true;
string[] title = { "Please select your Speciality:" };
string[] specialities = { "AGRESSIVE", "DEFENCIVE", "BALANCED" };
int especialityChoiceIndex = OptionChoice(false, title, specialities);
options[2] = "[3] Speciality: " + specialities[especialityChoiceIndex];
options.Add("");
options.Add("Press Enter to continue...");
switch (especialityChoiceIndex)
{
case 0:
specialityInput.speciality = CoachSpeciality.Agressive;
break;
case 1:
specialityInput.speciality = CoachSpeciality.Defencive;
break;
case 2:
specialityInput.speciality = CoachSpeciality.Balanced;
break;
};
}
// all info
else if (!specialityInput.done && specialityInput.speciality != CoachSpeciality.DefaultNone)
{
allInfoDone = true;
}
}
// get input values
else
{
// name
if (!nameInput.done)
{
switch (input)
{
case ConsoleKey.Backspace:
if (String.IsNullOrEmpty(nameInput.name)) { break; }
nameInput.name = nameInput.name.Remove(nameInput.name.Length - 1);
break;
case ConsoleKey.Spacebar:
nameInput.name += " ";
break;
default:
nameInput.name += input.ToString();
break;
};
options[0] = "[1] Name: " + nameInput.name;
}
// Age
else if (!ageInput.done)
{
switch (input)
{
case ConsoleKey.Backspace:
if (String.IsNullOrEmpty(ageInput.ageString)) { break; }
ageInput.ageString = ageInput.ageString.Remove(ageInput.ageString.Length - 1);
break;
default:
string inputValueString = input.ToString().Replace("D", "");
if (int.TryParse(inputValueString, out _))
{
if (ageInput.ageString.Length == 2) { break; }
ageInput.ageString += inputValueString;
}
else
{
//TODO TABLE WARNING
}
break;
};
options[1] = "[2] Age: " + ageInput.ageString;
}
}
} while (!allInfoDone);
int ageInt = Int32.Parse(ageInput.ageString);
return new CoachModel(
name: nameInput.name,
age: ageInt,
speciality:
specialityInput.speciality);
}
public static int SelectWorldCupTeam(string[] descriptionLines, string[] teamList)
{
int optionSelected = OptionChoiceMultiColumn("WORLD CUP", descriptionLines, teamList, 4);
return optionSelected;
}
// private methods
private static void DefaultTitile() => ConsoleHandler.TextArt(defaultTitle);
private static void OptionMenuTableUnicodeAlt(string[] descriptionLines, string[] options)
{
ColumnHeader header = new ColumnHeader(defaultTitle, Alignment.Left, Alignment.Center);
Table table = new Table(header);
foreach (string descriptionLine in descriptionLines) { table.AddRow(descriptionLine); }
table.AddRow(" ");
foreach (string option in options) { table.AddRow(option); }
table.Config = TableConfiguration.UnicodeAlt();
DefaultTitile();
Console.Write(table.ToString());
}
// column choice table
private static void MultiColumnTable(string title, string[] descriptionLines, string[] options, int numberOfColumns)
{
// info column
ColumnHeader titleHeader = new ColumnHeader(title, Alignment.Left, Alignment.Center);
Table infoTable = new Table(titleHeader);
infoTable.AddRow(" ");
foreach (string descriptionLine in descriptionLines) { infoTable.AddRow(descriptionLine); }
infoTable.Config = TableConfiguration.UnicodeAlt();
// options column table
Table optionsTable = new Table();
// - header: empty lines space
for (int i = 0; i < numberOfColumns; i++)
{
string emptyHeaderSpace = " ";
optionsTable.AddColumn(emptyHeaderSpace);
}
// - columns: options
// - add rows
int maxRows = options.Length / numberOfColumns;
for (int row = 1; row <= maxRows; row++)
{
int maxOptionsRow = numberOfColumns;
var maxIndex = maxOptionsRow * row;
var minIdex = maxIndex - maxOptionsRow;
var optionsRow = new List<string>();
for (int index = minIdex; index < maxIndex; index++)
{
optionsRow.Add(options[index]);
}
optionsTable.AddRow(optionsRow.ToArray());
}
optionsTable.AddRow("", "", "", "");
infoTable.Config = TableConfiguration.UnicodeAlt();
optionsTable.Config = TableConfiguration.Markdown();
DefaultTitile();
Console.Write(infoTable.ToString());
Console.Write(optionsTable.ToString());
}
// support methods
public static void TextArt(string text)
{
Console.Clear();
int red = 0;
int green = 255;
int blue = 0;
Console.WriteAscii(text, Color.FromArgb(red, green, blue));
}
private static int OptionChoiceMultiColumn(string title, string[] descriptionLines, string[] options, int numberOfColumns)
{
int optinsRange = options.Length - 1;
int currentSelection = 0;
ConsoleKey key;
Console.CursorVisible = false;
do
{
Console.Clear();
if (currentSelection < 0) { currentSelection = optinsRange; }
if (currentSelection > optinsRange) { currentSelection = 0; }
for (int i = 0; i < options.Length; i++)
{
options[i] = options[i].Replace(" <<", "");
if (i == currentSelection) { options[i] = options[i] + " <<"; }
}
// print table
MultiColumnTable(title, descriptionLines, options, numberOfColumns);
key = Console.ReadKey(true).Key;
switch (key)
{
case ConsoleKey.LeftArrow:
currentSelection--;
break;
case ConsoleKey.RightArrow:
currentSelection++;
break;
case ConsoleKey.DownArrow:
currentSelection += numberOfColumns;
break;
case ConsoleKey.UpArrow:
currentSelection -= numberOfColumns;
break;
case ConsoleKey.Escape:
break;
}
} while (key != ConsoleKey.Enter);
options[currentSelection] = options[currentSelection].Replace(" <<", "");
return currentSelection;
}
// simple choice table
public static int OptionChoice(bool canCancel, string[] descriptionLines, string[] options)
{
int optinsRange = options.Length - 1;
int currentSelection = 0;
ConsoleKey key;
Console.CursorVisible = false;
do
{
Console.Clear();
if (currentSelection < 0) { currentSelection = optinsRange; }
if (currentSelection > optinsRange) { currentSelection = 0; }
for (int i = 0; i < options.Length; i++)
{
options[i] = options[i].Replace(" <<", "");
if (i == currentSelection) { options[i] = options[i] + " <<"; }
}
// print table
OptionMenuTableUnicodeAlt(descriptionLines, options);
key = Console.ReadKey(true).Key;
switch (key)
{
case ConsoleKey.LeftArrow:
case ConsoleKey.DownArrow:
currentSelection++;
break;
case ConsoleKey.RightArrow:
case ConsoleKey.UpArrow:
currentSelection--;
break;
case ConsoleKey.Escape:
if (canCancel) { return -1; }
break;
}
} while (key != ConsoleKey.Enter);
options[currentSelection] = options[currentSelection].Replace(" <<", "");
return currentSelection;
}
}
}
|
using System;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace Convert_a_Text_File
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog(this);
if ( openFileDialog1.FileName != "")
{
textBox1.Text = openFileDialog1.FileName;
}
}
private void button1_Click(object sender, EventArgs e)
{
string fileExtension = new FileInfo(textBox1.Text).Extension;
string fileName = new FileInfo(textBox1.Text).FullName;
StreamReader sr = new StreamReader(fileName);
StreamWriter sw = new StreamWriter(fileName.Replace(fileExtension, "") + "-utf7" + fileExtension, false, Encoding.UTF7);
sw.WriteLine(sr.ReadToEnd());
sw.Close();
sr.Close();
}
}
}
|
using System;
using SLua;
using System.Collections.Generic;
[UnityEngine.Scripting.Preserve]
public class Lua_LTEvent : LuaObject {
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int constructor(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
LTEvent o;
System.Int32 a1;
checkType(l,2,out a1);
System.Object a2;
checkType(l,3,out a2);
o=new LTEvent(a1,a2);
pushValue(l,true);
pushValue(l,o);
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int get_id(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
LTEvent self=(LTEvent)checkSelf(l);
pushValue(l,true);
pushValue(l,self.id);
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int set_id(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
LTEvent self=(LTEvent)checkSelf(l);
System.Int32 v;
checkType(l,2,out v);
self.id=v;
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int get_data(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
LTEvent self=(LTEvent)checkSelf(l);
pushValue(l,true);
pushValue(l,self.data);
return 2;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int set_data(IntPtr l) {
try {
#if DEBUG
var method = System.Reflection.MethodBase.GetCurrentMethod();
string methodName = GetMethodName(method);
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.BeginSample(methodName);
#else
Profiler.BeginSample(methodName);
#endif
#endif
LTEvent self=(LTEvent)checkSelf(l);
System.Object v;
checkType(l,2,out v);
self.data=v;
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
#if DEBUG
finally {
#if UNITY_5_5_OR_NEWER
UnityEngine.Profiling.Profiler.EndSample();
#else
Profiler.EndSample();
#endif
}
#endif
}
[UnityEngine.Scripting.Preserve]
static public void reg(IntPtr l) {
getTypeTable(l,"LTEvent");
addMember(l,"id",get_id,set_id,true);
addMember(l,"data",get_data,set_data,true);
createTypeMetatable(l,constructor, typeof(LTEvent));
}
}
|
/* SLTrace
* Arguments.cs
*
* Copyright (c) 2010, Ewen Cheslack-Postava
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of SLTrace nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
namespace SLTrace {
class Arguments {
/** Tries to split an argument into a key-value pair according to the format
* --key=value.
*/
public static void AsKeyValue(string arg, out string key, out string value) {
string[] parts = arg.Split(new Char[] {'='}, 2);
string keyout = parts[0];
string valueout = parts.Length > 1 ? parts[1] : "";
keyout = keyout.Trim('-');
key = keyout;
value = valueout;
}
/** Parses a sequence of arguments into a dictionary of key-value pairs. */
public static Dictionary<string, string> Parse(IEnumerable<string> args) {
Dictionary<string, string> arg_dict = new Dictionary<string, string>();
foreach(string arg in args) {
string key, value;
AsKeyValue(arg, out key, out value);
arg_dict.Add(key, value);
}
return arg_dict;
}
/** Splits a string containing a sequence of arguments into an array of
* individual arguments. Arguments are denoted by the starting characters
* " --".
*/
public static string[] Split(string args_as_string) {
if (String.IsNullOrEmpty(args_as_string))
return new string[] {};
// FIXME this is a bit naive, we really need to also handle quoted args
// as well
string[] args = args_as_string.Split(' ');
return args;
}
/** Parse a string containing a duration. The TimeSpan.Parse() method uses
* an inconvenient format and is not particularly flexible, so we provide
* this one instead. Currently supports h, m, s, ms as postfixes for
* hours, minutes, seconds, and milliseconds.
*/
public static TimeSpan ParseDuration(string dur_string) {
if (dur_string.EndsWith("h")) {
return TimeSpan.FromHours(Double.Parse(dur_string.Substring(0, dur_string.Length-1)));
}
else if (dur_string.EndsWith("m")) {
return TimeSpan.FromMinutes(Double.Parse(dur_string.Substring(0, dur_string.Length-1)));
}
else if (dur_string.EndsWith("s")) {
return TimeSpan.FromSeconds(Double.Parse(dur_string.Substring(0, dur_string.Length-1)));
}
else if (dur_string.EndsWith("ms")) {
return TimeSpan.FromMilliseconds(Double.Parse(dur_string.Substring(0, dur_string.Length-2)));
}
return TimeSpan.Zero;
}
} // class Arguments
} // namespace SLTrace
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace PresentationLayer
{
public partial class SearchPhysician : System.Web.UI.Page
{
HMSEntities phyobjHMSEnt = new HMSEntities();
public void MsgBox(String ex, Page pg, Object obj) {
string s = "<SCRIPT language='javascript'>alert('" + ex.Replace("\r\n", "\\n").Replace("'", "") + "'); </SCRIPT>";
Type cstype = obj.GetType();
ClientScriptManager cs = pg.ClientScript;
cs.RegisterClientScriptBlock(cstype, s, s.ToString());
}
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
stateLoad();
PlanLoad();
DepartmentLoad();
}
}
public void stateLoad()
{
var stateID = from State in phyobjHMSEnt.tblStates
select new
{
stateID = State.state_id,
stateIDName = State.state_id + " - " + State.name,
};
ddlState.DataSource = stateID.ToList();
ddlState.DataValueField = "stateID";
ddlState.DataTextField = "stateIDName";
ddlState.DataBind();
ddlState.Items.Insert(0, "Select a State");
}
public void PlanLoad() {
var planID = from Plan in phyobjHMSEnt.tblPlans
select new {
planID = Plan.plan_id,
};
ddlPlan.DataSource = planID.ToList();
ddlPlan.DataValueField = "planID";
ddlPlan.DataTextField = "planID";
ddlPlan.DataBind();
ddlPlan.Items.Insert(0, "Select a Plan");
}
public void DepartmentLoad() {
var departmentID = from Department in phyobjHMSEnt.tblDepartments
select new {
departmentID = Department.department_id,
departmentIDName=Department.department_id+" - "+Department.department_name
};
ddlDept.DataSource = departmentID.ToList();
ddlDept.DataValueField = "departmentID";
ddlDept.DataTextField = "departmentIDName";
ddlDept.DataBind();
ddlDept.Items.Insert(0, "Select a Department");
}
protected void AddPhysicianData()
{
int count;
GridViewPhysician.DataSource = phyobjHMSEnt.SpPhysicianSearch(ddlState.SelectedItem.Value, ddlPlan.SelectedItem.Value, ddlDept.SelectedItem.Value);
GridViewPhysician.DataBind();
count = GridViewPhysician.Rows.Count;
if (count == 0)
{
MsgBox("No Record Found", this.Page, this);
}
}
protected void BtnSearch_Click(object sender, EventArgs e) {
//if (ddlDept.SelectedIndex == 0 || ddlPlan.SelectedIndex == 0 || ddlState.SelectedIndex == 0)
//{
// MsgBox("Please Select The Fields", this.Page, this);
//}
//else
//{
AddPhysicianData();
//}
}
protected void BtnReset_Click(object sender, EventArgs e) {
ddlState.SelectedIndex = 0;
ddlPlan.SelectedIndex = 0;
ddlDept.SelectedIndex = 0;
GridViewPhysician.DataSource = null;
GridViewPhysician.DataBind();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PageCollection : MonoBehaviour {
List<LinePageSim> pages;
List<LinePageSim> lPages;
List<LinePageSim> rPages;
public int initialTicks = 10;
public bool allPagesActive = false;
public bool isGrabbing { get; private set; }
public LineRenderer grabLine { get; private set; }
public int grabVertex { get; private set; }
public Vector3 grabVel { get; private set; }
Vector3 lastMousePos;
// Use this for initialization
void Start()
{
// Add all child pages to list
pages = new List<LinePageSim>();
lPages = new List<LinePageSim>();
rPages = new List<LinePageSim>();
for (int i = 0; i < transform.GetChildCount(); i++)
{
GameObject c = transform.GetChild(i).gameObject;
LinePageSim page = c.GetComponentInChildren<LinePageSim>();
if (page)
{
page.pages = GetComponent<PageCollection>();
pages.Add(page);
rPages.Add(page);
}
}
// Establish page/page connections
for (int i = 0; i < pages.Count; i++)
{
if (i > 0)
{
pages[i].prevPage = pages[i - 1];
}
if (i < pages.Count - 1)
{
pages[i].nextPage = pages[i + 1];
}
}
if (!allPagesActive)
{
// Run for a few ticks so pages can settle before locking them
for (int i = 0; i < initialTicks; i++)
{
RunAllPages();
}
// Now lock pages
for (int i = 0; i < pages.Count; i++)
{
if (!allPagesActive)
{
pages[i].move = false;
}
}
// Only activate top page
if (rPages.Count > 0)
{
rPages[0].move = true;
}
}
}
void RunAllPages()
{
// Run all simulations from bottom to top (i.e. forwards for L pages, backwards for R pages)
for (int i = rPages.Count - 1; i >= 0; i--)
{
rPages[i].GetComponent<LinePageSim>().Tick();
}
for (int i = 0; i < lPages.Count; i++)
{
lPages[i].GetComponent<LinePageSim>().Tick();
}
}
// Update is called once per frame
void Update() {
RunAllPages();
// Calculate closest point from all lines to mouse
float minDist = Mathf.Infinity;
LineRenderer minLine = null;
int minVertex = -1;
Vector3 mouseScreen = Input.mousePosition;
for(int i = 0; i < pages.Count; i++)
{
// Only moving pages can be grabbed
if(!pages[i].move)
{
continue;
}
for(int j = 0; j < pages[i].N; j++)
{
// Find closest point to mouse
LineRenderer line = pages[i].GetComponent<LineRenderer>();
Vector3 vertex = line.transform.TransformPoint(line.GetPosition(j));
Vector3 vertexScreen = Camera.main.WorldToScreenPoint(vertex);
float dist = Vector3.SqrMagnitude(vertexScreen - mouseScreen);
if(dist < minDist)
{
minDist = dist;
minLine = line;
//minVertex = j;
// Snapping to end of page for now
minVertex = pages[i].N - 1;
}
}
}
//Debug.LogFormat("Closest vertex: {0} ({1}m)", minVertex, minDist);
Debug.DrawRay(Camera.main.transform.position,
minLine.transform.TransformPoint(minLine.GetPosition(minVertex)) - Camera.main.transform.position,
Color.red);
//Color[] colors = new Color[N];
//for(int i = 0; i < N; i++)
//{
// colors[i] = Color.black;
//}
//colors[minVertex] = Color.red;
if (Input.GetMouseButtonDown(0))
{
isGrabbing = true;
grabLine = minLine;
grabVertex = minVertex;
}
if (Input.GetMouseButtonUp(0))
{
isGrabbing = false;
grabLine = null;
grabVertex = -1;
}
Vector3 mouseWorld = Camera.main.ScreenToWorldPoint(mouseScreen);
if(isGrabbing)
{
Vector3 dmouse = mouseWorld - lastMousePos;
Vector3 pos = grabLine.GetPosition(grabVertex);
// TODO: May need to change to Time.fixedDeltaTime
grabVel = dmouse / Time.deltaTime;
pos += dmouse;
grabLine.SetPosition(grabVertex, pos);
}
lastMousePos = mouseWorld;
// Moving across y axis switches page status
if(grabLine)
{
var v = grabLine.GetPosition(grabVertex);
var grabPage = grabLine.GetComponent<LinePageSim>();
if (v.x < 0 && !lPages.Contains(grabPage))
{
if(lPages.Count > 0 && !allPagesActive)
{
lPages[lPages.Count - 1].move = false;
}
lPages.Add(grabPage);
rPages.Remove(grabPage);
if(rPages.Count > 0 && !allPagesActive)
{
rPages[0].move = true;
}
}
if(v.x > 0 && !rPages.Contains(grabPage))
{
if(rPages.Count > 0 && !allPagesActive)
{
rPages[0].move = false;
}
rPages.Insert(0, grabPage);
lPages.Remove(grabPage);
if(lPages.Count > 0 && !allPagesActive)
{
lPages[lPages.Count - 1].move = true;
}
}
}
// Recolor pages to label them
foreach(var p in rPages)
{
Color targetColor;
if(p.move)
{
targetColor = Color.red;
}
else
{
targetColor = Color.grey;
}
p.GetComponent<LineRenderer>().startColor = targetColor;
p.GetComponent<LineRenderer>().endColor = targetColor;
}
foreach(var p in lPages)
{
Color targetColor;
if(p.move)
{
targetColor = Color.magenta;
}
else
{
targetColor = Color.grey;
}
p.GetComponent<LineRenderer>().startColor = targetColor;
p.GetComponent<LineRenderer>().endColor = targetColor;
}
//if(grabLine)
//{
// grabLine.startColor = Color.green;
// grabLine.endColor = Color.green;
//}
}
}
|
using System;
using NetPayroll.Guides.Common;
namespace NetPayroll.Guides.Interfaces
{
public interface IProfileContract
{
Period ContractPeriod();
IContractEmploy EmployContract();
IContractTaxing TaxingContract();
IContractHealth HealthContract();
IContractSocial SocialContract();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BorderController : MonoBehaviour
{
// Start is called before the first frame update
public float minX;
public float maxX;
public float minY;
public bool genеrаtionCompletion;
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Nop.Payment.PostPaymentCommon;
using NopSolutions.NopCommerce.BusinessLogic.Configuration.Settings;
using NopSolutions.NopCommerce.BusinessLogic.CustomerManagement;
using NopSolutions.NopCommerce.BusinessLogic.Orders;
using NopSolutions.NopCommerce.BusinessLogic.Products;
using NopSolutions.NopCommerce.BusinessLogic.Utils;
using NopSolutions.NopCommerce.Common.Utils;
namespace Nop.Payment.Assist
{
public class AssistPaymentProcessor: PostPaymentProcessor
{
#region IPaymentMethod Members
protected override void BuildPostForm(Order order, IndividualOrderCollection indOrders, decimal price, decimal shipping, Customer customer)
{
var remotePostHelper = new RemotePost { FormName = "AssistForm", Url = GetPaymentServiceUrl() };
remotePostHelper.Add("Merchant_ID", "706403");
remotePostHelper.Add("OrderNumber", order.OrderID.ToString());
remotePostHelper.Add("OrderAmount", Math.Round(price + shipping).ToString());
remotePostHelper.Add("OrderCurrency", ConvertToUsd ? "USD" : CurrencyId);
remotePostHelper.Add("TestMode", IsTestMode? "1": "0");
if (!String.IsNullOrEmpty(customer.BillingAddress.LastName))
{
remotePostHelper.Add("Lastname", customer.BillingAddress.LastName);
}
if (!String.IsNullOrEmpty(customer.BillingAddress.FirstName))
{
remotePostHelper.Add("Firstname", customer.BillingAddress.FirstName);
}
if (!String.IsNullOrEmpty(customer.BillingAddress.Email))
{
remotePostHelper.Add("Email", customer.BillingAddress.Email);
}
remotePostHelper.Add("URL_RETURN_OK", SettingManager.GetSettingValue("PaymentMethod.Assist.OkUrl"));
remotePostHelper.Add("URL_RETURN_NO", SettingManager.GetSettingValue("PaymentMethod.Assist.NoUrl"));
remotePostHelper.Post();
}
protected override decimal AddServiceFee(decimal totalPrice, bool convertToUsd)
{
decimal priceWithFee = totalPrice + ((totalPrice / 100) * SettingManager.GetSettingValueInteger("PaymentMethod.Assist.ServiceFee"));
if (!convertToUsd)
return Math.Ceiling((priceWithFee / 100) * 100);
return Math.Round((priceWithFee / 100) * 100);
}
protected override decimal CalculateTotalOrderServiceFee(OrderProductVariantCollection orderProducts, List<ProductVariant> prodVars, Order order, out object shippingPrice)
{
decimal retVal = ConvertToUsd
? prodVars.Sum(prodVar => (Math.Round(PriceConverter.ToUsd(AddServiceFee(prodVar.Price, ConvertToUsd)))*
orderProducts.First(op => op.ProductVariantID == prodVar.ProductVariantID).Quantity))
: prodVars.Sum(prodVar =>(AddServiceFee(prodVar.Price, ConvertToUsd)*
orderProducts.First(op => op.ProductVariantID == prodVar.ProductVariantID).Quantity));
if (ShoppingCartRequiresShipping)
{
decimal shippingBlr = AddServiceFee(((FreeShippingEnabled && retVal > FreeShippingBorder) ? 0 : ShippingRate),
ConvertToUsd);
shippingPrice = ConvertToUsd ? Math.Round(PriceConverter.ToUsd(shippingBlr)) : shippingBlr;
}
else
{
shippingPrice = (decimal) 0;
}
return retVal;
}
#endregion
public override string GetPaymentServiceUrl()
{
const string testUrl = "https://test.paysec.by/pay/order.cfm";
try
{
string paymentUrl = SettingManager.GetSettingValue("PaymentMethod.Assist.PaymentUrl");
if (!String.IsNullOrEmpty(paymentUrl))
return paymentUrl;
}
catch (Exception){}
return testUrl;
}
private static bool IsTestMode
{
get
{
try
{
return SettingManager.GetSettingValueBoolean("PaymentMethod.Assist.TestMode");
}
catch (Exception) { }
return true;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Alphabeth
{
static class MyForm
{
public static List<string> GetFilesFullPath(OpenFileDialog openFileDialog)
{
openFileDialog.FileName = "";
List<string> filesFullPath = new List<string>();
DialogResult result = openFileDialog.ShowDialog();
if (result == DialogResult.OK)
foreach (String file in openFileDialog.FileNames)
{
try
{
filesFullPath.Add(file);
}
catch (SecurityException ex)
{
// The user lacks appropriate permissions to read files, discover paths, etc.
MessageBox.Show("Security error. Please contact your administrator for details.\n\n" +
"Error message: " + ex.Message + "\n\n" +
"Details (send to Support):\n\n" + ex.StackTrace
);
}
catch (Exception ex)
{
// Could not load file.
MessageBox.Show("Cannot display the image: " + file.Substring(file.LastIndexOf('\\'))
+ ". You may not have permission to read the file, or " +
"it may be corrupt.\n\nReported error: " + ex.Message);
}
}
return filesFullPath;
}
}
}
|
//using System;
//using System.Collections.Generic;
//using System.ComponentModel;
//using System.IO;
//using System.Threading.Tasks;
//using Foundation;
//using UIKit;
//using Xam.Plugin.WebView.Abstractions;
//using Xam.Plugin.WebView.Abstractions.Delegates;
//using Xam.Plugin.WebView.Abstractions.Enumerations;
//using Xam.Plugin.WebView.iOS;
//using Xamarin.Forms;
//using Xamarin.Forms.Platform.iOS;
//[assembly: Xamarin.Forms.ExportRenderer(typeof(FormsWebView), typeof(FormsWebViewOldRenderer))]
//namespace Xam.Plugin.WebView.iOS
//{
// public class FormsWebViewOldRenderer : ViewRenderer<FormsWebView, UIWebView>
// {
// public FormsWebViewOldRenderer()
// {
// }
// public static event EventHandler<UIWebView> OnControlChanged;
// public static string BaseUrl { get; set; } = NSBundle.MainBundle.BundlePath;
// private Dictionary<string, int> _cookieDomains = new Dictionary<string, int>();
// protected override void OnElementChanged(ElementChangedEventArgs<FormsWebView> e)
// {
// base.OnElementChanged(e);
// if (Control == null && Element != null)
// SetupControl();
// if (e.NewElement != null)
// SetupElement(e.NewElement);
// if (e.OldElement != null)
// DestroyElement(e.OldElement);
// }
// void OnCallbackAdded(object sender, string e)
// {
// if (Element == null || string.IsNullOrWhiteSpace(e)) return;
// if ((sender == null && Element.EnableGlobalCallbacks) || sender != null)
// OnJavascriptInjectionRequest(FormsWebView.GenerateFunctionScript(e));
// }
// void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
// {
// switch (e.PropertyName) {
// case "Source":
// SetSource();
// break;
// }
// }
// private Task OnClearCookiesRequest()
// {
// if (Control == null) Task.FromResult<object>(null);
// foreach (var domain in _cookieDomains) {
// var domainUrl = NSUrl.FromString(domain.Key);
// foreach (var cookie in NSHttpCookieStorage.SharedStorage.CookiesForUrl(domainUrl)) {
// NSHttpCookieStorage.SharedStorage.DeleteCookie(cookie);
// _cookieDomains[domain.Key] = domain.Value - 1;
// }
// }
//#if DEBUG
// OnPrintCookiesRequested();
//#endif
// return Task.FromResult<object>(null);
// }
// private Task OnPrintCookiesRequested(IEnumerable<string> urls = null)
// {
//#if DEBUG
// NSHttpCookie[] cookies;
// System.Diagnostics.Debug.WriteLine("*** NSHttpCookieStorage.SharedStorage.Cookies ***");
// cookies = NSHttpCookieStorage.SharedStorage.Cookies;
// if (cookies != null) {
// foreach (var nsCookie2 in cookies) {
// System.Diagnostics.Debug.WriteLine($"Domain={nsCookie2.Domain}; Name={nsCookie2.Name}; Value={nsCookie2.Value};");
// }
// }
//#endif
// return Task.FromResult<object>(null);
// }
// private Task OnAddCookieRequested(System.Net.Cookie cookie)
// {
// if (Control == null || cookie == null || String.IsNullOrEmpty(cookie.Domain) || String.IsNullOrEmpty(cookie.Name))
// return Task.FromResult<object>(null);
// var nsCookie = new NSHttpCookie(cookie);
// NSHttpCookieStorage.SharedStorage.SetCookie(nsCookie);
// if (!_cookieDomains.ContainsKey(cookie.Domain)) {
// _cookieDomains[cookie.Domain] = 0;
// }
// _cookieDomains[cookie.Domain] = _cookieDomains[cookie.Domain] + 1;
//#if DEBUG
// OnPrintCookiesRequested();
//#endif
// return Task.FromResult<object>(null);
// }
// void OnRefreshRequested(object sender, EventArgs e)
// {
// if (Control == null) return;
// Control.Reload();
// }
// void OnForwardRequested(object sender, EventArgs e)
// {
// if (Control == null || Element == null) return;
// if (Control.CanGoForward)
// Control.GoForward();
// }
// void OnBackRequested(object sender, EventArgs e)
// {
// if (Control == null || Element == null) return;
// if (Control.CanGoBack)
// Control.GoBack();
// }
// internal Task<string> OnJavascriptInjectionRequest(string js)
// {
// if (Control == null || Element == null)
// return Task.FromResult(string.Empty);
// var response = string.Empty;
// try {
// response = Control.EvaluateJavascript(js);
// } catch (Exception exc) {
// /* The Webview might not be ready... */
// System.Diagnostics.Debug.WriteLine(exc.Message);
// }
// return Task.FromResult(response);
// }
// void SetupElement(FormsWebView element)
// {
// element.PropertyChanged += OnPropertyChanged;
// element.OnJavascriptInjectionRequest += OnJavascriptInjectionRequest;
// element.OnClearCookiesRequested += OnClearCookiesRequest;
// element.OnAddCookieRequested += OnAddCookieRequested;
// element.OnBackRequested += OnBackRequested;
// element.OnForwardRequested += OnForwardRequested;
// element.OnRefreshRequested += OnRefreshRequested;
// element.OnPrintCookiesRequested += OnPrintCookiesRequested;
// SetSource();
// }
// void DestroyElement(FormsWebView element)
// {
// element.PropertyChanged -= OnPropertyChanged;
// element.OnJavascriptInjectionRequest -= OnJavascriptInjectionRequest;
// element.OnClearCookiesRequested -= OnClearCookiesRequest;
// element.OnAddCookieRequested -= OnAddCookieRequested;
// element.OnBackRequested -= OnBackRequested;
// element.OnForwardRequested -= OnForwardRequested;
// element.OnRefreshRequested -= OnRefreshRequested;
// element.OnPrintCookiesRequested -= OnPrintCookiesRequested;
// element.Dispose();
// }
// void SetupControl()
// {
// var uiWebView = new UIWebView(Frame);
// uiWebView.BackgroundColor = UIColor.Black;
// FormsWebView.CallbackAdded += OnCallbackAdded;
// uiWebView.LoadError += UiWebView_LoadError;
// uiWebView.LoadStarted += UiWebView_LoadStarted;
// uiWebView.LoadFinished += UiWebView_LoadFinished;
// uiWebView.ShouldStartLoad += UiWebView_ShouldStartLoad;
// if(uiWebView.ScrollView != null) {
// uiWebView.ScrollView.Bounces = false;
// }
// uiWebView.ContentMode = UIViewContentMode.ScaleAspectFit;
// uiWebView.AutoresizingMask = UIViewAutoresizing.All;
// uiWebView.ScalesPageToFit = true;
// SetNativeControl(uiWebView);
// OnControlChanged?.Invoke(this, uiWebView);
// }
// public override SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint)
// {
// return new SizeRequest(Size.Zero, Size.Zero);
// }
// void SetSource()
// {
// if (Element == null || Control == null || string.IsNullOrWhiteSpace(Element.Source)) return;
// switch (Element.ContentType) {
// case WebViewContentType.Internet:
// LoadInternetContent();
// break;
// case WebViewContentType.LocalFile:
// LoadLocalFile();
// break;
// case WebViewContentType.StringData:
// LoadStringData();
// break;
// }
// }
// void LoadStringData()
// {
// if (Control == null || Element == null) return;
// var nsBaseUri = new NSUrl($"file://{Element.BaseUrl ?? BaseUrl}");
// Control.LoadHtmlString(Element.Source, nsBaseUri);
// }
// void LoadLocalFile()
// {
// if (Control == null || Element == null) return;
// // TODO: Not finished
// var path = Path.Combine(Element.BaseUrl ?? BaseUrl, Element.Source);
// var nsFileUri = new NSUrl($"file://{path}");
// var nsBaseUri = new NSUrl($"file://{Element.BaseUrl ?? BaseUrl}");
// var url = new NSUrl(Element.Source);
// var request = new NSMutableUrlRequest(url);
// Control.LoadRequest(request);
// }
// void LoadInternetContent()
// {
// if (Control == null || Element == null) return;
// var headers = new NSMutableDictionary();
// foreach (var header in Element.LocalRegisteredHeaders) {
// var key = new NSString(header.Key);
// if (!headers.ContainsKey(key))
// headers.Add(key, new NSString(header.Value));
// }
// if (Element.EnableGlobalHeaders) {
// foreach (var header in FormsWebView.GlobalRegisteredHeaders) {
// var key = new NSString(header.Key);
// if (!headers.ContainsKey(key))
// headers.Add(key, new NSString(header.Value));
// }
// }
// /*
// var cookieDictionary = NSHttpCookie.RequestHeaderFieldsWithCookies(NSHttpCookieStorage.SharedStorage.Cookies);
// foreach (var item in cookieDictionary) {
// headers.SetValueForKey(item.Value, new NSString(item.Key.ToString()));
// }
// */
// var url = new NSUrl(Element.Source);
// var request = new NSMutableUrlRequest(url) {
// Headers = headers
// };
// Control.LoadRequest(request);
// }
// void UiWebView_LoadError(object sender, UIWebErrorArgs e)
// {
// if (this.Element == null) return;
// this.Element.HandleNavigationError(Convert.ToInt32(e.Error.Code));
// }
// bool UiWebView_ShouldStartLoad(UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navigationType)
// {
// if (this.Element == null) return false;
// var dh = this.Element.HandleNavigationStartRequest(request.Url.ToString());
// if (dh.Cancel) {
// this.Control.StopLoading();
// return false;
// }
// return true;
// }
// void UiWebView_LoadStarted(object sender, EventArgs e)
// {
// if (this.Element == null) return;
// }
// void UiWebView_LoadFinished(object sender, EventArgs e)
// {
// if (this.Element == null) return;
// this.Element.HandleNavigationCompleted(this.Control.Request.Url.ToString());
// this.Element.HandleContentLoaded();
// }
// }
//}
|
using System;
using System.Collections.Generic;
using System.Linq;
using SiscomSoft.Models;
namespace SiscomSoft.Controller
{
public class ManejoAlmacen
{
/// <summary>
/// Funcion que se encarga de contar todos los registros de la tabla almacen y asignarlos como numero de folio
/// </summary>
/// <returns></returns>
public static string Folio()
{
try
{
using (var ctx = new DataModel())
{
var n = ctx.Almacenes.Count() + 1;
var folio = "I" + n;
return folio;
}
}
catch (Exception)
{
throw;
}
}
public static List<Almacen> Buscar(string valor, Boolean Status)
{
try
{
using (var ctx = new DataModel())
{
return ctx.Almacenes
.Where(r => r.bStatus == Status && r.sFolio.Contains(valor))
.ToList();
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Funcion encargada de guardar un nuevo almacen en a base de datos
/// </summary>
/// <param name="nAlmacen"></param>
/// <param name="pkCliente"></param>
public static void RegistrarNuevoAlmacen(Almacen nAlmacen, int pkCliente)
{
try
{
using (var ctx = new DataModel())
{
nAlmacen.cliente_id = pkCliente;
ctx.Almacenes.Add(nAlmacen);
ctx.SaveChanges();
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Funcion que se encargada de obtener todos los datos de los almacenes registrados en la base de datos
/// </summary>
/// <returns></returns>
public static List<Almacen> getAll()
{
try
{
using (var ctx = new DataModel())
{
return ctx.Almacenes.Where(r => r.bStatus == true).ToList();
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Funcion que se encarga de buscar un almacen dandole un id
/// </summary>
/// <param name="idAlmacen">variable de tipo entera</param>
/// <returns></returns>
public static Almacen getById(int idAlmacen)
{
try
{
using (var ctx = new DataModel())
{
return ctx.Almacenes
.Where(r => r.bStatus == true && r.idAlmacen == idAlmacen).FirstOrDefault();
}
}
catch (Exception)
{
throw;
}
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.EventSystems;
public class PreBattleDeployment : MonoBehaviour
{
[HideInInspector]
public static PreBattleDeployment pre_battle_deployment;
public Dictionary<string, int> deployable_units = new Dictionary<string, int>();
public int cur_deployed_units = 0;
public int maximum_deployable_units = 10;
public Dictionary<string, HeroStats> deployable_heroes = new Dictionary<string, HeroStats>(); // Contains the stats of all deployable heroes
public Dictionary<string, string> unit_art = new Dictionary<string, string>();
public string unit_to_spawn; // String that contains the location of the prefab to spawn
public string unit_to_spawn_name;
public SpriteRenderer deployable_sprite; // Sprite that follows the mouse to show the unit we're going to spawn
public GameObject deploy_unit_button; // Button to populate our deploy units list
public Transform deployable_panel; // Panel that gets populated with buttons to deploy units
public Text units_remaining_text;
[HideInInspector]
public Faction player_faction;
void Start ()
{
pre_battle_deployment = this;
// Look at the persistent battle settings for how many units we can deploy
if (PersistentBattleSettings.battle_settings != null)
maximum_deployable_units = PersistentBattleSettings.battle_settings.number_of_deployable_units;
// Get available units from the troop manager
if (TroopManager.playerTroops != null)
{
Debug.Log("Getting units from troop manager");
// Add units we can deploy to the deployment panel
foreach (KeyValuePair<string, int> pair in TroopManager.playerTroops.healthy)
{
if (pair.Value > 0)
deployable_units.Add(pair.Key, pair.Value);
}
// Add available non-wounded heroes to be deployed
foreach (GameObject hero_obj in TroopManager.playerTroops.heroes)
{
// Get the stats from the hero stats script
HeroStats hero_stats = hero_obj.GetComponent<HeroStats>();
if (!hero_stats.injured)
{
Debug.Log("Adding hero to deployment list: " + hero_stats.hero_name);
deployable_units.Add(hero_stats.hero_name, 1);
deployable_heroes.Add(hero_stats.hero_name, hero_stats);
}
}
}
else
{
// Setting up debug available units
Debug.Log("Setting available debug units");
deployable_units.Add("Odysseus", 1);
//deployable_heroes
deployable_units.Add("Daedalus", 1);
//deployable_heroes
deployable_units.Add("Automaton", 10);
deployable_units.Add("Hoplite", 10);
deployable_units.Add("Cavalry", 10);
deployable_units.Add("Archer", 10);
deployable_units.Add("Slinger", 10);
deployable_units.Add("Swordsman", 10);
deployable_units.Add("Cyclops", 10);
deployable_units.Add("Minotaur", 10);
deployable_units.Add("CentaurWarrior", 10);
deployable_units.Add("CentaurMarksman", 10);
deployable_units.Add("Peltast", 10);
deployable_units.Add("Wolves", 10);
}
// Populate the buttons to spawn units
// At the start the value of the pair is the number of healthy individuals of that category
Dictionary<string, int> temp_units = new Dictionary<string, int>();
foreach (KeyValuePair<string, int> pair in deployable_units)
{
GameObject newButton = Instantiate(deploy_unit_button) as GameObject;
newButton.name = pair.Key;
Button button = newButton.GetComponent<Button>();
Debug.Log(pair.Key + " x " + pair.Value);
string unit_name = pair.Key;
// Set the button image by instantiating a unit and then grabbing its sprite
GameObject instance = Instantiate(Resources.Load("Battles/Units/" + unit_name, typeof(GameObject))) as GameObject;
Unit unit = instance.GetComponent<Unit>();
button.image.sprite = unit.portrait;
int num_deployable_squads = pair.Value / unit.normal_squad_size;
temp_units.Add(pair.Key, num_deployable_squads);
button.onClick.AddListener(() => SelectUnitFromDeploymentMenu(unit_name, button));
Text text = newButton.GetComponentInChildren<Text>();
text.text = num_deployable_squads + "";//pair.Key + " x " + pair.Value;
newButton.transform.SetParent(deployable_panel);
newButton.transform.localScale = new Vector3(1, 1, 1);
GameObject.Destroy(instance);
if (pair.Value <= 0)
button.interactable = false;
}
deployable_units = temp_units;
SetUnitsRemainingText();
}
void Update ()
{
if (unit_to_spawn != "")
{
// Left click to deploy the unit
if (Input.GetMouseButtonDown(0)
&& !EventSystem.current.IsPointerOverGameObject()
&& PlayerInterface.player_interface.highlighted_hex != null
&& PlayerInterface.player_interface.highlighted_hex.occupying_unit == null
&& PlayerInterface.player_interface.highlighted_hex.deployment_zone
&& cur_deployed_units < maximum_deployable_units
&& !PlayerInterface.player_interface.highlighted_hex.impassable)
{
DeployUnit();
}
}
// Right clicking on a deployed unit un deploys it
if (Input.GetMouseButtonDown(1)
&& !EventSystem.current.IsPointerOverGameObject()
&& PlayerInterface.player_interface.highlighted_hex != null
&& PlayerInterface.player_interface.highlighted_hex.occupying_unit != null
&& PlayerInterface.player_interface.highlighted_hex.occupying_unit.owner == BattleManager.battle_manager.player_faction)
{
UndeployUnit();
}
}
public void DeployUnit()
{
int remaining_units = deployable_units[unit_to_spawn_name];
if (remaining_units > 0) // Spawn the unit if we have units available to spawn
{
Debug.Log("Spawning unit " + unit_to_spawn_name);
deployable_units[unit_to_spawn_name] = deployable_units[unit_to_spawn_name] - 1;
cur_deployed_units++;
SetUnitsRemainingText();
SetDeployButtonText(unit_to_spawn_name, deployable_units[unit_to_spawn_name]);
GameObject unit = BattleManager.battle_manager.SpawnUnit(player_faction, unit_to_spawn, PlayerInterface.player_interface.highlighted_hex, true);
Unit unit_script = unit.GetComponent<Unit>();
unit_script.Initialize();
// If there are viewable enemies on the field, face towards the nearest
List<Unit> enemies = BattleManager.battle_manager.player_faction.GetAllEnemyUnits();
if (enemies.Count > 0)
{
unit_script.SetImmediateRotation(
unit_script.GetAngleTowards(unit_script.location.world_coordinates,
BattleManager.battle_manager.player_faction.GetClosestEnemy(unit_script).location.world_coordinates));
}
else
unit_script.SetImmediateRotation(270);
// Check if this is a hero
HeroStats hero_stats;
if (deployable_heroes.TryGetValue(unit_to_spawn_name, out hero_stats))
{
Debug.Log("Adding stats and ability for hero " + hero_stats.hero_name);
switch (hero_stats.weaponType)
{
case Hero_Weapon_Skill_Types.Ranged:
AddRangedHeroAbilities(unit_script, hero_stats);
break;
}
AlterHeroStats(unit_script, hero_stats);
unit_script.ResetStats();
}
// Disable the deployment of that unit if we're out of those units to deploy
if (deployable_units[unit_to_spawn_name] <= 0)
{
deployable_panel.FindChild(unit_to_spawn_name).gameObject.GetComponent<Button>().interactable = false;
unit_to_spawn = "";
unit_to_spawn_name = "";
deployable_sprite.gameObject.SetActive(false);
}
}
}
public void UndeployUnit()
{
cur_deployed_units--;
SetUnitsRemainingText();
string name = PlayerInterface.player_interface.highlighted_hex.occupying_unit.prefab_name;
Debug.Log("Undeploying " + name);
deployable_units[name] = deployable_units[name] + 1;
SetDeployButtonText(name, deployable_units[name]);
// Re enable deployment button of this unit we just deleted
if (deployable_units[name] == 1)
{
deployable_panel.FindChild(name).gameObject.GetComponent<Button>().interactable = true;
}
PlayerInterface.player_interface.highlighted_hex.occupying_unit.RemoveUnit();
}
public void SetDeployButtonText(string unit_name, int number_available)
{
deployable_panel.FindChild(unit_name).GetComponentInChildren<Text>().text = "" + number_available;
}
public void SetUnitsRemainingText()
{
units_remaining_text.text = (maximum_deployable_units - cur_deployed_units) + " unit deployments remaining";
}
public void SelectUnitFromDeploymentMenu(string unit_name, Button button)
{
Debug.Log("Selected " + unit_name + " to deploy");
unit_to_spawn = "Battles/Units/" + unit_name;
unit_to_spawn_name = unit_name;
// Activate and set deployable sprite
deployable_sprite.gameObject.SetActive(true);
deployable_sprite.sprite = button.image.sprite;
}
// Based on the heroes stats, alter the units stats
public void AlterHeroStats(Unit hero, HeroStats hero_stats)
{
hero.maximum_health += hero_stats.strength * 30; // 30 HP per strength
}
// Adds an ability per level of bow skill
public void AddRangedHeroAbilities(Unit hero, HeroStats hero_stats)
{
for(int weapon_level = 1; weapon_level < hero_stats.bow; weapon_level++)
{
switch (weapon_level)
{
case 1:
hero.abilities.Add(new ShotOfLegends(hero));
break;
case 2:
hero.normal_attack_range++;
break;
case 3:
hero.counter_attacks = true;
break;
case 4:
hero.abilities.Add(new PiercingShot(hero));
break;
case 5:
// Speed shooting. Not implemented
break;
}
}
}
}
|
// Copyright 2006 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Configuration;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using System.Xml;
using System.Web;
namespace Google.Apps.SingleSignOn
{
/// <summary>
/// Provides methods to digital sign Xml documents.
/// </summary>
internal static class XmlDocumentSigner
{
public static void Sign(XmlDocument doc)
{
Sign(doc, LoadRsaKey());
}
// code outline borrowed from: http://blogs.msdn.com/shawnfa/archive/2003/11/12/57030.aspx
public static void Sign(XmlDocument doc, RSA key)
{
SignedXml signer = new SignedXml(doc);
// setup the key used to sign
signer.KeyInfo = new KeyInfo();
signer.KeyInfo.AddClause(new RSAKeyValue(key));
signer.SigningKey = key;
// create a reference to the root of the document
Reference orderRef = new Reference("");
orderRef.AddTransform(new XmlDsigEnvelopedSignatureTransform());
signer.AddReference(orderRef);
// add transforms that only select the order items, type, and
// compute the signature, and add it to the document
signer.ComputeSignature();
doc.DocumentElement.PrependChild(signer.GetXml());
}
// RSA PEM parser: http://www.jensign.com/opensslkey/
public static RSACryptoServiceProvider LoadRsaKey()
{
string xml;
xml = ConfigurationManager.AppSettings["Google.Apps.SingleSignOn.PfxFile"];
xml = HttpUtility.HtmlDecode(xml);
X509Certificate2 cert = new X509Certificate2(xml, "");
RSACryptoServiceProvider crypto = cert.PrivateKey as RSACryptoServiceProvider;
return crypto;
}
}
}
|
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Cryptography;
using Microsoft.Win32.SafeHandles;
namespace Sample
{
internal class X509Native
{
[StructLayout(LayoutKind.Sequential)]
internal struct CryptKeyProvInfo
{
[MarshalAs(UnmanagedType.LPWStr)]
internal string pwszContainerName;
[MarshalAs(UnmanagedType.LPWStr)]
internal string pwszProvName;
internal int dwProvType;
internal int dwFlags;
internal int cProvParam;
internal IntPtr rgProvParam;
internal int dwKeySpec;
}
[SecurityCritical]
internal static unsafe T GetCertificateProperty<T>(
SafeCertContextHandle certificateContext,
NativeMethods.Crypt32.CertificateProperty property
) where T : struct
{
fixed (byte* numRef =
GetCertificateProperty(certificateContext, property))
{
return (T) Marshal.PtrToStructure(new IntPtr(numRef), typeof(T));
}
}
internal enum ErrorCode
{
MoreData = 0xea,
Success = 0
}
[SecurityCritical]
public static byte[] GetCertificateProperty(
SafeCertContextHandle certificateContext,
NativeMethods.Crypt32.CertificateProperty property)
{
var pcbData = 0;
if (!NativeMethods.Crypt32.CertGetCertificateContextProperty(
certificateContext,
property,
null,
ref pcbData)
)
{
var code = (ErrorCode) Marshal.GetLastWin32Error();
if (code != ErrorCode.MoreData)
{
throw new CryptographicException((int) code);
}
}
var pvData = new byte[pcbData];
if (!NativeMethods.Crypt32.CertGetCertificateContextProperty(
certificateContext,
property,
pvData,
ref pcbData)
)
{
throw new CryptographicException(Marshal.GetLastWin32Error());
}
return pvData;
}
[SecurityCritical]
internal static bool HasCertificateProperty(
SafeCertContextHandle certificateContext,
NativeMethods.Crypt32.CertificateProperty property)
{
var pcbData = 0;
if (!NativeMethods.Crypt32.CertGetCertificateContextProperty(
certificateContext,
property,
null,
ref pcbData)
)
{
return Marshal.GetLastWin32Error() == (int)ErrorCode.MoreData;
}
return true;
}
[SecurityCritical]
internal static SafeCertContextHandle DuplicateCertContext(
IntPtr context)
{
return NativeMethods.Crypt32.CertDuplicateCertificateContext(context);
}
[SecurityCritical]
[SuppressMessage(
"Microsoft.Security",
"CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands",
Justification = "Safe use of LinkDemands")]
public static SafeNCryptKeyHandle AcquireCngPrivateKey(
SafeCertContextHandle certificateContext)
{
var freeKey = true;
SafeNCryptKeyHandle privateKey = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
if (!NativeMethods.Crypt32.CryptAcquireCertificatePrivateKey(
certificateContext,
NativeMethods.Crypt32.AcquireCertificateKeyOptions.AcquireOnlyNCryptKeys,
IntPtr.Zero,
out privateKey,
out _,
out freeKey))
{
throw new CryptographicException(Marshal.GetLastWin32Error());
}
return privateKey;
}
finally
{
// If we're not supposed to release they key handle, then we need to
// bump the reference count on the safe handle to correspond to the
// reference that Windows is holding on to.
// This will prevent the CLR from freeing the object handle.
//
// This is certainly not the ideal way to solve this problem - it
// would be better for SafeNCryptKeyHandle to maintain an internal
// bool field that we could toggle here and have that suppress the
// release when the CLR calls the ReleaseHandle override.
// However, that field does not currently exist, so we'll use this
// hack instead.
if (privateKey != null
&&
!freeKey)
{
var addedRef = false;
privateKey.DangerousAddRef(ref addedRef);
}
}
}
}
} |
/*
* Copyright 2014 Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using KaVE.VS.FeedbackGenerator.UserControls.ValueConverter;
using NUnit.Framework;
namespace KaVE.VS.FeedbackGenerator.Tests.UserControls.ValueConverter
{
internal class EnumLocalizationConverterTest
{
private EnumLocalizationConverter _sut;
[SetUp]
public void SetUp()
{
_sut = new EnumLocalizationConverter();
}
[Test]
public void ExistingKeys()
{
var actual = _sut.Convert(TestEnum.ExistingKey, null, null, null);
const string expected = "Localization";
Assert.AreEqual(expected, actual);
}
[Test]
public void NonExistingKeys()
{
var actual = _sut.Convert(TestEnum.NonExistingKey, null, null, null);
const string expected = "%TestEnum_NonExistingKey%";
Assert.AreEqual(expected, actual);
}
[Test, ExpectedException(typeof (NotImplementedException))]
public void ConvertBackIsNotImplemented()
{
_sut.ConvertBack(null, null, null, null);
}
private enum TestEnum
{
ExistingKey,
NonExistingKey
}
}
} |
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace exam
{
public partial class Home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\user1\documents\visual studio 2013\Projects\exam\exam\App_Data\Database1.mdf;Integrated Security=True");
String selectq = "select * from Student";
SqlCommand cmd = new SqlCommand(selectq, con);
con.Open();
SqlDataReader rdr;
rdr = cmd.ExecuteReader();
GridView1.DataSource = rdr;
GridView1.DataBind();
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("login.aspx");
}
}
} |
using UnityEngine;
using UnityEngine.Events;
using System.Collections.Generic;
public class EventManager : MonoBehaviour
{
public enum Triggers {
VAIntroduce,
LearningPhaseStart,
LearningPhaseSpawn,
PickedFruit,
VAOk,
VAKo,
FoundObject,
LearningPhaseEnd,
CheckingPhaseEnd,
CheckingPhaseStart,
LoadingComplete,
VAIntroductionEnd,
BasketEmpty,
SetTargetObject,
GuidedHarvesting,
PickedAnimal,
ObjectPositioning,
CorrectPositioning
};
Dictionary<Triggers, UnityEvent> eventDictionary;
static EventManager eventManager;
public static EventManager instance
{
get
{
if (!eventManager)
{
eventManager = FindObjectOfType(typeof(EventManager)) as EventManager;
if (!eventManager)
{
Debug.LogError("There needs to be one active EventManger script on a GameObject in your scene.");
}
else
{
eventManager.Init();
}
}
return eventManager;
}
}
void Init()
{
if (eventDictionary == null)
{
eventDictionary = new Dictionary<Triggers, UnityEvent>();
}
}
public static void StartListening(Triggers eventName, UnityAction listener)
{
UnityEvent thisEvent = null;
if (instance.eventDictionary.TryGetValue(eventName, out thisEvent))
{
thisEvent.AddListener(listener);
}
else
{
thisEvent = new UnityEvent();
thisEvent.AddListener(listener);
instance.eventDictionary.Add(eventName, thisEvent);
}
}
public static void StopListening(Triggers eventName, UnityAction listener)
{
if (eventManager == null) return;
UnityEvent thisEvent = null;
if (instance.eventDictionary.TryGetValue(eventName, out thisEvent))
{
thisEvent.RemoveListener(listener);
}
}
public static void TriggerEvent(Triggers eventName)
{
UnityEvent thisEvent = null;
if (instance.eventDictionary.TryGetValue(eventName, out thisEvent))
{
thisEvent.Invoke();
}
}
}
|
using Extractor;
using Extractor.Extractors;
using System;
using System.IO;
namespace CommandLine
{
internal static class Program
{
private static string outputFolderPath = "";
private static ExportType exportType;
private static ExportMode exportMode;
private static string mainGameFolder = "";
private static void Main(string[] args)
{
ParseCommandline(args);
RunExtractions();
Console.Out.WriteLine("\nPress Any Key to Quit");
Console.ReadKey();
}
public static void RunExtractions()
{
Console.Out.WriteLine("#---- Starting Extraction Operation ----#");
string exportTypeString;
if (exportType == ExportType.TextList)
{
exportTypeString = "Text List";
}
else if (exportType == ExportType.Json)
{
exportTypeString = "JSON";
}
else
{
exportTypeString = "Text List and JSON";
}
var localizationData = new LocalizationData(mainGameFolder, outputFolderPath);
switch (exportMode)
{
case ExportMode.Item_Extraction:
ExtractItems(localizationData, exportTypeString);
break;
case ExportMode.Location_Extraction:
ExtractLocations(exportTypeString);
break;
case ExportMode.Dump_All_XML:
DumpAllXml();
break;
case ExportMode.Extract_Items_Locations:
ExtractItems(localizationData, exportTypeString);
ExtractLocations(exportTypeString);
break;
case ExportMode.Everything:
ExtractItems(localizationData, exportTypeString);
ExtractLocations(exportTypeString);
DumpAllXml();
break;
}
Console.Out.WriteLine("#---- Finished Extraction Operation ----#");
}
public static void ExtractItems(LocalizationData localizationData, string exportTypeString)
{
Console.Out.WriteLine("--- Starting Extraction of Items as " + exportTypeString + " ---");
new ItemExtractor(mainGameFolder, outputFolderPath, exportMode, exportType).Extract(localizationData);
Console.Out.WriteLine("--- Extraction Complete! ---");
}
public static void ExtractLocations(string exportTypeString)
{
Console.Out.WriteLine("--- Starting Extraction of Locations as " + exportTypeString + " ---");
new LocationExtractor(mainGameFolder, outputFolderPath, exportMode, exportType).Extract();
Console.Out.WriteLine("--- Extraction Complete! ---");
}
public static void DumpAllXml()
{
Console.Out.WriteLine("--- Starting Extraction of All Files as XML ---");
new BinaryDumper().Extract(mainGameFolder, outputFolderPath);
Console.Out.WriteLine("--- Extraction Complete! ---");
}
private static void PrintHelp()
{
Console.WriteLine("How to use:\nao-id-extractor.exe modeID outFormat [outFolder]\n" +
"modeID\t\t#Extraction 0=Item Extraction, 1=Location Extraction, 2=Dump All, 3=Extract Items & Locations, 4=Everything\n" +
"outFormat\t#l=Text List, j=JSON b=Both\n" +
"[outFolder]\t#OPTIONAL: Output folder path. Default: current directory\n" +
"[gameFolder]\t#OPTIONAL: Location of the main AlbionOnline folder");
}
private static void ParseCommandline(string[] args)
{
if (args.Length >= 2)
{
var exportMode = int.Parse(args[0]);
if (exportMode >= 0 && exportMode <= 4)
{
Program.exportMode = (ExportMode)exportMode;
}
else
{
PrintHelp();
return;
}
if (args[1] == "l" || args[1] == "j" || args[1] == "b")
{
exportType = ExportType.Both;
switch (args[1])
{
case "l":
exportType = ExportType.TextList;
break;
case "j":
exportType = ExportType.Json;
break;
}
}
else
{
PrintHelp();
return;
}
if (args.Length >= 3)
{
if (string.IsNullOrWhiteSpace(args[2]))
{
outputFolderPath = Directory.GetCurrentDirectory();
}
else
{
outputFolderPath = args[2];
}
}
if (args.Length == 4)
{
mainGameFolder = args[3];
}
}
else
{
PrintHelp();
}
}
}
}
|
using System.Linq;
using System.Text;
using System.Web;
using IRunes.Data.Models;
using Microsoft.EntityFrameworkCore;
using SIS.HTTP.Requests.Contracts;
using SIS.HTTP.Responses.Contracts;
namespace IRunes.Controllers
{
public class TracksController : BaseController
{
public IHttpResponse Create(IHttpRequest request)
{
var username = this.GetUsername(request);
if (username == null)
{
return this.View("users/login");
}
string albumId = request.QueryData["albumId"].ToString();
this.ViewBag["albumId"] = albumId;
return this.View();
}
public IHttpResponse CreatePost(IHttpRequest request)
{
var username = this.GetUsername(request);
if (username == null)
{
return this.View("users/login");
}
string albumId = request.QueryData["albumId"].ToString();
string name = request.FormData["name"].ToString();
string link = request.FormData["link"].ToString();
decimal price = decimal.Parse(request.FormData["price"].ToString());
if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(link) || price == 0)
{
return this.View("/tracks/create");
}
var album =this.db.Albums.Include(x => x.Tracks).FirstOrDefault(x => x.Id == albumId);
album.Tracks.Add(new Track { Name = name, Link = link, Price = price });
db.SaveChanges();
string albumCover = HttpUtility.UrlDecode(album.Cover);
var tracksPrice = album.Tracks.Sum(x => x.Price);
var tracksPriceAfterDiscount = tracksPrice - (tracksPrice * 13 / 100);
var albumData = new StringBuilder();
albumData.Append($"<br/><img src=\"{albumCover}\" width=\"250\" height=\"250\"><br/>");
albumData.Append($"<b>Name: {album.Name}</b><br/>");
albumData.Append($"<b>Price: ${tracksPriceAfterDiscount}</b><br/>");
var tracks = album.Tracks.ToArray();
var sbTracks = new StringBuilder();
this.ViewBag["tracks"] = "";
if (tracks.Length > 0)
{
foreach (var track in tracks)
{
sbTracks.Append($"<a href=\"/tracks/details?id={track.Id}&albumId={albumId}\">{track.Name}</a></li><br/>");
}
this.ViewBag["tracks"] = sbTracks.ToString();
}
this.ViewBag["albumId"] = album.Id;
this.ViewBag["album"] = albumData.ToString();
return this.View("/albums/details");
}
public IHttpResponse Details(IHttpRequest request)
{
var username = this.GetUsername(request);
if (username == null)
{
return this.View("users/login");
}
//TODO trackId from string to int
var trackId = request.QueryData["id"].ToString();
var albumId = request.QueryData["albumId"].ToString();
var track = this.db.Tracks.FirstOrDefault(x => x.Id == int.Parse(trackId));
string trackLink = HttpUtility.UrlDecode(track.Link);
var trackInfo = new StringBuilder();
trackInfo.Append($"<b>Track Name: {track.Name}</b><br/>");
trackInfo.Append($"<b>Track Price: ${track.Price}</b><br/>");
string trackVideo = $"<iframe class=\"embed-responsive-item\" src=\"{trackLink}\"></iframe><br/>";
this.ViewBag["trackVideo"] = trackVideo;
this.ViewBag["trackInfo"] = trackInfo.ToString();
this.ViewBag["albumId"] = albumId;
return this.View();
}
}
} |
using System.Collections.Generic;
namespace Jacques.DataModel
{
public class ParametrosAutoSuggest
{
public string Agrupamento { get; set; }
public string Bairro { get; set; }
public string Cidade { get; set; }
public string CodAgrupamento { get; set; }
public string CodBairro { get; set; }
public string CodCidade { get; set; }
public string CodCliente { get; set; }
public string CodEstado { get; set; }
public string CodZona { get; set; }
public string Estado { get; set; }
public string NomeCliente { get; set; }
public string Zona { get; set; }
}
public class ResponseStatus
{
public string ErrorCode { get; set; }
public string Errors { get; set; }
public string Message { get; set; }
public string StackTrace { get; set; }
}
public class Foto
{
public int Altura { get; set; }
public string Descricao { get; set; }
public int Largura { get; set; }
public int Origem { get; set; }
public bool Principal { get; set; }
public int TipoOferta { get; set; }
public string UrlImagem { get; set; }
public string UrlImagemTamanhoG { get; set; }
public string UrlImagemTamanhoGG { get; set; }
public string UrlImagemTamanhoM { get; set; }
public string UrlImagemTamanhoP { get; set; }
public string UrlImagemTamanhoPP { get; set; }
}
public class Resultado2
{
public string AnuncianteTipo { get; set; }
public string ApresentarLinkEntrarEmContato { get; set; }
public int Area { get; set; }
public string AreaFormatada { get; set; }
public int AreaMaxima { get; set; }
public int AreaMinima { get; set; }
public string Bairro { get; set; }
public string BairroOficial { get; set; }
public string BlackList { get; set; }
public string CEP { get; set; }
public string Categoria { get; set; }
public string Cidade { get; set; }
public string CidadeOficial { get; set; }
public string ClassBotaoFavorito { get; set; }
public int CodCampanhaImovel { get; set; }
public int CodImobiliaria { get; set; }
public int CodigoAnunciante { get; set; }
public string CodigoOfertaImobiliaria { get; set; }
public int CodigoOfertaZAP { get; set; }
public int CodigoUsuario { get; set; }
public string ContatoCampanha { get; set; }
public string DataAtualizacaoHumanizada { get; set; }
public string DetalhesOferta { get; set; }
public string DistanciaMetro { get; set; }
public string DistanciaOnibus { get; set; }
public string DistanciaTrabalho { get; set; }
public string Empreendimento { get; set; }
public string Endereco { get; set; }
public string Estado { get; set; }
public int EstagioObra { get; set; }
public bool ExibirNotaAnuncio { get; set; }
public string FormatarSubTipoImovel { get; set; }
public string FormatarSubTipoOferta { get; set; }
public List<Foto> Fotos { get; set; }
public string FotosOfertas { get; set; }
public string FotosSerializadas { get; set; }
public string FuncaoOnclickBotaoFavorito { get; set; }
public string IdFavorito { get; set; }
public string IdSchema { get; set; }
public bool IndBloqueadoBlackListOPEC { get; set; }
public bool IndDistrato { get; set; }
public bool IndSitePersonalizado { get; set; }
public bool IndUsuarioOPEC { get; set; }
public string IndiceContatoCampanha { get; set; }
public double Latitude { get; set; }
public string LogNota { get; set; }
public double Longitude { get; set; }
public string MensagemContatePadrao { get; set; }
public string NomeAnunciante { get; set; }
public double Nota { get; set; }
public string Observacao { get; set; }
public string ObterMensagemToolTipTrabalho { get; set; }
public bool OcultadoPeloVisitante { get; set; }
public string OrigemLead { get; set; }
public bool PaginaAnunciante { get; set; }
public string PosicaoRB { get; set; }
public bool PossuiQualidadeTotal { get; set; }
public string PrecoCondominio { get; set; }
public string PrecoVendaMaximo { get; set; }
public string PrecoVendaMinimo { get; set; }
public List<object> ProdutosParceiros { get; set; }
public int QuantidadeQuartos { get; set; }
public string QuantidadeQuartosFormatada { get; set; }
public int QuantidadeQuartosMaxima { get; set; }
public int QuantidadeQuartosMinima { get; set; }
public int QuantidadeSuites { get; set; }
public string QuantidadeSuitesFormatada { get; set; }
public int QuantidadeSuitesMaxima { get; set; }
public int QuantidadeSuitesMinima { get; set; }
public int QuantidadeVagas { get; set; }
public string QuantidadeVagasFormatada { get; set; }
public int QuantidadeVagasMaxima { get; set; }
public int QuantidadeVagasMinima { get; set; }
public int SubTipo { get; set; }
public string SubTipoImovel { get; set; }
public string SubTipoOferta { get; set; }
public List<object> Telefones { get; set; }
public int Tipo { get; set; }
public string TipoDaOferta { get; set; }
public string TituloPagina { get; set; }
public string Transacao { get; set; }
public string URLAtendimento { get; set; }
public string UrlFicha { get; set; }
public string UrlFotoDestaqueTamanhoM { get; set; }
public string UrlFotoDestaqueTamanhoP { get; set; }
public string UrlLogotipoCliente { get; set; }
public bool UtilizarChatParceiro { get; set; }
public string Valor { get; set; }
public string ValorIPTU { get; set; }
public bool VerificarExibicaoUrlLogoCliente { get; set; }
public string ZapID { get; set; }
public string funcaoOnClickEntrarEmContato { get; set; }
public string funcaoOnClickVerTelefone { get; set; }
public bool possuiChat { get; set; }
public bool possuiEmail { get; set; }
public bool possuiTelefone { get; set; }
}
public class SitePersonalizado
{
public string AreaAtuacao { get; set; }
public string CodigoCliente { get; set; }
public string Creci { get; set; }
public bool IndSitePersonalizado { get; set; }
public string LogoCliente { get; set; }
public string NomeCliente { get; set; }
public string TextoInstitucional { get; set; }
}
public class Resultado1
{
public string AreaTotalMaxima { get; set; }
public string AreaTotalMinima { get; set; }
public string AreaUtilMaxima { get; set; }
public string AreaUtilMinima { get; set; }
public bool AtivarNovoResultadoZero { get; set; }
public string BairroOficialResultadoBusca { get; set; }
public string Caracteristica { get; set; }
public string CidadeOficialResultadoBusca { get; set; }
public string CodigoCliente { get; set; }
public string CodigoOferta { get; set; }
public string Contate { get; set; }
public string CriteriosAutoSuggest { get; set; }
public string DebugNota { get; set; }
public string DescricaoPagina { get; set; }
public string EnderecoTrabalho { get; set; }
public string FiltroDormitorios { get; set; }
public string FiltroSuites { get; set; }
public string FiltroVagas { get; set; }
public int Formato { get; set; }
public string FotosOfertas { get; set; }
public string GrupoNavegadores { get; set; }
public string IndDistrato { get; set; }
public bool IndExecutaResultadoZero { get; set; }
public bool IndResultadoCampanha { get; set; }
public bool IndResultadoZero { get; set; }
public bool IndSitePersonalizado { get; set; }
public int IndicePosicaoBanner { get; set; }
public string JsonLD { get; set; }
public double Latitude { get; set; }
public string LatitudeRuaPOI { get; set; }
public string ListaSubtiposLocacao { get; set; }
public string ListaSubtiposVenda { get; set; }
public string Localizacao { get; set; }
public double Longitude { get; set; }
public string LongitudeRuaPOI { get; set; }
public string Navegadores { get; set; }
public string NomeCliente { get; set; }
public string NomeImobiliariaBusca { get; set; }
public string Observacao { get; set; }
public string ObterSugestaoZero { get; set; }
public int Ordenacao { get; set; }
public string POI { get; set; }
public string POICompleta { get; set; }
public int PaginaAtual { get; set; }
public string PaginaAtualFormatado { get; set; }
public int PaginaOrigem { get; set; }
public List<ParametrosAutoSuggest> ParametrosAutoSuggest { get; set; }
public bool PossuiEndereco { get; set; }
public string PossuiFotos { get; set; }
public string PrecoCondominio { get; set; }
public long PrecoMaximo { get; set; }
public string PrecoMinimo { get; set; }
public int QuantidadePaginas { get; set; }
public string QuantidadePaginasFormatado { get; set; }
public int QuantidadeRegistros { get; set; }
public string QuantidadeRegistrosFormatado { get; set; }
public ResponseStatus ResponseStatus { get; set; }
public List<Resultado2> Resultado { get; set; }
public string SemFiador { get; set; }
public string Semente { get; set; }
public SitePersonalizado SitePersonalizado { get; set; }
public string SubTipoImovel { get; set; }
public int SubTipoOferta { get; set; }
public string SugestoesResultadoZero { get; set; }
public List<object> Tags { get; set; }
public string TextoBuscaAberta { get; set; }
public string TextoQuantidadeResultados { get; set; }
public int TipoAnunciante { get; set; }
public List<int> TiposOrdenacao { get; set; }
public string TituloBusca { get; set; }
public string TituloPagina { get; set; }
public int Transacao { get; set; }
public string ValorIPTU { get; set; }
}
public class Breadcrumb
{
public int Ordem { get; set; }
public string TextoAmigavel { get; set; }
public string Url { get; set; }
}
public class Silo2
{
public string Bairro { get; set; }
public string Cidade { get; set; }
public string Conteudo { get; set; }
public string DescricaoLink { get; set; }
public string Dormitorios { get; set; }
public string Estado { get; set; }
public int NumeroDoModulo { get; set; }
public int QuantidadeOfertas { get; set; }
public string TextoAmigavel { get; set; }
public string Tipo { get; set; }
public int TipoSiloRetornado { get; set; }
public int Transacao { get; set; }
public string URL { get; set; }
public string Url { get; set; }
public string Zona { get; set; }
}
public class Silo
{
public int NumeroModulo { get; set; }
public int NumeroOfertas { get; set; }
public List<Silo2> Silos { get; set; }
public string TituloModulo { get; set; }
public string Url { get; set; }
}
public class RootObject
{
public string FaixaPrecoModalAlerta { get; set; }
public string Formato { get; set; }
public bool IsContabilizarAssincrono { get; set; }
public bool IsPaginaAnunciante { get; set; }
public Resultado1 Resultado { get; set; }
public string TituloModalAlerta { get; set; }
public List<Breadcrumb> breadcrumb { get; set; }
public List<Silo> silos { get; set; }
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
namespace SimpleBlogEngine.Web.Models.CommentViewModels
{
public class CommentViewModel
{
public long Id { get; set; }
public string Name { get; set; }
public string Content { get; set; }
public long PostId { get; set; }
public string AddedDate { get; set; }
}
}
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace Filters
{
[Route("filter")]
public class FilterAttributeController : ControllerBase
{
[HttpGet("attribute")]
// at the response headers will be added TestHeader = Hello!
[ResultFilterSample("TestHeader", "Hello!")]
public IActionResult TestFilterAttribute()
{
return Ok();
}
}
public class ResultFilterSampleAttribute : ResultFilterAttribute
{
private string name;
private string value;
public ResultFilterSampleAttribute(string name, string value)
{
this.name = name;
this.value = value;
}
public override void OnResultExecuting(ResultExecutingContext context)
{
context.HttpContext.Response.Headers.Add(name, new string[] { value });
base.OnResultExecuting(context);
}
}
}
|
using System;
using System.Numerics;
class CalculateSum
{
static void Main (string[] args)
{
Console.Write ("Enter N: ");
int n = int.Parse (Console.ReadLine ());
Console.Write ("Enter K: ");
int k = int.Parse (Console.ReadLine ());
BigInteger factN = Factorial (n);
BigInteger factK = Factorial (k);
BigInteger factNMinusK = Factorial (n - k);
BigInteger result = factN / (factK * factNMinusK);
Console.WriteLine ("{0}! / ({1}! * ({0} - {1})!) = {2}", n, k, result);
}
private static BigInteger Factorial (int n)
{
if (n == 0)
return 1;
return n * Factorial (n - 1);
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace API.Omorfias.Domain.Base.Interfaces
{
public interface IDomainEvent
{
int Version { get; }
DateTime OccurrenceDate { get; }
}
}
|
using Hoteles.Modelos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hoteles.BL
{
public class DatosDelClienteBL
{
public List<DatosDelCliente> ListaDeClientes { get; set; }
public DatosDelClienteBL()
{
ListaDeClientes = new List<DatosDelCliente>();
CrearDatosDePrueba();
}
private void CrearDatosDePrueba()
{
var datoDelCliente1 = new DatosDelCliente(1, "Cliente");
var datoDelCliente2 = new DatosDelCliente(2, "Cliente2");
// var categoria3 = new Categoria(3, "Historial de Clientes"); //no se si dejarlo
ListaDeClientes.Add(datoDelCliente1);
ListaDeClientes.Add(datoDelCliente2);
// ListaDeCategorias.Add(categoria3);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TutorialNaikLevel4 : MonoBehaviour
{
public void NaikLevel() {
PlayerPrefs.SetInt("x", 87);
}
}
|
using System;
using System.Collections.Generic;
using Xamarin.Forms;
namespace City_Center.Page
{
public partial class CarruselPage : ContentPage
{
public CarruselPage()
{
InitializeComponent();
//DetailPage = new c(new CarruselPage());
}
}
}
|
using UnityEngine;
using System.Collections;
public class EnumRank
{
public readonly string name;
public readonly long minCoins;
public readonly long maxCoins;
private EnumRank(string name, long minCoins, long maxCoins)
{
this.name = name;
this.minCoins = minCoins;
this.maxCoins = maxCoins;
}
public static EnumRank[] Ranks =
{
new EnumRank("Wimpy N00b", 0L, 0L),
new EnumRank("Junior Seeker", 1L, 5000000L),
new EnumRank("Mediocre Scavenger", 5000000L, 10000000L),
new EnumRank("Assistant Investigator", 10000000L, 20000000L),
new EnumRank("Rising Detective", 20000000L, long.MaxValue)
};
public static EnumRank getRankFromCoins(long numCoins)
{
for (int x = 0; x < EnumRank.Ranks.Length; ++x)
{
if (numCoins <= EnumRank.Ranks[x].maxCoins)
{
return EnumRank.Ranks[x];
}
}
return null;
}
}
|
using Login_WepApi.BusinessLogic;
using Login_WepApi.Models;
using Microsoft.AspNetCore.Cors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;
using System.Web.Http.Cors;
namespace Login_WepApi.Controllers
{
[System.Web.Http.Cors.EnableCors(origins: "*", headers: "*", methods: "*")]
public class LoginController : ApiController
{
private List<User> _userAccessList;
private static List<User> LoggedInUsers = new List<User>();
[HttpPost]
public bool ValidateUsers(User user)
{
ReadUserXml readxml = new ReadUserXml();
try
{
_userAccessList = readxml.GetUserList();
var loggedInUser = _userAccessList.Where(x => x.UserName == user.UserName && x.Password == user.Password).Single();
if (loggedInUser.UserName != null)
{
LoggedInUsers.Add(loggedInUser);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
return true;
}
[HttpGet]
public List<User> GetLoggedInUsers()
{
if (LoggedInUsers!=null )
{
return LoggedInUsers;
}
else
{
return null;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace App1
{
public interface IMovieService
{
Task RefreshDataAsync();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace LuckyGitlabStatWebAPI.Models
{
public class Group
{
//public Group()
//{
// GroupName = "";
// GroupMonitor= "";
// GroupMembers ="";
//}
/// <summary>
/// 组名
/// </summary>
public string GroupName { set; get; }
/// <summary>
/// 组长
/// </summary>
public string GroupMonitor { set; get; }
/// <summary>
/// 小组成员
/// </summary>
public string GroupMembers { set; get; }
}
} |
namespace ns20
{
using System;
using System.Runtime.CompilerServices;
internal delegate U Delegate3<T, U>(T target, params object[] args);
}
|
using System.ComponentModel.DataAnnotations;
namespace LibraryWebApp.Entities
{
public class AuthorRequest
{
[Required]
public string Name { get; set; }
public AuthorRequest(string name)
{
this.Name = name;
}
public AuthorRequest()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using Memmberships.Entities;
namespace Memmberships.Areas.Admin.Models
{
public class SubscriptionProductModel
{
[DisplayName ("Product Id")]
public int ProductId { get; set; }
[DisplayName("Subscritption Id")]
public int SubscriptionId { get; set; }
[DisplayName ("Product Title")]
public string ProductTitle { get; set; }
[DisplayName ("Susbcription Title")]
public string SubscritionTitle { get; set; }
public ICollection <Product> Products { get; set; }
public ICollection <Subscription> Subscriptions { get; set; }
}
} |
//------------------------------------------------------------------------------
// The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.nopCommerce.com/License.aspx.
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
// See the License for the specific language governing rights and limitations under the License.
//
// The Original Code is nopCommerce.
// The Initial Developer of the Original Code is NopSolutions.
// All Rights Reserved.
//
// Contributor(s): _______.
//------------------------------------------------------------------------------
using System;
using NopSolutions.NopCommerce.BusinessLogic;
using NopSolutions.NopCommerce.BusinessLogic.Directory;
using NopSolutions.NopCommerce.BusinessLogic.Orders;
using NopSolutions.NopCommerce.BusinessLogic.Payment;
using NopSolutions.NopCommerce.BusinessLogic.Products;
using NopSolutions.NopCommerce.BusinessLogic.Shipping;
using NopSolutions.NopCommerce.BusinessLogic.Tax;
using NopSolutions.NopCommerce.BusinessLogic.Utils;
namespace NopSolutions.NopCommerce.Web.Modules
{
public partial class OrderTotalsControl : BaseNopUserControl
{
public void BindData()
{
ShoppingCart Cart = ShoppingCartManager.GetCurrentShoppingCart(ShoppingCartTypeEnum.ShoppingCart);
decimal indOrderTotal = 0;
IndividualOrderCollection indOrders = new IndividualOrderCollection();
if (NopContext.Current.Session != null)
{
Guid CustomerSessionGUID = NopContext.Current.Session.CustomerSessionGUID;
indOrders = IndividualOrderManager.GetIndividualOrderByCurrentUserSessionGuid(CustomerSessionGUID);
indOrderTotal = IndividualOrderManager.GetTotalPriceIndOrders(indOrders);
if (Request.Cookies["Currency"] != null && Request.Cookies["Currency"].Value == "USD")
{
indOrderTotal = Math.Round(PriceConverter.ToUsd(indOrderTotal));
}
}
if (Cart.Count > 0 || indOrders.Count > 0)
{
//payment method (if already selected)
int paymentMethodID = 0;
if (NopContext.Current.User != null)
paymentMethodID = NopContext.Current.User.LastPaymentMethodID;
//subtotal
string SubTotalError = string.Empty;
decimal shoppingCartSubTotalDiscountBase;
decimal shoppingCartSubTotalBase = ShoppingCartManager.GetShoppingCartSubTotal(Cart, NopContext.Current.User, out shoppingCartSubTotalDiscountBase, ref SubTotalError);
if (String.IsNullOrEmpty(SubTotalError))
{
decimal shoppingCartSubTotal = CurrencyManager.ConvertCurrency(shoppingCartSubTotalBase, CurrencyManager.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency);
shoppingCartSubTotal += indOrderTotal;
lblSubTotalAmount.Text = PriceHelper.FormatPrice(shoppingCartSubTotal);
if (Request.Cookies["Currency"] != null && Request.Cookies["Currency"].Value == "USD")
{
lblSubTotalAmount.Text += "$";
}
lblSubTotalAmount.CssClass = "productPrice";
if (shoppingCartSubTotalDiscountBase > decimal.Zero)
{
decimal shoppingCartSubTotalDiscount = CurrencyManager.ConvertCurrency(shoppingCartSubTotalDiscountBase, CurrencyManager.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency);
lblSubTotalDiscountAmount.Text = PriceHelper.FormatPrice(shoppingCartSubTotalDiscount, true, false);
phSubTotalDiscount.Visible = true;
}
else
{
phSubTotalDiscount.Visible = false;
}
}
else
{
lblSubTotalAmount.Text = GetLocaleResourceString("ShoppingCart.CalculatedDuringCheckout");
lblSubTotalAmount.CssClass = string.Empty;
}
//shipping info
bool shoppingCartRequiresShipping = ShippingManager.ShoppingCartRequiresShipping(Cart) && Session["SelfOrder"] == null;
if (shoppingCartRequiresShipping)
{
decimal? shoppingCartShippingBase = ShippingManager.GetShoppingCartShippingTotal(Cart, NopContext.Current.User);
if (shoppingCartShippingBase.HasValue)
{
decimal shoppingCartShipping = CurrencyManager.ConvertCurrency(shoppingCartShippingBase.Value, CurrencyManager.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency);
lblShippingAmount.Text = PriceHelper.FormatShippingPrice(shoppingCartShipping, true);
if (Request.Cookies["Currency"] != null && Request.Cookies["Currency"].Value == "USD")
{
lblShippingAmount.Text += "$";
}
lblShippingAmount.CssClass = "productPrice";
}
else
{
lblShippingAmount.Text = GetLocaleResourceString("ShoppingCart.CalculatedDuringCheckout");
lblShippingAmount.CssClass = string.Empty;
}
}
else
{
lblShippingAmount.Text = GetLocaleResourceString("ShoppingCart.ShippingNotRequired");
lblShippingAmount.CssClass = string.Empty;
}
//payment method fee
bool displayPaymentMethodFee = true;
decimal paymentMethodAdditionalFee = PaymentManager.GetAdditionalHandlingFee(paymentMethodID);
decimal paymentMethodAdditionalFeeWithTaxBase = TaxManager.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, NopContext.Current.User);
if (paymentMethodAdditionalFeeWithTaxBase > decimal.Zero)
{
decimal paymentMethodAdditionalFeeWithTax = CurrencyManager.ConvertCurrency(paymentMethodAdditionalFeeWithTaxBase, CurrencyManager.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency);
lblPaymentMethodAdditionalFee.Text = PriceHelper.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeWithTax, true);
}
else
{
displayPaymentMethodFee = false;
}
phPaymentMethodAdditionalFee.Visible = displayPaymentMethodFee;
//tax
bool displayTax = true;
if (TaxManager.HideTaxInOrderSummary && NopContext.Current.TaxDisplayType == TaxDisplayTypeEnum.IncludingTax)
{
displayTax = false;
}
else
{
string TaxError = string.Empty;
decimal shoppingCartTaxBase = TaxManager.GetTaxTotal(Cart, paymentMethodID, NopContext.Current.User, ref TaxError);
decimal shoppingCartTax = CurrencyManager.ConvertCurrency(shoppingCartTaxBase, CurrencyManager.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency);
//if (String.IsNullOrEmpty(TaxError))
//{
// if (shoppingCartTaxBase == 0 && TaxManager.HideZeroTax)
// {
// displayTax = false;
// }
// else
// {
// lblTaxAmount.Text = PriceHelper.FormatPrice(shoppingCartTax, true, false);
// lblTaxAmount.CssClass = "productPrice";
// }
//}
//else
//{
// lblTaxAmount.Text = GetLocaleResourceString("ShoppingCart.CalculatedDuringCheckout");
// lblTaxAmount.CssClass = string.Empty;
//}
}
phTaxTotal.Visible = false;// displayTax;
//total
decimal? shoppingCartTotalBase = ShoppingCartManager.GetShoppingCartTotal(Cart, paymentMethodID, NopContext.Current.User);
if (shoppingCartTotalBase.HasValue)
{
decimal shoppingCartTotal = CurrencyManager.ConvertCurrency(shoppingCartTotalBase.Value, CurrencyManager.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency);
if (Session["SelfOrder"] != null)
shoppingCartTotal -= ShippingManager.GetShoppingCartShippingTotal(Cart).Value;
shoppingCartTotal += indOrderTotal;
lblTotalAmount.Text = PriceHelper.FormatPrice(shoppingCartTotal);
if (Request.Cookies["Currency"] != null && Request.Cookies["Currency"].Value == "USD")
{
lblTotalAmount.Text += "$";
}
lblTotalAmount.CssClass = "productPrice";
}
else
{
lblTotalAmount.Text = GetLocaleResourceString("ShoppingCart.CalculatedDuringCheckout");
lblTotalAmount.CssClass = string.Empty;
}
}
else
{
this.Visible = false;
}
}
}
} |
using System;
using Frontend.Core.Model.Preferences.Interfaces;
namespace Frontend.Core.Model.PreferenceEntries.Interfaces
{
public interface IDatePreferenceEntry : IPreferenceEntry<DateTime, IDatePreference>
{
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tracker : MonoBehaviour {
public static bool endlessUnlocked;
void Start(){
endlessUnlocked = false;
DontDestroyOnLoad (this.transform.gameObject);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using System.Web.Mvc;
using Rastreador.Models;
namespace Rastreador
{
[MetadataType(typeof(TemplateMD))]
public partial class Template
{
public string TemplateFomatado(Encomenda e) {
string texto = HTML;
texto = texto.Replace("{Nome}", e.Nome);
texto = texto.Replace("{Data}", e.DataUltimaAtualizacao.ToString("dd/MM/yyyy HH:mm"));
string ultimaat = e.Status;
if (ultimaat == "Encaminhado") {
ultimaat = e.UltimaAtualizacao;
}
texto = texto.Replace("{Status}", ultimaat);
return texto;
}
}
public partial class TemplateMD
{
[Required(ErrorMessage = "* Campo requerido")]
[DisplayName("HTML:")]
[DataType(DataType.Html)]
[AllowHtml]
public string HTML { get; set; }
}
}
|
//
// 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.ComponentModel;
namespace DotNetNuke.Entities.Portals.Internal
{
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Deprecated in DotNetNuke 7.3.0. Use PortalController.Instance.GetCurrentPortalSettings to get a mockable PortalSettings. Scheduled removal in v10.0.0.")]
public interface IPortalSettings
{
string AdministratorRoleName { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test7._11
{
class Test {
public static int waterYield = 0;//储水量
//注水
public static void AddWater() {
if (waterYield >= 100){
Console.WriteLine("水已满,无法在注水");
} else {
waterYield += 10;
Console.WriteLine("已注入10升水,当前已注入{0}升水", waterYield);
}
}
//放水
public static void MinusWater() {
if (waterYield <= 0)
{
Console.WriteLine("水已放空无法继续放水");
}
else
{
waterYield -= 10;
Console.WriteLine("已放10升水,当前还剩{0}升水", waterYield);
}
}
}
class Program
{
static void Main(string[] args)
{
while (Test.waterYield < 100)
{
//注水
Test.AddWater();
}
while (Test.waterYield >0)
{
//放水
Test.MinusWater();
}
Console.ReadKey();
}
}
}
|
namespace StudentGroups
{
using System;
using System.Collections.Generic;
using System.Linq;
public static class Extensions
{
public static List<Student> OrderGroups(this List<Student> list) //where T: Student
{
List<Student> ordered =
list.Where(x => x.GroupNumber == 2).OrderBy(x => x.FirstName).ToList();
return ordered;
}
public static bool HaveTwoPoorMarks(this Student student)
{
int count = 0;
foreach (var mark in student.Marks)
{
if (mark == 2) count++;
}
if (count == 2) return true;
else return false;
}
public static string OrderByGroupName(this List<Student> list)
{
var groupedByGroupNumber = list
.OrderBy(x => x.GroupNumber)
.Select(x => new
{
Name = string.Format("{0,-20} ", x.FirstName + " " + x.LastName),
Group = x.GroupNumber
});
return string.Join(Environment.NewLine, groupedByGroupNumber);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MazeLib;
using SearchAlgorithmsLib;
namespace WebServer
{
//public class MultiGame
//public abstract class Game
public class MultiGame : Game
{
//private string name;
//protected string name;
//private Maze maze;
//protected Maze maze;
//private Solution<Position> solution;
//protected Solution<Position> solution;
//private List</*ClientNotifier*/string> gamers;
private string myPlayer;
private string otherPlayer;
/*/// <summary>
/// Gets or sets the maze.
/// </summary>
/// <value>
/// The maze.
/// </value>
public Maze Maze
{
get { return maze; }
set { maze = value; }
}
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>
/// The name.
/// </value>
public string Name
{
get { return name; }
set { name = value; }
}
/// <summary>
/// Initializes a new instance of the <see cref="MultiGame"/> class.
/// </summary>
/// <param name="name2">The name.</param>
/// <param name="maze2">The maze.</param>
/// <param name="solution2">The solution.</param>*/
//public MultiGame (string name2, Maze maze2, Solution<Position> solution2)
//public MultiGame ()
public MultiGame (string name2, Maze maze2, string playerName/*, Solution<Position> solution2*/) :
base (name2, maze2/*, solution2*/)
{
myPlayer = playerName;
otherPlayer = "";
//gamers = new List<ClientNotifier>();
}
/// <summary>
/// Adds the gamer.
/// </summary>
/// <param name="gamer">The gamer.</param>
public void AddGamer (/*ClientNotifier*/ string gamer)
{
//gamers.Add(gamer);
otherPlayer = gamer;
}
public string GetOtherPlayerName(string name)
{
if (IsAGamer(name))
{
if (myPlayer == name)
{
return otherPlayer;
}
else if (otherPlayer == name)
{
return myPlayer;
}
}
return "not a gamer";
}
/*/// <summary>
/// Notifies the gamers to send the message.
/// </summary>
public void NotifyGamers ()
//public void Notify ()
{
for (int i = 0; i < gamers.Count; i++)
{
//gamers.ElementAt(i).ToSend = true;
}
}*/
/// <summary>
/// Determines whether a gamer is a gamer.
/// </summary>
/// <param name="gamer">The gamer.</param>
/// <returns>
/// <c>true</c> if [is a gamer] [the specified gamer]; otherwise, <c>false</c>.
/// </returns>
private bool IsAGamer ( string gamer)
{
/*for (int i = 0; i < gamers.Count; i++)
{
if (gamers.ElementAt(i).Equals(gamer))
{
return true;
}
}*/
if ((myPlayer == gamer) || (otherPlayer == gamer))
{
return true;
}
return false;
}
/*/// <summary>
/// Updates the move.
/// </summary>
/// <param name="data">The data.</param>
/// <param name="gamer">The gamer.</param>
public void UpdateMove (string data, /*ClientNotifier string gamer)
{
//gamer.ToSend = false;
//gamer.Data = "";
for (int i = 0; i < gamers.Count; i++)
{
if (gamers.ElementAt(i).Equals(gamer))
{
continue;
}
//gamers.ElementAt(i).ToSend = true;
//gamers.ElementAt(i).Data = data;
}
}
/// <summary>
/// Closes the game.
/// </summary>
public void CloseGame ()
{
for (int i = 0; i < gamers.Count; i++)
{
//gamers.ElementAt(i).ChangeToClose = true;
//gamers.ElementAt(i).ToSend = true;
//gamers.ElementAt(i).Data = "close";
}
}*/
}
}
|
using PDV.DAO.Atributos;
namespace PDV.DAO.Entidades
{
public class Cfop
{
[CampoTabela("IDCFOP")]
[MaxLength(18)]
public decimal IDCfop { get; set; }
[CampoTabela("CODIGO")]
[MaxLength(4)]
public string Codigo { get; set; }
[CampoTabela("DESCRICAO")]
[MaxLength(250)]
public string Descricao { get; set; }
[CampoTabela("CODIGODESCRICAO")]
public string CodigoDescricao { get; set; }
[CampoTabela("ATIVO")]
[MaxLength(1)]
public decimal Ativo { get; set; } = 1;
[CampoTabela("TIPO")]
[MaxLength(1)]
public string Tipo { get; set; }
public Cfop()
{
}
}
}
|
using Microsoft.AspNetCore.Mvc;
using MRGGameTek.Models.Register;
using System.Text.Json;
using System.Threading.Tasks;
namespace MRGGameTek.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class RegisterController : ControllerBase
{
private readonly IRegisterRepository<MrGreen> _mrGreenRepository;
private readonly IRegisterRepository<RedBet> _redBetRepository;
public RegisterController(IRegisterRepository<MrGreen> mrGreenRepository, IRegisterRepository<RedBet> redBetRepository)
{
_mrGreenRepository = mrGreenRepository;
_redBetRepository = redBetRepository;
}
[HttpPost]
public async Task<IActionResult> Post([FromHeader] string tenantId)
{
if (string.IsNullOrEmpty(tenantId))
{
ModelState.AddModelError("tenantId", "Please provide your tenant ID in the tenantId header value");
return BadRequest(ModelState);
}
//Can be moved to mediatr cqrs
if (tenantId == "mrgreen")
{
return RegisterMrGreen(await JsonSerializer.DeserializeAsync<MrGreen>(Request.BodyReader.AsStream(true)));
}
else if (tenantId == "redbet")
{
return RegisterRedBet(await JsonSerializer.DeserializeAsync<RedBet>(Request.BodyReader.AsStream(true)));
}
else
{
return BadRequest();
}
}
private IActionResult RegisterRedBet(RedBet registrar)
{
registrar.Validate(ModelState);
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_redBetRepository.Register(registrar);
return Ok();
}
private IActionResult RegisterMrGreen(MrGreen registrar)
{
registrar.Validate(ModelState);
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_mrGreenRepository.Register(registrar);
return Ok();
}
}
}
|
using System;
using UnityEngine;
namespace ProBuilder2.Common
{
public class pb_XYZ_Color
{
public float x;
public float y;
public float z;
public pb_XYZ_Color(float x, float y, float z)
{
this.x = x;
this.y = y;
this.z = z;
}
public static pb_XYZ_Color FromRGB(Color col)
{
return pb_ColorUtil.RGBToXYZ(col);
}
public static pb_XYZ_Color FromRGB(float R, float G, float B)
{
return pb_ColorUtil.RGBToXYZ(R, G, B);
}
public override string ToString()
{
return string.Format("( {0}, {1}, {2} )", this.x, this.y, this.z);
}
}
}
|
using LuaInterface;
using SLua;
using System;
using UnityEngine;
public class Lua_UnityEngine_Bounds : LuaObject
{
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int constructor(IntPtr l)
{
int result;
try
{
Vector3 vector;
LuaObject.checkType(l, 2, out vector);
Vector3 vector2;
LuaObject.checkType(l, 3, out vector2);
Bounds bounds = new Bounds(vector, vector2);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, bounds);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int SetMinMax(IntPtr l)
{
int result;
try
{
Bounds bounds;
LuaObject.checkValueType<Bounds>(l, 1, out bounds);
Vector3 vector;
LuaObject.checkType(l, 2, out vector);
Vector3 vector2;
LuaObject.checkType(l, 3, out vector2);
bounds.SetMinMax(vector, vector2);
LuaObject.pushValue(l, true);
LuaObject.setBack(l, bounds);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int Encapsulate(IntPtr l)
{
int result;
try
{
int total = LuaDLL.lua_gettop(l);
if (LuaObject.matchType(l, total, 2, typeof(Bounds)))
{
Bounds bounds;
LuaObject.checkValueType<Bounds>(l, 1, out bounds);
Bounds bounds2;
LuaObject.checkValueType<Bounds>(l, 2, out bounds2);
bounds.Encapsulate(bounds2);
LuaObject.pushValue(l, true);
LuaObject.setBack(l, bounds);
result = 1;
}
else if (LuaObject.matchType(l, total, 2, typeof(Vector3)))
{
Bounds bounds3;
LuaObject.checkValueType<Bounds>(l, 1, out bounds3);
Vector3 vector;
LuaObject.checkType(l, 2, out vector);
bounds3.Encapsulate(vector);
LuaObject.pushValue(l, true);
LuaObject.setBack(l, bounds3);
result = 1;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int Expand(IntPtr l)
{
int result;
try
{
int total = LuaDLL.lua_gettop(l);
if (LuaObject.matchType(l, total, 2, typeof(Vector3)))
{
Bounds bounds;
LuaObject.checkValueType<Bounds>(l, 1, out bounds);
Vector3 vector;
LuaObject.checkType(l, 2, out vector);
bounds.Expand(vector);
LuaObject.pushValue(l, true);
LuaObject.setBack(l, bounds);
result = 1;
}
else if (LuaObject.matchType(l, total, 2, typeof(float)))
{
Bounds bounds2;
LuaObject.checkValueType<Bounds>(l, 1, out bounds2);
float num;
LuaObject.checkType(l, 2, out num);
bounds2.Expand(num);
LuaObject.pushValue(l, true);
LuaObject.setBack(l, bounds2);
result = 1;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int Intersects(IntPtr l)
{
int result;
try
{
Bounds bounds;
LuaObject.checkValueType<Bounds>(l, 1, out bounds);
Bounds bounds2;
LuaObject.checkValueType<Bounds>(l, 2, out bounds2);
bool b = bounds.Intersects(bounds2);
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 Contains(IntPtr l)
{
int result;
try
{
Bounds bounds;
LuaObject.checkValueType<Bounds>(l, 1, out bounds);
Vector3 vector;
LuaObject.checkType(l, 2, out vector);
bool b = bounds.Contains(vector);
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 SqrDistance(IntPtr l)
{
int result;
try
{
Bounds bounds;
LuaObject.checkValueType<Bounds>(l, 1, out bounds);
Vector3 vector;
LuaObject.checkType(l, 2, out vector);
float o = bounds.SqrDistance(vector);
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 IntersectRay(IntPtr l)
{
int result;
try
{
int num = LuaDLL.lua_gettop(l);
if (num == 2)
{
Bounds bounds;
LuaObject.checkValueType<Bounds>(l, 1, out bounds);
Ray ray;
LuaObject.checkValueType<Ray>(l, 2, out ray);
bool b = bounds.IntersectRay(ray);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, b);
result = 2;
}
else if (num == 3)
{
Bounds bounds2;
LuaObject.checkValueType<Bounds>(l, 1, out bounds2);
Ray ray2;
LuaObject.checkValueType<Ray>(l, 2, out ray2);
float o;
bool b2 = bounds2.IntersectRay(ray2, ref o);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, b2);
LuaObject.pushValue(l, o);
result = 3;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int ClosestPoint(IntPtr l)
{
int result;
try
{
Bounds bounds;
LuaObject.checkValueType<Bounds>(l, 1, out bounds);
Vector3 vector;
LuaObject.checkType(l, 2, out vector);
Vector3 o = bounds.ClosestPoint(vector);
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 op_Equality(IntPtr l)
{
int result;
try
{
Bounds bounds;
LuaObject.checkValueType<Bounds>(l, 1, out bounds);
Bounds bounds2;
LuaObject.checkValueType<Bounds>(l, 2, out bounds2);
bool b = bounds == bounds2;
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 op_Inequality(IntPtr l)
{
int result;
try
{
Bounds bounds;
LuaObject.checkValueType<Bounds>(l, 1, out bounds);
Bounds bounds2;
LuaObject.checkValueType<Bounds>(l, 2, out bounds2);
bool b = bounds != bounds2;
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 get_center(IntPtr l)
{
int result;
try
{
Bounds bounds;
LuaObject.checkValueType<Bounds>(l, 1, out bounds);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, bounds.get_center());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_center(IntPtr l)
{
int result;
try
{
Bounds bounds;
LuaObject.checkValueType<Bounds>(l, 1, out bounds);
Vector3 center;
LuaObject.checkType(l, 2, out center);
bounds.set_center(center);
LuaObject.setBack(l, bounds);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_size(IntPtr l)
{
int result;
try
{
Bounds bounds;
LuaObject.checkValueType<Bounds>(l, 1, out bounds);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, bounds.get_size());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_size(IntPtr l)
{
int result;
try
{
Bounds bounds;
LuaObject.checkValueType<Bounds>(l, 1, out bounds);
Vector3 size;
LuaObject.checkType(l, 2, out size);
bounds.set_size(size);
LuaObject.setBack(l, bounds);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_extents(IntPtr l)
{
int result;
try
{
Bounds bounds;
LuaObject.checkValueType<Bounds>(l, 1, out bounds);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, bounds.get_extents());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_extents(IntPtr l)
{
int result;
try
{
Bounds bounds;
LuaObject.checkValueType<Bounds>(l, 1, out bounds);
Vector3 extents;
LuaObject.checkType(l, 2, out extents);
bounds.set_extents(extents);
LuaObject.setBack(l, bounds);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_min(IntPtr l)
{
int result;
try
{
Bounds bounds;
LuaObject.checkValueType<Bounds>(l, 1, out bounds);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, bounds.get_min());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_min(IntPtr l)
{
int result;
try
{
Bounds bounds;
LuaObject.checkValueType<Bounds>(l, 1, out bounds);
Vector3 min;
LuaObject.checkType(l, 2, out min);
bounds.set_min(min);
LuaObject.setBack(l, bounds);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_max(IntPtr l)
{
int result;
try
{
Bounds bounds;
LuaObject.checkValueType<Bounds>(l, 1, out bounds);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, bounds.get_max());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_max(IntPtr l)
{
int result;
try
{
Bounds bounds;
LuaObject.checkValueType<Bounds>(l, 1, out bounds);
Vector3 max;
LuaObject.checkType(l, 2, out max);
bounds.set_max(max);
LuaObject.setBack(l, bounds);
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, "UnityEngine.Bounds");
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Bounds.SetMinMax));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Bounds.Encapsulate));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Bounds.Expand));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Bounds.Intersects));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Bounds.Contains));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Bounds.SqrDistance));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Bounds.IntersectRay));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Bounds.ClosestPoint));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Bounds.op_Equality));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Bounds.op_Inequality));
LuaObject.addMember(l, "center", new LuaCSFunction(Lua_UnityEngine_Bounds.get_center), new LuaCSFunction(Lua_UnityEngine_Bounds.set_center), true);
LuaObject.addMember(l, "size", new LuaCSFunction(Lua_UnityEngine_Bounds.get_size), new LuaCSFunction(Lua_UnityEngine_Bounds.set_size), true);
LuaObject.addMember(l, "extents", new LuaCSFunction(Lua_UnityEngine_Bounds.get_extents), new LuaCSFunction(Lua_UnityEngine_Bounds.set_extents), true);
LuaObject.addMember(l, "min", new LuaCSFunction(Lua_UnityEngine_Bounds.get_min), new LuaCSFunction(Lua_UnityEngine_Bounds.set_min), true);
LuaObject.addMember(l, "max", new LuaCSFunction(Lua_UnityEngine_Bounds.get_max), new LuaCSFunction(Lua_UnityEngine_Bounds.set_max), true);
LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_UnityEngine_Bounds.constructor), typeof(Bounds), typeof(ValueType));
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
namespace QLHD
{
/// <summary>
/// Class contain common enums in project
/// </summary>
public class CommonEnum
{
public enum FileExtension
{
Doc,
Docx,
Xls,
Xlsx,
Pdf,
Rar,
Zip,
Jpg,
Jpeg,
Png
}
public enum TapTinObjectLoai
{
BieuMau
}
public enum NhomThoiGian { tuan, thang, quy, nam };
}
} |
using UnityEngine;
using System.Collections;
public class BagDrag : MonoBehaviour {
private float downTime;
private bool isHandled;
private float lastClick = 0f;
private float waitTime = 0f;
private float start_y;
private Vector3 start_rotation;
void OnMouseDown () {
start_y = gameObject.GetComponent<Rigidbody>().position.y; // record the initial height of the box
start_rotation = gameObject.transform.localEulerAngles;
//start recording the time when a key is pressed and held.
downTime = Time.time;
isHandled = false;
lastClick = Time.time;
}
void OnMouseDrag(){
//open a menu when the key has been held for long enough.
if((Time.time > downTime + waitTime) && !isHandled){
Camera mainCamera = Camera.main;
Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
Plane hPlane = new Plane(Vector3.up,new Vector3(0f,gameObject.GetComponent<Rigidbody>().position.y,0f));//start_y,0f));
float distance = 0;
if(hPlane.Raycast(ray,out distance))
{
//gameObject.rigidbody.position.
gameObject.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.None;//.FreezePositionY;
gameObject.GetComponent<Rigidbody>().isKinematic = false;
gameObject.GetComponent<Rigidbody>().position = ray.GetPoint(distance);
//gameObject.transform.localEulerAngles = new Vector3(start_rotation.x,gameObject.gameObject.transform.localEulerAngles.y,start_rotation.z);
}
}
}
void OnMouseUp(){
if(!gameObject.GetComponent<Bag>().one_click)
{
UnityEngine.GameObject new_bag = (GameObject)Instantiate(gameObject,gameObject.transform.position,Quaternion.Euler(start_rotation.x,gameObject.gameObject.transform.localEulerAngles.y,start_rotation.z));
new_bag.GetComponent<Rigidbody>().isKinematic = false;
//gameObject.transform.localEulerAngles = new Vector3(;
Destroy(gameObject);
}
isHandled = true;// reset the timer for the next button press
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Console2.From_001_To_025
{
public class _006_AllSumUp
{
/*
* Given an integer (assume it's smaller than 50), write an algorithm that will generate all possible
* combinations of integers greater than 1 and they produce a sum equals to this number. The same number
* can appear more than once in a combination. What's the time complexity of your algorithm?
For example:
<=1 -> {}
2 -> {2},
3->{3},
4->{[4], [2, 2]},
5->{[5], [3, 2]},
6->{[6], [4, 2], [3, 3], [2, 2, 2]}
7->{[7], [5, 2], [4, 3], [3, 2, 2]}
8->{[8], [6, 2], [5, 3], [4, 4], [4, 2, 2], [3, 3, 2], [2, 2, 2, 2]}
*/
/// <summary>
///
/// </summary>
/// <param name="n"></param>
public void FindAllSumUpToANumber(int n)
{
}
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BaseConcurrentEntity.cs" company="CGI">
// Copyright (c) CGI. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CGI.Reflex.Core.Entities
{
public abstract class BaseConcurrentEntity : BaseEntity, IOptimisticConcurrency
{
#pragma warning disable 649
private int _concurrencyVersion;
#pragma warning restore 649
public virtual int ConcurrencyVersion
{
get { return _concurrencyVersion; }
}
}
}
|
using System.Threading.Tasks;
using System.Windows.Input;
namespace GistManager.Mvvm.Commands.Async.AsyncRelayCommand
{
public interface IAsyncRelayCommand : ICommand
{
Task ExecuteAsync(object parameter);
}
} |
using System;
using System.Collections.Generic;
namespace Yasl
{
public class KeyValuePairSerializer<TKey, TValue> : ISerializer
{
public void SerializeConstructor(ref object value, ISerializationWriter writer)
{
}
public void SerializeContents(ref object value, ISerializationWriter writer)
{
var kvp = (KeyValuePair<TKey, TValue>)value;
writer.Write(typeof(TKey), "Key", kvp.Key);
writer.Write(typeof(TValue), "Value", kvp.Value);
}
public void SerializeBacklinks(ref object value, ISerializationWriter writer)
{
}
public void DeserializeConstructor(out object value, int version, ISerializationReader reader)
{
value = null;
}
public void DeserializeContents(ref object value, int version, ISerializationReader reader)
{
TKey kvpKey = reader.Read<TKey>("Key");
TValue kvpValue = reader.Read<TValue>("Value");
value = new KeyValuePair<TKey, TValue>(kvpKey, kvpValue);
}
public void DeserializeBacklinks(ref object value, int version, ISerializationReader reader)
{
}
public void DeserializationComplete(ref object value, int version)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Rastreador;
using Rastreador.Models;
using Microsoft.Security.Application;
using Helpers;
namespace Rastreador.Controllers
{
[Authorize(Roles="admin")]
public class TemplateController : Controller
{
private readonly ITemplateRepository templateRepository;
// If you are using Dependency Injection, you can delete the following constructor
public TemplateController() : this(new TemplateRepository())
{
}
public TemplateController(ITemplateRepository templateRepository)
{
this.templateRepository = templateRepository;
}
//
// GET: /Template/
public ViewResult Index()
{
return View(templateRepository.AllIncluding(template => template.Usuario));
}
//
// GET: /Template/Details/5
public ViewResult Details(int id)
{
return View(templateRepository.Find(id));
}
//
// GET: /Template/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Template/Create
[HttpPost]
public ActionResult Create(Template template)
{
if (ModelState.IsValid) {
//HtmlUtility util = HtmlUtility.Instance;
//template.HTML = util.SanitizeHtml(template.HTML);
templateRepository.InsertOrUpdate(template);
templateRepository.Save();
return RedirectToAction("Index");
} else {
return View();
}
}
//
// GET: /Template/Edit/5
public ActionResult Edit(int id)
{
return View(templateRepository.Find(id));
}
//
// POST: /Template/Edit/5
[HttpPost]
public ActionResult Edit(Template template)
{
if (ModelState.IsValid) {
//HtmlUtility util = HtmlUtility.Instance;
//template.HTML = util.SanitizeHtml(template.HTML);
templateRepository.InsertOrUpdate(template);
templateRepository.Save();
return RedirectToAction("Index");
} else {
return View();
}
}
//
// GET: /Template/Delete/5
public ActionResult Delete(int id)
{
return View(templateRepository.Find(id));
}
//
// POST: /Template/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
templateRepository.Delete(id);
templateRepository.Save();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing) {
templateRepository.Dispose();
}
base.Dispose(disposing);
}
}
}
|
using System.Collections.Generic;
using Common.Geometry;
using OpenTK;
namespace OcTreeRevisited.OcTree
{
public class OcTreeItem
{
public OcTreeItem(BoundingVolume volume)
{
Volume = volume;
Objects = new List<GameObject>();
TryClearChildren();
HalfSize = volume.Width * 0.5f;
}
public int Number { get; set; }
public float HalfSize { get; set; }
public List<GameObject> Objects { get; set; }
public OcTreeItem[] Children { get; set; }
public BoundingVolume Volume { get; set; }
public int Level { get; internal set; }
public int InsertedObjectsCount { get; set; }
public bool IsLeaf => Children[0] == null;// && Objects.Count == 0;
public void AddObject(GameObject obj)
{
Objects.Add(obj);
AssureChildrenInitialized();
}
public BoundingVolume Insert(GameObject dataToInsert)
{
BoundingVolume insertedWhere = null;
var maxDimensionObject = dataToInsert.BoundingBox.MaxDimension;
bool forceSetToChildren = Volume.MaxDimension > maxDimensionObject * 10;
if (IsLeaf && !forceSetToChildren)
{
AddObject(dataToInsert);
insertedWhere = Volume;
}
else
{
AssureChildrenInitialized();
var child = Children.FindVolume(dataToInsert);
if (child != null)
{
insertedWhere = child.Insert(dataToInsert);
InsertedObjectsCount++;
var old = new List<GameObject>(Objects);
foreach (var o in old)
{
Objects.Remove(o);
Insert(o);
}
}
else
{
AddObject(dataToInsert);
insertedWhere = Volume;
}
}
dataToInsert.TreeSegment = insertedWhere;
return insertedWhere;
}
public override string ToString()
{
string res = string.Format("L {0}, N {1}, Hs {2}, (", Level, Number, HalfSize);
foreach (var o in Objects)
{
res += o.Name + ", ";
}
res = res.Trim(',');
res += ")";
return res;
}
/// <summary>
/// возвращает число удаленных
/// </summary>
/// <param name="dataToRemove"></param>
public int Remove(GameObject dataToRemove)
{
int result = 0;
var inside = Volume.Contains(dataToRemove.BoundingBox);
if (inside)
{
if (Objects.Remove(dataToRemove))
{
dataToRemove.TreeSegment = null;
result = 1;
}
else
{
var child = Children.FindVolume(dataToRemove);
if (child != null)
{
result = child.Remove(dataToRemove);
InsertedObjectsCount -= result;
TryClearChildren();
}
else
{
int i = 10;
i++;
}
}
}
return result;
}
private void TryClearChildren()
{
if (InsertedObjectsCount == 0)
{
Children = new OcTreeItem[8];
}
}
private void AssureChildrenInitialized()
{
if (Children[0] == null)
{
var parentCentre = Volume.Centre;
var h = HalfSize;
CreateChild0(parentCentre, h);
CreateChild1(parentCentre, h);
CreateChild2(parentCentre, h);
CreateChild3(parentCentre, h);
CreateChild4(parentCentre, h);
CreateChild5(parentCentre, h);
CreateChild6(parentCentre, h);
CreateChild7(parentCentre, h);
foreach (var child in Children)
{
child.Level = Level + 1;
}
}
}
#region создание дочерних узлов
private void CreateChild0(Vector3 parentCentre, float halfSize)
{
var bottom = new Vector3(parentCentre.X - halfSize, parentCentre.Y, parentCentre.Z - halfSize);
var top = new Vector3(parentCentre.X, parentCentre.Y + halfSize, parentCentre.Z);
var b0 = new BoundingVolume(bottom, top);
Children[0] = new OcTreeItem(b0) { Number = 0 };
}
private void CreateChild1(Vector3 centre, float halfSize)
{
var bottom = new Vector3(centre.X, centre.Y, centre.Z - halfSize);
var top = new Vector3(centre.X + halfSize, centre.Y + halfSize, centre.Z);
var b0 = new BoundingVolume(bottom, top);
Children[1] = new OcTreeItem(b0) { Number = 1 };
}
private void CreateChild2(Vector3 centre, float halfSize)
{
var bottom = new Vector3(centre.X, centre.Y, centre.Z);
var top = new Vector3(centre.X + halfSize, centre.Y + halfSize, centre.Z + halfSize);
var b0 = new BoundingVolume(bottom, top);
Children[2] = new OcTreeItem(b0) { Number = 2 };
}
private void CreateChild3(Vector3 centre, float halfSize)
{
var bottom = new Vector3(centre.X - halfSize, centre.Y, centre.Z);
var top = new Vector3(centre.X, centre.Y + halfSize, centre.Z + halfSize);
var b0 = new BoundingVolume(bottom, top);
Children[3] = new OcTreeItem(b0) { Number = 3 };
}
private void CreateChild4(Vector3 centre, float HalfSize)
{
var bottom = new Vector3(centre.X - HalfSize, centre.Y - HalfSize, centre.Z - HalfSize);
var top = new Vector3(centre.X, centre.Y, centre.Z);
var b4 = new BoundingVolume(bottom, top);
Children[4] = new OcTreeItem(b4) { Number = 4 };
}
private void CreateChild5(Vector3 centre, float HalfSize)
{
var bottom = new Vector3(centre.X, centre.Y - HalfSize, centre.Z - HalfSize);
var top = new Vector3(centre.X + HalfSize, centre.Y, centre.Z);
var b0 = new BoundingVolume(bottom, top);
Children[5] = new OcTreeItem(b0) { Number = 5 };
}
private void CreateChild6(Vector3 centre, float HalfSize)
{
var bottom = new Vector3(centre.X, centre.Y - HalfSize, centre.Z);
var top = new Vector3(centre.X + HalfSize, centre.Y, centre.Z + HalfSize);
var b0 = new BoundingVolume(bottom, top);
Children[6] = new OcTreeItem(b0) { Number = 6 };
}
private void CreateChild7(Vector3 centre, float HalfSize)
{
var bottom = new Vector3(centre.X - HalfSize, centre.Y - HalfSize, centre.Z);
var top = new Vector3(centre.X, centre.Y, centre.Z + HalfSize);
var b0 = new BoundingVolume(bottom, top);
Children[7] = new OcTreeItem(b0) { Number = 7 };
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Beamore.Contracts.DataTransferObjects.Account
{
/// <summary>
/// Result message after registration
/// </summary>
public class RegistrationResultDTO
{
/// <summary>
/// if register is success then return true otherwise return false
/// </summary>
public bool IsSuccess{ get; set; }
/// <summary>
/// İf there is error than return error message
/// </summary>
public string Message { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Shared.Notifications
{
public class ServiceNotifications
{
public List<string> ValidationMessages { get; set; }
public bool Invalid { get { return ValidationMessages.Count > 0; } }
}
}
|
using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
using CGCN.Framework;
using Npgsql;
using NpgsqlTypes;
using CGCN.DataAccess;
using PhieuNhapKho.DataAccess;
namespace PhieuNhapKho.BusinesLogic
{
/// <summary>
/// Mô tả thông tin cho bảng tblphieunhapkho
/// Cung cấp các hàm xử lý, thao tác với bảng tblphieunhapkho
/// Người tạo (C): tuanva
/// Ngày khởi tạo: 03/12/2015
/// </summary>
public class tblphieunhapkhoBL
{
private tblphieunhapkho objtblphieunhapkhoDA = new tblphieunhapkho();
public tblphieunhapkhoBL() { objtblphieunhapkhoDA = new tblphieunhapkho(); }
#region Public Method
/// <summary>
/// Lấy toàn bộ dữ liệu từ bảng tblphieunhapkho
/// </summary>
/// <returns>DataTable</returns>
public DataTable GetAll()
{
return objtblphieunhapkhoDA.GetAll();
}
/// <summary>
/// Hàm lấy tblphieunhapkho theo mã
/// </summary>
/// <returns>Trả về objtblphieunhapkho </returns>
public tblphieunhapkho GetByID(string strid)
{
return objtblphieunhapkhoDA.GetByID(strid);
}
/// <summary>
/// Hàm lấy hóa đơn nhập mới nhất theo ngày tạo(chặn cuối) và mã nhà cung cấp
/// </summary>
/// <param name="sngaytao">Ngày tạo kiểu string format: yyyy/MM/dd</param>
/// <param name="sidnhacc">Mã nhà cung cấp kiểu string</param>
/// <returns>tblphieunhapkho</returns>
public tblphieunhapkho GetNewFirstByNgayTaovsIDKH(string sngaytao, string sidnhacc)
{ return objtblphieunhapkhoDA.GetNewFirstByNgayTaovsIDKH(sngaytao,sidnhacc);}
/// <summary>
/// Thêm mới dữ liệu vào bảng: tblphieunhapkho
/// </summary>
/// <param name="obj">objtblphieunhapkho</param>
/// <returns>Trả về trắng: Thêm mới thành công; Trả về khác trắng: Thêm mới không thành công</returns>
public string Insert(tblphieunhapkho objtblphieunhapkho)
{
return objtblphieunhapkhoDA.Insert(objtblphieunhapkho);
}
/// <summary>
/// Cập nhật dữ liệu vào bảng: tblphieunhapkho
/// </summary>
/// <param name="obj">objtblphieunhapkho</param>
/// <returns>Trả về trắng: Cập nhật thành công; Trả về khác trắng: Cập nhật không thành công</returns>
public string Update(tblphieunhapkho objtblphieunhapkho)
{
return objtblphieunhapkho.Update(objtblphieunhapkho);
}
/// <summary>
/// Xóa dữ liệu từ bảng tblphieunhapkho
/// </summary>
/// <returns></returns>
public string Delete(string strid)
{
return objtblphieunhapkhoDA.Delete(strid);
}
/// <summary>
/// Hàm lấy tất cả dữ liệu trong bảng tblphieunhapkho
/// </summary>
/// <returns>Trả về List<<tblphieunhapkho>></returns>
public List<tblphieunhapkho> GetList()
{
return objtblphieunhapkhoDA.GetList();
}
/// <summary>
/// Hàm lấy danh sách objtblphieunhapkho
/// </summary>
/// <param name="recperpage">Số lượng bản ghi kiểu integer</param>
/// <param name="pageindex">Số trang kiểu integer</param>
/// <returns>Trả về List<<tblphieunhapkho>></returns>
public List<tblphieunhapkho> GetListPaged(int recperpage, int pageindex)
{
return objtblphieunhapkhoDA.GetListPaged(recperpage, pageindex);
}
/// <summary>
/// Hàm lấy danh sách objtblphieunhapkho
/// </summary>
/// <param name="recperpage">Số lượng bản ghi kiểu integer</param>
/// <param name="pageindex">Số trang kiểu integer</param>
/// <returns>Trả về List<<tblphieunhapkho>></returns>
public DataTable GetDataTablePaged(int recperpage, int pageindex)
{
return objtblphieunhapkhoDA.GetDataTablePaged(recperpage, pageindex);
}
/// <summary>
/// Hàm tìm kiếm phiếu nhập
/// </summary>
/// <param name="stungay">Từ ngày kiểu string format: yyyy/MM/dd</param>
/// <param name="sdenngay">Đến ngày kiểu string format: yyyy/MM/dd</param>
/// <returns>DataTable</returns>
public DataTable Filter(DateTime dtungay, DateTime dtdenngay)
{
string stungay = "";
string sdenngay = "";
if (dtungay.ToString("dd/MM/yyyy").Equals(dtdenngay.ToString("dd/MM/yyyy")) == true)
{
stungay = dtungay.ToString("yyyy/MM/dd").Trim();
sdenngay = dtungay.AddDays(7).ToString("yyyy/MM/dd").Trim();
}
else
{
stungay = dtungay.ToString("yyyy/MM/dd").Trim();
sdenngay = dtdenngay.AddDays(1).ToString("yyyy/MM/dd").Trim();
}
return objtblphieunhapkhoDA.Filter(stungay, sdenngay);
}
/// <summary>
/// Hàm tìm kiếu phiếu nhập kho
/// </summary>
/// <param name="skeyword">Từ khóa kiểu string</param>
/// <param name="tungay">Từ ngày kiểu DateTime</param>
/// <param name="denngay">Đến ngày kiểu DateTime</param>
/// <returns>DataTable</returns>
public DataTable Filter(string skeyword, DateTime tungay, DateTime denngay)
{
DateTime dttungay = DateTime.Now.AddMonths(-2);
try { dttungay = tungay; }
catch { }
DateTime dtdenngay = DateTime.Now.AddDays(1);
try { dtdenngay = denngay; }
catch { }
if (dttungay.ToString("dd/MM/yyyy").Trim().Equals(dtdenngay.ToString("dd/MM/yyyy").Trim()) == true)
{
dttungay = dtdenngay.AddMonths(-2);
}
return objtblphieunhapkhoDA.Filter(skeyword, dttungay.ToString("yyyy/MM/dd").Trim(), dtdenngay.AddDays(1).ToString("yyyy/MM/dd").Trim()); ;
}
/// <summary>
/// Hàm lấy tiền còn nợ của các toa trước
/// </summary>
/// <param name="dtngaytao">Ngày tạo hóa đơn kiểu DateTime</param>
/// <returns>double: Số tiền còn nợ của các toa trước</returns>
public double GetTienConNo(string sidnhacc, DateTime dtngaytao)
{ return objtblphieunhapkhoDA.GetTienConNo(sidnhacc, dtngaytao); }
/// <summary>
/// Hàm kiểm tra đã tồn tại phiếu nhập theo mã và ngày tạo
/// </summary>
/// <param name="sid">Mã phiếu nhập kiểu string (Guid)</param>
/// <param name="dtngaytao">Ngày tạo kiểu DateTime</param>
/// <returns>bool: False-Không tồn tại;True-Có tồn tại</returns>
public bool CheckExit(string sid, DateTime dtngaytao)
{ return objtblphieunhapkhoDA.CheckExit(sid, dtngaytao); }
#endregion
}
}
|
using NodeGraph.View;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NodeGraph.ViewModel {
[AttributeUsage(AttributeTargets.Class)]
public class NodeViewModelAttribute : Attribute {
public string ViewStyleName { get; set; } = "DefaultNodeViewStyle";
public Type ViewType { get; set; } = typeof(NodeView);
}
}
|
namespace Arch.Data.Common.Enums
{
enum OrderDirection
{
ASC,
DESC
}
} |
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
#region Usings
using System;
using System.Collections.Generic;
using System.Data;
using System.Runtime.Serialization;
using DotNetNuke.ComponentModel.DataAnnotations;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
#endregion
namespace Dnn.PersonaBar.Security.Services.Dto
{
public class UpdateIpFilterRequest
{
public string IPAddress { get; set; }
public string SubnetMask { get; set; }
public int RuleType { get; set; }
public int IPFilterID { get; set; }
}
}
|
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
namespace FunctionAppRabbitMQ
{
public static class RabbitMQTrigger
{
[FunctionName("RabbitMQTrigger")]
public static void Run(
[RabbitMQTrigger("TesteAzureFunctionsLocal", ConnectionStringSetting = "RabbitMQConnection")]string inputMessage,
ILogger log)
{
log.LogInformation($"Mensagem recebida: {inputMessage}");
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace at02.Models
{
public class Pacote
{
[ScaffoldColumn(false)]
[Key]
public int id {get;set;}
[ScaffoldColumn(false)]
public string autor {get;set;}
[Display(Name = "Nome do Pacote")]
[Required]
public string nome {get;set;}
[Display(Name = "Origem")]
[Required]
public string origem {get;set;}
[Display(Name = "Destino")]
[Required]
public string destino {get;set;}
[Display(Name = "Atrativo")]
[Required]
public string atrativo {get;set;}
[Display(Name = "Data de Saída")]
[DataType(DataType.Date)]
[Required]
public DateTime saida {get;set;}
[Display(Name = "Data de Retorno")]
[DataType(DataType.Date)]
[Required]
public DateTime retorno {get;set;}
[ScaffoldColumn(false)]
public int id_usuario {get;set;}
}
} |
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using static yocto.Preconditions;
// ReSharper disable InconsistentNaming
namespace yocto
{
internal partial class Container : IContainer, IFactoryProvider, IResolveByType
{
private readonly object _syncLock = new object();
private readonly List<Container> _children = new List<Container>();
private readonly ConcurrentDictionary<Type, IInstanceFactory> _factories =
new ConcurrentDictionary<Type, IInstanceFactory>();
protected readonly Container _parent;
private bool _disposed;
internal Container()
{
}
protected Container(Container parent)
{
CheckIsNotNull(nameof(parent), parent);
_parent = parent;
}
~Container()
{
Dispose(false);
}
protected void Dispose(bool dispose)
{
if (_disposed)
return;
Cleanup.SafeMethod(() =>
{
_parent?.RemoveChild(this);
List<Container> childrenToDispose;
lock (_syncLock)
{
childrenToDispose = _children.ToList();
_children.Clear();
}
foreach (var c in childrenToDispose)
{
((IDisposable)c).Dispose();
}
var factoriesToDispose = _factories.Values.ToList();
foreach (var f in factoriesToDispose)
{
f.Dispose();
}
_factories.Clear();
});
_disposed = true;
if (dispose)
GC.SuppressFinalize(this);
}
public IChildContainer GetChildContainer()
{
var child = new ChildContainer(this);
lock (_syncLock)
{
_children.Add(child);
}
return child;
}
private void RemoveChild(Container child)
{
lock (_syncLock)
{
_children.Remove(child);
}
}
public IRegistration Register<T>(T instance) where T : class
{
CheckIsNotNull(nameof(instance), instance);
return new FactoryRegistration<T>(this, () => instance).AsMultiple();
}
public IRegistration Register<T>(Func<T> factory) where T : class
{
CheckIsNotNull(nameof(factory), factory);
return new FactoryRegistration<T>(this, factory).AsMultiple();
}
public IRegistration Register<T,V>() where V : class, T where T : class
{
return new Registration<T, V>(this).AsMultiple();
}
private void Remove<T>() where T : class
{
var interfaceType = typeof(T);
if (_factories.TryRemove(interfaceType, out var instanceFactory))
{
instanceFactory.Dispose();
}
}
public T Resolve<T>() where T : class
{
if (!TryResolve(out T instance))
throw new Exception("Interface type is not registered.");
return instance;
}
public T Resolve<T>(Type type) where T : class
{
CheckIsNotNull(nameof(type), type);
if (!TryResolve(type, out T instance))
throw new Exception("Interface type is not registered.");
return instance;
}
public object Resolve(Type type)
{
CheckIsNotNull(nameof(type), type);
if (!TryResolve(type, out object instance))
throw new Exception("Interface type is not registered.");
return instance;
}
public bool CanResolve<T>() where T : class
{
bool canResolve = _factories.ContainsKey(typeof (T));
if ((!canResolve) && (_parent != null))
{
return _parent.CanResolve<T>();
}
return canResolve;
}
public bool CanResolve(Type type)
{
CheckIsNotNull(nameof(type), type);
bool canResolve = _factories.ContainsKey(type);
if ((!canResolve) && (_parent != null))
{
return _parent.CanResolve(type);
}
return canResolve;
}
public bool TryGetFactory(Type type, out IInstanceFactory factory)
{
CheckIsNotNull(nameof(type), type);
bool found = _factories.TryGetValue(type, out factory);
if (!found && _parent != null)
{
found = _parent.TryGetFactory(type, out factory);
}
return found;
}
public bool TryResolve<T>(out T instance) where T : class
{
instance = null;
if (_factories.TryGetValue(typeof(T), out var instanceFactory))
{
instance = instanceFactory.Create<T>();
}
else if (_parent != null)
{
return _parent.TryResolve(out instance);
}
return (instance != null);
}
public bool TryResolve<T>(Type type, out T instance) where T : class
{
instance = null;
if (_factories.TryGetValue(type, out var instanceFactory))
{
instance = instanceFactory.Create<T>();
}
else if (_parent != null)
{
return _parent.TryResolve(type, out instance);
}
return (instance != null);
}
private void CreateInstanceFactory(Type interfaceType, Type implementationType, string lifetime, params object[] values)
{
CreateInstanceFactory(interfaceType, implementationType, lifetime, null, values);
}
private void CreateInstanceFactory(Type interfaceType, Type implementationType, string lifetime, Func<object> factory, params object[] values)
{
var lifetimeFactory = Lifetimes.GetLifetimeFactory(lifetime);
var instanceFactory = lifetimeFactory.GetInstanceFactory(this, interfaceType, implementationType, factory, values);
_factories.AddOrUpdate(interfaceType, t => instanceFactory,
(t, of) =>
{
of.Dispose();
return instanceFactory;
});
}
}
} |
using AutoMapper;
using FictionFantasyServer.Data.Entities;
namespace FictionFantasyServer.Models.Mappings
{
public class BookProfile : Profile
{
public BookProfile()
{
CreateMap<Book, BookEntity>().ReverseMap();
}
}
}
|
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Yeasca.Metier;
using Yeasca.Mongo;
using Yeasca.Requete;
namespace Yeasca.TestsUnitaires.Requete.Profiles
{
[TestClass]
public class TestRechercheClientRequete
{
private string _nomClient = "Pouet";
[TestInitialize]
public void initialiser()
{
ConfigurationTest.initialiserLesEntrepotsMongo();
ConfigurationTest.initialiserLaSessionHTTP(TypeUtilisateur.Huissier);
IEntrepotProfile entrepot = EntrepotMongo.fabriquerEntrepot<IEntrepotProfile>();
entrepot.ajouter(new Client());
entrepot.ajouter(new Client() { Nom = _nomClient });
}
[TestMethod]
public void TestRechercheClientRequete_peutTrouverLesClients()
{
IRechercheClientMessage message = new RechercheClientMessageTest();
message.Texte = _nomClient;
message.NuméroPage = 1;
message.NombreDElémentsParPage = 10;
ReponseRequete réponse = BusRequete.exécuter(message);
Assert.IsTrue(réponse.Réussite);
List<ClientReponse> résultat = réponse.Résultat as List<ClientReponse>;
Assert.IsNotNull(résultat);
Assert.AreEqual(1, résultat.Count);
}
}
public class RechercheClientMessageTest : IRechercheClientMessage
{
public int NuméroPage { get; set; }
public int NombreDElémentsParPage { get; set; }
public string Texte { get; set; }
}
}
|
using BankingSite.Models;
using HtmlAgilityPack;
using NUnit.Framework;
using RazorGenerator.Testing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankingSite.ViewTest
{
[TestFixture ]
public class LoanApplicationSearchApplicationStatusViewTests
{
[Test]
public void ShouldRenderAcceptedMessage()
{
var sut = new Views.LoanApplicationSearch.ApplicationStatus();
var model = new LoanApplication
{
IsAccepted = true
};
HtmlDocument html = sut.RenderAsHtml(model);
//var message = html.GetElementbyId("status").InnerText;
//Assert.That(message, Contains.Substring("Yay! Accepted!"));
var isAcceptedMessageRendred = html.GetElementbyId("acceptedMessage") != null;
var isAcDeclinedMessageRendred = html.GetElementbyId("declinedMessage") != null;
Assert.That(isAcceptedMessageRendred, Is.True);
Assert.That(isAcDeclinedMessageRendred, Is.False);
}
}
}
|
using UnityEngine;
using System.Collections;
public class MouseWasd : MonoBehaviour {
private float mainSpeed = 50.0f; //regular speed
private float shiftAdd = 150.0f; //multiplied by how long shift is held. Basically running
private float maxShift = 600.0f; //Maximum speed when holdin gshift
private float camSens = 0.25f; //How sensitive it with mouse
private Vector3 lastMouse = new Vector3(255f, 255f, 255f); //kind of in the middle of the screen, rather than at the top (play)
private float totalRun = 1.0f;
private int zoomRate = 500;
//private int panSpeed = 100;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void LateUpdate () {
lastMouse = Input.mousePosition - lastMouse ;
lastMouse = new Vector3(-lastMouse.y * camSens, lastMouse.x * camSens, 0 );
lastMouse = new Vector3(transform.eulerAngles.x + lastMouse.x , transform.eulerAngles.y + lastMouse.y, 0);
if(Input.GetButton("Fire2"))
{
transform.eulerAngles = lastMouse;
}
lastMouse = Input.mousePosition;
//Mouse & camera angle done.
//Keyboard commands
float f = 0.0f;
Vector3 p = GetBaseInput();
if (Input.GetKey (KeyCode.LeftShift)){
totalRun += Time.deltaTime;
p = p * totalRun * shiftAdd;
p.x = Mathf.Clamp(p.x, -maxShift, maxShift);
p.y = Mathf.Clamp(p.y, -maxShift, maxShift);
p.z = Mathf.Clamp(p.z, -maxShift, maxShift);
}
else{
totalRun = Mathf.Clamp(totalRun * 0.5f, 1f, 1000f);
p = p * mainSpeed;
}
//if (Input.GetMouseButton(2))
//{
//Debug.Log(tempwheel*Time.deltaTime*zoomRate);
if (Input.GetKey(KeyCode.LeftShift)){
p = p+ new Vector3(0f, 0f , 1f)*Input.GetAxis("Mouse ScrollWheel")*Time.deltaTime*zoomRate*shiftAdd; // new Vector3(1f,1f,1f);// p.normalized*tempwheel * Time.deltaTime * zoomRate;
}
else{
p = p+ new Vector3(0f, 0f , 1f)*Input.GetAxis("Mouse ScrollWheel")*Time.deltaTime*zoomRate*mainSpeed;
}
//desiredDistance -= Input.GetAxis("Mouse Y") * Time.deltaTime * zoomRate*0.125f * Mathf.Abs(desiredDistance);
// }
p = p * Time.deltaTime;
if (Input.GetKey(KeyCode.Space)){ //If player wants to move on X and Z axis only
f = transform.position.y;
transform.Translate(p);
transform.position = new Vector3(transform.position.x, f,transform.position.z);
}
else{
transform.Translate( p);
}
if (Input.GetMouseButton(2))
{
if (Input.GetKey(KeyCode.LeftShift)){
p = new Vector3(-Input.GetAxis("Mouse X") * shiftAdd, 0f , 0f) + new Vector3(0f, 0f,-Input.GetAxis("Mouse Y") * shiftAdd);
}
else
{
p = new Vector3(-Input.GetAxis("Mouse X") * mainSpeed, 0f , 0f) + new Vector3(0f, 0f,-Input.GetAxis("Mouse Y") * mainSpeed);
}
p = p*Time.deltaTime;
f = transform.position.y;
transform.Translate(p);
transform.position = new Vector3(transform.position.x, f,transform.position.z);
//p = p + transform.rotation.eulerAngles
//grab the rotation of the camera so we can move in a psuedo local XY space
//target.rotation = transform.rotation;
//p = p+ new Vector3(-Input.GetAxis("Mouse X") * panSpeed, 0f , 0f);
//p = p+ ;
// transform.right *( );
//p = p+ transform.up *( -Input.GetAxis("Mouse Y")) * panSpeed;
}
}
private Vector3 GetBaseInput(){ //returns the basic values, if it's 0 than it's not active.
Vector3 p_Velocity = new Vector3(0f,0f,0f);
if (Input.GetKey (KeyCode.W)){
p_Velocity += new Vector3(0f, 0f , 1f);
}
if (Input.GetKey (KeyCode.S)){
p_Velocity += new Vector3(0f, 0f , -1f);
}
if (Input.GetKey (KeyCode.A)){
p_Velocity += new Vector3(-1f, 0f , 0f);
}
if (Input.GetKey (KeyCode.D)){
p_Velocity += new Vector3(1f, 0f , 0f);
}
if (Input.GetKey (KeyCode.Q)){
p_Velocity += new Vector3(0f, -1f , 0f);
}
if (Input.GetKey (KeyCode.E)){
p_Velocity += new Vector3(0f, 1f , 0f);
}
return p_Velocity;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.