text stringlengths 13 6.01M |
|---|
using System;
using System.Diagnostics;
using System.IO;
using System.Web.Mvc;
namespace CarDealer.App.Filters
{
public class TimerAttribute : ActionFilterAttribute
{
private readonly Stopwatch _stopwatch = new Stopwatch();
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
this._stopwatch.Start();
base.OnActionExecuted(filterContext);
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
this._stopwatch.Stop();
var timePassed = _stopwatch.Elapsed;
this._stopwatch.Reset();
var logTimeStamp = DateTime.Now;
var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
var actionName = filterContext.ActionDescriptor.ActionName;
string log = $"{logTimeStamp} – {controllerName}.{actionName} – {timePassed}";
File.AppendAllText(@"c:\temp\timer.log", log);
base.OnActionExecuting(filterContext);
}
}
} |
using System;
using StarBastardCore.Website.Code.Game.Gameworld.Units.Starships;
namespace StarBastardCore.Website.Code.Game.Gameplay.Actions
{
public class Move : GameActionBase
{
public string DestinationPlanetId
{
get { return Item<string>("DestinationPlanetId"); }
set { Parameters["DestinationPlanetId"] = value; }
}
public Guid StarshipId
{
get { return Item<Guid>("StarshipId"); }
set { Parameters["StarshipId"] = value; }
}
public IStarship Starship
{
get { return Item<IStarship>("Starship"); }
set { Parameters["Starship"] = value; }
}
public Move()
{
}
public Move(GameActionBase action)
{
Parameters = action.Parameters;
}
}
} |
namespace GameProject.Entities
{
public interface IEntities
{
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DSSCriterias.Logic.Extensions;
namespace DSSCriterias.Logic.Criterias
{
public class CriteriaMinMax : Criteria
{
public CriteriaMinMax(IStatGame game) : base(game)
{
Name = "Критерий Минимакса";
Situation.Goal = StateGoal.Get(Goals.MinRisc);
Situation.Usage = StateUsage.Get(Usages.Couple);
Situation.Chances = StateChances.Unknown();
Description = "...";
DecizionAlgoritm = "- Найти наилучшие варианты исхода по каждой альтернативе\n- Из них выбрать наихудший вариант выбора альтернативы";
}
protected override void Count()
{
List<double> maxes = new List<double>((int)Rows);
for (int i = 0; i < Rows; i++)
{
maxes.Add(Arr.MaxFromRow(i));
}
SetResult(maxes.Min(), maxes);
AddStep("Максимумы", maxes);
AddStep("Минимум", Result);
}
}
}
|
using System;
using System.Collections.Generic;
namespace DemoEF.Domain.Models
{
public partial class TbAccount
{
public long UserId { get; set; }
public string Account { get; set; }
public string Pwd { get; set; }
public string Name { get; set; }
public string Role { get; set; }
public int? AccountState { get; set; }
public string Email { get; set; }
public string Tels { get; set; }
public string Addr { get; set; }
public string CompanyLevel { get; set; }
public DateTime? RegistTime { get; set; }
public string DecoratorReceiveArea { get; set; }
public int DecoratorLevel { get; set; }
public string DecoratorTags { get; set; }
public string Oldpwd { get; set; }
public string Openid { get; set; }
public string AccountConfig { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace BradescoPGP.Web.Models.Modelos_dos_Arquivos
{
public class Investfacil
{
public int Id { get; set; }
[StringLength(10)]
public string CONTA { get; set; }
[StringLength(10)]
public string AGENCIA { get; set; }
public decimal Vlr_Evento { get; set; }
}
} |
using FluentNHibernate.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Common.Models.Mapping
{
public class KursleiterKursMap : ClassMap<KursleiterKurs>
{
public KursleiterKursMap()
{
Id(x => x.KursleiterKursID).GeneratedBy.HiLo("10");
Map(x => x.Honorar).Not.Nullable();
Map(x => x.Zulage);
References(x => x.KursleiterID).Column("KursleiterID").Not.Nullable().Not.LazyLoad();
References(x => x.KursID).Column("KursID").Not.Nullable().Not.LazyLoad();
}
}
}
|
using System;
using System.Collections.Generic;
using Xunit;
namespace YouScan.Sale.UnitTests
{
public class PointOfSaleTerminalTests
{
[Fact]
public void CalculateTotal_Should_Return_0_If_No_Scan()
{
// arrange
IPointOfSaleTerminal terminal = new PointOfSaleTerminal();
IReadOnlyDictionary<string, ProductPricingSettings> settings = new Dictionary<string, ProductPricingSettings>
{
{ "A", new ProductPricingSettings(1.25, 3, 3) },
{ "B", new ProductPricingSettings(4.25) },
{ "C", new ProductPricingSettings(1, 5, 6) },
{ "D", new ProductPricingSettings(0.75) }
};
terminal.SetPricing(settings);
// act
double result = terminal.CalculateTotal();
// assert
Assert.Equal(0, result);
}
[Theory]
[InlineData("ABCDABA", 13.25)]
[InlineData("CCCCCCC", 6.00)]
[InlineData("ABCD", 7.25)]
[InlineData("ABCDABCD", 14.5)]
[InlineData("E", 0.75)]
[InlineData("EE", 1.5)]
public void CalculateTotal_Should_Return_Correct_Sum(string productCodes, double totalPrice)
{
// arrange
IPointOfSaleTerminal terminal = new PointOfSaleTerminal();
IReadOnlyDictionary<string, ProductPricingSettings> settings = new Dictionary<string, ProductPricingSettings>
{
{ "A", new ProductPricingSettings(1.25, 3, 3) },
{ "B", new ProductPricingSettings(4.25) },
{ "C", new ProductPricingSettings(1, 5, 6) },
{ "D", new ProductPricingSettings(0.75) },
{ "E", new ProductPricingSettings(1, 0.75, 1) }
};
terminal.SetPricing(settings);
foreach (char productCode in productCodes)
{
terminal.Scan(productCode.ToString());
}
// act
double result = terminal.CalculateTotal();
// assert
Assert.Equal(totalPrice, result);
}
[Fact]
public void CalculateTotal_Should_Throw_ArgumentException_If_ProductPricingSettings_Is_Null_or_Empty()
{
// arrange
IPointOfSaleTerminal terminal = new PointOfSaleTerminal();
// assert
Assert.Throws<ArgumentException>(() => terminal.CalculateTotal());
}
[Theory]
[InlineData("F")]
[InlineData("ABCDE")]
public void CalculateTotal_Should_Throw_Exception_If_ProductPricingSettings_Were_Not_Found_For_Product(string productCodes)
{
// arrange
IPointOfSaleTerminal terminal = new PointOfSaleTerminal();
IReadOnlyDictionary<string, ProductPricingSettings> settings = new Dictionary<string, ProductPricingSettings>
{
{ "A", new ProductPricingSettings(1.25, 3, 3) },
{ "B", new ProductPricingSettings(4.25) },
{ "C", new ProductPricingSettings(1, 5, 6) },
{ "D", new ProductPricingSettings(0.75) }
};
terminal.SetPricing(settings);
foreach (char productCode in productCodes)
{
terminal.Scan(productCode.ToString());
}
// assert
Assert.Throws<Exception>(() => terminal.CalculateTotal());
}
[Theory]
[InlineData("")]
[InlineData(null)]
public void Scan_Should_Throw_ArgumentNullException_If_ProductCode_Is_Null_or_Empty(string productCode)
{
// arrange
IPointOfSaleTerminal terminal = new PointOfSaleTerminal();
// assert
Assert.Throws<ArgumentNullException>(() => terminal.Scan(productCode));
}
[Fact]
public void SetPricing_Should_Throw_ArgumentException_If_ProductPricingSettings_Is_Null_or_Empty()
{
// arrange
IPointOfSaleTerminal terminal = new PointOfSaleTerminal();
// assert
Assert.Throws<ArgumentException>(() => terminal.SetPricing(null));
Assert.Throws<ArgumentException>(() => terminal.SetPricing(new Dictionary<string, ProductPricingSettings>()));
}
[Theory]
[InlineData("ABCDABA", 9.25)]
[InlineData("CCCCCCC", 0)]
[InlineData("ABCD", 5)]
[InlineData("ABCDABCD", 10)]
[InlineData("E", 0)]
[InlineData("EE", 0)]
[InlineData("ABCDABCDFFF", 10)]
public void CalculateForDiscount_Should_Return_Correct_Sum(string productCodes, double totalPrice)
{
// arrange
IPointOfSaleTerminal terminal = new PointOfSaleTerminal();
IReadOnlyDictionary<string, ProductPricingSettings> settings = new Dictionary<string, ProductPricingSettings>
{
{ "A", new ProductPricingSettings(1.25, 3, 3) },
{ "B", new ProductPricingSettings(4.25) },
{ "C", new ProductPricingSettings(1, 5, 6) },
{ "D", new ProductPricingSettings(0.75) },
{ "E", new ProductPricingSettings(1, 0.75, 1) }
};
terminal.SetPricing(settings);
foreach (char productCode in productCodes)
{
terminal.Scan(productCode.ToString());
}
// act
double result = terminal.CalculateForDiscount();
// assert
Assert.Equal(totalPrice, result);
}
[Fact]
public void CalculateForDiscount_Should_Return_0_If_No_Scan()
{
// arrange
IPointOfSaleTerminal terminal = new PointOfSaleTerminal();
IReadOnlyDictionary<string, ProductPricingSettings> settings = new Dictionary<string, ProductPricingSettings>
{
{ "A", new ProductPricingSettings(1.25, 3, 3) },
{ "B", new ProductPricingSettings(4.25) },
{ "C", new ProductPricingSettings(1, 5, 6) },
{ "D", new ProductPricingSettings(0.75) }
};
terminal.SetPricing(settings);
// act
double result = terminal.CalculateForDiscount();
// assert
Assert.Equal(0, result);
}
[Fact]
public void CalculateForDiscount_Should_Return_0_If_ProductPricingSettings_Is_Null_or_Empty()
{
// arrange
IPointOfSaleTerminal terminal = new PointOfSaleTerminal();
// act
double result = terminal.CalculateForDiscount();
// assert
Assert.Equal(0, result);
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Phenix.Core;
using Phenix.Core.Log;
using Phenix.Core.SyncCollections;
namespace Phenix.Services.Host.Core
{
/// <summary>
/// Fetch性能记录数
/// </summary>
internal class PerformanceFetchCount
{
public PerformanceFetchCount(string businessName)
{
_businessName = businessName;
_maxCount = new PerformanceFetchMaxCount(businessName, 0, null);
}
#region 属性
private readonly string _businessName;
/// <summary>
/// 业务类名
/// </summary>
public string BusinessName
{
get { return _businessName; }
}
//计数
private long _tally;
//按照10000条记录数递增计数
private readonly SynchronizedDictionary<long, long> _tallyInterval = new SynchronizedDictionary<long, long>();
//最大记录数
private PerformanceFetchMaxCount _maxCount;
#endregion
#region 方法
/// <summary>
/// 检查最大记录数
/// </summary>
public bool CheckMaxCount(PerformanceFetchMaxCount newMaxCount)
{
try
{
_tally = _tally + 1;
long scale = (newMaxCount.Value % 10000 > 0 ? newMaxCount.Value / 10000 + 1 : newMaxCount.Value / 10000) * 10000;
_tallyInterval[scale] = (_tallyInterval.ContainsKey(scale) ? _tallyInterval[scale] : 0) + 1;
if (newMaxCount.Value > _maxCount.Value)
{
_maxCount = newMaxCount;
return true;
}
return false;
}
finally
{
if (_tally < 100 && _tally % 10 == 5 || _tally % 100 == 0)
try
{
string directory = Path.Combine(AppConfig.BaseDirectory, "PerformanceFetch");
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
using (StreamWriter logFile = File.CreateText(Path.Combine(directory, String.Format("{0}.Count.Log", BusinessName))))
{
logFile.Write(ToString());
logFile.Flush();
}
}
catch (IOException)
{
EventLog.SaveLocal(ToString());
}
}
}
public override string ToString()
{
StringBuilder result = new StringBuilder();
result.AppendLine(_businessName);
result.AppendLine();
result.Append("tally: ");
result.AppendLine(_tally.ToString());
result.AppendLine();
foreach (KeyValuePair<long, long> kvp in _tallyInterval)
result.AppendLine(String.Format("<= {0} rec: {1} in {2}%", kvp.Key, kvp.Value, kvp.Value*100/_tally));
result.AppendLine();
result.AppendLine(_maxCount.ToString());
return result.ToString();
}
#endregion
}
}
|
public class Solution {
public bool IsAnagram(string s, string t) {
if (s.Length != t.Length) return false;
int[] cnt = new int[26];
for (int i = 0; i < s.Length; i ++) {
cnt[s[i] - 'a'] ++;
}
for (int i = 0; i < t.Length; i ++) {
if (-- cnt[t[i] - 'a'] < 0) return false;
}
return true;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EQ2LuaEditor
{
class Scripts
{
private static string GetHeader()
{
// Standard header at the top of every script
string ret = "--[[\n\tScript Name\t\t:\t<script-name>\n\tScript Purpose\t:\t<purpose>\n\tScript Author\t:\t" + ((EQ2LuaEditor.Settings.AuthorName == "NULL" || EQ2LuaEditor.Settings.AuthorName == string.Empty) ? "<author-name>" : EQ2LuaEditor.Settings.AuthorName) + "\n\tScript Date\t\t:\t" + DateTime.UtcNow.Date.ToString("d") + "\n\tScript Notes\t:\t<special-instructions>\n--]]\n\n";
return ret;
}
private static string GetQuestHeader()
{
string ret;
// Start with the original header
ret = GetHeader();
// Strip off the "--[[\n\n" at the end
ret = ret.Substring(0, ret.Length - 6);
// Add the extra info that the quest header have
ret += "\n\tZone\t\t\t:\t<zone-name>\n\tQuest Giver\t\t:\t<quest-giver-name>\n\tPreceded by\t\t:\t<preceded-quest-name(lua file)>\n\tFollowed by\t\t:\t<followed-by-quest-name(lua file)>\n--]]\n\n";
return ret;
}
public static string GetSpawnScript()
{
string ret = GetHeader();
ret += "function spawn(NPC)\nend\n\n"
+ "function respawn(NPC)\n\tspawn(NPC)\nend\n\n"
+ "function hailed(NPC, Spawn)\nend\n\n"
+ "function hailed_busy(NPC, Spawn)\nend\n\n"
+ "function casted_on(NPC, Spawn, Message)\nend\n\n"
+ "function targeted(NPC, Spawn)\nend\n\n"
+ "function attacked(NPC, Spawn)\nend\n\n"
+ "function aggro(NPC, Spawn)\nend\n\n"
+ "function healthchanged(NPC, Spawn)\nend\n\n"
+ "function auto_attack_tick(NPC, Spawn)\nend\n\n"
+ "function death(NPC, Spawn)\nend\n\n"
+ "function killed(NPC, Spawn)\nend\n\n"
+ "function CombatReset(NPC)\nend\n\n"
+ "function randomchat(NPC, Message)\nend";
return ret;
}
public static string GetZoneScript()
{
string ret = GetHeader();
ret += "function init_zone_script(zone)\nend\n\n"
+ "function player_entry(zone, player)\nend\n\n"
+ "function enter_location(zone, spawn, grid)\nend\n\n"
+ "function leave_location(zone, spawn, grid)\nend\n\n"
+ "function dawn(zone)\nend\n\n"
+ "function dusk(zone)\nend";
return ret;
}
public static string GetItemScript()
{
string ret = GetHeader();
ret += "function obtained(Item, Player)\nend\n\n"
+ "function removed(Item, Player)\nend\n\n"
+ "function destroyed(Item, Player)\nend\n\n"
+ "function examined(Item, Player)\nend\n\n"
+ "function used(Item, Player)\nend\n\n"
+ "function cast(Item, Player)\nend\n\n"
+ "function equipped(Item, Player)\nend\n\n"
+ "function unequipped(Item, Player)\nend\n\n"
+ "function proc(Item, Caster, Target, Type)\nend";
return ret;
}
public static string GetSpellScript()
{
string ret = GetHeader();
ret += "function cast(Caster, Target) -- Add more params as needed for the values from the db\nend\n\n"
+ "function tick(Caster, Target) -- Add more params as needed for the values from the db\nend\n\n"
+ "function proc(Caster, Target)\nend\n\n"
+ "function remove(Caster, Target)\nend";
return ret;
}
public static string GetQuestScript()
{
string ret = GetQuestHeader();
ret += "function Init(Quest)\nend\n\n"
+ "function Accepted(Quest, QuestGiver, Player)\nend\n\n"
+ "function Deleted(Quest, QuestGiver, Player)\nend\n\n"
+ "function Declined(Quest, QuestGiver, Player)\nend\n\n"
+ "function Reload(Quest, QuestGiver, Player, Step)\nend";
return ret;
}
}
}
|
using System.Data;
using System.Linq;
using System.Web.Mvc;
using Centroid.Models;
namespace Centroid.Controllers
{
public class HomeController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: Home
public ActionResult Index()
{
HomeViewModels model = new HomeViewModels();
var homeImages = db.Homes.Where(h => h.Active == true).ToList();
var about = db.Abouts.Select(a => a.AboutUs).FirstOrDefault();
var vision = db.Abouts.Select(a => a.Vision).FirstOrDefault();
var keyRecords = db.KeyRecords.ToList();
model.HomeImages = homeImages;
model.About = about;
model.Vision = vision;
model.KeyRecords = keyRecords;
return View(model);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GreenSpawner : MonoBehaviour
{
public GameObject theEnemy;
GameObject enemyClone;
public int xPos;
public int zPos;
public int enemyCount;
public static int enemyDeaths;
public static int levelNum;
public static int levelDeath;
public static ArrayList enemiesAlive = new ArrayList();
bool gameRunning;
public GameObject level1Tag;
public GameObject level2Tag;
public GameObject level3Tag;
public GameObject level4Tag;
public GameObject level5Tag;
public GameObject playerDeathTag;
public GameObject endingTag;
static bool goodTogo;
// Start is called before the first frame update
public void Start()
{
if (GreenStartUp.gameStart)
{
Debug.Log("lalalla");
gameRunning = true;
levelNum++;
StartCoroutine(EnemyDrop());
}
}
IEnumerator EnemyDrop()
{
if (levelNum == 1)
{
enemyCount = 0;
while (enemyCount < 3)
{
xPos = Random.Range(25, 80);
zPos = Random.Range(25, 40);
enemyClone = Instantiate(theEnemy, new Vector3(xPos, 2, zPos), Quaternion.identity);
enemyClone.GetComponent<GreenEnemy>().speedNum = Random.Range(5, 6);
enemiesAlive.Add(enemyClone);
yield return new WaitForSeconds(0.1f);
enemyCount++;
}
while (enemyCount < 5)
{
xPos = Random.Range(25, 80);
zPos = Random.Range(40, 100);
enemyClone = Instantiate(theEnemy, new Vector3(xPos, 2, zPos), Quaternion.identity);
enemyClone.GetComponent<GreenEnemy>().speedNum = Random.Range(6, 7);
enemiesAlive.Add(enemyClone);
yield return new WaitForSeconds(0.1f);
enemyCount++;
}
while (enemyCount < 7)
{
xPos = Random.Range(25, 80);
zPos = Random.Range(80, 100);
enemyClone = Instantiate(theEnemy, new Vector3(xPos, 2, zPos), Quaternion.identity);
enemyClone.GetComponent<GreenEnemy>().speedNum = Random.Range(7, 9);
enemiesAlive.Add(enemyClone);
yield return new WaitForSeconds(0.1f);
enemyCount++;
}
}
if (levelNum == 2)
{
Debug.Log("fffff");
enemyCount = 0;
while (enemyCount < 4)
{
xPos = Random.Range(25, 80);
zPos = Random.Range(25, 40);
enemyClone = Instantiate(theEnemy, new Vector3(xPos, 2, zPos), Quaternion.identity);
enemyClone.GetComponent<GreenEnemy>().speedNum = Random.Range(5, 6);
enemiesAlive.Add(enemyClone);
yield return new WaitForSeconds(0.1f);
enemyCount++;
}
while (enemyCount < 8)
{
xPos = Random.Range(25, 80);
zPos = Random.Range(40, 100);
enemyClone = Instantiate(theEnemy, new Vector3(xPos, 2, zPos), Quaternion.identity);
enemyClone.GetComponent<GreenEnemy>().speedNum = Random.Range(6, 7);
enemiesAlive.Add(enemyClone);
yield return new WaitForSeconds(0.1f);
enemyCount++;
}
while (enemyCount < 11)
{
xPos = Random.Range(25, 80);
zPos = Random.Range(80, 100);
enemyClone = Instantiate(theEnemy, new Vector3(xPos, 2, zPos), Quaternion.identity);
enemyClone.GetComponent<GreenEnemy>().speedNum = Random.Range(7, 9);
enemiesAlive.Add(enemyClone);
yield return new WaitForSeconds(0.1f);
enemyCount++;
}
}
if (levelNum == 3)
{
enemyCount = 0;
while (enemyCount < 3)
{
xPos = Random.Range(10, 20);
zPos = Random.Range(80, 100);
enemyClone = Instantiate(theEnemy, new Vector3(xPos, 2, zPos), Quaternion.identity);
enemiesAlive.Add(enemyClone);
enemyClone.GetComponent<GreenEnemy>().speedNum = Random.Range(6, 9);
yield return new WaitForSeconds(0.1f);
enemyCount++;
}
while (enemyCount < 6)
{
xPos = Random.Range(30, 40);
zPos = Random.Range(80, 100);
enemyClone = Instantiate(theEnemy, new Vector3(xPos, 2, zPos), Quaternion.identity);
enemiesAlive.Add(enemyClone);
enemyClone.GetComponent<GreenEnemy>().speedNum = Random.Range(10, 11);
yield return new WaitForSeconds(0.1f);
enemyCount++;
}
while (enemyCount < 9)
{
xPos = Random.Range(50, 60);
zPos = Random.Range(80, 100);
enemyClone = Instantiate(theEnemy, new Vector3(xPos, 2, zPos), Quaternion.identity);
enemiesAlive.Add(enemyClone);
enemyClone.GetComponent<GreenEnemy>().speedNum = Random.Range(16, 17);
yield return new WaitForSeconds(0.1f);
enemyCount++;
}
while (enemyCount < 12)
{
xPos = Random.Range(70, 80);
zPos = Random.Range(80, 100);
enemyClone = Instantiate(theEnemy, new Vector3(xPos, 2, zPos), Quaternion.identity);
enemiesAlive.Add(enemyClone);
enemyClone.GetComponent<GreenEnemy>().speedNum = Random.Range(3, 5);
yield return new WaitForSeconds(0.1f);
enemyCount++;
}
while (enemyCount < 15)
{
xPos = Random.Range(20, 80);
zPos = Random.Range(80, 100);
enemyClone = Instantiate(theEnemy, new Vector3(xPos, 2, zPos), Quaternion.identity);
enemiesAlive.Add(enemyClone);
enemyClone.GetComponent<GreenEnemy>().speedNum = Random.Range(6, 7);
yield return new WaitForSeconds(0.1f);
enemyCount++;
}
}
if (levelNum == 4)
{
enemyCount = 0;
EarthWeapon.speed = 50f;
while (enemyCount < 1)
{
//xPos = Random.Range(30, 40);
//zPos = Random.Range(50, 60);
enemyClone = Instantiate(theEnemy, new Vector3(50, 2, 80), Quaternion.identity);
enemyClone.GetComponent<GreenEnemy>().hydra = true;
enemyClone.GetComponent<GreenEnemy>().speedNum = 4.5f;
enemiesAlive.Add(enemyClone);
yield return new WaitForSeconds(0.1f);
enemyCount++;
}
}
if (levelNum == 5)
{
enemyCount = 0;
EarthWeapon.speed = 100f;
// hydra
while (enemyCount < 1)
{
enemyClone = Instantiate(theEnemy, new Vector3(20, 2, 90), Quaternion.identity);
enemyClone.GetComponent<GreenEnemy>().hydra = true;
enemyClone.GetComponent<GreenEnemy>().speedNum = 3;
enemiesAlive.Add(enemyClone);
yield return new WaitForSeconds(0.1f);
enemyCount++;
}
//cluster
while (enemyCount < 4)
{
xPos = Random.Range(30, 35);
enemyClone = Instantiate(theEnemy, new Vector3(xPos, 2, 40), Quaternion.identity);
enemyClone.GetComponent<GreenEnemy>().speedNum = 6;
enemiesAlive.Add(enemyClone);
yield return new WaitForSeconds(0.1f);
enemyCount++;
}
//cluster
while (enemyCount < 6)
{
xPos = Random.Range(60, 65);
enemyClone = Instantiate(theEnemy, new Vector3(xPos, 2, 80), Quaternion.identity);
enemyClone.GetComponent<GreenEnemy>().speedNum = 7;
enemiesAlive.Add(enemyClone);
yield return new WaitForSeconds(0.1f);
enemyCount++;
}
//cluster
while (enemyCount < 9)
{
xPos = Random.Range(40, 45);
enemyClone = Instantiate(theEnemy, new Vector3(xPos, 2, 50), Quaternion.identity);
enemyClone.GetComponent<GreenEnemy>().speedNum = 4;
enemiesAlive.Add(enemyClone);
yield return new WaitForSeconds(0.1f);
enemyCount++;
}
//speeders
while (enemyCount < 13)
{
xPos = Random.Range(20, 80);
zPos = Random.Range(80, 100);
enemyClone = Instantiate(theEnemy, new Vector3(xPos, 2, zPos), Quaternion.identity);
enemiesAlive.Add(enemyClone);
enemyClone.GetComponent<GreenEnemy>().speedNum = Random.Range(10, 11);
yield return new WaitForSeconds(0.1f);
enemyCount++;
}
//randoms
while (enemyCount < 19)
{
xPos = Random.Range(40, 60);
zPos = Random.Range(50, 70);
enemyClone = Instantiate(theEnemy, new Vector3(xPos, 2, zPos), Quaternion.identity);
enemiesAlive.Add(enemyClone);
enemyClone.GetComponent<GreenEnemy>().speedNum = Random.Range(4, 5);
yield return new WaitForSeconds(0.1f);
enemyCount++;
}
//cluster
while (enemyCount < 23)
{
xPos = Random.Range(70, 80);
enemyClone = Instantiate(theEnemy, new Vector3(xPos, 2, 50), Quaternion.identity);
enemyClone.GetComponent<GreenEnemy>().speedNum = 4;
enemiesAlive.Add(enemyClone);
yield return new WaitForSeconds(0.1f);
enemyCount++;
}
// hydra
while (enemyCount < 24)
{
enemyClone = Instantiate(theEnemy, new Vector3(75, 2, 200), Quaternion.identity);
enemyClone.GetComponent<GreenEnemy>().hydra = true;
enemyClone.GetComponent<GreenEnemy>().speedNum = 3.5f;
enemiesAlive.Add(enemyClone);
yield return new WaitForSeconds(0.1f);
enemyCount++;
}
}
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
Invoke("goToBase", 2f);
}
goodTogo = true;
for (int i = 0; i < enemiesAlive.Count; i++)
{
if ((enemiesAlive[i] + "yes") == "nullyes") goodTogo = goodTogo && true;
else goodTogo = goodTogo && false;
}
if (gameRunning)
{
if (Player.greenHitCount >= 5)
{
levelDeath = levelNum;
playerDeathTag.SetActive(true);
gameRunning = false;
}
else
{
if (enemyDeaths >= 7 && levelNum == 1 && goodTogo && Player.greenHitCount < 5)
{
goodTogo = false;
enemyDeaths = 0;
level2Tag.SetActive(true);
level2Tag.GetComponent<MessageTwo>().Start();
Invoke("Start", 2f);
Debug.Log("wewewewe");
}
else if (enemyDeaths >= 11 && levelNum == 2 && goodTogo && Player.greenHitCount < 5)
{
goodTogo = false;
enemyDeaths = 0;
level3Tag.SetActive(true);
level3Tag.GetComponent<MessageThree>().Start();
Invoke("Start", 2f);
Debug.Log("dfdfdfdf");
}
else if (enemyDeaths >= 15 && levelNum == 3 && goodTogo && Player.greenHitCount < 5)
{
goodTogo = false;
enemyDeaths = 0;
level4Tag.SetActive(true);
level4Tag.GetComponent<MessageFour>().Start();
Invoke("Start", 2f);
Debug.Log("thththth");
}
else if (enemyDeaths >= 7 && levelNum == 4 && goodTogo && Player.greenHitCount < 5)
{
goodTogo = false;
enemyDeaths = 0;
level5Tag.SetActive(true);
level5Tag.GetComponent<MessageFive>().Start();
Invoke("Start", 2f);
Debug.Log("qsqsqsqsq");
}
else if (enemyDeaths >= 28 && levelNum == 5 && goodTogo && Player.greenHitCount < 5)
{
enemyDeaths = 0;
Debug.Log("Game Over");
endingTag.SetActive(true);
}
}
}
}
void goToBase()
{
SceneManager.LoadScene("MainTown");
}
}
|
using System;
namespace gView.Interoperability.GeoServices.Exceptions
{
public class GeoServicesException : Exception
{
public GeoServicesException() { }
public GeoServicesException(string message, int errorCode)
: base(message)
{
this.ErrorCode = errorCode;
}
public int ErrorCode { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace SomeTask
{
public partial class AutofacComponent : Component
{
public AutofacComponent()
{
InitializeComponent();
Init();
}
public AutofacComponent(IContainer container)
{
container.Add(this);
InitializeComponent();
Init();
}
public void Init()
{
Bootstrap.Init();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class EnterStage : MonoBehaviour
{
public void StageLoad1()
{
SceneManager.LoadScene("Stage1");
}
}
|
using System.Collections.Generic;
using Fingo.Auth.DbAccess.Models.Policies.Enums;
using Fingo.Auth.Domain.Policies.Enums;
namespace Fingo.Auth.Domain.Policies.ConfigurationClasses
{
public static class PolicyData
{
public static Dictionary<Policy , string> Name = new Dictionary<Policy , string>
{
{Policy.PasswordExpirationDate , "Password expiration date"} ,
{Policy.AccountExpirationDate , "Account expiration date"} ,
{Policy.MinimumPasswordLength , "Minimum password length"} ,
{Policy.RequiredPasswordCharacters , "Required password characters"} ,
{Policy.ExcludeCommonPasswords , "Exclude common passwords"}
};
public static Dictionary<Policy , PolicyType> Type = new Dictionary<Policy , PolicyType>
{
{Policy.PasswordExpirationDate , PolicyType.LogIn} ,
{Policy.AccountExpirationDate , PolicyType.LogIn} ,
{Policy.MinimumPasswordLength , PolicyType.AccountCreation} ,
{Policy.RequiredPasswordCharacters , PolicyType.AccountCreation} ,
{Policy.ExcludeCommonPasswords , PolicyType.AccountCreation}
};
public static Dictionary<Policy , bool> IsConfigurablePerUser = new Dictionary<Policy , bool>
{
{Policy.PasswordExpirationDate , false} ,
{Policy.AccountExpirationDate , true} ,
{Policy.MinimumPasswordLength , false} ,
{Policy.RequiredPasswordCharacters , false} ,
{Policy.ExcludeCommonPasswords , false}
};
}
} |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Threading;
using System.Web.Configuration;
using log4net;
namespace mssngrrr
{
public static class Settings
{
static Settings()
{
TryUpdate();
updateThread = new Thread(() =>
{
TryUpdate();
Thread.Sleep(30000);
}) {IsBackground = true};
updateThread.Start();
}
public static ConnectionStringSettings ConnectionString { get; private set; }
public static string BasicAuthHashPrefix { get; private set; }
public static string BasicAuthHashSalt { get; private set; }
public static byte[] HmacKey { get; private set; }
public static Guid Admin { get; private set; }
public static HashSet<string> LocalIPs { get; private set; }
public static string UploadPath { get; private set; }
public static int MaxFileSize { get; private set; }
public static int MaxImageWidth { get; private set; }
public static int MaxImageHeight { get; private set; }
public static HashSet<string> AllowedExtensions { get; private set; }
public static HashSet<string> AllowedMimeTypes { get; private set; }
public static int MaxSubjectLength { get; private set; }
public static int MaxMessageLength { get; private set; }
public static int MaxImageFilenameLength { get; private set; }
public static int DelayBeforeNextMessageToAdminSec { get; private set; }
public static int DelayBeforeNextMessageToUserSec { get; private set; }
public static int MaxRequestLength { get; private set; }
private static void TryUpdate()
{
try
{
ConnectionString = ConfigurationManager.ConnectionStrings["main"];
BasicAuthHashPrefix = ConfigurationManager.AppSettings["BasicAuthHashPrefix"];
BasicAuthHashSalt = ConfigurationManager.AppSettings["BasicAuthHashSalt"];
HmacKey = Convert.FromBase64String(ConfigurationManager.AppSettings["HmacKey"]);
Admin = Guid.Parse(ConfigurationManager.AppSettings["Admin"]);
LocalIPs = new HashSet<string>(ConfigurationManager.AppSettings["LocalIPs"].Split('|'));
UploadPath = ConfigurationManager.AppSettings["UploadPath"];
MaxFileSize = int.Parse(ConfigurationManager.AppSettings["MaxFileSize"]);
MaxImageWidth = int.Parse(ConfigurationManager.AppSettings["MaxImageWidth"]);
MaxImageHeight = int.Parse(ConfigurationManager.AppSettings["MaxImageHeight"]);
AllowedExtensions = new HashSet<string>(ConfigurationManager.AppSettings["AllowedExtensions"].Split('|'), StringComparer.InvariantCultureIgnoreCase);
AllowedMimeTypes = new HashSet<string>(ConfigurationManager.AppSettings["AllowedMimeTypes"].Split('|'), StringComparer.InvariantCultureIgnoreCase);
MaxSubjectLength = int.Parse(ConfigurationManager.AppSettings["MaxSubjectLength"]);
MaxMessageLength = int.Parse(ConfigurationManager.AppSettings["MaxMessageLength"]);
MaxImageFilenameLength = int.Parse(ConfigurationManager.AppSettings["MaxImageFilenameLength"]);
DelayBeforeNextMessageToAdminSec = int.Parse(ConfigurationManager.AppSettings["DelayBeforeNextMessageToAdminSec"]);
DelayBeforeNextMessageToUserSec = int.Parse(ConfigurationManager.AppSettings["DelayBeforeNextMessageToUserSec"]);
MaxRequestLength = ((HttpRuntimeSection)ConfigurationManager.GetSection("system.web/httpRuntime")).MaxRequestLength;
}
catch(Exception e)
{
Log.Error("Failed to update settings", e);
}
}
private static readonly ILog Log = LogManager.GetLogger(typeof(Settings));
private static readonly Thread updateThread;
}
} |
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Loading : MonoBehaviour
{
public Text textExpired;
public Slider loadingSlider;
void Start()
{
StartCoroutine(waitAndStart());
}
IEnumerator waitAndStart()
{
yield return new WaitForSeconds(0.2f);
StartCoroutine(LoadAsynchronously("Menu"));
}
IEnumerator LoadAsynchronously(string scenceName)
{
AsyncOperation operation = SceneManager.LoadSceneAsync(scenceName);
while (!operation.isDone)
{
loadingSlider.value = operation.progress;
yield return null;
}
}
}
|
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using UsersLib.DbContextSettings;
using UsersLib.Entity;
namespace UsersLib.DbControllers
{
public class DbSiteController : IDbSiteController
{
public Site GetSite(int siteId)
{
using (UsersLibDbContext dbContext = new UsersLibDbContext())
{
return dbContext.Sites.FirstOrDefault(item => item.SiteId == siteId);
}
}
public Site GetSite(string siteKey)
{
using (UsersLibDbContext dbContext = new UsersLibDbContext())
{
return dbContext.Sites.FirstOrDefault(item => item.Name == siteKey);
}
}
public List<Site> GetSites()
{
using (UsersLibDbContext dbContext = new UsersLibDbContext())
{
return dbContext.Sites.ToList();
}
}
public Dictionary<Site, List<Group>> GetSitesByGroups()
{
using (UsersLibDbContext dbContext = new UsersLibDbContext())
{
return dbContext.Sites.Include(site => site.Groups)
.ToDictionary(item => item, item => item.Groups.ToList());
}
}
public List<Group> GetSiteGroups(int siteId)
{
using (UsersLibDbContext dbContext = new UsersLibDbContext())
{
return dbContext.Sites
.Where(item => item.SiteId == siteId)
.SelectMany(item => item.Groups)
.ToList();
}
}
public void SaveSite(Site site)
{
if (site == null)
{
return;
}
using (UsersLibDbContext dbContext = new UsersLibDbContext())
{
dbContext.Sites.AddOrUpdate(site);
dbContext.SaveChanges();
}
}
public void SaveSecureSiteData(SecureSiteData secureSiteData)
{
using (UsersLibDbContext dbContext = new UsersLibDbContext())
{
dbContext.SecureSiteData.AddOrUpdate(secureSiteData);
dbContext.SaveChanges();
}
}
public void SaveSiteGroups(int siteId, List<int> siteGroupIds)
{
if (siteId == 0)
{
return;
}
using (UsersLibDbContext dbContext = new UsersLibDbContext())
{
Site site = dbContext.Sites
.Where(item => item.SiteId == siteId)
.Include(item => item.Groups).FirstOrDefault();
List<Group> groups = dbContext.Groups
.Where(item => siteGroupIds.Contains(item.Id))
.ToList();
if (site != null)
{
site.Groups.Clear();
foreach (Group group in groups)
{
site.Groups.Add(group);
}
dbContext.SaveChanges();
}
}
}
public SecureSiteData GetSecureSiteData(int siteId)
{
using (UsersLibDbContext dbContext = new UsersLibDbContext())
{
return dbContext.SecureSiteData.FirstOrDefault(item => item.SiteId == siteId);
}
}
public void DeleteSite(int siteId)
{
using (UsersLibDbContext dbContext = new UsersLibDbContext())
{
IEnumerable<Site> sites = dbContext.Sites.Where(item => item.SiteId == siteId);
dbContext.Sites.RemoveRange(sites);
dbContext.SaveChanges();
}
}
}
} |
using System.ComponentModel.DataAnnotations;
namespace RESTfulAPI.ViewModel
{
public class ViewUser
{
public int Id { get; set; }
[Required]
public string UserName { get; set; }
public string Birthday { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
}
} |
using UnityEngine;
using System.Collections;
public class learning01 : MonoBehaviour {
int myInt;
int MyInt (int _i, int _j) {
return _i + _j;
}
void Start () {
myInt = MyInt (2,4);
print (myInt);
}
void Update () {
print (myInt);
if (Input.GetButtonDown ("Fire1")) {
myInt++;
}
if (Input.GetButtonDown ("Fire2")) {
myInt--;
}
}
} |
using System;
using System.Collections.Generic;
using UnityEngine;
public class BoardBorderConstraint : Constraint
{
#region Constraint implementation
public void ChangeMove (List<Vector3> endPoints, Vector3 startPoint, Board[] boards)
{
endPoints.RemoveAll(point => point.z < 0 || point.z >= boards.Length || point.x < 0 || point.x >= boards [(int)point.z].GetLength () || point.y < 0 || point.y >= boards[(int)point.z].GetHeight ());
}
#endregion
}
|
namespace StudentSystem.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using Models;
public class Configuration : DbMigrationsConfiguration<StudentSystem.StudentSystemContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
ContextKey = "StudentSystem.StudentSystemContext";
}
protected override void Seed(StudentSystem.StudentSystemContext context)
{
Course java = new Course()
{
Name = "Java",
Description = "Course about Java",
EndDate = DateTime.Now,
Price = 180m,
StartDate = DateTime.Now
};
java.Resources.Add(new Resource()
{
Name = "Resource1",
TypeOfResource = ResourceType.Document,
Url = "www.Resource1.com"
});
java.Resources.Add(new Resource()
{
Name = "Resource2",
TypeOfResource = ResourceType.Presentation,
Url = "www.Resource2.com"
});
java.Resources.Add(new Resource()
{
Name = "Resource3",
TypeOfResource = ResourceType.Video,
Url = "www.Resource3.com"
});
java.Resources.Add(new Resource()
{
Name = "Resource4",
TypeOfResource = ResourceType.Video,
Url = "www.Resource4.com"
});
java.Resources.Add(new Resource()
{
Name = "Resource5",
TypeOfResource = ResourceType.Video,
Url = "www.Resource5.com"
});
java.Resources.Add(new Resource()
{
Name = "Resource6",
TypeOfResource = ResourceType.Video,
Url = "www.Resource6.com"
});
Student pesho = new Student()
{
Birthday = DateTime.Now,
Name = "Pesho",
PhoneNumber = "+239843294",
RegistrationDate = DateTime.Now
};
pesho.Courses.Add(java);
pesho.Homeworks.Add(new Homework()
{
Content = "This is Pesho's first homework.",
ContentType = ContentType.Application,
Course = pesho.Courses.FirstOrDefault(),
SubmissionDate = DateTime.Now
});
pesho.Homeworks.Add(new Homework()
{
Content = "This is Pesho's second homework.",
ContentType = ContentType.Pdf,
Course = pesho.Courses.FirstOrDefault(),
SubmissionDate = DateTime.Now
});
pesho.Homeworks.Add(new Homework()
{
Content = "This is Pesho's third homework.",
ContentType = ContentType.Zip,
Course = pesho.Courses.FirstOrDefault(),
SubmissionDate = DateTime.Now
});
Student gosho = new Student()
{
Birthday = DateTime.Now,
Name = "Gosho",
PhoneNumber = "+239843294",
RegistrationDate = DateTime.Now
};
pesho.Courses.Add(new Course()
{
Name = "C#",
Description = "Course about C#",
EndDate = DateTime.Now,
Price = 220m,
StartDate = DateTime.Now
});
context.Students.AddOrUpdate(s => s.Name, pesho);
context.Students.AddOrUpdate(s => s.Name, gosho);
context.SaveChanges();
}
}
}
|
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using WebApplication.Services;
namespace WebApplication.Controllers
{
[ApiController]
[Route("Header")]
public class HeaderInfoController : Controller
{
private HeaderInfoService _service;
public HeaderInfoController(HeaderInfoService service)
{
_service = service;
}
[HttpGet]
public List<string> Get()
{
return _service.GetHeaderInfos();
}
}
}
|
// Copyright (c) 2017 Gwaredd Mountain, https://opensource.org/licenses/MIT
using System;
using System.Collections;
using System.Collections.Generic;
namespace gw.gql
{
////////////////////////////////////////////////////////////////////////////////////////////////////
// interpreters provide the "DOM" search interface to a given type
public class Interpreter
{
public class Child
{
public Child( string name, object value )
{
Name = name;
Value = value;
}
public string Name;
public object Value;
}
virtual public object Attr( object obj, string name ) { return null; }
virtual public Child[] Children( object obj ) { return null; }
}
////////////////////////////////////////////////////////////////////////////////////////////////////
public static class Interpreters
{
static Interpreter mDefault = new InterpreterDefault();
static Dictionary<Type, Interpreter> mInterpreters = new Dictionary<Type, Interpreter>();
static public void Add( Type type, Interpreter interpreter )
{
mInterpreters[ type ] = interpreter;
}
static public void Remove( Type type )
{
mInterpreters.Remove( type );
}
static public Interpreter Get( Type type )
{
return mInterpreters.ContainsKey( type ) ? mInterpreters[ type ] : mDefault;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// default interpreter - use reflection to provide interface onto object
public class InterpreterDefault : Interpreter
{
//----------------------------------------------------------------------------------------------------
// attr
public override object Attr( object obj, string name )
{
var type = obj.GetType();
// find field?
var field = type.GetField( name );
if( field != null )
{
if( field.IsPrivate )
{
return null;
}
return field.GetValue( obj );
}
// property?
var prop = type.GetProperty( name );
if( prop != null )
{
if( prop.CanRead == false )
{
return null;
}
return prop.GetValue( obj, null );
}
return null;
}
//----------------------------------------------------------------------------------------------------
// children
override public Child[] Children( object obj )
{
// only for collection types
var dict = obj as IDictionary;
if( dict != null )
{
var children = new Child[ dict.Count ];
var i = 0;
foreach( var key in dict.Keys )
{
children[ i++ ] = new Child( key.ToString(), dict[ key ] );
}
return children;
}
// array
var type = obj.GetType();
if( typeof( IEnumerable ).IsAssignableFrom( type ) )
{
var results = new List<Child>();
foreach( var child in obj as IEnumerable )
{
results.Add( new Child( null, child ) );
}
return results.ToArray();
}
else if( type.IsArray )
{
// foreach element, pass query
var results = new List<Child>();
foreach( var element in obj as object[] )
{
results.Add( new Child( null, element ) );
}
return results.ToArray();
}
return null;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using Inventor;
using Autodesk.DesignScript.Geometry;
using Autodesk.DesignScript.Interfaces;
using Autodesk.DesignScript.Runtime;
using Dynamo.Models;
using Dynamo.Utilities;
using InventorLibrary.GeometryConversion;
using InventorServices.Persistence;
using Point = Autodesk.DesignScript.Geometry.Point;
namespace InventorLibrary.API
{
[IsVisibleInDynamoLibrary(false)]
public class InvComponentOccurrence
{
#region Internal properties
internal Inventor.ComponentOccurrence InternalComponentOccurrence { get; set; }
internal string Internal_DisplayName
{
get { return ComponentOccurrenceInstance._DisplayName; }
}
internal bool Internal_IsSimulationOccurrence
{
get { return ComponentOccurrenceInstance._IsSimulationOccurrence; }
}
internal string InternalActiveDesignViewRepresentation
{
get { return ComponentOccurrenceInstance.ActiveDesignViewRepresentation; }
}
internal string InternalActiveLevelOfDetailRepresentation
{
get { return ComponentOccurrenceInstance.ActiveLevelOfDetailRepresentation; }
}
internal Object InternalApplication
{
get { return ComponentOccurrenceInstance.Application; }
}
internal InvAttributeSets InternalAttributeSets
{
get { return InvAttributeSets.ByInvAttributeSets(ComponentOccurrenceInstance.AttributeSets); }
}
////internal InvAssemblyConstraintsEnumerator InternalConstraints
////{
//// get { return InvAssemblyConstraintsEnumerator.ByInvAssemblyConstraintsEnumerator(ComponentOccurrenceInstance.Constraints); }
////}
internal InvComponentDefinition InternalContextDefinition
{
get { return InvComponentDefinition.ByInvComponentDefinition(ComponentOccurrenceInstance.ContextDefinition); }
}
internal InvComponentDefinition InternalDefinition
{
get { return InvComponentDefinition.ByInvComponentDefinition(ComponentOccurrenceInstance.Definition); }
}
internal InvDocumentTypeEnum InternalDefinitionDocumentType
{
get { return ComponentOccurrenceInstance.DefinitionDocumentType.As<InvDocumentTypeEnum>(); }
}
////internal InvComponentDefinitionReference InternalDefinitionReference
////{
//// get { return InvComponentDefinitionReference.ByInvComponentDefinitionReference(ComponentOccurrenceInstance.DefinitionReference); }
////}
internal bool InternalEdited
{
get { return ComponentOccurrenceInstance.Edited; }
}
internal bool InternalHasBodyOverride
{
get { return ComponentOccurrenceInstance.HasBodyOverride; }
}
////internal InviMateDefinitionsEnumerator InternaliMateDefinitions
////{
//// get { return InviMateDefinitionsEnumerator.ByInviMateDefinitionsEnumerator(ComponentOccurrenceInstance.iMateDefinitions); }
////}
internal bool InternalIsiAssemblyMember
{
get { return ComponentOccurrenceInstance.IsiAssemblyMember; }
}
internal bool InternalIsiPartMember
{
get { return ComponentOccurrenceInstance.IsiPartMember; }
}
internal bool InternalIsPatternElement
{
get { return ComponentOccurrenceInstance.IsPatternElement; }
}
internal bool InternalIsSubstituteOccurrence
{
get { return ComponentOccurrenceInstance.IsSubstituteOccurrence; }
}
////internal InvAssemblyJointsEnumerator InternalJoints
////{
//// get { return InvAssemblyJointsEnumerator.ByInvAssemblyJointsEnumerator(ComponentOccurrenceInstance.Joints); }
////}
////internal InvMassProperties InternalMassProperties
////{
//// get { return InvMassProperties.ByInvMassProperties(ComponentOccurrenceInstance.MassProperties); }
////}
////internal InvComponentOccurrencesEnumerator InternalOccurrencePath
////{
//// get { return InvComponentOccurrencesEnumerator.ByInvComponentOccurrencesEnumerator(ComponentOccurrenceInstance.OccurrencePath); }
////}
internal InvAssemblyComponentDefinition InternalParent
{
get { return InvAssemblyComponentDefinition.ByInvAssemblyComponentDefinition(ComponentOccurrenceInstance.Parent); }
}
internal InvComponentOccurrence InternalParentOccurrence
{
get { return InvComponentOccurrence.ByInvComponentOccurrence(ComponentOccurrenceInstance.ParentOccurrence); }
}
////internal InvOccurrencePatternElement InternalPatternElement
////{
//// get { return InvOccurrencePatternElement.ByInvOccurrencePatternElement(ComponentOccurrenceInstance.PatternElement); }
////}
////internal InvBox InternalRangeBox
////{
//// get { return InvBox.ByInvBox(ComponentOccurrenceInstance.RangeBox); }
////}
////internal InvDocumentDescriptor InternalReferencedDocumentDescriptor
////{
//// get { return InvDocumentDescriptor.ByInvDocumentDescriptor(ComponentOccurrenceInstance.ReferencedDocumentDescriptor); }
////}
////internal InvReferencedFileDescriptor InternalReferencedFileDescriptor
////{
//// get { return InvReferencedFileDescriptor.ByInvReferencedFileDescriptor(ComponentOccurrenceInstance.ReferencedFileDescriptor); }
////}
////internal InvComponentOccurrencesEnumerator InternalSubOccurrences
////{
//// get { return InvComponentOccurrencesEnumerator.ByInvComponentOccurrencesEnumerator(ComponentOccurrenceInstance.SubOccurrences); }
////}
internal bool InternalSuppressed
{
get { return ComponentOccurrenceInstance.Suppressed; }
}
////internal InvSurfaceBodies InternalSurfaceBodies
////{
//// get { return InvSurfaceBodies.ByInvSurfaceBodies(ComponentOccurrenceInstance.SurfaceBodies); }
////}
internal InvObjectTypeEnum InternalType
{
get { return ComponentOccurrenceInstance.Type.As<InvObjectTypeEnum>(); }
}
internal string InternalActivePositionalRepresentation { get; set; }
internal string InternalActivePositionalState { get; set; }
internal bool InternalAdaptive { get; set; }
internal Asset InternalAppearance { get; set; }
internal AppearanceSourceTypeEnum InternalAppearanceSourceType { get; set; }
internal BOMStructureEnum InternalBOMStructure { get; set; }
internal bool InternalContactSet { get; set; }
internal bool InternalCustomAdaptive { get; set; }
internal ActionTypeEnum InternalDisabledActionTypes { get; set; }
internal bool InternalEnabled { get; set; }
internal bool InternalExcluded { get; set; }
internal bool InternalFlexible { get; set; }
internal bool InternalGrounded { get; set; }
internal Object InternalInterchangeableComponents { get; set; }
internal bool InternalIsAssociativeToDesignViewRepresentation { get; set; }
internal bool InternalLocalAdaptive { get; set; }
internal string InternalName { get; set; }
internal double InternalOverrideOpacity { get; set; }
internal bool InternalReference { get; set; }
internal RenderStyle InternalRenderStyle { get; set; }
internal bool InternalShowDegreesOfFreedom { get; set; }
internal Matrix InternalTransformation { get; set; }
internal bool InternalVisible { get; set; }
#endregion
#region Private constructors
private InvComponentOccurrence(InvComponentOccurrence invComponentOccurrence)
{
InternalComponentOccurrence = invComponentOccurrence.InternalComponentOccurrence;
}
private InvComponentOccurrence(Inventor.ComponentOccurrence invComponentOccurrence)
{
InternalComponentOccurrence = invComponentOccurrence;
}
#endregion
#region Private methods
private void InternalChangeRowOfiAssemblyMember(Object newRow, Object options)
{
ComponentOccurrenceInstance.ChangeRowOfiAssemblyMember( newRow, options);
}
private void InternalChangeRowOfiPartMember(Object newRow, Object customInput)
{
ComponentOccurrenceInstance.ChangeRowOfiPartMember( newRow, customInput);
}
private void InternalCreateGeometryProxy(Object geometry, out Object result)
{
ComponentOccurrenceInstance.CreateGeometryProxy( geometry, out result);
}
private void InternalDelete()
{
ComponentOccurrenceInstance.Delete();
}
private void InternalEdit()
{
ComponentOccurrenceInstance.Edit();
}
private void InternalExitEdit(ExitTypeEnum exitTo)
{
ComponentOccurrenceInstance.ExitEdit( exitTo);
}
private void InternalGetDegreesOfFreedom(out int translationDegreesCount, out ObjectsEnumerator translationDegreesVectors, out int rotationDegreesCount, out ObjectsEnumerator rotationDegreesVectors, out Point dOFCenter)
{
Inventor.Point dOFCenterInv;
ComponentOccurrenceInstance.GetDegreesOfFreedom(out translationDegreesCount, out translationDegreesVectors, out rotationDegreesCount, out rotationDegreesVectors, out dOFCenterInv);
dOFCenter = dOFCenterInv.ToPoint();
}
private DisplayModeEnum InternalGetDisplayMode(out DisplayModeSourceTypeEnum displayModeSourceType)
{
return ComponentOccurrenceInstance.GetDisplayMode(out displayModeSourceType);
}
private void InternalGetReferenceKey(ref byte[] referenceKey, int keyContext)
{
ComponentOccurrenceInstance.GetReferenceKey(ref referenceKey, keyContext);
}
private RenderStyle InternalGetRenderStyle(out StyleSourceTypeEnum styleSourceType)
{
return ComponentOccurrenceInstance.GetRenderStyle(out styleSourceType);
}
private void InternalReplace(string fileName, bool replaceAll)
{
ComponentOccurrenceInstance.Replace( fileName, replaceAll);
}
private void InternalSetDesignViewRepresentation(string representation, string reserved, bool associative)
{
ComponentOccurrenceInstance.SetDesignViewRepresentation( representation, reserved, associative);
}
private void InternalSetDisplayMode(DisplayModeSourceTypeEnum displayModeSourceType, Object displayMode)
{
ComponentOccurrenceInstance.SetDisplayMode( displayModeSourceType, displayMode);
}
private void InternalSetLevelOfDetailRepresentation(string representation, bool skipDocumentSave)
{
ComponentOccurrenceInstance.SetLevelOfDetailRepresentation( representation, skipDocumentSave);
}
private void InternalSetRenderStyle(StyleSourceTypeEnum styleSourceType, Object renderStyle)
{
ComponentOccurrenceInstance.SetRenderStyle( styleSourceType, renderStyle);
}
private void InternalSetTransformWithoutConstraints(Matrix matrix)
{
ComponentOccurrenceInstance.SetTransformWithoutConstraints( matrix);
}
private void InternalShowRelationships()
{
ComponentOccurrenceInstance.ShowRelationships();
}
private void InternalSuppress(bool skipDocumentSave)
{
ComponentOccurrenceInstance.Suppress( skipDocumentSave);
}
private void InternalUnsuppress()
{
ComponentOccurrenceInstance.Unsuppress();
}
#endregion
#region Public properties
public Inventor.ComponentOccurrence ComponentOccurrenceInstance
{
get { return InternalComponentOccurrence; }
set { InternalComponentOccurrence = value; }
}
public string _DisplayName
{
get { return Internal_DisplayName; }
}
public bool _IsSimulationOccurrence
{
get { return Internal_IsSimulationOccurrence; }
}
public string ActiveDesignViewRepresentation
{
get { return InternalActiveDesignViewRepresentation; }
}
public string ActiveLevelOfDetailRepresentation
{
get { return InternalActiveLevelOfDetailRepresentation; }
}
public Object Application
{
get { return InternalApplication; }
}
public InvAttributeSets AttributeSets
{
get { return InternalAttributeSets; }
}
////public InvAssemblyConstraintsEnumerator Constraints
////{
//// get { return InternalConstraints; }
////}
public InvComponentDefinition ContextDefinition
{
get { return InternalContextDefinition; }
}
public InvComponentDefinition Definition
{
get { return InternalDefinition; }
}
public InvDocumentTypeEnum DefinitionDocumentType
{
get { return InternalDefinitionDocumentType; }
}
////public InvComponentDefinitionReference DefinitionReference
////{
//// get { return InternalDefinitionReference; }
////}
public bool Edited
{
get { return InternalEdited; }
}
public bool HasBodyOverride
{
get { return InternalHasBodyOverride; }
}
////public InviMateDefinitionsEnumerator iMateDefinitions
////{
//// get { return InternaliMateDefinitions; }
////}
public bool IsiAssemblyMember
{
get { return InternalIsiAssemblyMember; }
}
public bool IsiPartMember
{
get { return InternalIsiPartMember; }
}
public bool IsPatternElement
{
get { return InternalIsPatternElement; }
}
public bool IsSubstituteOccurrence
{
get { return InternalIsSubstituteOccurrence; }
}
////public InvAssemblyJointsEnumerator Joints
////{
//// get { return InternalJoints; }
////}
////public InvMassProperties MassProperties
////{
//// get { return InternalMassProperties; }
////}
////public InvComponentOccurrencesEnumerator OccurrencePath
////{
//// get { return InternalOccurrencePath; }
////}
public InvAssemblyComponentDefinition Parent
{
get { return InternalParent; }
}
public InvComponentOccurrence ParentOccurrence
{
get { return InternalParentOccurrence; }
}
////public InvOccurrencePatternElement PatternElement
////{
//// get { return InternalPatternElement; }
////}
////public InvBox RangeBox
////{
//// get { return InternalRangeBox; }
////}
////public InvDocumentDescriptor ReferencedDocumentDescriptor
////{
//// get { return InternalReferencedDocumentDescriptor; }
////}
////public InvReferencedFileDescriptor ReferencedFileDescriptor
////{
//// get { return InternalReferencedFileDescriptor; }
////}
////public InvComponentOccurrencesEnumerator SubOccurrences
////{
//// get { return InternalSubOccurrences; }
////}
public bool Suppressed
{
get { return InternalSuppressed; }
}
////public InvSurfaceBodies SurfaceBodies
////{
//// get { return InternalSurfaceBodies; }
////}
public InvObjectTypeEnum Type
{
get { return InternalType; }
}
public string ActivePositionalRepresentation
{
get { return InternalActivePositionalRepresentation; }
set { InternalActivePositionalRepresentation = value; }
}
public string ActivePositionalState
{
get { return InternalActivePositionalState; }
set { InternalActivePositionalState = value; }
}
public bool Adaptive
{
get { return InternalAdaptive; }
set { InternalAdaptive = value; }
}
////public InvAsset Appearance
////{
//// get { return InternalAppearance; }
//// set { InternalAppearance = value; }
////}
////public InvAppearanceSourceTypeEnum AppearanceSourceType
////{
//// get { return InternalAppearanceSourceType; }
//// set { InternalAppearanceSourceType = value; }
////}
////public InvBOMStructureEnum BOMStructure
////{
//// get { return InternalBOMStructure; }
//// set { InternalBOMStructure = value; }
////}
public bool ContactSet
{
get { return InternalContactSet; }
set { InternalContactSet = value; }
}
public bool CustomAdaptive
{
get { return InternalCustomAdaptive; }
set { InternalCustomAdaptive = value; }
}
////public InvActionTypeEnum DisabledActionTypes
////{
//// get { return InternalDisabledActionTypes; }
//// set { InternalDisabledActionTypes = value; }
////}
public bool Enabled
{
get { return InternalEnabled; }
set { InternalEnabled = value; }
}
public bool Excluded
{
get { return InternalExcluded; }
set { InternalExcluded = value; }
}
public bool Flexible
{
get { return InternalFlexible; }
set { InternalFlexible = value; }
}
public bool Grounded
{
get { return InternalGrounded; }
set { InternalGrounded = value; }
}
public Object InterchangeableComponents
{
get { return InternalInterchangeableComponents; }
set { InternalInterchangeableComponents = value; }
}
public bool IsAssociativeToDesignViewRepresentation
{
get { return InternalIsAssociativeToDesignViewRepresentation; }
set { InternalIsAssociativeToDesignViewRepresentation = value; }
}
public bool LocalAdaptive
{
get { return InternalLocalAdaptive; }
set { InternalLocalAdaptive = value; }
}
public string Name
{
get { return InternalName; }
set { InternalName = value; }
}
public double OverrideOpacity
{
get { return InternalOverrideOpacity; }
set { InternalOverrideOpacity = value; }
}
public bool Reference
{
get { return InternalReference; }
set { InternalReference = value; }
}
////public InvRenderStyle RenderStyle
////{
//// get { return InternalRenderStyle; }
//// set { InternalRenderStyle = value; }
////}
public bool ShowDegreesOfFreedom
{
get { return InternalShowDegreesOfFreedom; }
set { InternalShowDegreesOfFreedom = value; }
}
////public InvMatrix Transformation
////{
//// get { return InternalTransformation; }
//// set { InternalTransformation = value; }
////}
public bool Visible
{
get { return InternalVisible; }
set { InternalVisible = value; }
}
#endregion
#region Public static constructors
public static InvComponentOccurrence ByInvComponentOccurrence(InvComponentOccurrence invComponentOccurrence)
{
return new InvComponentOccurrence(invComponentOccurrence);
}
public static InvComponentOccurrence ByInvComponentOccurrence(Inventor.ComponentOccurrence invComponentOccurrence)
{
return new InvComponentOccurrence(invComponentOccurrence);
}
#endregion
#region Public methods
public void ChangeRowOfiAssemblyMember(Object newRow, Object options)
{
InternalChangeRowOfiAssemblyMember( newRow, options);
}
public void ChangeRowOfiPartMember(Object newRow, Object customInput)
{
InternalChangeRowOfiPartMember( newRow, customInput);
}
public void CreateGeometryProxy(Object geometry, out Object result)
{
InternalCreateGeometryProxy( geometry, out result);
}
public void Delete()
{
InternalDelete();
}
public void Edit()
{
InternalEdit();
}
public void ExitEdit(ExitTypeEnum exitTo)
{
InternalExitEdit( exitTo);
}
public void GetDegreesOfFreedom(out int translationDegreesCount, out ObjectsEnumerator translationDegreesVectors, out int rotationDegreesCount, out ObjectsEnumerator rotationDegreesVectors, out Point dOFCenter)
{
InternalGetDegreesOfFreedom(out translationDegreesCount, out translationDegreesVectors, out rotationDegreesCount, out rotationDegreesVectors, out dOFCenter);
}
public DisplayModeEnum GetDisplayMode(out DisplayModeSourceTypeEnum displayModeSourceType)
{
return InternalGetDisplayMode(out displayModeSourceType);
}
public void GetReferenceKey(ref byte[] referenceKey, int keyContext)
{
InternalGetReferenceKey(ref referenceKey, keyContext);
}
public RenderStyle GetRenderStyle(out StyleSourceTypeEnum styleSourceType)
{
return InternalGetRenderStyle(out styleSourceType);
}
public void Replace(string fileName, bool replaceAll)
{
InternalReplace( fileName, replaceAll);
}
public void SetDesignViewRepresentation(string representation, string reserved, bool associative)
{
InternalSetDesignViewRepresentation( representation, reserved, associative);
}
public void SetDisplayMode(DisplayModeSourceTypeEnum displayModeSourceType, Object displayMode)
{
InternalSetDisplayMode( displayModeSourceType, displayMode);
}
public void SetLevelOfDetailRepresentation(string representation, bool skipDocumentSave)
{
InternalSetLevelOfDetailRepresentation( representation, skipDocumentSave);
}
public void SetRenderStyle(StyleSourceTypeEnum styleSourceType, Object renderStyle)
{
InternalSetRenderStyle( styleSourceType, renderStyle);
}
public void SetTransformWithoutConstraints(Matrix matrix)
{
InternalSetTransformWithoutConstraints( matrix);
}
public void ShowRelationships()
{
InternalShowRelationships();
}
public void Suppress(bool skipDocumentSave)
{
InternalSuppress( skipDocumentSave);
}
public void Unsuppress()
{
InternalUnsuppress();
}
#endregion
}
}
|
using ClinicWebAPI.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ClinicWebAPI.Data
{
public class ClinicContext : DbContext
{
public ClinicContext(DbContextOptions options)
: base(options)
{}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Patient>()
.HasOne(d => d.Doctor)
.WithMany(p => p.Patients)
.HasForeignKey(d => d.DoctorId);
builder.Entity<Ailment>()
.HasOne(p => p.Patient)
.WithMany(a => a.Ailments)
.HasForeignKey(p => p.PatientId);
builder.Entity<Medication>()
.HasOne(p => p.Patient)
.WithMany(a => a.Medications)
.HasForeignKey(p => p.PatientId);
builder.Entity<Visit>()
.HasOne(p => p.Patient)
.WithMany(a => a.Visits)
.HasForeignKey(p => p.PatientId);
}
public DbSet<Ailment> Ailments { get; set; }
public DbSet<Medication> Medications { get; set; }
public DbSet<Patient> Patients { get; set; }
public DbSet<Doctor> Doctors { get; set; }
public DbSet<Visit> Visits { get; set; }
}
} |
namespace Infrastructure.PasswordPolicies
{
/// <summary>
/// Interface for password policy
/// </summary>
public interface IPasswordPolicy
{
/// <summary>
/// Validate password against policy
/// </summary>
/// <param name = "password">Password</param>
/// <returns>Boolean indicating if password is valid according to policy</returns>
bool Validate(string password);
}
} |
namespace PatientWebAppTests.CreateObjectsForTests
{
public class StubRepository
{
/*
private readonly TestObjectFactory _objectFactory;
public StubRepository()
{
_objectFactory = new TestObjectFactory();
}
public IActivePatientRepository CreatePatientStubRepository()
{
var patientStubRepository = new Mock<IActivePatientRepository>();
var patientValidObject = _objectFactory.GetPatient().CreateValidTestObject();
var patients = new List<Patient>();
patients.Add(patientValidObject);
patientStubRepository.Setup(m => m.GetPatientByJmbg("1234567891234")).Returns(patients[0]);
patientStubRepository.Setup(m => m.AddPatient(new Patient()));
patientStubRepository.Setup(m => m.GetNumberOfCanceledExaminations("1234567891234")).Returns(3);
patientStubRepository.Setup(m => m.GetPatientByUsernameAndPassword("pera", "12345678")).Returns(patients[0]);
patientStubRepository.Setup(m => m.GetPatientByUsernameAndPassword("milic_milan@gmail.com", "milanmilic965")).Throws(new NotFoundException());
patientStubRepository.Setup(m => m.GetPatientByUsernameAndPassword("tamara", "33345678")).Throws(new BadRequestException());
return patientStubRepository.Object;
}
public IActivePatientCardRepository CreatePatientCardStubRepository()
{
var patientCardStubRepository = new Mock<IActivePatientCardRepository>();
var patientCardValidObject = _objectFactory.GetPatientCard().CreateValidTestObject();
var patientCards = new List<PatientCard>();
patientCards.Add(patientCardValidObject);
patientCardStubRepository.Setup(m => m.GetPatientCardByJmbg("1234567891234")).Returns(patientCards[0]);
patientCardStubRepository.Setup(m => m.AddPatientCard(new PatientCard()));
patientCardStubRepository.Setup(m => m.CheckIfPatientCardExists(1)).Returns(true);
return patientCardStubRepository.Object;
}
public ISurveyRepository CreateSurveyStubRepository()
{
var surveyStubRepository = new Mock<ISurveyRepository>();
var surveyResultAboutDoctorValidObject = _objectFactory.GetSurveyResultAboutDoctor().CreateValidTestObject();
var surveyResultsAboutDoctor = new List<SurveyResult> { surveyResultAboutDoctorValidObject };
var surveyResultAboutHospitalValidObject = _objectFactory.GetSurveyResultAboutHospital().CreateValidTestObject();
var surveyResultsAboutHospital = new List<SurveyResult> { surveyResultAboutHospitalValidObject };
var surveyResultAboutMedicalStaffValidObject = _objectFactory.GetSurveyResultAboutMedicalStaff().CreateValidTestObject();
var surveyResultsAboutMedicalStaff = new List<SurveyResult> { surveyResultAboutMedicalStaffValidObject };
surveyStubRepository.Setup(m => m.AddSurvey(new Survey()));
surveyStubRepository.Setup(m => m.GetSurveyResultsAboutDoctor("2211985888888")).Returns(surveyResultsAboutDoctor);
surveyStubRepository.Setup(m => m.GetSurveyResultsAboutHospital()).Returns(surveyResultsAboutHospital);
surveyStubRepository.Setup(m => m.GetSurveyResultsAboutMedicalStaff()).Returns(surveyResultsAboutMedicalStaff);
return surveyStubRepository.Object;
}
public IExaminationRepository CreateExaminationStubRepository()
{
var examinationStubRepository = new Mock<IExaminationRepository>();
Examination examinationCanBeCanceled = _objectFactory.GetExamination().CreateValidCanBeCanceledTestObject();
Examination examinationCantBeCanceled = _objectFactory.GetExamination().CreateValidCantBeCanceledTestObject();
Examination examinationValidForSurvey = _objectFactory.GetExamination().CreateValidTestObjectForSurvey();
Examination examinationInvalidForSurvey = _objectFactory.GetExamination().CreateInvalidTestObjectForSurvey();
List<Examination> examinations = _objectFactory.GetExamination().CreateValidTestObjects();
List<Examination> canceledExaminations = GetCanceledExamination(examinations);
List<Examination> previousExaminations = GetPreviousExaminations(examinations);
examinationStubRepository.Setup(m => m.AddExamination(new Examination()));
examinationStubRepository.Setup(m => m.GetExaminationById(1)).Returns(examinationCanBeCanceled);
examinationStubRepository.Setup(m => m.GetExaminationById(2)).Returns(examinationCantBeCanceled);
examinationStubRepository.Setup(m => m.GetExaminationById(9)).Returns(examinationValidForSurvey);
examinationStubRepository.Setup(m => m.GetExaminationById(10)).Returns(examinationInvalidForSurvey);
examinationStubRepository.Setup(m => m.GetExaminationsByPatient("1309998775018")).Returns(examinations);
examinationStubRepository.Setup(m => m.GetPreviousExaminationsByPatient("1309998775018")).Returns(previousExaminations);
examinationStubRepository.Setup(m => m.GetFollowingExaminationsByPatient("1309998775018")).Returns(examinations);
examinationStubRepository.Setup(m => m.GetCanceledExaminationsByPatient("1309998775018")).Returns(canceledExaminations);
return examinationStubRepository.Object;
}
public ITherapyRepository CreateTherapyStubRepository()
{
var therapyStubRepository = new Mock<ITherapyRepository>();
var therapyValidObject = _objectFactory.GetTherapy().CreateValidTestObject();
var therapies = new List<Therapy>();
therapies.Add(therapyValidObject);
therapyStubRepository.Setup(m => m.GetTherapyByPatient("1309998775018")).Returns(therapies);
return therapyStubRepository.Object;
}
private List<Examination> GetCanceledExamination(List<Examination> examinations)
{
examinations.ForEach(e => e.ExaminationStatus = ExaminationStatus.CANCELED);
return examinations;
}
private List<Examination> GetPreviousExaminations(List<Examination> examinations)
{
examinations.ForEach(e => e.ExaminationStatus = ExaminationStatus.FINISHED);
return examinations;
}
public IRoomRepository CreateRoomStubRepository()
{
var roomStubRepository = new Mock<IRoomRepository>();
var roomValidObject = _objectFactory.GetRoom().CreateValidTestObject();
var rooms = new List<Room>();
rooms.Add(roomValidObject);
roomStubRepository.Setup(m => m.GetRoomByNumber(1)).Returns(rooms[0]);
roomStubRepository.Setup(m => m.CheckIfRoomExists(1)).Returns(true);
return roomStubRepository.Object;
}
public IDoctorRepository CreateDoctorStubRepository()
{
var doctorStubRepository = new Mock<IDoctorRepository>();
var doctorValidObject = _objectFactory.GetDoctor().CreateValidTestObject();
var doctors = new List<Doctor>();
doctors.Add(doctorValidObject);
doctorStubRepository.Setup(m => m.GetDoctorByJmbg("0909965768767")).Returns(doctors[0]);
doctorStubRepository.Setup(m => m.CheckIfDoctorExists("0909965768767")).Returns(true);
return doctorStubRepository.Object;
}
public IAdminRepository CreateAdminStubRepository()
{
var adminStubRepository = new Mock<IAdminRepository>();
var doctorValidObject = _objectFactory.GetAdmin().CreateValidTestObject();
var admins = new List<Admin>();
admins.Add(doctorValidObject);
adminStubRepository.Setup(m => m.GetAdminByUsernameAndPassword("milic_milan@gmail.com", "milanmilic965")).Returns(admins[0]);
adminStubRepository.Setup(m => m.GetAdminByUsernameAndPassword("pera", "12345678")).Throws(new NotFoundException());
adminStubRepository.Setup(m => m.GetAdminByUsernameAndPassword("tamara", "33345678")).Throws(new BadRequestException());
return adminStubRepository.Object;
}
*/
}
}
|
namespace CheckIt
{
using System.Collections.Generic;
using CheckIt.Compilation;
using CheckIt.Syntax;
internal class CheckClass : CheckType, IClass
{
private readonly ICompilationInfo compilationInfo;
public CheckClass(string name, string nameSpace, ICompilationInfo compilationInfo, Position position)
: base(name, nameSpace, position)
{
this.compilationInfo = compilationInfo;
}
public override IEnumerable<IMethod> Method(string name)
{
foreach (var method in this.compilationInfo.Get<IMethod>())
{
if (FileUtil.FilenameMatchesPattern(method.Name, name))
{
if (method.Type == this)
{
yield return method;
}
}
}
}
}
} |
#region License
// Copyright (c) 2012 Trafficspaces Inc.
//
// 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.
//
// Reference Documentation: http://support.trafficspaces.com/kb/api/api-introduction
#endregion
using System;
namespace Trafficspaces.Api.Model {
/// <summary>
/// An implementation of the Contact resource as defined in http://support.trafficspaces.com/kb/api/api-contacts.
/// </summary>
public class Contact : Resource {
//******************************
//** INPUT & OUTPUT VARIABLES **
//******************************
public string name { get; set; }
public Profile profile { get; set; }
public LinkedResource linked_user { get; set; }
//******************************
//*** OUTPUT ONLY VARIABLES ****
//******************************
public string realm { get; set; }
public DateTime creation_date { get; set; }
public DateTime last_modified_date { get; set; }
public Contact() {}
public static Contact CreateContact(string name, Profile profile, LinkedResource linked_user) {
Contact contact = new Contact();
contact.name = name;
contact.profile = profile;
contact.linked_user = linked_user;
return contact;
}
public static Profile CreateProfile(string email, string company_name, int type) {
Profile profile = new Profile();
profile.email = email;
profile.company_name = company_name;
profile.type = type;
profile.contact_details = new Profile.ContactDetails();
return profile;
}
public class Profile : Resource {
public static int TYPE_ADVERTISER = 0;
public static int TYPE_PUBLISHER = 1;
//******************************
//** INPUT & OUTPUT VARIABLES **
//******************************
public string reference { get; set; }
public string company_name { get; set; }
public string website { get; set; }
public string email { get; set; }
public int type { get; set; }
public ContactDetails contact_details { get; set; }
public class ContactDetails : Resource {
//******************************
//** INPUT & OUTPUT VARIABLES **
//******************************
public string street { get; set; }
public string street2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zip { get; set; }
public string country { get; set; }
public string mobile { get; set; }
public string telephone { get; set; }
public string fax { get; set; }
}
}
}
} |
using System;
namespace interfaces
{
public class Helicopter : IVehicle, IAir
{
public int Wheels { get; set; } = 0;
public int Doors { get; set; } = 2;
public int PassengerCapacity { get; set; } = 6;
public bool Winged { get; set; } = false;
public double EngineVolume { get; set; } = 21.1;
public double MaxAirSpeed { get; set; } = 200.7;
public void Fly()
{
Console.WriteLine("The helicopter darts through the air like a gratuitously violent hummingbird");
}
}
} |
using GalaSoft.MvvmLight;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace WpfAppParking.Model
{
class Rij : INotifyPropertyChanged, IDataErrorInfo
{
public event PropertyChangedEventHandler PropertyChanged;
private int id;
private int parking_ID;
private int totale_plaatsen;
private int bezette_plaatsen;
private bool volzet;
public int ID
{
get
{
return id;
}
set
{
id = value;
NotifyPropertyChanged();
}
}
public int Parking_ID
{
get
{
return parking_ID;
}
set
{
parking_ID = value;
NotifyPropertyChanged();
}
}
public int Totale_plaatsen
{
get
{
return totale_plaatsen;
}
set
{
totale_plaatsen = value;
NotifyPropertyChanged();
}
}
public int Bezette_plaatsen
{
get
{
return bezette_plaatsen;
}
set
{
bezette_plaatsen = value;
NotifyPropertyChanged();
}
}
public bool Volzet
{
get
{
return volzet;
}
set
{
if (bezette_plaatsen == totale_plaatsen)
{
volzet = true;
}
else
{
volzet = false;
}
NotifyPropertyChanged();
}
}
public string Error
{
get
{
return string.Empty;
}
}
public string this[string columnName]
{
get
{
string result = string.Empty;
return result;
}
}
public Rij()
{ }
public void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using Kulula.com.Helpers;
using Kulula.com.Models;
using Kulula.com.Services;
using Kulula.com.ViewModels;
using Kulula.com.Views;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Kulula.com.ViewModels
{
class CardDataViewModel
{
public IList<Flight_Departure> flight_Departures { get; set; }
public IList<FlightArrival> flightArrivals { get; set; }
public IList<FlightBooking> flightBookings { get; set; }
public object selectedItem { get; set; }
public CardDataViewModel() {
flight_Departures = new List<Flight_Departure>();
flightArrivals = new List<FlightArrival>();
flightBookings = new List<FlightBooking>();
GenerateCardModel();
}
private void GenerateCardModel() {
flight_Departures = new ObservableCollection<Flight_Departure>
{
new Flight_Departure{
AirportName = Settings.AirportID,
DepartingDate = Settings.FlightDate,
}
};
flightArrivals = new ObservableCollection<FlightArrival>
{
new FlightArrival
{
AirportName = Settings.ArrivalID
}
};
flightBookings = new ObservableCollection<FlightBooking>
{
new FlightBooking{
NumberOfTravellers =Convert.ToInt32(Settings.NumberOfTravellers),
ReturningDate = Settings.ReturningFlightTime
}
};
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
class ABC128A{
public static void Main(){
var ap = Console.ReadLine().Split(' ').Select(int.Parse);
Console.WriteLine((ap.ElementAt(0)*3+ap.ElementAt(1))/2);
}
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinearCodeApproach
{
public class Search
{
int distanceCalculated;
private List<Restaurant> LoadData()
{
var allRest = new List<Restaurant>();
using (var reader = new StreamReader(@"C:\Users\Tolnes\Documents\Sync\Infomations teknologi\6. Semester\Bachelor\500k.csv"))
{
int i = 0;
while (!reader.EndOfStream)
{
i++;
var line = reader.ReadLine();
var values = line.Split('|');
if (values.Length == 6)
{
var kw = values[5].Split(';');
allRest.Add(new Restaurant(values[4], kw.ToList(), Convert.ToDouble(values[2]), Convert.ToDouble(values[3])));
}
else
{
Console.WriteLine(i.ToString());
Console.WriteLine(values[1]);
}
}
return allRest;
}
}
/// <summary>
/// Linear Search
/// </summary>
/// <param name="lat">Users Latitude</param>
/// <param name="lng">Users Longitude</param>
/// <param name="all">List of All restaurants</param>
/// <param name="k">The desired number of results</param>
/// <param name="keywords">User defined keywords</param>
/// <param name="result">List to store the results</param>
private void LinearSearch(double lat, double lng, List<Restaurant> all, int k, List<string> keywords, out List<Restaurant> result)
{
result = new List<Restaurant>();
var nearby = new List<Restaurant>();
nearby = Distance.CalculateDistance(all, lat, lng).ToList();
nearby = nearby.OrderBy(r => r.Distance).ToList();
foreach (var rest in nearby)
{
/*** search for all keywords ***/
//if (keywords.All(kw => rest.Keywords.Contains(kw)))
// result.Add(rest);
/*** search for any keywords ***/
if (keywords.Any(kw => rest.Keywords.Contains(kw)))
result.Add(rest);
if (result.Count == k)
{
break;
}
}
}
//Initializes and invokes the linear search algorithm
public void SearchWithLinearSearch()
{
var lat = 57.04;
var lng = 9.92;
var allRest = new List<Restaurant>();
allRest = LoadData();
//Initializes the list of keywords to search for
var keywords = new List<string>();
keywords.Add("Italian");
keywords.Add("Pizza");
keywords.Add("Pasta");
//keywords.Add("Burger");
//keywords.Add("American");
//keywords.Add("Pie");
//keywords.Add("Milkshake");
//keywords.Add("Fried chicken");
var result = new List<Restaurant>();
var sw = new Stopwatch();
var timeList = new List<string>();
for (int i = 1; i <= 100; i++)
{
sw.Start();
LinearSearch(lng, lat, allRest, 10, keywords, out result);
sw.Stop();
var time = sw.Elapsed.TotalMilliseconds;
timeList.Add(Convert.ToString(time));
Console.WriteLine(time);
sw.Reset();
}
foreach (var rest in result)
{
Console.WriteLine(rest);
}
Console.WriteLine(distanceCalculated);
Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace PagosCredijal
{
public partial class Settings : System.Web.UI.Page
{
#region Events
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserName"] == null)
{
Response.Redirect("LogIn.aspx");
}
else if (Session["UserName"].ToString() != "administrator" && Session["UserName"].ToString().ToLower() != "gtecobranza")
{
Response.Redirect("Default.aspx");
}
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
scriptManager.RegisterPostBackControl(this.btnAddUser);
scriptManager.RegisterPostBackControl(this.btnCrearCola);
scriptManager.RegisterPostBackControl(this.gvQueueUsers);
scriptManager.RegisterPostBackControl(this.btnGenerarReporte);
scriptManager.RegisterPostBackControl(this.gvRecordReport);
if (IsPostBack)
{
TabName.Value = Request.Form[TabName.UniqueID];
}
else
{
SetInitialData();
}
}
protected void btnAddUser_Click(object sender, EventArgs e)
{
try
{
User user = new User(txtUserName.Text.Trim(), txtUsrPassword.Text.Trim(), txtUsrFirstName.Text.Trim() + " " + txtUsrLastName.Text.Trim());
ValidateUser validate = new ValidateUser(user);
if (!validate.UserNameExist())
{
RegisterUser register = new RegisterUser(user);
register.Register();
ClearRegisterUserData();
lblMessageAddUser.Text = "Usuario creado exitosamente";
lblMessageAddUser.CssClass = "successfully";
lblMessageAddUser.Visible = true;
}
else
{
lblMessageAddUser.Text = "Ya existe un usuario con el Username: " + txtUserName.Text.Trim();
lblMessageAddUser.CssClass = "error";
lblMessageAddUser.Visible = true;
ScriptManager.RegisterStartupScript(this, this.GetType(), "tmp2", "var t2 = document.getElementById('" + txtUserName.ClientID + "'); t2.focus();t2.value = t2.value;", true);
}
}
catch (Exception ex)
{
lblMessageAddUser.Text = "Ha occurrido un error. Póngase en contacto con el administrador";
lblMessageAddUser.CssClass = "error";
lblMessageAddUser.Visible = true;
}
}
protected void btnCrearCola_Click(object sender, EventArgs e)
{
try
{
QueueOperations queue = new QueueOperations(rblMora.SelectedItem != null ? true : false, cbScoring.Checked, txtContadormora.Text.Trim() != String.Empty ? true : false, cbMontoFinanciado.Checked,
cbMontoVencido.Checked, ddlUltimoEstatusRegistrado.SelectedItem.Value != "0" ? true : false, cbPromesaPagoRota.Checked, rblTipoFinanciamiento.SelectedItem != null ? true : false,
rblCreditoSimple.SelectedItem != null ? true : false, rblArrendamiento.SelectedItem != null ? true : false);
queue.SaveQueueU(txtNombreCola.Text.Trim(), rblMora.SelectedItem != null ? rblMora.SelectedItem.Value : String.Empty, txtContadormora.Text.Trim(),
ddlUltimoEstatusRegistrado.SelectedItem.Value != "0" ? ddlUltimoEstatusRegistrado.SelectedItem.Text : String.Empty
, rblTipoFinanciamiento.SelectedItem != null ? rblTipoFinanciamiento.SelectedItem.Value : String.Empty
, rblCreditoSimple.SelectedItem != null ? rblCreditoSimple.SelectedItem.Value : String.Empty, rblArrendamiento.SelectedItem != null ? rblArrendamiento.SelectedItem.Value : String.Empty);
ClearQueueData();
FillQueueUsersGrid();
lblMensajeColasTrabajo.Text = "Cola creada correctamente";
lblMensajeColasTrabajo.CssClass = "successfully";
lblMensajeColasTrabajo.Visible = true;
}
catch (Exception ex)
{
lblMensajeColasTrabajo.Text = "Ha occurrido un error. Póngase en contacto con el administrador";
lblMensajeColasTrabajo.CssClass = "error";
lblMensajeColasTrabajo.Visible = true;
}
}
protected void btnGenerarReporte_Click1(object sender, EventArgs e)
{
BindDataReport();
}
protected void gvQueueUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddlQueues = (e.Row.FindControl("ddlQueues") as DropDownList);
DropDownElements.SetQueues(ddlQueues);
//Select the Queue of User in DropDownList
String queue = (e.Row.FindControl("lblQueue") as Label).Text;
if (queue != String.Empty)
{
ddlQueues.Items.FindByText(queue).Selected = true;
}
}
}
protected void ddlQueues_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
DropDownList ddl = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddl.Parent.Parent;
String userName = HttpUtility.HtmlDecode(row.Cells[1].Text);
String pkUser = new User(userName).GetID();
String pkQueue = ddl.SelectedItem.Value;
QueueOperations qo = new QueueOperations(Convert.ToInt32(pkUser), Convert.ToInt32(pkQueue));
qo.SaveQueueByUser();
} catch (Exception ex)
{
throw ex;
}
}
protected void gvRecordReport_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
gvRecordReport.PageIndex = e.NewPageIndex;
BindDataReport();
}
catch (Exception ex)
{
Response.Write("<script>alert('Error: " + ex.Message + "');</script>");
}
}
#endregion
private void ClearRegisterUserData()
{
txtUsrFirstName.Text = String.Empty;
txtUsrLastName.Text = String.Empty;
txtUserName.Text = String.Empty;
}
private void BindDataReport()
{
try
{
String tipoReporte = rblReportes.SelectedItem.Value;
DateTime fechaFinal = DateTime.ParseExact(DatePicker.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
Reports reporte = new Reports(fechaFinal);
switch (tipoReporte)
{
case "dia":
gvRecordReport.DataSource = reporte.GetReportByDay();
gvRecordReport.DataBind();
break;
case "semana":
gvRecordReport.DataSource = reporte.GetReportByWeek();
gvRecordReport.DataBind();
break;
case "mes":
gvRecordReport.DataSource = reporte.GetReportByMonth();
gvRecordReport.DataBind();
break;
}
}
catch (Exception ex)
{
throw ex;
}
}
private void ClearQueueData()
{
rblMora.SelectedIndex = -1;
cbScoring.Checked = false;
txtContadormora.Text = String.Empty;
cbMontoFinanciado.Checked = false;
cbMontoVencido.Checked = false;
ddlUltimoEstatusRegistrado.SelectedValue = "0";
cbPromesaPagoRota.Checked = false;
rblTipoFinanciamiento.SelectedIndex = -1;
rblCreditoSimple.SelectedIndex = -1;
rblArrendamiento.SelectedIndex = -1;
txtNombreCola.Text = String.Empty;
}
private void SetInitialData()
{
FillQueueUsersGrid();
FillDropDown();
}
private void FillQueueUsersGrid()
{
gvQueueUsers.DataSource = QueueOperations.GetQueueByUsers();
gvQueueUsers.DataBind();
}
private void FillDropDown()
{
DropDownElements.SetStatus(ddlUltimoEstatusRegistrado);
}
}
} |
using System;
using System.IO;
using System.Linq;
namespace UnitTestProject1
{
public class CodeCleaner
{
private string _directory;
public CodeCleaner(string directory)
{
_directory = directory;
}
public void EatRegions()
{
LineEater.EatFromDirectory(_directory , "#region");
LineEater.EatFromDirectory(_directory, "#endregion");
}
public void EatComments()
{
LineEater.EatFromDirectory(_directory, @"///");
}
}
} |
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 MySql.Data.MySqlClient;
using System.Windows.Forms;
namespace WindowsFormsApplication5
{
public partial class Order : Form
{
int ID_StOrd;
int ID_Client;
int ID_Manag;
string serv = "server=localhost;user=root;password=;database=Holiday_Cakes;SslMode=none";
private BindingSource bindingSource = new BindingSource();
public Order()
{
InitializeComponent();
// Select_StOrd();
Select_Client();
Select_Manag();
}
//void Select_StOrd()
//{
// try
// {
// MySqlConnection conn = new MySqlConnection(serv);
// conn.Open();
// string command = "SELECT `Name` FROM `Status_Order` WHERE 1";
// MySqlCommand cmd = new MySqlCommand(command, conn);
// MySqlDataReader reader = cmd.ExecuteReader();
// while (reader.Read())
// comboBox_StOrd.Items.Add(reader[0].ToString());
// conn.Close();
// }
// catch (Exception ex)
// {
// MessageBox.Show(ex.Message);
// }
//}
//void Search_StOrd()
//{
// try
// {
// MySqlConnection conn = new MySqlConnection(serv);
// conn.Open();
// string command = "SELECT `ID_Status_Order` FROM `Status_Order` WHERE `Name` = '" + comboBox_StOrd.Text.ToString() + "'";
// MySqlCommand cmd = new MySqlCommand(command, conn);
// MySqlDataReader reader = cmd.ExecuteReader();
// while (reader.Read())
// ID_StOrd = Convert.ToInt16(reader[0].ToString());
// conn.Close();
// }
// catch (Exception ex)
// {
// MessageBox.Show(ex.Message);
// }
//}
void Select_Client()
{
try
{
MySqlConnection conn = new MySqlConnection(serv);
conn.Open();
string command = "SELECT `Full_Name` FROM `User` WHERE `ID_Role` = '1'";
MySqlCommand cmd = new MySqlCommand(command, conn);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
comboBox_Client.Items.Add(reader[0].ToString());
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void Search_Client()
{
try
{
MySqlConnection conn = new MySqlConnection(serv);
conn.Open();
string command = "SELECT `ID_User` FROM `User` WHERE `Full_Name` = '" + comboBox_StOrd.Text.ToString() + "'";
MySqlCommand cmd = new MySqlCommand(command, conn);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
ID_Client = Convert.ToInt16(reader[0].ToString());
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void Select_Manag()
{
try
{
MySqlConnection conn = new MySqlConnection(serv);
conn.Open();
string command = "SELECT `Full_Name` FROM `User` WHERE `ID_Role` = '2'";
MySqlCommand cmd = new MySqlCommand(command, conn);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
comboBox_Manag.Items.Add(reader[0].ToString());
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void Search_Manag()
{
try
{
MySqlConnection conn = new MySqlConnection(serv);
conn.Open();
string command = "SELECT `ID_User` FROM `User` WHERE `Full_Name` = '" + comboBox_StOrd.Text.ToString() + "'";
MySqlCommand cmd = new MySqlCommand(command, conn);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
ID_Manag = Convert.ToInt16(reader[0].ToString());
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void label5_Click(object sender, EventArgs e)
{
}
private void Order_Load(object sender, EventArgs e)
{
dateTime_Acquistions.Format = DateTimePickerFormat.Custom;
dateTime_Acquistions.CustomFormat = "yyyy-MM-dd";
}
private void dataGrid_Instr_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
//Search_StOrd();
Search_Client();
Search_Manag();
MySqlConnection connection = new MySqlConnection("server=localhost;user=root;password=;database=Holiday_Cakes;SslMode=none");
connection.Open();
MySqlCommand myCommand = new MySqlCommand(String.Format("INSERT INTO `Order` VALUES (NULL, '" + dateTime_Order.Value + "', '" + richTextB_Name.Text + "', '" + ID_StOrd + "', '" + ID_Client + "', '" + textBox_Cost_Order.Text + "', '" + dateTime_Acquistions.Value + "', '" + ID_Manag + "')"), connection);
myCommand.ExecuteScalar();
connection.Close();
MessageBox.Show("Запись добавлена");
}
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
Form Orders = new Orders();
Orders.ShowDialog();
this.Close();
}
private void comboBox_StOrd_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
|
namespace KRFTemplateApi.Infrastructure.Database.Configuration
{
using KRFTemplateApi.Domain.Database.Sample;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
public static class SampleTableConfiguration
{
public static void Configure( EntityTypeBuilder<SampleTable> entity )
{
entity.ToTable( "SampleTable" );
entity.HasKey( s => s.Code ).HasName( "PK_SAMPLE" );
entity.Property( x => x.Code ).HasMaxLength( 100 ).IsRequired();
entity.Property( x => x.Description ).HasMaxLength( 200 ).IsRequired();
entity.Property( x => x.TemperatureMin ).IsRequired();
entity.Property( x => x.TemperatureMax ).IsRequired();
}
}
}
|
using System.Collections.Generic;
namespace IPTV_Checker_2.DTO
{
public class JsonData
{
public string Country
{
get;
set;
}
public string UserAgent
{
get;
set;
}
public List<JsonChannel> Channels
{
get;
set;
}
public JsonData()
{
Channels = new List<JsonChannel>();
}
}
}
|
using System;
using System.Collections.Generic;
namespace PterodactylEngine
{
public class Hyperlink
{
private string _text;
private string _link;
public Hyperlink(string text, string link)
{
Text = text;
Link = link;
}
public string Create()
{
string reportPart = "[" + Text + "](" + Link + ")";
return reportPart;
}
public string Text
{
get { return _text; }
set { _text = value; }
}
public string Link
{
get { return _link; }
set { _link = value; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ApartmentApps.Api.Modules;
using ApartmentApps.Data.Repository;
using ApartmentApps.Modules.Payments.Data;
using ApartmentApps.Portal.Controllers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Ninject;
namespace ApartmentApps.Tests
{
[TestClass]
public class PaymentsControllerTests : PropertyControllerTest<PaymentsController>
{
[TestInitialize]
public override void Init()
{
base.Init();
}
public API.Service.Controllers.PaymentsController ServiceController { get; set; }
[TestMethod]
public void TestOnetimePaymentRequest()
{
var userLeaseInfos = Context.Kernel.Get<IRepository<UserLeaseInfo>>();
var invoices = Context.Kernel.Get<IRepository<Invoice>>();
//create user lease info
var userId = Context.UserContext.UserId;
UserLeaseInfo pRequest;
var modelData = new CreateUserLeaseInfoBindingModel()
{
Amount = 200,
UserId = Context.UserContext.UserId,
InvoiceDate = DateTime.Now + TimeSpan.FromDays(10),
Title = nameof(pRequest),
UseInterval = false, //one time
UseCompleteDate = false
};
Controller.SubmitCreateUserLeaseInfo(modelData);
pRequest = userLeaseInfos.GetAll().FirstOrDefault(s=>s.Title == nameof(pRequest));
//Initial tests for payment request itself
Assert.IsTrue(pRequest != null);
Assert.IsTrue(pRequest.Amount == modelData.Amount);
Assert.IsTrue(pRequest.IntervalMonths == modelData.IntervalMonths);
Assert.IsTrue(pRequest.NextInvoiceDate == null);
Assert.IsTrue(pRequest.State == LeaseState.Active);
var testPaymentRequest1Invoice1 = invoices.GetAll().FirstOrDefault(i=>i.UserLeaseInfoId == pRequest.Id);
//Initial tests for corresponding invoice
Assert.IsTrue(testPaymentRequest1Invoice1 != null);
Assert.IsTrue(testPaymentRequest1Invoice1.Amount == modelData.Amount);
Assert.IsTrue(testPaymentRequest1Invoice1.Title == modelData.Title);
Assert.IsTrue(testPaymentRequest1Invoice1.DueDate == modelData.InvoiceDate);
Assert.IsTrue(testPaymentRequest1Invoice1.State == InvoiceState.NotPaid);
Assert.IsTrue(testPaymentRequest1Invoice1.IsArchived == false);
//Test edit payment request
}
[TestCleanup]
public override void DeInit()
{
RemoveAll<UserLeaseInfo>();
RemoveAll<Invoice>();
RemoveAll<TransactionHistoryItem>();
base.DeInit();
}
public PaymentsController PaymentsController { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace MinOstov
{
class Program
{
static void Main(string[] args)
{
var dictPath = Directory.GetCurrentDirectory();
var input = Path.Combine(dictPath, "in.txt");
var output = Path.Combine(dictPath, "out.txt");
var content = File.ReadAllLines(input);
var length = int.Parse(content[0]);
var points = new PlanePoint[length];
for (int i = 1; i < length + 1; i++)
{
var row = content[i].Split(' ');
var x = int.Parse(row[0]);
var y = int.Parse(row[1]);
points[i - 1] = new PlanePoint(x, y, i);
}
var result = FindMinOstov(points);
var outContent = points.Select(point => point.NeighboringPoints).ToList();
var str = "";
for (int i = 0; i < outContent.Count; i++)
{
var listPoints = outContent[i].Select(point => point.Number).OrderBy(key => key).ToList();
for (var j = 0; j < listPoints.Count; j++)
{
var numberPoint = listPoints[j];
str += numberPoint + " ";
}
str += "0\r\n";
}
str += result;
File.WriteAllText(output, str);
}
public static int FindMinOstov(PlanePoint[] points)
{
if (points.Length == 0)
return 0;
var visitedPoints = new List<PlanePoint>();
var startPoint = points[0];
startPoint.Visited = true;
visitedPoints.Add(startPoint);
var sumDistnces = 0;
while (visitedPoints.Count < points.Length)
{
int minDistance = int.MaxValue;
PlanePoint nearestPoint = new PlanePoint();
PlanePoint actualPoint = new PlanePoint();
for (int i = 0; i < visitedPoints.Count; i++)
{
var point = visitedPoints[i];
for (int j = 0; j < points.Length; j++)
{
var otherPoint = points[j];
if (otherPoint.Visited) continue;
var distance = point.DistanceToOtherPoint(otherPoint);
if (distance >= minDistance) continue;
minDistance = distance;
actualPoint = point;
nearestPoint = otherPoint;
}
}
actualPoint.NeighboringPoints.Add(nearestPoint);
nearestPoint.NeighboringPoints.Add(actualPoint);
nearestPoint.Visited = true;
visitedPoints.Add(nearestPoint);
sumDistnces += minDistance;
}
return sumDistnces;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _3.BeatifullNumbers
{
class Numbers
{
static void Main()
{
Console.WriteLine("Enter 5 digit number: ");
string line = Console.ReadLine();
byte first = byte.Parse(line[0].ToString());
byte second = byte.Parse(line[1].ToString());
byte third = byte.Parse(line[2].ToString());
byte fourth = byte.Parse(line[3].ToString());
byte fifth = byte.Parse(line[4].ToString());
int sum = second + third + fourth + fifth;
if (first >= sum)
{
Console.WriteLine("Yes");
}
else
{
Console.WriteLine("No");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Threading.Tasks;
using Oracle.ManagedDataAccess.Client;
using Oracle.ManagedDataAccess.Types;
using Dapper;
namespace ChatAPI.Models.ChannelsModel
{
public class ChannelsRepository : IChannelRepository
{
string connectionString = null;
public ChannelsRepository(string dbConnectionString)
{
connectionString = dbConnectionString;
}
public IEnumerable<ChannelsModel> GetUserChannels(int userId)
{
using (OracleConnection db = new OracleConnection(connectionString))
{
string sql = "SELECT channel_id AS ChannelId, name, theme, " +
"creation_time AS CreationTime, count_of_messages AS CountOfMessages " +
"FROM Channels WHERE channel_id IN " +
"(SELECT channel_id FROM User_has_channel WHERE user_id = :ID)";
db.Open();
return db.Query<ChannelsModel>(sql, new { ID = userId });
}
}
public IEnumerable<ChannelsModel> GetChannels()
{
using (OracleConnection db = new OracleConnection(connectionString))
{
string sql = "SELECT channel_id AS ChannelId, name, theme, " +
"creation_time AS CreationTime, count_of_messages AS CountOfMessages " +
"FROM Channels ";
db.Open();
return db.Query<ChannelsModel>(sql);
}
}
public ChannelsModel GetChannel(int channelId)
{
using (OracleConnection db = new OracleConnection(connectionString))
{
string sql = "SELECT channel_id AS ChannelId, name, theme, " +
"creation_time AS CreationTime, count_of_messages AS CountOfMessages " +
"FROM Channels WHERE channel_id = :ID ";
db.Open();
return db.Query<ChannelsModel>(sql, new { ID = channelId }).FirstOrDefault();
}
}
public int AddChannel(string name, string theme, string creationTime)
{
using (OracleConnection db = new OracleConnection(connectionString))
{
string sql = "INSERT INTO Channels(name, theme, creation_time) " +
"VALUES(:Name,:Theme, to_date(:CreationTime, \'dd.MM.yyyy hh24:mi:ss\'))";
db.Open();
db.Execute(sql, new { Name = name, Theme = theme, CreationTime = creationTime });
return db.Query<int>("SELECT channel_id FROM Channels WHERE creation_time = to_date(:CRtime, \'dd.MM.yyyy hh24:mi:ss\') ", new { CRtime = creationTime }).FirstOrDefault();
}
}
public void DeleteChannel (int id)
{
using (OracleConnection db = new OracleConnection(connectionString))
{
string sql = "DELETE FROM Channels WHERE channel_id = :ID";
db.Open();
db.Execute(sql, new { ID = id });
}
}
public void UserJoinChannel(int channelId , int userId)
{
using (OracleConnection db = new OracleConnection(connectionString))
{
string sql = "INSERT INTO User_has_channel(user_id, channel_id ) " +
"VALUES(:usId, :chId)";
db.Open();
db.Execute(sql, new { chId = channelId, usId = userId });
}
}
public void UserLeaveChannel(int channelId, int userId)
{
using (OracleConnection db = new OracleConnection(connectionString))
{
string sql = "DELETE FROM User_has_channel WHERE user_id = :usId AND channel_id = :chId";
db.Open();
db.Execute(sql, new { chId = channelId, usId = userId });
}
}
}
}
|
using UnityEngine;
using System.Collections;
using System.IO;
public static class UniTunesTextureFactory
{
//for editor
public static Texture2D playBtn;
public static Texture2D stopBtn;
public static Texture2D upBtn;
public static Texture2D downBtn;
public static Texture2D upFullBtn;
public static Texture2D downFullBtn;
public static Texture2D upDownBlank;
public static Texture2D removeBtn;
public static Texture2D soundcloudLogo;
private static byte[] GetImageData(string imgPath)
{
FileStream fs = new FileStream(imgPath, FileMode.Open, FileAccess.Read);
byte[] imageData = new byte[fs.Length];
fs.Read(imageData, 0, (int) fs.Length);
return imageData;
}
public static void ClearTextures()
{
playBtn = null;
stopBtn = null;
upBtn = null;
downBtn = null;
upFullBtn = null;
downFullBtn = null;
upDownBlank = null;
removeBtn = null;
soundcloudLogo = null;
}
public static Texture2D GetRemoveBtnTexture()
{
if(removeBtn == null) {
//do the loading
removeBtn = new Texture2D(55, 55);
removeBtn.LoadImage(GetImageData(Path.Combine(UniTunesConsts.EDITOR_TEXTURE_PATH, "btn_remove.png")));
}
return removeBtn;
}
public static Texture2D GetPlayBtnTexture()
{
if(playBtn == null) {
//do the loading
playBtn = new Texture2D(55, 55);
playBtn.LoadImage(GetImageData(Path.Combine(UniTunesConsts.EDITOR_TEXTURE_PATH, "btn_play.png")));
}
return playBtn;
}
public static Texture2D GetStopBtnTexture()
{
if(stopBtn == null) {
//do the loading
stopBtn = new Texture2D(55, 55);
stopBtn.LoadImage(GetImageData(Path.Combine(UniTunesConsts.EDITOR_TEXTURE_PATH, "btn_stop.png")));
}
return stopBtn;
}
public static Texture2D GetUpBtnTexture()
{
if(upBtn == null) {
//do the loading
upBtn = new Texture2D(55, 55);
upBtn.LoadImage(GetImageData(Path.Combine(UniTunesConsts.EDITOR_TEXTURE_PATH, "btn_up.png")));
}
return upBtn;
}
public static Texture2D GetDownBtnTexture()
{
if(downBtn == null) {
//do the loading
downBtn = new Texture2D(55, 55);
downBtn.LoadImage(GetImageData(Path.Combine(UniTunesConsts.EDITOR_TEXTURE_PATH, "btn_down.png")));
}
return downBtn;
}
public static Texture2D GetDownFullBtnTexture()
{
if(downFullBtn == null) {
//do the loading
downFullBtn = new Texture2D(55, 55);
downFullBtn.LoadImage(GetImageData(Path.Combine(UniTunesConsts.EDITOR_TEXTURE_PATH, "btn_down_full.png")));
}
return downFullBtn;
}
public static Texture2D GetUpFullBtnTexture()
{
if(upFullBtn == null) {
//do the loading
upFullBtn = new Texture2D(55, 55);
upFullBtn.LoadImage(GetImageData(Path.Combine(UniTunesConsts.EDITOR_TEXTURE_PATH, "btn_up_full.png")));
}
return upFullBtn;
}
public static Texture2D GetUpDownBlankTexture()
{
if(upDownBlank == null) {
//do the loading
upDownBlank = new Texture2D(55, 55);
upDownBlank.LoadImage(GetImageData(Path.Combine(UniTunesConsts.EDITOR_TEXTURE_PATH, "btn_up_down_blank.png")));
}
return upDownBlank;
}
public static Texture2D GetSoundCloudLogo()
{
if(soundcloudLogo == null) {
//do the loading
soundcloudLogo = new Texture2D(55, 55);
soundcloudLogo.LoadImage(GetImageData(Path.Combine(UniTunesConsts.EDITOR_TEXTURE_PATH, "pb_soundcloud_logo.png")));
}
return soundcloudLogo;
}
}
|
using CocosSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ChipmunkSharp;
using Microsoft.Xna.Framework.Input;
namespace ChipmunkExample
{
class convexLayer : ChipmunkDemoLayer
{
float DENSITY = 1f / 10000f;
cpShape shape;
public override void OnEnter()
{
base.OnEnter();
space.SetIterations(30);
space.SetGravity(new cpVect(0, -500));
space.SetSleepTimeThreshold(0.5f);
space.SetCollisionSlop(0.5f);
cpBody body, staticBody = space.GetStaticBody();
// Create segments around the edge of the screen.
//this.addFloor();
this.shape = space.AddShape(new cpSegmentShape(staticBody, new cpVect(-320, -240), new cpVect(320, -240), 0f)) as cpSegmentShape;
this.shape.SetFriction(1.0f);
this.shape.SetElasticity(0.6f);
this.shape.SetFilter(NOT_GRABBABLE_FILTER);
var width = 50;
var height = 70;
var mass = width * height * DENSITY;
var moment = cp.MomentForBox(mass, width, height);
body = space.AddBody(new cpBody(mass, moment));
body.SetPosition(new cpVect(0, 0));
this.shape = space.AddShape(cpPolyShape.BoxShape(body, width, height, 0.0f));
this.shape.SetFriction(0.6f);
Schedule();
}
public override void Update(float dt)
{
base.Update(dt);
var tolerance = 2;
//var mouse = new cpVect(mouseState.X, mouseState.Y);
if (!CCMouse.Instance.HasPosition)
return;
cpPointQueryInfo info = null;
//CCMouse.Instance.UpdatePosition()
var d = this.shape.PointQuery(CCMouse.Instance.Position, ref info);
var actualShape = (shape as cpPolyShape);
if ((CCMouse.Instance.rightclick || CCMouse.Instance.dblclick) && d > tolerance)
{
var body = actualShape.body;
var count = actualShape.Count;
// Allocate the space for the new vertexes on the stack.
cpVect[] verts = new cpVect[count + 1]; // * sizeof(cpVect));
for (int i = 0; i < count; i++)
verts[i] = actualShape.GetVert(i);
verts[count] = body.WorldToLocal(CCMouse.Instance.Position);
// This function builds a convex hull for the vertexes.
// Because the result array is NULL, it will reduce the input array instead.
int hullCount = cp.ConvexHull(count + 1, verts, ref verts, null, tolerance);
// Figure out how much to shift the body by.
var centroid = cp.CentroidForPoly(hullCount, verts);
// Recalculate the body properties to match the updated shape.
var mass = cp.AreaForPoly(hullCount, verts, 0.0f) * DENSITY;
body.SetMass(mass);
body.SetMoment(cp.MomentForPoly(mass, hullCount, verts, cpVect.cpvneg(centroid), 0.0f));
body.SetPosition(body.LocalToWorld(centroid));
// Use the setter function from chipmunk_unsafe.h.
// You could also remove and recreate the shape if you wanted.
actualShape.SetVerts(hullCount, verts,
cpTransform.Translate(cpVect.cpvneg(centroid)));
}
var steps = 1;
dt = dt / steps;
for (var i = 0; i < steps; i++)
this.space.Step(dt);
}
}
}
|
using StringStreamService.Engine;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StringStreamService.Service
{
internal class SessionWorker : ISessionWorker
{
public Guid Id { get; private set; }
private readonly TextProcessor processor;
internal SessionWorker()
{
this.Id = Guid.NewGuid();
this.processor = new TextProcessor(this.Id);
}
public void Clear()
{
this.processor.Clear();
}
public void Process(string[] text)
{
foreach (var line in text)
{
this.processor.AppendLine(line);
}
}
public Stream GetSortedStream()
{
return this.processor.GetSortedStream();
}
public string[] GetSortedTextFull()
{
return this.processor.GetSortedTextFull();
}
}
}
|
using System.Collections.Generic;
namespace SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Requests.Apprentices
{
public class GetEditApprenticeshipCourseRequest : IGetApiRequest
{
public long ProviderId { get; }
public long ApprenticeshipId { get; set; }
public GetEditApprenticeshipCourseRequest(long providerId, long apprenticeshipId)
{
ProviderId = providerId;
ApprenticeshipId = apprenticeshipId;
}
public string GetUrl => $"provider/{ProviderId}/apprentices/{ApprenticeshipId}/edit/select-course";
}
public class GetEditApprenticeshipCourseResponse
{
public string ProviderName { get; set; }
public string EmployerName { get; set; }
public bool IsMainProvider { get; set; }
public IEnumerable<Standard> Standards { get; set; }
public class Standard
{
public string CourseCode { get; set; }
public string Name { get; set; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Net;
namespace Apache.Shiro.Session
{
public interface ISession
{
#region Properties
ICollection<object> AttributeKeys
{
get;
}
string Host
{
get;
}
object Id
{
get;
}
DateTime LastAccessTime
{
get;
}
DateTime StartTime
{
get;
}
long Timeout
{
get;
set;
}
#endregion
#region Methods
object GetAttribute(object key);
object RemoveAttribute(object key);
void SetAttribute(object key, object value);
void Stop();
void Touch();
#endregion
}
}
|
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// A single vertical line of players in the game field.
/// This class encapsulates control and the bounding box
/// for a group of players in a single line. Any number
/// of field players may be included in the line.
/// </summary>
public class FieldPlayerLine : MonoBehaviour
{
/// <summary>
/// Allows enabling or disabling of control of the line of players.
/// </summary>
public bool ControlEnabled { get; set; }
/// <summary>
/// Defines the type of controller for movement of the player.
/// If human control, a human controller script should be attached.
/// If computer control, a computer controller script should be attached.
/// </summary>
public PlayerMovementControlType MovementControllerType = PlayerMovementControlType.HUMAN_CONTROL;
/// <summary>
/// The world boundaries of the line of players.
/// The bounds are stored as their own field because the bounds directly
/// attached to a collider cannot be modified as desired.
/// It is a public variable, rather than a property, to make it easier
/// to modify center parts of the bounds.
/// </summary>
public Bounds Bounds;
/// <summary>
/// All of the field players included in this line.
/// </summary>
private List<FieldPlayer> m_fieldPlayers;
/// <summary>
/// The movement controller to use for human user input, if this line
/// is controlled by a human.
/// </summary>
private HumanFieldPlayerLineController m_humanController;
/// <summary>
/// The movement controller to use for computer AI, if this line
/// is controlled by the computer.
/// </summary>
private ComputerFieldPlayerLineController m_computerController;
/// <summary>
/// Initializes the line of players.
/// This method is intended to mimic a constructor. An explicit
/// initialize method was chosen over implementing the standard
/// Start() method to better control when this component gets
/// initialized.
/// </summary>
/// <param name="fieldPlayers">All of the field players to include in the line.</param>
/// <param name="humanController">The controller for the line to control movement based
/// on human user input. Required if the line is to be controlled by a human.</param>
/// <param name="computerController">The controlller for the line to control movement based
/// on computer AI. Required if the line is to be controlled by the computer.</param>
public void Initialize(
List<FieldPlayer> fieldPlayers,
HumanFieldPlayerLineController humanController,
ComputerFieldPlayerLineController computerController)
{
// STORE THE FIELD PLAYERS.
m_fieldPlayers = fieldPlayers;
// STORE THE CONTROLLERS.
m_humanController = humanController;
m_computerController = computerController;
// RESIZE THE BOUNDARIES OF THE LINE BASED ON THE ATTACHED PLAYERS.
ResizeBounds();
}
/// <summary>
/// Calculates the bounding box of the line based on the attached players.
/// </summary>
private void ResizeBounds()
{
// FIND THE MINIMUM AND MAXIMUM COORDINATES FOR THE BOUNDING BOX OF ALL ATTACHED PLAYERS.
// Unity's Bounds class does not seem to work as expected when trying to grow it to encapsulate
// other Bounds. In particular, we cannot initialize an instance of it with a size of zero
// and then gradually grow it to include other bounds. Therefore, the minimum and maximum
// boundaries of the players must be separately determined in order to construct the bounds
// with proper values. Since trying to determine the minimum or maximum against a zero vector
// may not work, the vectors are nullable to allow detecting if they haven't been set yet.
Vector3? boundingBoxMinimum = null;
Vector3? boundingBoxMaximum = null;
foreach (FieldPlayer currentPlayer in m_fieldPlayers)
{
// RETRIEVE THE BOUNDS FOR THE CURRENT PLAYER.
Bounds playerBounds = currentPlayer.Bounds;
// UPDATE THE MINIMUM BOUNDING BOX COORDINATES.
if (!boundingBoxMinimum.HasValue)
{
// The minimum hasn't been set yet, so use the current bounds minimum.
boundingBoxMinimum = playerBounds.min;
}
else
{
boundingBoxMinimum = Vector3.Min(boundingBoxMinimum.Value, playerBounds.min);
}
// UPDATE THE MAXIMUM BOUNDING BOX COORDINATES.
if (!boundingBoxMaximum.HasValue)
{
// The maximum hasn't been set yet, so use the current bounds maximum.
boundingBoxMaximum = playerBounds.max;
}
else
{
boundingBoxMaximum = Vector3.Max(boundingBoxMaximum.Value, playerBounds.max);
}
}
// CALCULATE THE SIZE OF THE BOUNDING BOX.
Vector3 size = boundingBoxMaximum.Value - boundingBoxMinimum.Value;
// CREATE THE PROPER BOUNDING BOX FOR THE LINE OF PLAYERS.
Bounds = new Bounds(transform.position, size);
}
/// <summary>
/// Updates the line of players to move based on the configured controller.
/// </summary>
private void Update()
{
// UPDATES THE CENTER OF THE BOUNDING BOX.
// The line of players may have moved since last update.
Bounds.center = transform.position;
// CHECK IF MOVEMENT CONTROL IS ENABLED.
if (!ControlEnabled)
{
// No movement needs to be performed.
return;
}
// MOVE BASED ON THE CONTROLLER TYPE.
switch (MovementControllerType)
{
case PlayerMovementControlType.HUMAN_CONTROL:
m_humanController.MoveBasedOnInput();
break;
case PlayerMovementControlType.COMPUTER_CONTROL:
m_computerController.MoveBasedOnAi();
break;
default:
// The controller type is invalid, so don't do anything.
break;
}
}
}
|
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using CoreRest.Models;
namespace CoreRest.Controllers {
[Route("api/[controller]")]
[ApiController]
public class CustomerController : ControllerBase
{
// private readonly CustomerContext _context;
// public CustomerController(CustomerContext context){
// _context = context;
// }
// [HttpGet]
// public ActionResult<IEnumerable<Customer>> GetCustomerItems(){
// return this._context.CustomerItems;
// }
[HttpGet]
public ActionResult<IEnumerable<string>> Get(){
return new string[] {"this", "is", "a", "string", "arr"};
}
public IActionResult Hello()
{
return View();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using TMPro;
public class Village : MonoBehaviour
{
public GameObject gemButton;
public GameObject coinButton;
public GameObject foodButton;
public GameObject ancientButton;
public GameObject humanButton;
public GameObject graveyardButton;
public GameObject LoadScreen;
public GameObject CanvasUI;
private GameMaster gm;
public GameObject message;
void Start()
{
gm = GameObject.FindGameObjectWithTag("GameMaster").GetComponent<GameMaster>();
message.SetActive(true);
GameMaster.scene = 3;
}
void Update()
{
LoadScreen.SetActive(false);
}
public void MainMenu()
{
GameMaster.villageLoot = false;
SceneManager.LoadScene(0);
PauseMenu.restartTrigger = true;
gm.SavePlayer();
}
public void PauseGame()
{
PauseMenu.paused = !PauseMenu.paused;
CanvasUI.GetComponent<CanvasGroup>().blocksRaycasts = !CanvasUI.GetComponent<CanvasGroup>().blocksRaycasts;
}
public void Close()
{
message.SetActive(false);
}
public void NextDay()
{
gm.SavePlayer();
GameMaster.day ++;
SceneManager.LoadScene(1);
GameMaster.villageLoot = true;
}
public void GemButton()
{
OffButton();
gemButton.transform.GetChild(0).gameObject.SetActive(true);
}
public void CoinButton()
{
OffButton();
coinButton.transform.GetChild(0).gameObject.SetActive(true);
}
public void AncientButton()
{
OffButton();
ancientButton.transform.GetChild(0).gameObject.SetActive(true);
}
public void FoodButton()
{
OffButton();
foodButton.transform.GetChild(0).gameObject.SetActive(true);
}
public void HumanButton()
{
OffButton();
humanButton.transform.GetChild(0).gameObject.SetActive(true);
}
public void GraveyardButton()
{
OffButton();
graveyardButton.transform.GetChild(0).gameObject.SetActive(true);
}
public void OffButton()
{
gemButton.transform.GetChild(0).gameObject.SetActive(false);
coinButton.transform.GetChild(0).gameObject.SetActive(false);
foodButton.transform.GetChild(0).gameObject.SetActive(false);
ancientButton.transform.GetChild(0).gameObject.SetActive(false);
humanButton.transform.GetChild(0).gameObject.SetActive(false);
graveyardButton.transform.GetChild(0).gameObject.SetActive(false);
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using ODL.DomainModel.Person;
namespace ODL.DataAccess.Repositories
{
public class PersonRepository : IPersonRepository
{
private ODLDbContext DbContext { get; }
private readonly Repository<Person, ODLDbContext> _internalGenericRepository;
public PersonRepository(ODLDbContext dbContext)
{
//TODO-Marie
DbContext = dbContext;
_internalGenericRepository = new Repository<Person, ODLDbContext>(DbContext);
}
public Person GetByPersonnummer(string personnummer)
{
return DbContext.Person.SingleOrDefault(person => person.Personnummer == personnummer);
}
public bool Exists(string personnummer)
{
return DbContext.Person.Any(person => person.Personnummer == personnummer);
}
public void Update()
{
_internalGenericRepository.Update();
}
public void Add(Person nyPerson)
{
_internalGenericRepository.Add(nyPerson);
}
/*
// Här kan man implementera mer specialiserade metoder för att hämta Person, direkt genom context eller genom att använda den generiska Repository<T>
public IEnumerable<Person> GetAll()
{
return _internalGenericRepository.GetAll();
}
public Person GetById(int id)
{
return _internalGenericRepository.GetById(id);
}
public void Update()
{
_internalGenericRepository.Update(); // alt. dbContext.SaveChanges();
}
*/
}
}
|
using System.Collections.Generic;
namespace Game.Global.Buffer
{
/// <summary>
/// 提供缓存机制的 string-string buffer,在超过一定长度之后自动删去之前的文件缓存,采取队列删除策略
/// </summary>
class FileBuffer
{
//文件结构管理
private class CFile
{
public string fileName;
public string fileContent;
public CFile(string fName, string fContent)
{
fileName = fName;
fileContent = fContent;
}
}
List<CFile> g_cfgFileBuffer = new List<CFile>();
int m_maxBufferCount = 3;
public void SetBufferSize(int count)
{
m_maxBufferCount = count;
}
public int GetBufferSize()
{
return m_maxBufferCount;
}
/// <summary>
/// 将文件名、文件内容放入缓冲区
/// </summary>
public void PushToBuffer(string fileName, string fileContent)
{
if (g_cfgFileBuffer.Count + 1 > m_maxBufferCount)
{
//Pop the first one:
g_cfgFileBuffer.RemoveAt(0);
}
g_cfgFileBuffer.Add(new CFile(fileName, fileContent));
}
/// <summary>
/// 获得对应文件名的缓存,如果不存在则返回false
/// </summary>
public bool GetFileContent(string fileName, out string fileContent)
{
for (int i = 0; i < g_cfgFileBuffer.Count; i++)
{
if (g_cfgFileBuffer[i].fileName == fileName)
{
fileContent = g_cfgFileBuffer[i].fileContent;
return true;
}
}
fileContent = null;
return false;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _4._3_LINQ
{
class Student
{
public string First { get; set; }
public string Last { get; set; }
public int ID { get; set; }
public List<int> Scores;
// Create a data source by using a collection initializer.
public List<Student> listaEstudante { get; } = new List<Student>()
{
new Student {First = "Svetlana", Last = "Omelchenko", ID = 111, Scores = new List<int> {97, 92, 81, 60}},
new Student {First = "Claire", Last = "O'Donnell", ID = 112, Scores = new List<int> {75, 84, 91, 39}},
new Student {First = "Sven", Last = "Mortensen", ID = 113, Scores = new List<int> {88, 94, 65, 91}},
new Student {First = "Cesar", Last = "Garcia", ID = 114, Scores = new List<int> {97, 89, 85, 82}},
new Student {First = "Debra", Last = "Garcia", ID = 115, Scores = new List<int> {35, 72, 91, 70}},
new Student {First = "Fadi", Last = "Fakhouri", ID = 116, Scores = new List<int> {99, 86, 90, 94}},
new Student {First = "Hanying", Last = "Feng", ID = 117, Scores = new List<int> {93, 92, 80, 87}},
new Student {First = "Hugo", Last = "Garcia", ID = 118, Scores = new List<int> {92, 90, 83, 78}},
new Student {First = "Lance", Last = "Tucker", ID = 119, Scores = new List<int> {68, 79, 88, 92}},
new Student {First = "Terry", Last = "Adams", ID = 120, Scores = new List<int> {99, 82, 81, 79}},
new Student {First = "Eugene", Last = "Zabokritski", ID = 121, Scores = new List<int> {96, 85, 91, 60}},
new Student {First = "Michael", Last = "Tucker", ID = 122, Scores = new List<int> {94, 92, 91, 91}}
};
public Student()
{
}
}
}
|
using System;
namespace hierarchia
{
internal class Lo : Allat
{
public int suly;
public Lo(string nev) : base(nev)
{
}
public override void AdatokFelvesz()
{
base.AdatokFelvesz();
Console.WriteLine("Add meg a súlyát!");
suly = int.Parse(Console.ReadLine());
}
public override void AdatokKiolvas()
{
base.AdatokKiolvas();
Console.WriteLine("Fajtája: " + GetType().Name);
Console.WriteLine("Súlya: " + suly);
}
}
} |
using UnityEngine;
using System.Collections;
public class LevelManager : MonoBehaviour {
public void LoadLevelGame ()
{
Application.LoadLevel(1);
}
public void QuitRequest ()
{
Application.Quit();
Debug.Log("I want to Quit!");
}
public void LoadLevelStart()
{
Application.LoadLevel(0);
}
public void LoadLevelLose()
{
Application.LoadLevel(2);
}
public void LoadLevelWin()
{
Application.LoadLevel(3);
}
}
|
using Common.Enums;
using Common.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace KontrolerSistema
{
public static class PowerSimulator
{
public static void Run()
{
while (Data.RunningFlag)
{
Data.LocalGenerators = Data.Dbg.ReadAllLocal().Where(g => g.State == EState.ONLINE).ToList();
Data.RemoteGenerators = Data.Dbg.ReadAllRemote().Where(g => Data.Dblc.IsOnline(g.LCCode)).OrderBy(g => g.WorkPrice).ThenBy(g => g.MinPower).ToList();
double requiredPower = Data.Dbsc.GetRequiredPower();
double requiredPowerLeft = requiredPower;
double currentPowerGenerated = 0;
foreach (Generator g in Data.LocalGenerators)
{
requiredPowerLeft -= g.CurrentPower;
currentPowerGenerated += g.CurrentPower;
}
Generator tmp;
double powerSetting = 0;
if (requiredPowerLeft > 0)
{
foreach (Generator g in Data.RemoteGenerators)
{
if (requiredPowerLeft > 0)
{
if (requiredPowerLeft >= g.MaxPower)
{
powerSetting = g.MaxPower;
requiredPowerLeft -= powerSetting;
currentPowerGenerated += powerSetting;
}
else if (requiredPowerLeft < g.MaxPower && requiredPowerLeft >= g.MinPower)
{
powerSetting = requiredPowerLeft;
requiredPowerLeft = 0;
currentPowerGenerated += powerSetting;
}
else
{
powerSetting = g.MinPower;
requiredPowerLeft -= powerSetting;
currentPowerGenerated += powerSetting;
}
}
else if (requiredPowerLeft <= 0)
{
powerSetting = 0;
}
SendSetpoints(g.Id, powerSetting);
if (requiredPowerLeft < 0)
{
do
{
tmp = Data.RemoteGenerators
.Where(gen => Data.Dblc.IsOnline(gen.LCCode))
.OrderByDescending(gen => gen.WorkPrice)
.FirstOrDefault(gen => gen.CurrentPower == gen.MaxPower);
if (tmp != null)
{
if ((tmp.MaxPower - tmp.MinPower) >= Math.Abs(requiredPowerLeft))
{
powerSetting = tmp.CurrentPower;
powerSetting += requiredPowerLeft;
currentPowerGenerated -= Math.Abs(requiredPowerLeft);
requiredPowerLeft = 0;
}
else
{
requiredPowerLeft += tmp.CurrentPower - tmp.MinPower;
currentPowerGenerated -= tmp.CurrentPower - tmp.MinPower;
powerSetting = tmp.MinPower;
}
SendSetpoints(tmp.Id, powerSetting);
}
else
{
requiredPowerLeft = 0;
}
} while (requiredPowerLeft < 0);
}
}
}
Thread.Sleep(10000);
}
}
public static void SendSetpoints(int genId, double powerSetting)
{
Generator g = Data.Dbg.GetGenerator(genId);
if(g.Setpoints.Count == 10)
{
for (int i = 0; i < 10; i++)
{
g.Setpoints[i].Value = powerSetting;
g.Setpoints[i].Date = DateTime.Now.AddSeconds(10 * i);
}
}
Data.Dbsc.SaveSetpoints(g);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SimbaTvaerfagligt
{
public class AnimalStats
{
public int TotalFemaleWildebeests { get; set; }
public int TotalMaleWildebeests { get; set; }
public int TotalMaleLions { get; set; }
public int TotalFemaleLions { get; set; }
public int TotalNbrOffspringWildebeests { get; set; }
public int TotalNbrOffspringLions { get; set; }
public int TotalNbrOffAnimals { get; set; }
// Mangler nedenstående:
//public int TotalNbrWildbeestPreyEaten { get; set; }
//public int TotalNbrWildbeestDiedStarvation { get; set; }
//public int TotalNbrLionsDiedStarvation { get; set; }
}
}
|
using System.Collections.Generic;
using Assets.Scripts.Models.ResourceObjects;
using Assets.Scripts.Models.ResourceObjects.CraftingResources;
namespace Assets.Scripts.Models.Clothes
{
public class FurCap : Cap
{
public FurCap()
{
LocalizationName = "fur_cap";
IconName = "fur_cap_icon";
CraftAmount = 1;
Durability = 15000;
Effect = ItemEffectType.Damage;
EffectAmount = 4;
CraftRecipe = new List<HolderObject>();
CraftRecipe.Add(HolderObjectFactory.GetItem(typeof(Fur), 5));
CraftRecipe.Add(HolderObjectFactory.GetItem(typeof(Rope), 1));
}
}
}
|
using DsStardewLib.Config;
using StardewModdingAPI;
namespace NoAddedFlyingMineMonsters
{
class ModConfig : HarmonyConfig
{
public bool HarmonyDebug { get; set; } = false;
public bool HarmonyLoad { get; set; } = true;
public bool NoRandomMonsters { get; set; } = true;
public SButton NoRandomMonstersButton { get; set; } = SButton.None;
}
}
|
using System;
using System.Collections.Generic;
using System.Xml;
namespace gView.Framework.OGC.WFS
{
public enum WFSRequestType
{
GetCapabilities,
DescribeFeatureType,
GetFeature
}
public class WFSParameterDescriptor
{
#region Declarations
private WFSRequestType _requestType = WFSRequestType.GetCapabilities;
private string _version = "1.0.0", _typeName = "", _srsName = String.Empty;
private int _maxFeatures = -1;
private XmlNode _filter = null;
private XmlNode _sortBy = null;
private string _subfields = "*";
#endregion
public WFSParameterDescriptor()
{
}
#region Parse
public bool ParseParameters(string[] parameters)
{
ParseParameters(new Parameters(parameters));
return true;
}
private void ParseParameters(Parameters Request)
{
if (Request["REQUEST"] == null)
{
WriteError("mandatory REQUEST parameter is missing");
}
switch (Request["REQUEST"].ToUpper())
{
case "GETCAPABILITIES":
_requestType = WFSRequestType.GetCapabilities;
break;
case "DESCRIBEFEATURETYPE":
_requestType = WFSRequestType.DescribeFeatureType;
break;
case "GETFEATURE":
_requestType = WFSRequestType.GetFeature;
break;
}
if (Request["VERSION"] == null)
{
WriteError("mandatory VERSION parameter is missing");
}
_version = Request["VERSION"];
if (Request["TYPENAME"] == null && _requestType != WFSRequestType.GetCapabilities)
{
WriteError("mandatory VERSION parameter is missing");
}
_typeName = Request["TYPENAME"];
if (Request["MAXFEATURES"] != null)
{
_maxFeatures = int.Parse(Request["MAXFEATURES"]);
}
if (Request["FILTER"] != null)
{
XmlDocument doc = new XmlDocument();
doc.Load(Request["FILTER"]);
_filter = doc.SelectSingleNode("Filter");
}
}
public bool ParseParameters(XmlDocument doc)
{
if (doc == null)
{
return false;
}
XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);
ns.AddNamespace("WFS", "http://www.opengis.net/wfs");
ns.AddNamespace("OGC", "http://www.opengis.net/ogc");
XmlNode request = doc.SelectSingleNode("WFS:GetCapabilities", ns);
if (request != null)
{
_requestType = WFSRequestType.GetCapabilities;
}
if (request == null)
{
request = doc.SelectSingleNode("WFS:DescribeFeatureType", ns);
if (request != null)
{
_requestType = WFSRequestType.DescribeFeatureType;
}
}
if (request == null)
{
request = doc.SelectSingleNode("WFS:GetFeature", ns);
if (request != null)
{
_requestType = WFSRequestType.GetFeature;
}
}
if (request == null)
{
return false;
}
if (request.Attributes["version"] == null)
{
WriteError("mandatory VERSION parameter is missing");
}
_version = request.Attributes["version"].Value;
if (request.Attributes["maxfeatures"] != null)
{
_maxFeatures = int.Parse(request.Attributes["maxfeatures"].Value);
}
else if (request.Attributes["maxFeatures"] != null)
{
_maxFeatures = int.Parse(request.Attributes["maxFeatures"].Value);
}
XmlNode query = request.SelectSingleNode("WFS:Query[@typeName]", ns);
if (query != null)
{
_typeName = query.Attributes["typeName"].Value;
_filter = query.SelectSingleNode("Filter", ns);
if (_filter == null)
{
_filter = query.SelectSingleNode("WFS:Filter", ns);
}
if (_filter == null)
{
_filter = query.SelectSingleNode("OGC:Filter", ns);
}
_sortBy = query.SelectSingleNode("SortBy", ns);
if (_sortBy == null)
{
_sortBy = query.SelectSingleNode("WFS:SortBy", ns);
}
if (_sortBy == null)
{
_sortBy = query.SelectSingleNode("OGC:SortBy", ns);
}
if (query.Attributes["srsName"] != null)
{
_srsName = query.Attributes["srsName"].Value;
}
}
XmlNode typeName = request.SelectSingleNode("WFS:TypeName", ns);
if (typeName != null)
{
_typeName = typeName.InnerText;
}
return true;
}
#endregion
#region ErrorReport
private void WriteError(String msg)
{
WriteError(msg, null);
}
private void WriteError(String msg, String code)
{
}
protected void WriteKMLError(string msg, string code)
{
//Response.ClearContent();
//Response.ClearHeaders();
//Response.Clear();
//Response.Buffer = true;
//Response.ContentType = "application/vnd.google-earth.kml+xml";
//Response.ContentEncoding = System.Text.Encoding.UTF8;
String sRet = String.Empty;
sRet = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
sRet += "<kml xmlns=\"http://earth.google.com/kml/2.0\">";
sRet += "<Folder>";
sRet += "<name>ERROR</name>";
sRet += "<description>" + msg + "</description>";
sRet += "</Folder>";
sRet += "</kml>";
//Response.Write(sRet);
//Response.Flush();
//Response.End();
}
#endregion
public WFSRequestType Request
{
get { return _requestType; }
set { _requestType = value; }
}
public string Version
{
get { return _version; }
set { _version = value; }
}
public string TypeName
{
get { return _typeName; }
set { _typeName = value; }
}
public int MaxFeatures
{
get { return _maxFeatures; }
set { _maxFeatures = value; }
}
public XmlNode Filter
{
get { return _filter; }
set { _filter = value; }
}
public XmlNode SortBy
{
get { return _sortBy; }
set { _sortBy = value; }
}
public string SubFields
{
get { return _subfields; }
}
public string SrsName
{
get { return _srsName; }
}
private class Parameters
{
private Dictionary<string, string> _parameters = new Dictionary<string, string>();
public Parameters(string[] list)
{
if (list == null)
{
return;
}
foreach (string l in list)
{
string[] p = l.Split('=');
string p1 = p[0].Trim().ToUpper(), pp;
string p2 = ((p.Length > 1) ? p[1].Trim() : "");
if (_parameters.TryGetValue(p1, out pp))
{
continue;
}
_parameters.Add(p1, p2);
}
}
public string this[string parameter]
{
get
{
string o;
if (!_parameters.TryGetValue(parameter.ToUpper(), out o))
{
return null;
}
return o;
}
}
}
}
}
|
#if DEBUG
using AsyncClasses;
using Contracts.Callback;
using System.Collections.Generic;
using System.ServiceModel;
using System.Threading.Tasks;
namespace Contracts.MPD
{
[ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(IAsyncListCallback),
Namespace = "http://www.noof.com/", Name = "MPDListAsync")]
[ServiceKnownType(typeof(MPDTableLoader))]
public interface IMPDAsyncListService
{
[OperationContract]
void CancelGetTemplatesAsync();
[OperationContract]
Task<List<string>> GetTemplatesAsync(object userState);
}
}
#endif |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Plugin.Settings;
using Rg.Plugins.Popup.Animations;
using Rg.Plugins.Popup.Interfaces;
using Rg.Plugins.Popup.Services;
using Rg.Plugins.Popup.Pages;
using System.Runtime.CompilerServices;
using System.Diagnostics;
using System.ComponentModel;
namespace CustomXamarinControls
{
public class ColorPickerCell : ViewCell
{
public static readonly BindableProperty TitleProperty
= BindableProperty.Create(nameof(Title), typeof(string), typeof(ColorPickerCell), "", BindingMode.TwoWay,
propertyChanged: (BindableObject bindable, object oldValue, object newValue) => {
(bindable as ColorPickerCell).TitleLabel.Text = (string)newValue;
});
public string Title
{
get { return (string)GetValue(TitleProperty); }
set { SetValue(TitleProperty, value); }
}
public static readonly BindableProperty PlaceholderProperty
= BindableProperty.Create(nameof(Placeholder), typeof(string), typeof(ColorPickerCell), "", BindingMode.TwoWay,
propertyChanged: (BindableObject bindable, object oldValue, object newValue) => {
(bindable as ColorPickerCell).ColorPick.Title = (string)newValue;
});
public string Placeholder
{
get { return (string)GetValue(PlaceholderProperty); }
set { SetValue(PlaceholderProperty, value); }
}
public static readonly BindableProperty StorageKeyProperty
= BindableProperty.Create(nameof(StorageKey), typeof(string), typeof(ColorPickerCell), "", BindingMode.TwoWay,
propertyChanged: (BindableObject bindable, object oldValue, object newValue) => {
(bindable as ColorPickerCell).ColorPick.StorageKey = (string) newValue;
});
public string StorageKey
{
get { return (string)GetValue(StorageKeyProperty); }
set { SetValue(StorageKeyProperty, value); }
}
public static readonly BindableProperty MessageProperty
= BindableProperty.Create(nameof(Message), typeof(string), typeof(ColorPickerCell), "", BindingMode.TwoWay);
public string Message
{
get { return (string)GetValue(MessageProperty); }
set { SetValue(MessageProperty, value); }
}
public static readonly BindableProperty CommandProperty =
BindableProperty.Create(nameof(Command),typeof(Command), typeof(ColorPickerCell), null, BindingMode.TwoWay);
public Command Command
{
get { return (Command)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
Color newColor;
Label TitleLabel;
ColorPicker ColorPick;
RoundableBoxView ColorPreview;
FlatButton Save;
public ColorPickerCell()
{
Color color = Color.White;
newColor = Color.FromHex(CrossSettings.Current.GetValueOrDefault(StorageKey, color.ToHex()));
TitleLabel = new Label()
{
HorizontalOptions = LayoutOptions.Start,
VerticalOptions = LayoutOptions.Center,
VerticalTextAlignment = TextAlignment.Center,
HorizontalTextAlignment = TextAlignment.Start,
WidthRequest = 90
};
ColorPreview = new RoundableBoxView()
{
BackgroundColor = newColor,
CornerRadius = 28,
HeightRequest = 28,
WidthRequest = 28,
IsVisible = false,
HorizontalOptions = LayoutOptions.End,
VerticalOptions = LayoutOptions.Center
};
ColorPick = new ColorPicker()
{
HorizontalOptions = LayoutOptions.FillAndExpand,
WidthRequest = 80
};
ColorPick.SelectedIndexChanged += SelectedItem;
ColorPreview.PropertyChanged += ColorPreviewPropertyChanged;
if (ColorPick.SelectedItem != null)
{
ColorPreview.IsVisible = true;
}
Save = new FlatButton()
{
Text = "Save",
TextColor = Color.DodgerBlue,
HorizontalTextAlignment = TextAlignment.Start,
FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)),
FontAttributes = FontAttributes.Bold,
BackgroundColor = Color.Transparent,
HorizontalOptions = LayoutOptions.Start,
VerticalOptions = LayoutOptions.Center,
WidthRequest = 60,
IsVisible = false
};
Save.Clicked += SaveClicked;
View = new StackLayout()
{
Children =
{
TitleLabel,
ColorPreview,
ColorPick,
Save
},
Padding = new Thickness(18,0,18,0),
Orientation = StackOrientation.Horizontal
};
}
private void ColorPreviewPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (nameof(ColorPreview.IsVisible).Equals(e.PropertyName))
{
var ColorPreviewTapped = new TapGestureRecognizer();
ColorPreviewTapped.Tapped += OnColorPreviewTap;
if (ColorPreview.IsVisible)
{
ColorPreview.GestureRecognizers.Add(ColorPreviewTapped);
}
else
{
ColorPreview.GestureRecognizers.Remove(ColorPreviewTapped);
}
}
}
private async void OnColorPreviewTap(object sender, EventArgs e)
{
PopupPage Popup = new PopupPage()
{
BackgroundColor = Color.Transparent,
Content = new Frame()
{
BackgroundColor = newColor,
HeightRequest = 200,
WidthRequest = 200,
VerticalOptions = LayoutOptions.Start,
HorizontalOptions = LayoutOptions.Start,
CornerRadius = 50
},
Animation = new ScaleAnimation(),
Padding = new Thickness(50, 40, 0, 0),
CloseWhenBackgroundIsClicked = true
};
var Close = new TapGestureRecognizer();
Close.Tapped += async (object s, EventArgs Ayer) => { await PopupNavigation.PopAsync(); };
Popup.Content.GestureRecognizers.Add(Close);
await PopupNavigation.PushAsync(Popup);
}
void SelectedItem(object sender, EventArgs e)
{
Color color = Color.FromHex(CrossSettings.Current.GetValueOrDefault(StorageKey, Color.White.ToHex()));
if ((ColorPick.SelectedItem as ColorItem).Name != ColorPick.ViewModel.Colors.GetNameByColor(color))
{
Save.IsVisible = true;
ColorPreview.IsVisible = true;
}
else
{
Save.IsVisible = false;
ColorPreview.IsVisible = true;
}
if ((ColorPick.SelectedItem as ColorItem).Name == "Default")
{
newColor = Color.White;
ColorPreview.BackgroundColor = newColor;
}
else
{
newColor = (ColorPick.SelectedItem as ColorItem).Color;
ColorPreview.BackgroundColor = newColor;
}
}
void SaveClicked(object sender, EventArgs e)
{
if ((ColorPick.SelectedItem as ColorItem).Name == "Default")
{
Color color = Color.White;
CrossSettings.Current.AddOrUpdateValue(StorageKey, color.ToHex());
CrossSettings.Current.Remove(StorageKey);
}
else
{
CrossSettings.Current.AddOrUpdateValue(StorageKey, ColorPick.ViewModel.SelectedColor.Hex);
}
MessagingCenter.Send(this, Message, newColor);
Save.IsVisible = false;
if (Command != null && Command.CanExecute(null))
{
Command.Execute(null);
}
}
protected override void OnAppearing()
{
Color color = Color.FromHex(CrossSettings.Current.GetValueOrDefault(StorageKey, Color.White.ToHex()));
ColorPick.SelectedItem = ColorPick.ViewModel.Colors.FirstOrDefault(x => x.Color == color);
base.OnAppearing();
}
}
public static class ExtensionMethods
{
public static TKey GetKeyByValue<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TValue Value)
{
return dictionary.FirstOrDefault(x => x.Value.ToString() == Value.ToString()).Key;
}
public static string ToHex(this Xamarin.Forms.Color color)
{
var red = (int)(color.R * 255);
var green = (int)(color.G * 255);
var blue = (int)(color.B * 255);
var alpha = (int)(color.A * 255);
var hex = $"#{alpha:X2}{red:X2}{green:X2}{blue:X2}";
return hex;
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EquipFootballController : Controller
{
public override void Execute(object data)
{
UIShop shop = MVC.GetView<UIShop>();
int id = (int)data;
GameModel gm = Game.M_Instance.M_GM;
gm.M_TakeOnFootball = id;
//shop.UpdateFootballBuyButton(id);
//shop.UpdateFootballGizmo();
}
}
|
using UnityEngine;
[System.Serializable]
public class Rotation {
public static Rotation UP = new Rotation(
0,
"up",
Vector2Int.up,
EnumAxis.Y,
EnumRotation.UP);
public static Rotation RIGHT = new Rotation(
1,
"right",
Vector2Int.right,
EnumAxis.X,
EnumRotation.RIGHT);
public static Rotation DOWN = new Rotation(
2,
"down",
Vector2Int.down,
EnumAxis.Y,
EnumRotation.DOWN);
public static Rotation LEFT = new Rotation(
3,
"left",
Vector2Int.left,
EnumAxis.X,
EnumRotation.LEFT);
public static Rotation[] ALL = new Rotation[] { UP, RIGHT, DOWN, LEFT };
public readonly int id;
public readonly string name;
public readonly Vector2Int vector;
public readonly Vector2 vectorF;
public readonly EnumAxis axis;
public readonly EnumRotation enumRot;
public readonly int xDir;
public readonly int yDir;
/// <summary>
/// Converts an EnumRotation to a Rotation. If the enum is None, null is returned.
/// </summary>
public static Rotation fromEnum(EnumRotation rotation) {
if(rotation == EnumRotation.NONE) {
return null;
} else {
return Rotation.ALL[(int)rotation];
}
}
/// <summary>
/// Converts a direction vector to a Rotation.
/// </summary>
public static Rotation directionToRotation(Vector2 dir) {
//get the normalized direction
Vector2 normDir = dir.normalized;
//calculate how many degrees one slice is
float step = 360f / 4; // 4 slices
//get the angle from -180 to 180 of the direction vector relative to the Up vector.
//this will return the angle between dir and North.
float angle = Vector2.SignedAngle(Vector2.up, normDir);
angle *= -1;
//if angle is negative, then let's make it positive by adding 360 to wrap it around.
if(angle < 0) {
angle += 360;
}
int index = Mathf.FloorToInt(angle / step);
return Rotation.ALL[index];
}
private Rotation(int id, string name, Vector2Int dir, EnumAxis axis, EnumRotation enumRot) {
this.id = id;
this.name = name;
this.vector = dir;
this.vectorF = this.vector;
this.axis = axis;
this.enumRot = enumRot;
this.xDir = dir.x;
this.yDir = dir.y;
}
public override string ToString() {
return "Rotation(" + this.name + ")";
}
public Rotation clockwise() {
return this.func(1);
}
public Rotation counterClockwise() {
return this.func(-1);
}
public Rotation opposite() {
return this.func(2);
}
public Rotation rotate(Rotation cellRotation) {
return this.func(cellRotation.id);
}
private Rotation func(int dir) {
int i = this.id + dir;
if(i < 0) {
i += ALL.Length;
} else if(i > 3) {
i -= ALL.Length;
}
return ALL[i];
}
}
|
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using SelectionCommittee.DAL.Entities;
using SelectionCommittee.DAL.EntityFramework;
using SelectionCommittee.DAL.Interfaces;
namespace SelectionCommittee.DAL.Repositories
{
public class FacultySubjectRepository : IFacultySubjectRepository
{
private ApplicationContext _context;
public FacultySubjectRepository(ApplicationContext db)
{
_context = db;
}
public void CreateRange(IEnumerable<FacultySubject> facultySubjects)
{
_context.FacultySubjects.AddRange(facultySubjects);
}
public IEnumerable<FacultySubject> GetAllByFacultyId(int facultyId)
{
return _context.FacultySubjects.Where(faculty => faculty.FacultyId == facultyId).ToList();
}
public void UpdateRange(IEnumerable<FacultySubject> facultySubjects)
{
foreach (var facultySubject in facultySubjects)
{
_context.Entry(facultySubject).State = EntityState.Modified;
}
}
}
} |
using ConcurrentCollections;
using Discord;
using Discord.Commands;
using JhinBot.DiscordObjects;
using JhinBot.Services;
using JhinBot.Utils;
using System;
using System.Linq;
using System.Timers;
namespace JhinBot
{
public class PollService : IPollService
{
private const double DEFAULT_TIME_TILL_PUBLIC_CLOSE = 120000;
private ConcurrentHashSet<Poll> _polls = new ConcurrentHashSet<Poll>();
private readonly IEmbedService _embedService;
private readonly IResourceService _resources;
private readonly IBotConfig _botConfig;
public PollService(IEmbedService embedService, IResourceService resourceService, IBotConfig botConfig)
{
_embedService = embedService;
_resources = resourceService;
_botConfig = botConfig;
}
private Poll GetPoll(ICommandContext context)
{
return _polls.FirstOrDefault(p =>
p.GuildId == context.Guild.Id &&
p.ChannelId == context.Channel.Id
);
}
public bool TryToStartNewPoll(string[] pollChoices, ICommandContext context)
{
var newPoll = GetPoll(context);
if (newPoll == null)
{
newPoll = new Poll(context.Guild.Id, context.Channel.Id, context.User.Id);
newPoll.AssignPollChoices(pollChoices);
_polls.Add(newPoll);
return true;
}
return false;
}
public void TryAddingNewVote(string pollVote, ICommandContext context)
{
if (!PeekPollForContext(context))
return;
var poll = GetPoll(context);
if (!poll.Voters.Contains(context.User.Id))
{
int.TryParse(pollVote, out var pollChoice);
if (poll.CurrentPollChoices.ContainsKey(pollChoice))
{
++poll.CurrentPollChoices[pollChoice];
poll.Voters.Add(context.User.Id);
}
}
}
public bool TryToClosePoll(ICommandContext context)
{
var poll = GetPoll(context);
return poll.CheckIfPollCanBeClosed(context.User.Id);
}
public EmbedBuilder GetPollStartEmbed(ICommandContext context)
{
var poll = GetPoll(context);
return GetCurrentPollState("poll_header_start_msg", "poll_vote_desc", poll, context.User);
}
public EmbedBuilder GetPollShowEmbed(ICommandContext context)
{
var poll = GetPoll(context);
return GetCurrentPollState("poll_header_current_msg", "poll_vote_desc", poll, context.User);
}
public EmbedBuilder GetPollClosedEmbed(ICommandContext context)
{
var poll = GetPoll(context);
return GetCurrentPollState("poll_header_close_msg", "", poll, context.User);
}
public EmbedBuilder GetPollCantBeClosedEmbed(ICommandContext context)
{
var poll = GetPoll(context);
var timeLeftString = ((poll.TimeStarted + (DEFAULT_TIME_TILL_PUBLIC_CLOSE / 1000)) - DateTimeOffset.Now.ToUnixTimeSeconds()).ToString();
return _embedService.CreateInfoEmbed("poll_publicclose_error_title", "poll_publicclose_error_desc", context.User, timeLeftString);
}
private EmbedBuilder GetCurrentPollState(string resxTitle, string resxDesc, Poll poll, IUser user)
{
if (poll != null)
{
var pollChoiceList = poll.GetCurrentPollChoiceStates();
return _embedService.CreateEmbedWithList(resxTitle, _botConfig.OkColor, pollChoiceList, user, resxDesc);
}
return _embedService.CreateInfoEmbed("poll_error_title", "poll_none_desc", user);
}
public void ClosePoll(ICommandContext context)
{
var poll = GetPoll(context);
_polls.TryRemove(poll);
}
private void CreateNewExpireTimerForConversation(Poll poll)
{
var timer = new Timer(DEFAULT_TIME_TILL_PUBLIC_CLOSE);
timer.Elapsed += (object sender, ElapsedEventArgs e) =>
{
timer.Stop();
poll.MakeCloseableToPublic();
};
timer.Start();
}
public bool PeekPollForContext(ICommandContext context)
=> GetPoll(context) != null;
}
}
|
using gView.Framework.Carto;
using gView.Framework.Data;
using gView.Framework.Data.Filters;
using gView.Framework.Data.Metadata;
using gView.Framework.Geometry;
using gView.Framework.IO;
using gView.Framework.Symbology;
using gView.Framework.Sys.UI;
using gView.Framework.system;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace gView.Framework.UI.Controls
{
internal class PreviewFeatureDataset : DatasetMetadata, IFeatureDataset
{
private IEnvelope _envelope = null;
private ISpatialReference _sRef = null;
private ILayer _layer = null;
public PreviewFeatureDataset(IFeatureClass fc)
{
if (fc == null)
{
return;
}
_envelope = fc.Envelope;
_sRef = fc.SpatialReference;
_layer = new PreviewFeatureLayer(fc);
}
public PreviewFeatureDataset(IRasterLayer rasterLayer)
{
if (rasterLayer == null || rasterLayer.RasterClass != null || rasterLayer.RasterClass.Polygon == null)
{
return;
}
_envelope = rasterLayer.RasterClass.Polygon.Envelope;
_sRef = rasterLayer.RasterClass.SpatialReference;
_layer = rasterLayer;
}
#region IFeatureDataset Members
public Task<gView.Framework.Geometry.IEnvelope> Envelope()
{
return Task.FromResult(_envelope);
}
public Task<ISpatialReference> GetSpatialReference()
{
return Task.FromResult(_sRef);
}
public void SetSpatialReference(ISpatialReference value)
{
_sRef = value;
}
#endregion
#region IDataset Members
public void Dispose()
{
}
public string ConnectionString
{
get
{
return "";
}
}
public Task<bool> SetConnectionString(string value)
{
return Task.FromResult(true);
}
public string DatasetGroupName
{
get { return ""; }
}
public string DatasetName
{
get { return "Preview Dataset"; }
}
public string ProviderName
{
get { return "gView"; }
}
public DatasetState State
{
get { return DatasetState.unknown; }
}
public Task<bool> Open()
{
return Task.FromResult(true);
}
public string LastErrorMessage
{
get; set;
}
public int order
{
get
{
return 0;
}
set
{
}
}
public IDatasetEnum DatasetEnum
{
get { return null; }
}
public Task<List<IDatasetElement>> Elements()
{
List<IDatasetElement> _elements = new List<IDatasetElement>();
if (_layer != null)
{
_elements.Add(_layer);
}
return Task.FromResult(_elements);
}
public string Query_FieldPrefix
{
get { return ""; }
}
public string Query_FieldPostfix
{
get { return ""; }
}
public gView.Framework.FDB.IDatabase Database
{
get { return null; }
}
public Task<IDatasetElement> Element(string title)
{
if (_layer == null)
{
return null;
}
if (_layer.Title == title)
{
return Task.FromResult<IDatasetElement>(_layer);
}
return Task.FromResult<IDatasetElement>(null); ;
}
public Task RefreshClasses()
{
return Task.CompletedTask;
}
#endregion
#region IPersistableLoadAsync
public Task<bool> LoadAsync(IPersistStream stream)
{
return Task.FromResult(true);
}
public void Save(IPersistStream stream)
{
}
#endregion
}
internal class PreviewFeatureLayer : Layer, IFeatureLayer
{
private IFeatureClass _fc;
private IFeatureRenderer _renderer;
private IFieldCollection _fields;
public PreviewFeatureLayer(IFeatureClass fc)
{
_fc = fc;
if (_fc == null)
{
return;
}
this.Title = fc.Name;
this.Visible = true;
_renderer = PlugInManager.Create(KnownObjects.Carto_SimpleRenderer) as IFeatureRenderer2;
if (_renderer is ISymbolCreator)
{
((IFeatureRenderer2)_renderer).Symbol = ((ISymbolCreator)_renderer).CreateStandardSymbol(_fc.GeometryType);
}
_fields = new FieldCollection();
}
#region IFeatureLayer Members
public gView.Framework.Carto.IFeatureRenderer FeatureRenderer
{
get
{
return _renderer;
}
set
{
_renderer = value;
}
}
public gView.Framework.Carto.IFeatureRenderer SelectionRenderer
{
get
{
return null;
}
set
{
}
}
public gView.Framework.Carto.ILabelRenderer LabelRenderer
{
get
{
return null;
}
set
{
}
}
public bool ApplyRefScale
{
get
{
return true;
}
set
{
}
}
public bool ApplyLabelRefScale
{
get
{
return true;
}
set
{
}
}
public float MaxRefScaleFactor { get; set; }
public float MaxLabelRefScaleFactor { get; set; }
public IFeatureClass FeatureClass
{
get { return _fc; }
}
public IQueryFilter FilterQuery
{
get
{
return null;
}
set
{
}
}
public IFieldCollection Fields
{
get { return _fields; }
}
public FeatureLayerJoins Joins
{
get { return null; }
set { }
}
public GeometryType LayerGeometryType
{
get
{
return this.FeatureClass != null ? this.FeatureClass.GeometryType : GeometryType.Unknown;
}
set
{
}
}
#endregion
}
internal class ExplorerMapApplication : License, IMapApplication
{
IGUIApplication _application = null;
//private MapView _mapView = null;
private PreviewControl _control = null;
public event EventHandler OnApplicationStart { add { } remove { } }
public ExplorerMapApplication(IGUIApplication application, PreviewControl control)
{
_application = application;
_control = control;
}
public ExplorerMapApplication(IGUIApplication application, PreviewControl control, object mapView)
: this(application, control)
{
}
#region IMapApplication Members
public event AfterLoadMapDocumentEvent AfterLoadMapDocument { add { } remove { } }
public event ActiveMapToolChangedEvent ActiveMapToolChanged { add { } remove { } }
public event OnCursorPosChangedEvent OnCursorPosChanged { add { } remove { } }
public bool InvokeRequired
{
get
{
return _application.InvokeRequired;
}
}
public object Invoke(Delegate method)
{
return _application.Invoke(method);
}
async public Task LoadMapDocument(string filename)
{
if (_application is IMapApplication)
{
await ((IMapApplication)_application).LoadMapDocument(filename);
}
}
async public Task RefreshActiveMap(DrawPhase drawPhase)
{
if (_application is IMapApplication)
{
await ((IMapApplication)_application).RefreshActiveMap(drawPhase);
}
else if (_control != null)
{
await _control.RefreshMap();
}
}
public Task RefreshTOC()
{
return Task.CompletedTask;
}
public void RefreshTOCElement(IDatasetElement element)
{
}
public void SaveMapDocument(string filename, bool performEncryption)
{
if (_application is IMapApplication)
{
((IMapApplication)_application).SaveMapDocument(filename, performEncryption);
}
}
public string DocumentFilename
{
get
{
return String.Empty;
}
set
{
}
}
public void SaveMapDocument()
{
if (_application is IMapApplication)
{
((IMapApplication)_application).SaveMapDocument();
}
}
public IDocumentWindow DocumentWindow
{
get
{
if (_application is IMapApplication)
{
return ((IMapApplication)_application).DocumentWindow;
}
return null;
}
}
public IMapApplicationModule IMapApplicationModule(Guid guid)
{
return null;
}
public bool ReadOnly { get { return false; } }
public void DrawReversibleGeometry(IGeometry geometry, System.Drawing.Color color)
{
}
#endregion
#region IGUIApplication Members
public void AddDockableWindow(IDockableWindow window, string ParentDockableWindowName)
{
if (_application != null)
{
_application.AddDockableWindow(window, ParentDockableWindowName);
}
}
public void AddDockableWindow(IDockableWindow window, DockWindowState state)
{
if (_application != null)
{
_application.AddDockableWindow(window, state);
}
}
public IGUIAppWindow ApplicationWindow
{
get
{
if (_application == null)
{
return null;
}
return _application.ApplicationWindow;
}
}
public event DockWindowAddedEvent DockWindowAdded { add { } remove { } }
public List<IDockableWindow> DockableWindows
{
get
{
if (_application == null)
{
return new List<IDockableWindow>();
}
return _application.DockableWindows;
}
}
public event OnShowDockableWindowEvent OnShowDockableWindow { add { } remove { } }
public void ShowDockableWindow(IDockableWindow window)
{
if (_application != null)
{
_application.ShowDockableWindow(window);
}
}
public void SetCursor(object cursor)
{
}
//public List<object> ToolStrips
//{
// get
// {
// if (_application == null) return new List<object>();
// return _application.ToolStrips;
// }
//}
public ITool Tool(Guid guid)
{
if (_control != null)
{
return _control.Tool(guid);
}
return null;
}
public List<ITool> Tools
{
get { return new List<ITool>(); }
}
public IToolbar Toolbar(Guid guid)
{
return null;
}
public List<IToolbar> Toolbars
{
get
{
return new List<IToolbar>();
}
}
public ITool ActiveTool
{
get { return null; }
set { }
}
public void ValidateUI()
{
if (_application != null)
{
_application.ValidateUI();
}
}
public IStatusBar StatusBar
{
get
{
return null;
}
}
public void AppendContextMenuItems(ContextMenuStrip strip, object context)
{
}
#endregion
#region IApplication Members
public void Exit()
{
if (_application != null)
{
_application.Exit();
}
}
public string Title
{
get
{
if (_application == null)
{
return "";
}
return _application.Title;
}
set
{
if (_application != null)
{
_application.Title = value;
}
}
}
#endregion
public void ShowBackstageMenu()
{
}
public void HideBackstageMenu()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Plus1.Models;
namespace Plus1.Areas.Admin.Controllers
{
[Authorize(Roles = "Admin")]
public class AdminSubSubCategoriesController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: Admin/AdminSubSubCategories
public ActionResult Index()
{
var subSubCategory = db.SubSubCategory.Include(s => s.Parent);
return View(subSubCategory.ToList());
}
// GET: Admin/AdminSubSubCategories/Details/5
public ActionResult Details(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
SubSubCategory subSubCategory = db.SubSubCategory.Find(id);
if (subSubCategory == null)
{
return HttpNotFound();
}
return View(subSubCategory);
}
// GET: Admin/AdminSubSubCategories/Create
public ActionResult Create()
{
ViewBag.ParentName = new SelectList(db.SubCategory, "Name", "ParentName");
return View();
}
// POST: Admin/AdminSubSubCategories/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Name,ParentName,Image")] SubSubCategory subSubCategory)
{
if (ModelState.IsValid)
{
db.SubSubCategory.Add(subSubCategory);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ParentName = new SelectList(db.SubCategory, "Name", "ParentName", subSubCategory.ParentName);
return View(subSubCategory);
}
// GET: Admin/AdminSubSubCategories/Edit/5
public ActionResult Edit(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
SubSubCategory subSubCategory = db.SubSubCategory.Find(id);
if (subSubCategory == null)
{
return HttpNotFound();
}
ViewBag.ParentName = new SelectList(db.SubCategory, "Name", "ParentName", subSubCategory.ParentName);
return View(subSubCategory);
}
// POST: Admin/AdminSubSubCategories/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(SubSubCategory subSubCategory, HttpPostedFileBase fileUpload)
{
if (ModelState.IsValid && fileUpload != null && fileUpload.ContentLength > 0)
{
string fileGuid = Guid.NewGuid().ToString();
string extension = Path.GetExtension(fileUpload.FileName);
string newFilename = fileGuid + extension;
string uploadPath = Path.Combine(Server.MapPath("~/Content/uploads/"));
fileUpload.SaveAs(Path.Combine(uploadPath, newFilename));
subSubCategory.Image = newFilename;
if (ModelState.IsValid)
{
db.Entry(subSubCategory).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
return View(subSubCategory);
}
// GET: Admin/AdminSubSubCategories/Delete/5
public ActionResult Delete(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
SubSubCategory subSubCategory = db.SubSubCategory.Find(id);
if (subSubCategory == null)
{
return HttpNotFound();
}
return View(subSubCategory);
}
// POST: Admin/AdminSubSubCategories/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(string id)
{
SubSubCategory subSubCategory = db.SubSubCategory.Find(id);
db.SubSubCategory.Remove(subSubCategory);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
// Copyright (c) 2018 FiiiLab Technology Ltd
// Distributed under the MIT software license, see the accompanying
// file LICENSE or or http://www.opensource.org/licenses/mit-license.php.
using EdjCase.JsonRpc.Router;
using EdjCase.JsonRpc.Router.Abstractions;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using FiiiChain.DTO;
using FiiiChain.Framework;
using FiiiChain.Business;
using FiiiChain.Messages;
using FiiiChain.Consensus;
using FiiiChain.Entities;
using Newtonsoft.Json;
using System.Numerics;
using System.Text;
using Microsoft.Extensions.Caching.Memory;
namespace FiiiChain.Wallet.API
{
public class BlockChainController : BaseRpcController
{
private IMemoryCache _cache;
public BlockChainController(IMemoryCache memoryCache) { _cache = memoryCache; }
public IRpcMethodResult StopEngine()
{
try
{
Startup.EngineStopAction();
return Ok();
}
catch (CommonException ce)
{
return Error(ce.ErrorCode, ce.Message, ce);
}
catch (Exception ex)
{
return Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex);
}
}
public IRpcMethodResult GetBlockChainStatus()
{
try
{
var result = Startup.GetEngineJobStatusFunc();
return Ok(result);
}
catch (CommonException ce)
{
return Error(ce.ErrorCode, ce.Message, ce);
}
catch (Exception ex)
{
return Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex);
}
}
public IRpcMethodResult GetBlock(string blockHash, int format = 0)
{
try
{
var blockComponent = new BlockComponent();
var block = blockComponent.GetBlockMsgByHash(blockHash);
if(block != null)
{
if(format == 0)
{
var bytes = block.Serialize();
var result = Base16.Encode(bytes);
return Ok(result);
}
else
{
return Ok(block);
}
}
else
{
return Ok();
}
}
catch (CommonException ce)
{
return Error(ce.ErrorCode, ce.Message, ce);
}
catch (Exception ex)
{
return Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex);
}
}
public IRpcMethodResult GetBlockByHeight(long height, int format = 0)
{
try
{
var blockComponent = new BlockComponent();
var block = blockComponent.GetBlockMsgByHeight(height);
if (block != null)
{
if (format == 0)
{
var bytes = block.Serialize();
var result = Base16.Encode(bytes);
return Ok(result);
}
else
{
return Ok(block);
}
}
else
{
return Ok();
}
}
catch (CommonException ce)
{
return Error(ce.ErrorCode, ce.Message, ce);
}
catch (Exception ex)
{
return Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex);
}
}
public IRpcMethodResult GetBlockCount()
{
try
{
var blockComponent = new BlockComponent();
var height = blockComponent.GetLatestHeight();
return Ok(height);
}
catch (CommonException ce)
{
return Error(ce.ErrorCode, ce.Message, ce);
}
catch (Exception ex)
{
return Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex);
}
}
public IRpcMethodResult GetBlockHash(long blockHeight)
{
try
{
var blockComponent = new BlockComponent();
var block = blockComponent.GetBlockEntiytByHeight(blockHeight);
if(block != null)
{
return Ok(block.Hash);
}
else
{
return Ok();
}
}
catch (CommonException ce)
{
return Error(ce.ErrorCode, ce.Message, ce);
}
catch (Exception ex)
{
return Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex);
}
}
public IRpcMethodResult GetBlockHeader(string blockHash, int format = 0)
{
try
{
var blockComponent = new BlockComponent();
var header = blockComponent.GetBlockHeaderMsgByHash(blockHash);
if (header != null)
{
if (format == 0)
{
var bytes = header.Serialize();
var result = Base16.Encode(bytes);
return Ok(result);
}
else
{
return Ok(header);
}
}
else
{
return Ok();
}
}
catch (CommonException ce)
{
return Error(ce.ErrorCode, ce.Message, ce);
}
catch (Exception ex)
{
return Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex);
}
}
public IRpcMethodResult GetChainTips()
{
try
{
var dict = new BlockComponent().GetChainTips();
var result = new List<GetChainTipsOM>();
foreach(var block in dict.Keys)
{
var item = new GetChainTipsOM();
item.height = block.Height;
item.hash = block.Hash;
item.branchLen = dict[block];
if(item.branchLen == 0)
{
item.status = "active";
}
else
{
if(block.IsDiscarded)
{
item.status = "invalid";
}
else
{
item.status = "unknown";
}
}
result.Add(item);
}
return Ok(result.ToArray());
}
catch (CommonException ce)
{
return Error(ce.ErrorCode, ce.Message, ce);
}
catch (Exception ex)
{
return Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex);
}
}
public IRpcMethodResult GetDifficulty()
{
try
{
var blockComponent = new BlockComponent();
var height = blockComponent.GetLatestHeight();
var newHeight = height + 1;
var previousBlockEntity = blockComponent.GetBlockEntiytByHeight(height);
Block prevStepBlock = null;
if (newHeight >= POW.DIFFIUCLTY_ADJUST_STEP)
{
prevStepBlock = blockComponent.GetBlockEntiytByHeight(newHeight - POW.DIFFIUCLTY_ADJUST_STEP);
//if (!GlobalParameters.IsTestnet && newHeight <= POC.DIFFICULTY_CALCULATE_LOGIC_ADJUST_HEIGHT)
//{
// prevStepBlock = blockComponent.GetBlockEntiytByHeight(newHeight - POC.DIFFIUCLTY_ADJUST_STEP - 1);
//}
//else
//{
// prevStepBlock = blockComponent.GetBlockEntiytByHeight(newHeight - POW.DIFFIUCLTY_ADJUST_STEP);
//}
}
var bits = POW.CalculateBaseTarget(height, previousBlockEntity, prevStepBlock).ToString();
var result = new GetDifficultyOM()
{
height = newHeight,
hashTarget = bits
};
return Ok(result);
}
catch (CommonException ce)
{
return Error(ce.ErrorCode, ce.Message, ce);
}
catch (Exception ex)
{
return Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex);
}
}
public IRpcMethodResult GenerateNewBlock(string minerName, string address = null, string remark = null,
int format = 0)
{
try
{
BlockComponent blockComponent = new BlockComponent();
var block = blockComponent.CreateNewBlock(minerName, address, remark);
if (block != null)
{
if (format == 0)
{
var bytes = block.Serialize();
var block1 = new BlockMsg();
int index = 0;
block1.Deserialize(bytes, ref index);
var result = Base16.Encode(bytes);
return Ok(result);
}
else
{
return Ok(block);
}
}
else
{
return Ok();
}
}
catch (CommonException ce)
{
return Error(ce.ErrorCode, ce.Message, ce);
}
catch (Exception ex)
{
return Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex);
}
}
public IRpcMethodResult SubmitBlock(string blockData)
{
try
{
var bytes = Base16.Decode(blockData);
var block = new BlockMsg();
int index = 0;
try
{
block.Deserialize(bytes, ref index);
}
catch
{
throw new CommonException(ErrorCode.Service.BlockChain.BLOCK_DESERIALIZE_FAILED);
}
var blockComponent = new BlockComponent();
var blockInDB = blockComponent.GetBlockEntiytByHeight(block.Header.Height);
if (blockInDB == null)
{
var result = blockComponent.SaveBlockIntoDB(block);
if (result)
{
Startup.P2PBroadcastBlockHeaderAction(block.Header);
}
else
{
throw new CommonException(ErrorCode.Service.BlockChain.BLOCK_SAVE_FAILED);
}
}
else
{
throw new CommonException(ErrorCode.Service.BlockChain.SAME_HEIGHT_BLOCK_HAS_BEEN_GENERATED);
}
return Ok();
}
catch (CommonException ce)
{
return Error(ce.ErrorCode, ce.Message, ce);
}
catch (Exception ex)
{
return Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex);
}
}
public IRpcMethodResult GetBaseTarget(long blockHeight)
{
try
{
var blockComponent = new BlockComponent();
Block lastBlock = null;
Block prevStepBlock = null;
if (blockHeight > 0)
{
lastBlock = blockComponent.GetBlockEntiytByHeight(blockHeight - 1);
if (blockHeight >= POW.DIFFIUCLTY_ADJUST_STEP)
{
prevStepBlock = blockComponent.GetBlockEntiytByHeight(blockHeight - POW.DIFFIUCLTY_ADJUST_STEP);
//if (!GlobalParameters.IsTestnet && blockHeight <= POC.DIFFICULTY_CALCULATE_LOGIC_ADJUST_HEIGHT)
//{
// prevStepBlock = blockComponent.GetBlockEntiytByHeight(blockHeight - POC.DIFFIUCLTY_ADJUST_STEP - 1);
//}
//else
//{
// prevStepBlock = blockComponent.GetBlockEntiytByHeight(blockHeight - POC.DIFFIUCLTY_ADJUST_STEP);
//}
}
}
long baseTarget;
if (lastBlock != null)
baseTarget = POW.CalculateBaseTarget(blockHeight, lastBlock, prevStepBlock);
else
baseTarget = POW.CalculateBaseTarget(0, null, null);
return Ok(baseTarget);
}
catch (CommonException ce)
{
return Error(ce.ErrorCode, ce.Message, ce);
}
catch (Exception ex)
{
return Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex);
}
}
public IRpcMethodResult GetVerifiedHashes(List<string> hashes)
{
try
{
BlockComponent component = new BlockComponent();
List<Block> result = component.GetVerifiedHashes(hashes);
return Ok(result);
}
catch (CommonException ce)
{
return Error(ce.ErrorCode, ce.Message, ce);
}
catch (Exception ex)
{
return Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex);
}
}
/// <summary>
/// 估算交易费用
/// </summary>
/// <returns></returns>
public IRpcMethodResult EstimateSmartFee()
{
try
{
BlockComponent block = new BlockComponent();
long fee = block.EstimateSmartFee();
return Ok(fee);
}
catch (CommonException ce)
{
LogHelper.Error(ce.ToString());
return Error(ce.ErrorCode, ce.Message, ce);
}
catch (Exception ex)
{
LogHelper.Error(ex.ToString());
return Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex);
}
}
/// <summary>
/// 获取区块的所有奖励,包含挖矿和手续费
/// </summary>
/// <param name="blockHash"></param>
/// <returns></returns>
public IRpcMethodResult GetBlockReward(string blockHash)
{
try
{
BlockComponent block = new BlockComponent();
long reward = block.GetBlockReward(blockHash);
return Ok(reward);
}
catch (CommonException ce)
{
return Error(ce.ErrorCode, ce.Message, ce);
}
catch (Exception ex)
{
return Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex);
}
}
public IRpcMethodResult SignMessage(string address, string message)
{
try
{
var account = new AccountComponent().GetAccountById(address);
if (account == null || string.IsNullOrWhiteSpace(account.PrivateKey))
{
throw new CommonException(ErrorCode.Service.Account.ACCOUNT_NOT_FOUND);
}
ECDsa dsa = ECDsa.ImportPrivateKey(Base16.Decode(DecryptPrivateKey(account.PrivateKey)));
var signResult = Base16.Encode(dsa.SingnData(Encoding.UTF8.GetBytes(message)));
var result = new
{
signature = signResult,
publicKey = account.PublicKey
};
return Ok(result);
}
catch (CommonException ce)
{
return Error(ce.ErrorCode, ce.Message, ce);
}
catch (Exception ex)
{
return Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex);
}
}
public IRpcMethodResult VerifyMessage(string publicKey, string signature, string message)
{
try
{
ECDsa dsa = ECDsa.ImportPublicKey(Base16.Decode(publicKey));
var result = dsa.VerifyData(Encoding.UTF8.GetBytes(message), Base16.Decode(signature));
return Ok(result);
}
catch (CommonException ce)
{
return Error(ce.ErrorCode, ce.Message, ce);
}
catch (Exception ex)
{
return Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex);
}
}
private string DecryptPrivateKey(string privateKey)
{
var setting = new SettingComponent().GetSetting();
if (setting.Encrypt)
{
if (!string.IsNullOrWhiteSpace(_cache.Get<string>("WalletPassphrase")))
{
try
{
return AES128.Decrypt(privateKey, _cache.Get<string>("WalletPassphrase"));
}
catch
{
throw new CommonException(ErrorCode.Service.Transaction.WALLET_DECRYPT_FAIL);
}
}
else
{
//是否需要调用解密的逻辑
throw new CommonException(ErrorCode.Service.Transaction.WALLET_DECRYPT_FAIL);
}
}
else
{
return privateKey;
}
}
}
}
|
using DatabaseUpdater.Updaters.Classes;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
namespace DatabaseUpdater
{
class CategoryUpdater
{
public List<Category> AllCat = new List<Category>();
public List<SubCategory> AllSubCat = new List<SubCategory>();
public List<SubSubCategory> AllSubSubCat = new List<SubSubCategory>();
public Program p = new Program();
public void Run()
{
Console.WriteLine("Start Category Table Routine");
RunCategory();
Console.ReadKey();
}
public void RunCategory()
{
XmlDocument doc = new XmlDocument();
doc.Load(p.BaseURL + "categories");
string xmlcontents = doc.InnerXml;
XmlElement xelRoot = doc.DocumentElement;
XmlNodeList Categories = xelRoot.SelectNodes("/Categories/Category");
foreach (XmlNode xndNode in Categories)
{
Category c = new Category();
c.Name = xndNode["Name"].InnerText;
AllCat.Add(c);
Console.WriteLine("Category: " + c.Name);
XmlNodeList SubCategories = xndNode.SelectNodes("Subcategory");
foreach (XmlNode SubNode in SubCategories)
{
SubCategory sc = new SubCategory();
sc.Name = SubNode["Name"].InnerText;
AllSubCat.Add(sc);
Console.WriteLine("SubCategory: " + SubNode["Name"].InnerText);
XmlNodeList SubSubCategories = SubNode.SelectNodes("Subcategory");
foreach (XmlNode SubSubNode in SubCategories)
{
SubSubCategory ssc = new SubSubCategory();
ssc.Name = SubSubNode["Name"].InnerText;
AllSubSubCat.Add(ssc);
Console.WriteLine("SubSubCategory: " + SubSubNode["Name"].InnerText);
}
}
}
}
public void InsertCategory()
{
using (var connection = new SqlConnection(p.ConnectionString))
{
connection.Open();
foreach (Category cat in AllCat)
{
var sql = "INSERT INTO Categories(Name) VALUES(@Name)";
using (var cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.AddWithValue("@Name", cat.Name);
cmd.ExecuteNonQuery();
}
}
foreach (SubCategory subcat in AllSubCat)
{
var sql = "INSERT INTO Categories(SubName) VALUES(@Name)";
using (var cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.AddWithValue("@SubName", subcat.Name);
cmd.ExecuteNonQuery();
}
}
}
}
}
}
|
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
namespace Gap.NetFest.DataAccess.Repositories
{
public class BaseRepository
{
public ChocolateCompanyContext Context{ get; set; }
public BaseRepository()
{
this.Context = new ChocolateCompanyContext();
this.Context.Database.SetCommandTimeout(150000);
}
public ChocolateCompanyContext GetInstance() {
return this.Context;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/*************************************************************
* 标准查询运算符是组成Linq模式的方法,其中大多数方法都作用于序列.
* 其中,序列指类型实现IEnumerable<T>接口或IQueryable<T>接口的对象.
* 标准查询运算符提供包括筛选,投影,聚合,排序等查询功能
*************************************************************/
namespace StandardQueryOperator
{
class Program
{
static void Main(string[] args)
{
string sentence = "the quick brown fox jumps over the lazy dog";
string[] words = sentence.Split(' ');
//按单词长度升序排列
var query1 =
from word in words
orderby word.Length
select word;
//方法语法的升序排列
var query2 =
words.Select(p => p).
OrderBy(p => p.Length);
//按单词长度降序排列
var query3 =
from word in words
orderby word.Length descending
select word;
//方法语法的降序排列
var query4 =
words.Select(p => p).
OrderByDescending(p => p.Length);
//按单词长度降序排列
var query5 =
from word in words
orderby word.Length, word[0]
select word;
//方法语法的降序排列
var query6 =
words.Select(p => p).
OrderByDescending(p => p.Length).
ThenBy(p=>p[0]);
//反转元素
//var query = words.Reverse();
//查询语法
//按照单词从长度进行分组,并对组按长度排序
//var query =
// from word in words
// group word.ToUpper() by word.Length into gr
// orderby gr.Key
// select new { Length = gr.Key, Words = gr };
//方法语法
//var query2 = words.
// GroupBy(w => w.Length, w => w.ToUpper()).
// Select(g => new { Length = g.Key, Words = g }).
// OrderBy(o => o.Length);
//foreach (var obj in query)
//{
// Console.WriteLine("Words of length {0}:", obj.Length);
// foreach (string word in obj.Words)
// Console.WriteLine(word);
//}
//string[] planets1 = { "Mercury", "Venus", "Earth", "Jupiter" };
//string[] planets2 = { "Mercury", "Earth", "Mars", "Jupiter" };
//IEnumerable<string> query = from planet in planets1.Except(planets2)
// select planet;
//foreach (var str in query)
//{
// Console.WriteLine(str);
//}
///*This code produces the following output:
//*
//*Venus
//*/
//string[] planets1 = { "Mercury", "Venus", "Earth", "Jupiter" };
//string[] planets2 = { "Mercury", "Earth", "Mars", "Jupiter" };
////返回序列包含两个序列的共有元素
//IEnumerable<string> query = from planet in planets1.Intersect(planets2)
// select planet;
//foreach (var str in query)
//{
// Console.WriteLine(str);
//}
///*This code produces the following output:
//*Mercury
//* Earth
//* Jupiter
//*/
string[] planets1 = { "Mercury", "Venus", "Earth", "Jupiter" };
string[] planets2 = { "Mercury", "Earth", "Mars", "Jupiter" };
IEnumerable<string> query = from planet in planets1.Union(planets2)
select planet;
foreach (var str in query)
{
Console.WriteLine(str);
}
/*This code produces the following output:
* Mercury
* Venus
* Earth
* Jupiter
* Mars
*/
Example();
Console.ReadKey();
}
//class Market
//{
// public string Name { get; set; }
// public string[] Items { get; set; }
//}
//public static void Example()
//{
// List<Market> markets = new List<Market>
// {
// new Market { Name = "Emily's", Items = new string[] { "kiwi", "cheery", "banana" } },
// new Market { Name = "Kim's", Items = new string[] { "melon", "mango", "olive" } },
// new Market { Name = "Adam's", Items = new string[] { "kiwi", "apple", "orange" } },
// };
// // 确定集合中的元素长度是否等于5,输出符合条件的项
// IEnumerable<string> names = from market in markets
// where market.Items.All(item => item.Length == 5)
// select market.Name;
// foreach (string name in names)
// {
// Console.WriteLine($"{name} market");
// }
// // This code produces the following output:
// //
// // Kim's market
//}
class Product
{
public string Name { get; set; }
public int CategoryId { get; set; }
}
class Category
{
public int Id { get; set; }
public string CategoryName { get; set; }
}
public static void Example()
{
List<Product> products = new List<Product>
{
new Product { Name = "Cola", CategoryId = 0 },
new Product { Name = "Tea", CategoryId = 0 },
new Product { Name = "Apple", CategoryId = 1 },
new Product { Name = "Kiwi", CategoryId = 1 },
new Product { Name = "Carrot", CategoryId = 2 },
};
List<Category> categories = new List<Category>
{
new Category { Id = 0, CategoryName = "Beverage" },
new Category { Id = 1, CategoryName = "Fruit" },
new Category { Id = 2, CategoryName = "Vegetable" }
};
// Join products and categories based on CategoryId
//var query = from product in products
// where product.CategoryId == 0
// join category in categories on product.CategoryId equals category.Id
// select new { product.Name, category.CategoryName };
var query = from category in categories
join product in products on category.Id equals product.CategoryId into productGroup
select productGroup;
foreach (IEnumerable<Product> productGroup in query)
{
Console.WriteLine("Group");
foreach (Product product in productGroup)
{
Console.WriteLine($"{product.Name,8}");
}
}
// This code produces the following output:
//
// Group
// Cola
// Tea
// Group
// Apple
// Kiwi
// Group
// Carrot
}
}
}
|
namespace Shipwreck.TypeScriptModels.Declarations
{
public interface IInterfaceMemberVisitor<T>
{
T VisitField(FieldDeclaration member);
T VisitIndex(IndexSignature member);
T VisitMethod(MethodDeclaration member);
T VisitGetAccessor(GetAccessorDeclaration member);
T VisitSetAccessor(SetAccessorDeclaration member);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Awesomium.Core;
using SKYPE4COMLib;
namespace Skyply
{
public partial class MainForm : Form
{
public MainForm()
{
WebConfig wc = new WebConfig();
wc.RemoteDebuggingPort = 7777;
wc.AutoUpdatePeriod = 1;
WebCore.Initialize(wc);
InitializeComponent();
}
public Skype skype = new Skype();
public NotificationManager notificationManager;
private void Form1_Load(object sender, EventArgs e)
{
this.Visible = false;
notificationManager = new NotificationManager(this);
skype.MessageStatus += skype_MessageStatus;
skype.Attach(8, false);
}
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
void skype_MessageStatus(ChatMessage pMessage, TChatMessageStatus Status)
{
if (Status == TChatMessageStatus.cmsReceived && skype.CurrentUserStatus != TUserStatus.cusDoNotDisturb && System.Diagnostics.Process.GetProcessesByName("Skype")[0].MainWindowHandle != GetForegroundWindow())
{
notificationManager.AddNotification(pMessage);
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
|
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
namespace Atc.CodeDocumentation.Markdown
{
/// <summary>
/// MarkdownCodeDocGenerator.
/// </summary>
public static class MarkdownCodeDocGenerator
{
internal const string GeneratedBy = "<hr /><div style='text-align: right'><i>Generated by MarkdownCodeDoc version 1.2</i></div>";
/// <summary>Runs on the specified assembly to document the code in markdown files.</summary>
/// <param name="assemblyToCodeDoc">The assembly to code document.</param>
/// <param name="outputPath">The output path.</param>
/// <exception cref="IOException">No CodeDoc output path found for the assembly: {assemblyToCodeDoc.FullName}.</exception>
/// <code><![CDATA[MarkdownCodeDocGenerator.Run(Assembly.GetAssembly(typeof(OneTypeFromTheAssemblyToDocument)));]]></code>
/// <example><![CDATA[MarkdownCodeDocGenerator.Run(Assembly.GetAssembly(typeof(LocalizedDescriptionAttribute)));]]></example>
public static void Run(Assembly assemblyToCodeDoc, DirectoryInfo? outputPath = null)
{
// Due to some build issue with GenerateDocumentationFile=true and xml-file location, this hack is made for now.
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return;
}
var typeComments = AssemblyCommentHelper.CollectExportedTypesWithComments(assemblyToCodeDoc);
if (!typeComments.Any())
{
return;
}
outputPath ??= GetOutputPath(assemblyToCodeDoc);
if (outputPath == null)
{
throw new IOException($"No CodeDoc output path found for the assembly: {assemblyToCodeDoc.FullName}");
}
PrepareOutputPath(outputPath);
GenerateAndWrites(typeComments, outputPath);
}
private static DirectoryInfo? GetOutputPath(Assembly assembly)
{
var assemblyName = assembly.GetName().Name;
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
var index = baseDirectory.IndexOf(assemblyName, StringComparison.Ordinal);
if (index == -1)
{
return null;
}
baseDirectory = baseDirectory.Substring(0, index + assemblyName.Length);
return new DirectoryInfo(Path.Combine(baseDirectory, "CodeDoc"));
}
private static void PrepareOutputPath(DirectoryInfo outputPath)
{
if (!Directory.Exists(outputPath.FullName))
{
Directory.CreateDirectory(outputPath.FullName);
}
else
{
foreach (var file in Directory.GetFiles(outputPath.FullName, "*.md", SearchOption.AllDirectories))
{
File.Delete(file);
}
}
}
private static void GenerateAndWrites(TypeComments[] typeComments, DirectoryInfo outputPath)
{
var homeBuilder = new MarkdownBuilder();
homeBuilder.AppendLine("<div style='text-align: right'>");
homeBuilder.AppendLine("[References extended](IndexExtended.md)");
homeBuilder.AppendLine("</div>");
homeBuilder.AppendLine();
homeBuilder.Header(1, "References");
homeBuilder.AppendLine();
var homeExtendedBuilder = new MarkdownBuilder();
homeExtendedBuilder.AppendLine("<div style='text-align: right'>");
homeExtendedBuilder.AppendLine("[References](Index.md)");
homeExtendedBuilder.AppendLine("</div>");
homeExtendedBuilder.AppendLine();
homeExtendedBuilder.Header(1, "References extended");
homeExtendedBuilder.AppendLine();
foreach (var g in typeComments.GroupBy(x => x.Namespace, StringComparer.Ordinal).OrderBy(x => x.Key))
{
homeBuilder.HeaderWithLink(2, g.Key, g.Key + ".md");
homeBuilder.AppendLine();
homeExtendedBuilder.HeaderWithLink(2, g.Key, g.Key + ".md");
homeExtendedBuilder.AppendLine();
var sb = new StringBuilder();
sb.AppendLine("<div style='text-align: right'>");
sb.AppendLine();
sb.AppendLine("[References](Index.md) - [References extended](IndexExtended.md)");
sb.AppendLine("</div>");
sb.AppendLine();
sb.AppendLine($"# {g.Key}");
foreach (var item in g.OrderBy(x => x.Name))
{
var beautifyItemName1 = item.BeautifyHtmlName;
var beautifyItemName2 = item.BeautifyHtmlName
.Replace(",", string.Empty, StringComparison.Ordinal)
.Replace(" ", "-", StringComparison.Ordinal)
.ToLower(GlobalizationConstants.EnglishCultureInfo);
homeBuilder.ListLink(beautifyItemName1, g.Key + ".md" + "#" + beautifyItemName2);
homeExtendedBuilder.ListLink(beautifyItemName1, g.Key + ".md" + "#" + beautifyItemName2);
homeExtendedBuilder.SubList(item);
sb.Append(MarkdownHelper.Render(item));
}
homeBuilder.AppendLine();
homeExtendedBuilder.AppendLine();
sb.AppendLine(GeneratedBy);
File.WriteAllText(Path.Combine(outputPath.FullName, g.Key + ".md"), sb.ToString());
}
homeBuilder.AppendLine(GeneratedBy);
File.WriteAllText(Path.Combine(outputPath.FullName, "Index.md"), homeBuilder.ToString());
homeExtendedBuilder.AppendLine(GeneratedBy);
File.WriteAllText(Path.Combine(outputPath.FullName, "IndexExtended.md"), homeExtendedBuilder.ToString());
}
}
} |
namespace T4WFI.App.UserControls
{
public partial class UCExluded : System.Web.UI.UserControl
{
}
} |
using System;
namespace SOLIDPrinciples.CouplingProblem.Example01.Worst
{
public class EnviadorDeEmail
{
public void EnviarEmail(NotaFiscal nf)
{
//throw new NotImplementedException();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibraryCommon.DTO
{
class GenreDTO
{
public int GenreID { get; set; }
public bool isFiction { get; set; }
public string Description { get; set; }
public string Name { get; set; }
}
}
|
using App.Core.Interfaces.Dto.Requests;
using App.Core.Interfaces.Dto.Responses;
namespace App.Core.Interfaces.Services
{
public interface IProfileService
{
ProfileGetMineResponseDto GetMine(ProfileGetMineRequestDto request);
ProfileGetByUsernameResponseDto GetByUsername(ProfileGetByUsernameRequestDto request);
ProfileCheckUsernameResponseDto CheckUsername(ProfileCheckUsernameRequestDto request);
ProfileUpdateResponseDto Update(ProfileUpdateRequestDto request);
}
} |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
#pragma warning disable 0414
public class CBahram_SALAgent : MonoBehaviour,ISaveAndLoadAgent {
#region Private Fields
private static ArrayList _instances = new ArrayList();//Part of singleton system.
private List<ISaveAndloadClient> _clientsInstances;
#endregion
#region Public Fields
public int var1 ;
public int var2 ;
public int var3 ;
public int var4 ;
#endregion
#region Properties
//Implementing Singleton pattern.
//Every objectes that need access to class functionality most use this property.
public static CBahram_SALAgent Instance{
get{
return (CBahram_SALAgent)CSingleton.GetSingletonInstance(
ref _instances,
typeof(CBahram_SALAgent),
CGlobalInfo.stSaveAndLoad.TagName,
CGlobalInfo.stSaveAndLoad.GameObjectName);
}
}
public List<ISaveAndloadClient> ClientsInstances {
get {
return _clientsInstances;
}
}
#endregion
#region MonoBehaviour
void Awake(){
//singleton functionality
_instances.Add(this) ;
CSingleton.DestroyExtraInstances(_instances);
_clientsInstances = new List<ISaveAndloadClient>();
}
void Start(){
// Registr this agent to the list of "CSaveAndLoadManager" agents.
CSaveAndLoadManager.Instance.RegisterAgent((ISaveAndLoadAgent)this);
//this agent Save its clients.
//will use for "OnSave()" and "OnLoad()" calling from "CSaveAndLoadManager"
_clientsInstances.Add((ISaveAndloadClient)CBahram.Instance);//add CBahram
_clientsInstances.Add((ISaveAndloadClient)CBahram_Temp.Instance);//add CBahram_Temp
}
#endregion
#region ISaveAndLoadAgent Implementation
public bool SaveToFile (ref System.IO.Stream s,CSaveAndLoadTypes.eFormatters format){
BinaryFormatter bFormatter;
if (s == null) {CDebug.LogError(CDebug.eMessageTemplate.NullRefrences); return false;}
if (format == CSaveAndLoadTypes.eFormatters.Binary){
bFormatter = new BinaryFormatter();
bFormatter.Serialize(s,CBahram_SALContainer.Instance_Save);
}
return true;
}
public bool LoadFromFile (ref Stream s, CSaveAndLoadTypes.eFormatters format){
BinaryFormatter bFormatter;
if (format== CSaveAndLoadTypes.eFormatters.Binary){
bFormatter = new BinaryFormatter();
CBahram_SALContainer.Instance_Load = (CBahram_SALContainer)bFormatter.Deserialize(s);
}
return true;
}
#endregion
}
|
using UnityEngine;
using System.Collections;
using System;
public class ShootingMode : GameMode
{
private Action notifyStart;
private Action notifyEnd;
private World world;
public Tile currentPosition { get; internal set; }
private Action<ShootingMode> notifyNewPosition;
public Boolean inRange { get; internal set; }
public ShootingMode(World world)
{
this.world = world;
}
public void click(Tile tile)
{
//TODO:
}
public void start()
{
if (notifyStart != null)
{
notifyStart();
inRange = false;
currentPosition = null;
}
}
public void updateMousePosition(Tile tile)
{
if (currentPosition == null || currentPosition != tile)
{
currentPosition = tile;
inRange = calculateRange(world.gameState.currentActor, currentPosition);
if (notifyNewPosition != null)
{
notifyNewPosition(this);
}
}
}
private bool calculateRange(Actor actor, Tile target)
{
Tile origin = actor.currentTile;
foreach (Wall wall in world.walls)
{
if (intersect(origin.x, origin.y, target.x, target.y, wall.getStartPoint().x, wall.getStartPoint().y, wall.getEndPoint().x, wall.getEndPoint().y))
{
return false;
}
}
return true;
}
private Boolean intersect(float p0_x, float p0_y, float p1_x, float p1_y,
float p2_x, float p2_y, float p3_x, float p3_y)
{
Vector3 start1 = new Vector3(p0_x, p0_y, -9);
Vector3 end1 = new Vector3(p1_x, p1_y, -9);
Debug.DrawLine(start1, end1, Color.cyan, 5f);
Vector3 start2 = new Vector3(p2_x, p2_y, -9);
Vector3 end2 = new Vector3(p3_x, p3_y, -9);
Debug.DrawLine(start2, end2, Color.red, 5f);
float s1_x = p1_x - p0_x;
float s1_y = p1_y - p0_y;
float s2_x = p3_x - p2_x;
float s2_y = p3_y - p2_y;
float s = (-s1_y * (p0_x - p2_x) + s1_x * (p0_y - p2_y)) / (-s2_x * s1_y + s1_x * s2_y);
float t = (s2_x * (p0_y - p2_y) - s2_y * (p0_x - p2_x)) / (-s2_x * s1_y + s1_x * s2_y);
if (s >= 0 && s <= 1 && t >= 0 && t <= 1)
{
// Collision detected
return true;
}
return false; // No collision
}
public void newPositionCallback(Action<ShootingMode> callback)
{
notifyNewPosition += callback;
}
public void startCallback(Action callback)
{
notifyStart += callback;
}
public void endCallback(Action callback)
{
notifyEnd += callback;
}
public void end()
{
if (notifyEnd != null)
{
notifyEnd();
}
}
}
|
using Common.Business;
using Common.Data;
using Common.Log;
using Contracts.Content;
using Entity;
using LFP.Common.DataAccess;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.ServiceModel;
namespace Services.Content
{
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.PerSession)]
public class ContentService : IContentService
{
#region Private Fields
private string mConnectionString = String.Empty;
private DataAccess mDataAccess = null;
private string mUserName = String.Empty;
#endregion
#region Constructors
public ContentService()
{
Logging.MinimumLogLevel = (LogLevel)Enum.Parse(typeof(LogLevel), ConfigurationManager.AppSettings["LogLevel"]);
}
#endregion
#region Public Methods
public void CreateContentMethods(string connectionString, string userName)
{
mConnectionString = connectionString;
mUserName = userName;
mDataAccess = new DataAccess(connectionString, userName);
}
public List<ScreenerContentInfo> GetCharacteristicsList(string type)
{
SystemSceneCharacteristics ssc = null;
SystemSceneCharacteristicsGay sscg = null;
try
{
if (type.Equals("gay"))
{
sscg = new SystemSceneCharacteristicsGay();
return sscg.GetCharacteristics(mConnectionString);
}
ssc = new SystemSceneCharacteristics();
return ssc.GetCharacteristics(mConnectionString);
}
finally
{
ssc = null;
sscg = null;
}
}
public List<string> GetCharacteristicsValues(string type, int templateId)
{
SearchTemplateChar stc = null;
SearchTemplateCharGay stcg = null;
try
{
if (type.Equals("gay"))
{
stcg = new SearchTemplateCharGay();
return stcg.GetCharacteristicsValues(mConnectionString, templateId);
}
stc = new SearchTemplateChar();
return stc.GetCharacteristicsValues(mConnectionString, templateId);
}
finally
{
stc = null;
stcg = null;
}
}
public List<ScreenerContentInfo> GetClothingList(string type)
{
SystemSceneCloth ssc = null;
SystemSceneClothGay sscg = null;
try
{
if (type.Equals("gay"))
{
sscg = new SystemSceneClothGay();
return sscg.GetClothing(mConnectionString);
}
ssc = new SystemSceneCloth();
return ssc.GetClothing(mConnectionString);
}
finally
{
ssc = null;
sscg = null;
}
}
public List<string> GetClothingValues(string type, int templateId)
{
SearchTemplateClothing stc = null;
SearchTemplateClothingGay stcg = null;
try
{
if(type.Equals("gay"))
{
stcg = new SearchTemplateClothingGay();
return stcg.GetClothingValues(mConnectionString, templateId);
}
stc = new SearchTemplateClothing();
return stc.GetClothingValues(mConnectionString, templateId);
}
finally
{
stc = null;
stcg = null;
}
}
public List<string> GetCompValues(int templateId)
{
SearchTemplateCompositionGay stcg = new SearchTemplateCompositionGay();
try
{
return stcg.GetCompValues(mConnectionString, templateId);
}
finally
{
stcg = null;
}
}
public List<ScreenerContentInfo> GetContentList(string type)
{
SystemSceneSexContent sssc = null;
SystemSceneSexContentGay ssscg = null;
try
{
if (type.Equals("gay"))
{
ssscg = new SystemSceneSexContentGay();
return ssscg.GetSexContent(mConnectionString);
}
sssc = new SystemSceneSexContent();
return sssc.GetSexContent(mConnectionString);
}
finally
{
sssc = null;
ssscg = null;
}
}
public List<ScreenerContentInfo> GetGenderList(string type)
{
SystemSceneGenders ssg = null;
SystemSceneGendersGay ssgg = null;
try
{
if (type.Equals("gay"))
{
ssgg = new SystemSceneGendersGay();
return ssgg.GetGenders(mConnectionString);
}
ssg = new SystemSceneGenders();
return ssg.GetGenders(mConnectionString);
}
finally
{
ssg = null;
ssgg = null;
}
}
public List<string> GetGenderValues(string type, int templateId)
{
SearchTemplateGender stg = null;
SearchTemplateGenderGay stgg = null;
try
{
if (type.Equals("gay"))
{
stgg = new SearchTemplateGenderGay();
return stgg.GetGenderValues(mConnectionString, templateId);
}
stg = new SearchTemplateGender();
return stg.GetGenderValues(mConnectionString, templateId);
}
finally
{
stg = null;
stgg = null;
}
}
public List<ScreenerContentInfo> GetOtherList()
{
SystemSceneCompositionGay sscg = new SystemSceneCompositionGay();
try
{
return sscg.GetOther(mConnectionString);
}
finally
{
sscg = null;
}
}
public List<ScreenerContentInfo> GetSettingList(string type)
{
SystemSceneSetting sss = null;
SystemSceneSettingGay sssg = null;
try
{
if (type.Equals("gay"))
{
sssg = new SystemSceneSettingGay();
return sssg.GetSetting(mConnectionString);
}
sss = new SystemSceneSetting();
return sss.GetSetting(mConnectionString);
}
finally
{
sss = null;
sssg = null;
}
}
public List<string> GetSettingValues(string type, int templateId)
{
SearchTemplateSettings sts = null;
SearchTemplateSettingsGay stsg = null;
try
{
if(type.Equals("gay"))
{
stsg = new SearchTemplateSettingsGay();
return stsg.GetSettingValues(mConnectionString, templateId);
}
sts = new SearchTemplateSettings();
return sts.GetSettingValues(mConnectionString, templateId);
}
finally
{
sts = null;
stsg = null;
}
}
public List<string> GetSexualValues(string type, int templateId)
{
SearchTemplateSexual sts = null;
SearchTemplateSexualGay stsg = null;
try
{
if (type.Equals("gay"))
{
stsg = new SearchTemplateSexualGay();
return stsg.GetSexualValues(mConnectionString, templateId);
}
sts = new SearchTemplateSexual();
return sts.GetSexualValues(mConnectionString, templateId);
}
finally
{
sts = null;
stsg = null;
}
}
public List<ScreenerContentInfo> GetThemesList(string type)
{
SystemSceneTheme sst = null;
SystemSceneThemeGay sstg = null;
try
{
if (type.Equals("gay"))
{
sstg = new SystemSceneThemeGay();
return sstg.GetThemes(mConnectionString);
}
sst = new SystemSceneTheme();
return sst.GetThemes(mConnectionString);
}
finally
{
sst = null;
sstg = null;
}
}
public List<string> GetThemesValues(string type, int templateId)
{
SearchTemplateTheme stt = null;
SearchTemplateThemeGay sttg = null;
try
{
if(type.Equals("gay"))
{
sttg = new SearchTemplateThemeGay();
return sttg.GetThemesValues(mConnectionString, templateId);
}
stt = new SearchTemplateTheme();
return stt.GetThemesValues(mConnectionString, templateId);
}
finally
{
stt = null;
sttg = null;
}
}
public List<ScreenerContentInfo> GetToysList(string type)
{
SystemSceneToys sst = null;
SystemSceneToysGay sstg = null;
try
{
if (type.Equals("gay"))
{
sstg = new SystemSceneToysGay();
return sstg.GetToys(mConnectionString);
}
sst = new SystemSceneToys();
return sst.GetToys(mConnectionString);
}
finally
{
sst = null;
sstg = null;
}
}
public List<string> GetToysValues(string type, int templateId)
{
SearchTemplateToys stt = null;
SearchTemplateToysGay sttg = null;
try
{
if (type.Equals("gay"))
{
sttg = new SearchTemplateToysGay();
return sttg.GetToysValues(mConnectionString, templateId);
}
stt = new SearchTemplateToys();
return stt.GetToysValues(mConnectionString, templateId);
}
finally
{
stt = null;
sttg = null;
}
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pe.Stracon.SGC.Aplicacion.TransferObject.Response.Base
{
/// <summary>
///
/// </summary>
public class BaseResponse
{
/// <summary>
///
/// </summary>
public Int64 FilasTotal { get; set; }
/// <summary>
///
/// </summary>
public Int64 NumeroFila { get; set; }
}
}
|
using StardewModdingAPI;
using StardewValley;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JunimoIntelliBox
{
class InputHelper
{
public bool IsOneOfTheseKeysDown(SButton button, InputButton[] keys)
{
IEnumerable<InputButton> result = keys.Where(b => ((int)b.key) == (int)button);
return result.Any();
}
}
}
|
namespace RoliTheCoder
{
using System;
using System.Collections.Generic;
using System.Linq;
public class StartUp
{
public static void Main()
{
var command = Console.ReadLine();
var eventRegister = new Dictionary<int, string>();
var eventParticipans = new Dictionary<string, List<string>>();
while (command != "Time for Code")
{
if (command.Contains("#"))
{
var eventInfo = command
.Split(new char[] { ' ', '#' }, StringSplitOptions.RemoveEmptyEntries)
.ToList();
var id = int.Parse(eventInfo[0]);
var eventName = eventInfo[1];
var participants = new List<string>();
for (int i = 2; i < eventInfo.Count; i++)
{
participants.Add(eventInfo[i]);
}
if (!eventRegister.ContainsKey(id))
{
eventRegister.Add(id, eventName);
eventParticipans.Add(eventName, participants);
}
else if (eventRegister[id] == eventName)
{
eventParticipans[eventName].AddRange(participants);
}
}
command = Console.ReadLine();
}
foreach (var eventName in eventParticipans.OrderByDescending(x => x.Value.Distinct().Count()).ThenBy(x => x.Key))
{
Console.WriteLine($"{eventName.Key} - {eventName.Value.Distinct().Count()}");
foreach (var participan in eventName.Value.OrderBy(x => x).Distinct())
{
Console.WriteLine($"{participan}");
}
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public Class EnemyClass;
}
public enum Class
{
Hohei
}
|
using AudioText.Models.ViewModels;
using AudioText.Services;
using AudioText.Models;
using System.Web.Mvc;
namespace AudioText.Controllers
{
public class FilterController : Controller
{
FilterService filterService;
public FilterController()
{
filterService = new FilterService();
}
public ActionResult Index()
{
return View(new FilterListItemViewModel(filterService.GetAllFilters()));
}
public void UpdateFilter(Models.Filter filterToUpdate)
{
filterService.SaveFilter(filterToUpdate);
}
public void DeleteFilter(int FilterId)
{
filterService.DeleteFilter(FilterId);
}
}
} |
using System;
using Elrond.Dotnet.Sdk.Domain.Codec;
using Elrond.Dotnet.Sdk.Domain.Values;
using NUnit.Framework;
namespace Elrond_sdk.dotnet.tests.Domain.Codec
{
public class BytesBinaryCodecTests
{
private BytesBinaryCodec _sut;
[SetUp]
public void Setup()
{
_sut = new BytesBinaryCodec();
}
[Test]
public void BytesBinaryCodec_DecodeNested()
{
var buffer = Convert.FromHexString("0000000445474c44");
// Act
var actual = _sut.DecodeNested(buffer, TypeValue.BytesValue);
var hex = Convert.ToHexString((actual.Value.ValueOf<BytesValue>()).Buffer);
// Assert
Assert.AreEqual("45474C44", hex);
}
[Test]
public void BytesBinaryCodec_EncodeNested()
{
// Arrange
var buffer = Convert.FromHexString("45474C44");
var value = new BytesValue(buffer, TypeValue.BytesValue);
// Act
var actual = _sut.EncodeNested(value);
var hex = Convert.ToHexString(actual);
// Assert
Assert.AreEqual(buffer.Length + 4, actual.Length);
Assert.AreEqual("0000000445474C44", hex);
}
[Test]
public void BytesBinaryCodec_EncodeNested_AndDecode()
{
// Arrange
var expected = "FDB32E9ED34CAF6009834C5A5BEF293097EA39698B3E82EFD8C71183CB731B42";
var buffer = Convert.FromHexString(expected);
var value = new BytesValue(buffer, TypeValue.BytesValue);
// Act
var encoded = _sut.EncodeNested(value);
var actual = _sut.DecodeNested(encoded, TypeValue.BytesValue);
var hex = Convert.ToHexString((actual.Value.ValueOf<BytesValue>()).Buffer);
// Assert
Assert.AreEqual(expected, hex);
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace FitApp.Services
{
public class MealsService
{
public string Image { get; set; }
public string Titile { get; set; }
public string Ingredients { get; set; }
public string Step1 { get; set; }
public string Step2 { get; set; }
public string Step3 { get; set; }
public string Step4 { get; set; }
public string Step5 { get; set; }
public string Step6 { get; set; }
public void SetRecipe(string image, string title, string ingredients, string s1, string s2, string s3, string s4, string s5, string s6)
{
Image = image;
Titile = title;
Ingredients = ingredients;
Step1 = s1;
Step2 = s2;
Step3 = s3;
Step4 = s4;
Step5 = s5;
Step6 = s6;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using JourniAPI.Models;
using MongoDB.Bson;
using MongoDB.Driver;
namespace JourniAPI.Services
{
public class TripService
{
private readonly IMongoCollection<User> _users;
private readonly UserService _userService;
public TripService(IJourniDatabaseSettings settings, UserService userService)
{
var client = new MongoClient(settings.ConnectionString);
var database = client.GetDatabase(settings.DatabaseName);
_users = database.GetCollection<User>(settings.UsersCollectionName);
_userService = userService;
}
public List<Trip> GetAllTrips(string userId)
{
User user = _userService.Get(userId);
return user.Trips;
}
public Trip GetTrip(string userID, ObjectId tripId)
{
User user = _userService.Get(userID);
Trip trip = user.Trips.Find(trip => trip._id == tripId);
return trip;
}
public Trip CreateTrip(string userID, Trip trip)
{
User user = _userService.Get(userID);
user.Trips.Add(trip);
_users.FindOneAndUpdate(
user => user.User_ID == userID,
Builders<User>.Update.Set("Trips", user.Trips));
return trip;
}
public void RemoveTrip(string userID, ObjectId tripId)
{
User user = _userService.Get(userID);
var item = user.Trips.Single(trip1 => trip1._id == tripId);
item.Days.ForEach(day => day.Places.ForEach(place => {
var index = user.Places.FindIndex(p => p == place.PlaceId);
user.Places.RemoveAt(index);
}));
user.Trips.Remove(item);
_users.FindOneAndUpdate(
user => user.User_ID == userID,
Builders<User>.Update.Set("Trips", user.Trips));
_users.FindOneAndUpdate(
user => user.User_ID == userID,
Builders<User>.Update.Set("Places", user.Places));
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GodUiManager : MonoBehaviour
{
public GameObject BrushUi;
public GameObject AbilityUi;
public GodStateManager GodState;
// Use this for initialization
private void Start()
{
UpdateUiState();
}
// Update is called once per frame
private void Update()
{
UpdateUiState();
}
private void UpdateUiState()
{
if (GodState.BrushMng.gameObject.GetActive())
{
AbilityUi.SetActive(false);
BrushUi.SetActive(true);
}
else
{
BrushUi.SetActive(false);
AbilityUi.SetActive(true);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace com.Sconit.Web.Models.SearchModels.ORD
{
public class ProdTraceCodeSearchModel : SearchModelBase
{
public string TraceCode { get; set; }
public string HuId { get; set; }
}
} |
using Chloe.ViewModels.Contracts;
using System.Collections.Generic;
namespace Chloe.ViewModels
{
public class MetaDataViewModel: IMetaDataViewModel
{
public string Title { get; set; }
public void Initialize(ICollection<IComponent> components)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;
namespace ManageWeb
{
public class ApiBaseController : Controller
{
public int ServerId { get; private set; }
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
System.Diagnostics.Trace.WriteLine("on");
object[] attr = filterContext.ActionDescriptor.GetCustomAttributes(typeof(ClientAuthAttribute), false);
ClientAuthAttribute tt = new ClientAuthAttribute();
if (attr == null || attr.Length == 0)
{
attr = filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(ClientAuthAttribute), false);
}
if (attr != null && attr.Length > 0)
tt = attr[0] as ClientAuthAttribute;
if (tt.AuthType != ClientAuthType.None)
{
ManageDomain.BLL.ServerMachineBll serverbll = new ManageDomain.BLL.ServerMachineBll();
string macs = filterContext.RequestContext.HttpContext.Request.Headers["Client_Macs"] ?? "";
string ips = filterContext.RequestContext.HttpContext.Request.Headers["Client_IPs"] ?? "";
string clientid = filterContext.RequestContext.HttpContext.Request.Headers["Client_ID"] ?? "";
ips += "," + filterContext.RequestContext.HttpContext.Request.UserHostAddress;
string[] arrmac = macs.Split(',').Where(x => !string.IsNullOrEmpty(x)).ToArray();
string[] arrip = ips.Split(',').Where(x => !string.IsNullOrEmpty(x)).ToArray();
var model = serverbll.GetServerByClientId(clientid);// serverbll.GetUnionServer(arrmac, arrip, clientid);
if (model == null)
{
ManageDomain.ClientsCache.AddClientInfo(clientid, string.Format("ClientId:{2} MAC:{0} IP:{1}", macs, ips, clientid));
}
else
{
ManageDomain.ClientsCache.Remove(clientid);
}
if (model == null && tt.AuthType == ClientAuthType.Auth)
{
throw new ManageDomain.MException(ManageDomain.MExceptionCode.NoPermission, "无权限");
//filterContext.HttpContext.Response.StatusCode = 200;
//var vresult = Json(new JsonEntity() { code = (int)ManageDomain.MExceptionCode.NoPermission, data = null, msg = "无权限" }, JsonRequestBehavior.AllowGet);
//vresult.ExecuteResult(filterContext.Controller.ControllerContext);
//filterContext.Controller.ControllerContext.HttpContext.Response.End();
//filterContext.HttpContext.Response.Close();
//throw new System.Web.HttpUnhandledException("无权限");
}
if (model != null)
ServerId = model.ServerId;
}
base.OnActionExecuting(filterContext);
}
public JsonResult ApiResult(object obj)
{
return JsonE(obj);
}
protected override void OnException(ExceptionContext filterContext)
{
int code = (int)ManageDomain.MExceptionCode.ServerError;
if (filterContext.Exception is ManageDomain.MException)
{
code = (filterContext.Exception as ManageDomain.MException).Code;
}
filterContext.HttpContext.Response.StatusCode = 200;
var vresult = Json(new JsonEntity() { code = code, data = null, msg = filterContext.Exception.Message }, JsonRequestBehavior.AllowGet);
vresult.ExecuteResult(filterContext.Controller.ControllerContext);
filterContext.Controller.ControllerContext.HttpContext.Response.End();
}
public JsonResult JsonE(object data)
{
return Json(new JsonEntity() { code = 1, data = data, msg = "" });
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System;
public class Clock : MonoBehaviour {
public static double timeAcum = 0;
public Text txt;
void Update()
{ if (!spawn1.tiempo) {
if(!spawn1.parar)timeAcum += Math.Truncate (Time.deltaTime * 100) / 100;
txt.text = "Tiempo\n" + timeAcum.ToString ("0.##");
} else {
txt.text = "";
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.