text stringlengths 13 6.01M |
|---|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GoToScene : MonoBehaviour {
private XboxControllerManager _xboxController;
private PlayerManager _playerManager;
void Start() {
_xboxController = XboxControllerManager.Instance;
_playerManager = PlayerManager.Instance;
}
void Update() {
_playerManager.UpdatePlayerList();
for (int i = 0; i < _playerManager.Players.Count; i++)
{
if (_xboxController.GetButtonPressed(_playerManager.Players[i], ButtonType.BUTTON_A))
GoToThisScene(1);
}
}
/// <summary>
/// Makes the game go to the next scene
/// </summary>
/// <param name="iSceneNumber"></param>
public void GoToThisScene(int iSceneNumber) {
SceneManager.LoadScene(iSceneNumber);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FolderBackup.Shared
{
[Serializable()]
public abstract class FBAbstractElement
{
public string Name { get; set; }
public FBAbstractElement() { }
public FBAbstractElement(string name)
{
this.Name = name;
}
abstract public Boolean isEqualTo(FBAbstractElement other);
public override bool Equals(object obj)
{
if (obj.GetType() != this.GetType()) return false;
return this.isEqualTo((FBAbstractElement) obj);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class spikeTrap : MonoBehaviour
{
// Use this for initialization
void Start()
{
}
private void OnCollisionEnter2D(Collision2D coll)
{
}
}
|
using System;
using NFluent;
using NFluent.Extensibility;
namespace TestUtilities
{
public static class DoubleCheck
{
public static ICheckLink<ICheck<double>> IsEqualsWithDelta(this ICheck<double> check, double refValue, double delta)
{
var checker = ExtensibilityHelper.ExtractChecker(check);
return checker.ExecuteCheck(
() =>
{
if (Math.Abs(checker.Value - refValue) > delta)
{
var errorMesssage =
FluentMessage.BuildMessage(
$"The {checker.Value} differs more than {delta} from reference value {refValue}");
throw new FluentCheckException(errorMesssage.ToString());
}
},
FluentMessage.BuildMessage(
$"The {checker.Value} differs more than {delta} from reference value {refValue}").ToString());
}
}
}
|
using Cosmos.HAL;
using FrameOS.Systems.Logs;
using System;
using System.Collections.Generic;
using System.Text;
using Sys = Cosmos.System;
namespace FrameOS
{
public class Kernel : Sys.Kernel
{
public static string boottime = RTC.Month + "/" + RTC.DayOfTheMonth + "/" + RTC.Year + ", " + RTC.Hour + ":" + RTC.Minute + ":" + RTC.Second;
public static string logFileTime = RTC.Month + "-" + RTC.DayOfTheMonth + "-" + RTC.Year + "_" + RTC.Hour + "-" + RTC.Minute + "-" + RTC.Second;
protected override void BeforeRun()
{
VGADriverII.Initialize(VGAMode.Text90x60);
Boot.Boot.StartUp();
}
protected override void Run()
{
try
{
Terminal.TextColor = ConsoleColor.Cyan;
Terminal.Write(UserSystem.UserProfileSystem.CurrentUser);
Terminal.TextColor = ConsoleColor.Green;
Terminal.Write("@" + FileSystem.Filesystem.GetCurrentPath() + "> ");
Terminal.TextColor = ConsoleColor.White;
string input = Terminal.ReadLine();
Terminal.TextColor = ConsoleColor.Gray;
Shell.Shell.Run(input);
Terminal.NewLine();
}
catch (Exception e)
{
if (e is FatalException)
{
Shell.Shell.Crash(e);
}
else
{
Terminal.WriteLine("Error: " + e.Message);
LogManager.Log(e.Message, LogType.Error);
}
}
}
}
class FatalException : Exception
{
public FatalException(string additionalData) : base("FatalException: " + additionalData) { }
public FatalException() : base("FatalException") { }
}
}
|
using UnityEngine;
using System.Collections;
/// <summary>
/// Sends a message up the game object heirarchy when a game
/// object with name name enters the trigger area.
/// </summary>
public class NearTrigger : MonoBehaviour {
public string name;
void OnTriggerEnter2D(Collider2D other)
{
if (other.name.StartsWith(name))
{
this.gameObject.SendMessageUpwards ("Near" + name, other.gameObject);
}
}
}
|
#if UNITY_EDITOR
using System;
namespace DChildDebug
{
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public class BossNameAttribute : Attribute
{ }
}
#endif |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Terraria;
using Terraria.ModLoader;
using Microsoft.Xna.Framework;
using Terraria.ID;
using Microsoft.Xna.Framework.Graphics;
using Terraria.DataStructures;
namespace StarlightRiver.NPCs.Boss.OvergrowBoss
{
public partial class OvergrowBoss : ModNPC
{
private void Phase1Spin()
{
if(npc.ai[3] <= 60)
{
npc.Center = Vector2.SmoothStep(npc.Center, spawnPoint, npc.ai[3] / 60f);
flail.npc.Center = Vector2.SmoothStep(flail.npc.Center, spawnPoint, npc.ai[3] / 60f);
if (npc.Center == spawnPoint) npc.ai[3] = 61;
}
if(npc.ai[3] == 61)
{
npc.TargetClosest();
targetPoint = Main.player[npc.target].Center;
Main.NewText(targetPoint);
}
float size = Vector2.Distance(targetPoint, npc.Center);
if (size > 400) size = 400;
//Main.NewText(size);
if (npc.ai[3] <= 120)
flail.npc.Center = Vector2.Lerp(flail.npc.Center, npc.Center, (npc.ai[3] - 60) / 40);
if (npc.ai[3] > 120 && npc.ai[3] <= 160)
flail.npc.Center = Vector2.SmoothStep(npc.Center, npc.Center + new Vector2(0, size), (npc.ai[3] - 120) / 40f);
if (npc.ai[3] > 160 && npc.ai[3] <= 280)
{
int x = (int)npc.ai[3] - 160;
float rot = 0.314f * -0.042f * x + 0.003f * (float)Math.Pow(x, 2) - 0.00002f * (float)Math.Pow(x, 3);
//function to model the desired rotation, thanks wolfram alpha :3
flail.npc.Center = npc.Center + new Vector2(0, 1).RotatedBy(rot) * size;
if (npc.ai[3] > 165 && npc.ai[3] < 250)
{
for (int k = 0; k < 3; k++)
Dust.NewDust(flail.npc.position, flail.npc.width, flail.npc.height, ModContent.DustType<Dusts.Gold2>());
for (int k = 0; k < 8; k++)
Dust.NewDustPerfect(Vector2.Lerp(flail.npc.Center, flail.npc.oldPosition + flail.npc.Size / 2, k / 8f), ModContent.DustType<Dusts.Gold2>(), Vector2.One.RotatedByRandom(6.28f) * 0.5f);
}
}
if (npc.ai[3] == 280)
{
flail.npc.velocity = flail.npc.position - flail.npc.oldPosition;
flail.npc.velocity.X *= 0.2f;
}
if(npc.ai[3] > 280 && npc.ai[3] <= 450)
{
if (Vector2.Distance(flail.npc.Center, npc.Center) < size) flail.npc.velocity.Y += 0.8f;
else
{
float cos = (float)Math.Cos((npc.Center - flail.npc.Center).ToRotation());
flail.npc.velocity.X += flail.npc.velocity.Y * cos;
flail.npc.velocity.Y *= -0.1f;
}
flail.npc.velocity.X += (npc.Center.X - flail.npc.Center.X) * 0.01f;
flail.npc.velocity *= 0.96f;
}
if (npc.ai[3] == 451) ResetAttack();
}
private void Phase1Pendulum()
{
if (npc.ai[3] > 1 && npc.ai[3] <= 60)
{
flail.npc.Center = Vector2.SmoothStep(flail.npc.Center, npc.Center, npc.ai[3] / 60f);
}
if (npc.ai[3] == 60) targetPoint = Main.player[npc.target].Center;
int direction = -Math.Sign(targetPoint.X - spawnPoint.X);
if(npc.ai[3] > 60 && npc.ai[3] <= 90)
{
if(targetPoint.Y > npc.Center.Y)
{
flail.npc.Center = Vector2.SmoothStep(flail.npc.Center, npc.Center + new Vector2(0, targetPoint.Y - npc.Center.Y), (npc.ai[3] - 60) / 30f);
}
else
{
flail.npc.Center = Vector2.SmoothStep(flail.npc.Center, npc.Center + new Vector2(0, 150), (npc.ai[3] - 60) / 30f);
}
}
if(npc.ai[3] > 90 && npc.ai[3] <= 160)
{
npc.Center = Vector2.SmoothStep(npc.Center, spawnPoint + new Vector2((500) * -direction, 0), (npc.ai[3] - 90) / 70f);
flail.npc.Center = Vector2.SmoothStep(flail.npc.Center, spawnPoint + new Vector2((500) * -direction, flail.npc.Center.Y - npc.Center.Y), (npc.ai[3] - 90) / 60f);
}
if (npc.ai[3] == 210) ResetAttack();
}
private void Phase1Bolts()
{
Vector2 handpos = npc.Center; //used as a basepoint for this attack to match the animation
if(npc.ai[3] <= 30)
{
float rot = Main.rand.NextFloat(6.28f); //random rotation for the dust
Dust.NewDustPerfect(handpos + Vector2.One.RotatedBy(rot) * 50, ModContent.DustType<Dusts.Gold2>(), -Vector2.One.RotatedBy(rot) * 2); //"suck in" charging effect
}
if(npc.ai[3] == 30)
{
RandomTarget(); //pick a random target
if(Main.player[npc.target] == null) //safety check
{
ResetAttack();
return;
}
}
if(npc.ai[3] == 60) targetPoint = Main.player[npc.target].Center;
if (npc.ai[3] >= 60 && npc.ai[3] <= 120 && npc.ai[3] % 30 == 0) //3 rounds of projectiles
{
Main.PlaySound(ModLoader.GetMod("StarlightRiver").GetLegacySoundSlot(SoundType.Custom, "Sounds/ProjectileLaunch1"), npc.Center);
for (float k = -0.6f; k <= 0.6f; k += 0.3f) //5 projectiles in even spread
{
Vector2 trajectory = Vector2.Normalize(targetPoint - handpos).RotatedBy(k + (npc.ai[3] == 90 ? 0.15f : 0)) * 1.6f; //towards the target, alternates on the second round
Projectile.NewProjectile(handpos, trajectory, ModContent.ProjectileType<OvergrowBossProjectile.Phase1Bolt>(), 20, 0.2f);
}
}
if (npc.ai[3] == 200) ResetAttack();
}
private void Phase1Toss()
{
if (npc.ai[3] <= 60)
flail.npc.Center = Vector2.Lerp(flail.npc.Center, npc.Center, npc.ai[3] / 50);
if (npc.ai[3] == 60)
{
npc.TargetClosest();
targetPoint = Main.player[npc.target].Center + Main.player[npc.target].velocity * 30; //sets the target to the closest player
if (Vector2.Distance(Main.player[npc.target].Center, targetPoint) > 300) targetPoint = Main.player[npc.target].Center + Vector2.Normalize(Main.player[npc.target].Center + targetPoint) * 300; //clamp to 3d00 pixels away
}
if (Main.player[npc.target] == null && npc.ai[3] == 60) ResetAttack(); //defensive programminginging!!
Vector2 trajectory = -Vector2.Normalize(npc.Center - targetPoint); //boss' toss direction
if(npc.ai[3] > 60 && npc.ai[3] < 120)
{
flail.npc.Center = Vector2.Lerp(npc.Center, npc.Center + trajectory * -20, (npc.ai[3] - 60) / 120f); //pull it back
}
if (npc.ai[3] == 120) flail.npc.velocity = trajectory * 20;
if ((flail.npc.velocity.Y == 0 || flail.npc.velocity.X == 0 || Main.tile[(int)flail.npc.Center.X / 16, (int)flail.npc.Center.Y / 16 + 1].collisionType == 1) && !(flail.npc.velocity.Y == 0 && flail.npc.velocity.X == 0)) //hit the ground
{
//updates
flail.npc.velocity *= 0;
npc.ai[3] = 180;
//visuals
for (int k = 0; k < 50; k++)
{
Dust.NewDust(flail.npc.position, flail.npc.width, flail.npc.height, ModContent.DustType<Dusts.Stone>(), Main.rand.NextFloat(-3, 3), Main.rand.NextFloat(-3, 3));
Dust.NewDustPerfect(flail.npc.Center, ModContent.DustType<Dusts.Gold2>(), Vector2.One.RotatedByRandom(6.28f) * Main.rand.NextFloat(5), 0, default, 1);
}
//audio
Main.PlaySound(SoundID.Item70, flail.npc.Center);
Main.PlaySound(SoundID.NPCHit42, flail.npc.Center);
//screenshake
int distance = (int)Vector2.Distance(Main.LocalPlayer.Center, flail.npc.Center);
((StarlightPlayer)Main.LocalPlayer.GetModPlayer<StarlightPlayer>()).Shake += distance < 100 ? distance / 20 : 5;
}
if (npc.ai[3] == 240) ResetAttack();
}
private void DrawTossTell(SpriteBatch sb)
{
float glow = npc.ai[3] > 90 ? (1 - (npc.ai[3] - 90) / 30f) : ((npc.ai[3] - 60) / 30f);
Color color = new Color(255, 70, 70) * glow;
Texture2D tex = ModContent.GetTexture("StarlightRiver/Gores/TellBeam");
sb.End();
sb.Begin(default, BlendState.Additive, default, default, default, default, Main.GameViewMatrix.TransformationMatrix);
for (float k = 0; 1 == 1; k++)
{
Vector2 point = Vector2.Lerp(npc.Center, npc.Center + Vector2.Normalize(targetPoint - npc.Center) * tex.Frame().Width, k);
sb.Draw(tex, point - Main.screenPosition, tex.Frame(), color, (targetPoint - npc.Center).ToRotation(), tex.Frame().Size() / 2, 1, 0, 0);
if (!WorldGen.InWorld((int)point.X / 16, (int)point.Y / 16)) break;
Tile tile = Framing.GetTileSafely(point / 16);
if (tile.active()) break;
}
sb.End();
sb.Begin(default, default, default, default, default, default, Main.GameViewMatrix.TransformationMatrix);
}
private void Phase1Trap()
{
Main.NewText(npc.ai[3]);
if (npc.ai[3] == 1)
{
RandomTarget();
targetPoint = Main.player[npc.target].Center + new Vector2(0, -50);
}
if(npc.ai[3] == 90)
{
foreach(Player player in Main.player.Where( p => p.active && Helper.CheckCircularCollision(targetPoint, 100, p.Hitbox))) //circular collision
{
player.Hurt(PlayerDeathReason.ByCustomReason(player.name + " was strangled..."), 50, 0); //hurt em
//debuff em
}
//dusts
for(float k = 0; k < 6.28f; k+= 0.1f)
{
Dust.NewDustPerfect(targetPoint + Vector2.One.RotatedBy(k) * 90, ModContent.DustType<Dusts.Leaf>(), null, 0, default, 1.5f);
Dust.NewDustPerfect(targetPoint + Vector2.One.RotatedBy(k) * Main.rand.NextFloat(95, 105), ModContent.DustType<Dusts.Gold2>(), null, 0, default, 0.6f);
if (Main.rand.Next(4) == 0) Dust.NewDustPerfect(targetPoint + Vector2.One.RotatedBy(k) * Main.rand.Next(100), ModContent.DustType<Dusts.Leaf>());
}
}
if (npc.ai[3] >= 180) ResetAttack();
}
private void DrawTrapTell(SpriteBatch sb)
{
float glow = npc.ai[3] > 45 ? (1 - (npc.ai[3] - 45) / 45f) : ((npc.ai[3]) / 45f);
Color color = new Color(255, 40, 40) * glow;
Texture2D tex = ModContent.GetTexture("StarlightRiver/Gores/TellCircle");
sb.End();
sb.Begin(default, BlendState.Additive, default, default, default, default, Main.GameViewMatrix.TransformationMatrix);
if(npc.ai[3] <= 90) sb.Draw(tex, targetPoint - Main.screenPosition, tex.Frame(), color, 0, tex.Frame().Size() / 2, 2, 0, 0);
else if(npc.ai[3] <= 100) sb.Draw(tex, targetPoint - Main.screenPosition, tex.Frame(), new Color(255, 200, 30) * (1 - (npc.ai[3] - 90) / 10f), 0, tex.Frame().Size() / 2, 2, 0, 0);
sb.End();
sb.Begin(default, default, default, default, default, default, Main.GameViewMatrix.TransformationMatrix);
}
private void RapidToss()
{
if (npc.ai[3] <= 15)
flail.npc.Center = Vector2.Lerp(flail.npc.Center, npc.Center, npc.ai[3] / 15);
if (npc.ai[3] == 15)
{
npc.TargetClosest();
targetPoint = Main.player[npc.target].Center + Main.player[npc.target].velocity * 10; //sets the target to the closest player
if (Vector2.Distance(Main.player[npc.target].Center, targetPoint) > 300) targetPoint = Main.player[npc.target].Center + Vector2.Normalize(Main.player[npc.target].Center + targetPoint) * 300; //clamp to 3d00 pixels away
npc.ai[3] = 60; //i am lazy
}
if (Main.player[npc.target] == null && npc.ai[3] == 20) ResetAttack(); //defensive programminginging!!
Vector2 trajectory = -Vector2.Normalize(npc.Center - targetPoint); //boss' toss direction
if (npc.ai[3] > 60 && npc.ai[3] < 120)
{
flail.npc.Center = Vector2.Lerp(npc.Center, npc.Center + trajectory * -10, (npc.ai[3] - 60) / 120f); //pull it back
npc.ai[3]++; //double time! im lazy.
}
if (npc.ai[3] == 120) flail.npc.velocity = trajectory * 24;
if ((flail.npc.velocity.Y == 0 || flail.npc.velocity.X == 0 || Main.tile[(int)flail.npc.Center.X / 16, (int)flail.npc.Center.Y / 16 + 1].collisionType == 1) && !(flail.npc.velocity.Y == 0 && flail.npc.velocity.X == 0)) //hit the ground
{
//updates
flail.npc.velocity *= 0;
npc.ai[3] = 160;
//visuals
for (int k = 0; k < 50; k++)
{
Dust.NewDust(flail.npc.position, flail.npc.width, flail.npc.height, ModContent.DustType<Dusts.Stone>(), Main.rand.NextFloat(-3, 3), Main.rand.NextFloat(-3, 3));
Dust.NewDustPerfect(flail.npc.Center, ModContent.DustType<Dusts.Gold2>(), Vector2.One.RotatedByRandom(6.28f) * Main.rand.NextFloat(5), 0, default, 1);
}
//audio
Main.PlaySound(SoundID.Item70, flail.npc.Center);
Main.PlaySound(SoundID.NPCHit42, flail.npc.Center);
//screenshake
int distance = (int)Vector2.Distance(Main.LocalPlayer.Center, flail.npc.Center);
((StarlightPlayer)Main.LocalPlayer.GetModPlayer<StarlightPlayer>()).Shake += distance < 100 ? distance / 20 : 5;
}
if (npc.ai[3] == 180) ResetAttack();
}
private void RandomTarget()
{
List<int> players = new List<int>();
foreach (Player player in Main.player.Where(p => Vector2.Distance(npc.Center, p.Center) < 2000)) players.Add(player.whoAmI);
if (players.Count == 0) return;
npc.target = players[Main.rand.Next(players.Count)];
Main.NewText("Random target chosen!");
}
public void ResetAttack()
{
flail.npc.velocity *= 0;
npc.ai[3] = 0;
npc.ai[2] = 0;
}
}
}
|
using System;
using FluentValidation;
using WorkScheduleManagement.Application.Models.Requests;
namespace WorkScheduleManagement.Application.ModelValidators
{
public class RequestValidator : AbstractValidator<RequestCreationModel>
{
public RequestValidator()
{
RuleFor(x => x.DateFrom)
.GreaterThanOrEqualTo(DateTime.Today)
.WithMessage("Некорректная дата");
// .SetValidator(new RequestDateValidator());
RuleFor(x => x.DateFrom)
.LessThanOrEqualTo(x => x.DateTo)
.WithMessage("Некорректный промежуток дат");
RuleFor(x => x.DateTo)
.GreaterThanOrEqualTo(DateTime.Today)
.WithMessage("Некорректная дата");
// .SetValidator(new RequestDateValidator());
RuleForEach(x => x.CustomDays)
.GreaterThanOrEqualTo(DateTime.Today)
.WithMessage("Некорректная дата");
// .SetValidator(new RequestDateValidator());
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TwiBo.Components.Model;
namespace TwiBo.Web.Models
{
public class DashboardModel
{
public string Name { get; set; }
public ICollection<TweetHistory> TweetHistory { get; set; }
}
} |
namespace _02._JediGalaxy
{
using System;
using System.Linq;
public class Startup
{
public static void Main()
{
int[] dimensions = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
int rows = dimensions[0];
int cols = dimensions[1];
int[][] matrix = CreateMatrix(rows, cols);
long points = 0;
string input = Console.ReadLine();
while (input != "Let the Force be with you")
{
int[] ivoStartPosition = input.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
int ivoRow = ivoStartPosition[0];
int ivoCol = ivoStartPosition[1];
int[] evilStartPostion = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
int evilRow = evilStartPostion[0];
int evilCol = evilStartPostion[1];
GetAllEvilPositions(matrix, evilRow, evilCol);
points += GetAllPoints(matrix, ivoRow, ivoCol);
input = Console.ReadLine();
}
Console.WriteLine(points);
}
private static long GetAllPoints(int[][] matrix, int ivoRow, int ivoCol)
{
long points = 0;
while (ivoRow >= 0 && ivoCol < matrix[0].Length)
{
if (CheckPositionInMatrix(matrix, ivoRow, ivoCol))
{
points += matrix[ivoRow][ivoCol];
}
ivoRow--;
ivoCol++;
}
return points;
}
private static void GetAllEvilPositions(int[][] matrix, int evilRow, int evilCol)
{
while (evilRow >= 0 && evilCol >= 0)
{
if (CheckPositionInMatrix(matrix, evilRow, evilCol))
{
matrix[evilRow][evilCol] = 0;
}
evilRow--;
evilCol--;
}
}
private static bool CheckPositionInMatrix(int[][] matrix, int row, int col)
{
if (row >= 0 && row < matrix.Length && col >= 0 && col < matrix[row].Length)
{
return true;
}
return false;
}
private static int[][] CreateMatrix(int rows, int cols)
{
int[][] matrix = new int[rows][];
int number = 0;
for (int row = 0; row < matrix.Length; row++)
{
matrix[row] = new int[cols];
for (int col = 0; col < matrix[row].Length; col++)
{
matrix[row][col] = number;
number++;
}
}
return matrix;
}
}
} |
using UnityEngine;
public class EnemySpawnerScript : MonoBehaviour
{
[SerializeField] private GameObject enemyObj;
[SerializeField] private Vector2[] spawnPosition;
[SerializeField] private float maxTimeToIncreaseEnemies;
public int enemyCount;
private int maxEnemyCount;
private float spawnTime;
private float spawnOffset;
private float timeToIncreaseEnemies;
private void Awake()
{
spawnOffset = 50f;
spawnTime = Random.Range(20f, 40f);
maxEnemyCount = 2;
EnemyScript.DeathByAsteroid += EnemyDeath;
}
private void Start()
{
timeToIncreaseEnemies = maxTimeToIncreaseEnemies;
}
private void Update()
{
SpawnEnemy();
}
private void FixedUpdate()
{
timeToIncreaseEnemies -= Time.deltaTime;
if (timeToIncreaseEnemies < 0)
{
timeToIncreaseEnemies = maxTimeToIncreaseEnemies;
maxEnemyCount++;
}
}
private void SpawnEnemy()
{
spawnTime -= Time.deltaTime;
if (spawnTime < 0 && enemyCount < 1)
{
enemyCount = maxEnemyCount;
for (int i = 0; i < maxEnemyCount; i++)
{
spawnPosition = new Vector2[2];
spawnPosition[0] = new Vector2((-Screen.width / 2 - spawnOffset), Random.Range((-Screen.height / 2) * 0.8f, (Screen.height / 2) * 0.8f));
spawnPosition[1] = new Vector2((Screen.width / 2 + spawnOffset), Random.Range((-Screen.height / 2) * 0.8f, (Screen.height / 2) * 0.8f));
int randomNumber = Random.Range(0, spawnPosition.Length);
Instantiate(enemyObj, spawnPosition[randomNumber], Quaternion.Euler(0f,0f,0f));
}
spawnTime = Random.Range(20f, 40f);
}
}
private void EnemyDeath(int value)
{
enemyCount -= value;
}
}
|
using RogueDungeonCrawler.Enum;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RogueDungeonCrawler.Classes
{
public class Room
{
public bool IsVisited { get; set; }
public bool IsStart { get; set; }
public bool IsEnd { get; set; }
//array 0=N 1=O 2=Z 3=W
Hallway[] Hallways = new Hallway[4];
public Room()
{
}
public Hallway GetHallway(Direction direction)
{
return this.Hallways[(int)direction] ?? null;
}
public void SetHallway(Direction direction, Hallway hallway)
{
this.Hallways[(int)direction] = hallway;
}
public Hallway GetLowestLevelHallway(List<Room> visited)
{
Hallway lowest = new Hallway(999, new Room());
for (int i = 0; i < 4; i++)
{
if ((this.Hallways[i] != null
&& this.Hallways[i].IsCollapsed == false
&& visited.Contains(this.Hallways[i].GetConnectedRoom(this)) == false)
&& this.Hallways[i].Enemy < lowest.Enemy)
{
lowest = this.Hallways[i];
}
}
return lowest;
}
public Hallway[] GetHallways()
{
return this.Hallways;
}
public char GetSymbol()
{
if (IsVisited)
{
return '*';
}
else if(IsStart)
{
return 'S';
}
else if(IsEnd)
{
return 'E';
}
else
{
return 'X';
}
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour {
[SerializeField] GameObject enemyProjectile;
[SerializeField] float projectileSpeed = 10f;
[SerializeField] float shotCount;
[SerializeField] float minTimeBetweenShots = 0.2f;
[SerializeField] float maxTimeBetweenShots = 1f;
[SerializeField] AudioClip enemyShootingSound;
[SerializeField] AudioClip enemyShootingSound2;
[SerializeField] [Range(0, 1)] float soundVolume = 0.5f;
private void Start()
{
shotCount =UnityEngine.Random.Range(minTimeBetweenShots, maxTimeBetweenShots);
}
private void Update()
{
shotCount -= Time.deltaTime;
if(shotCount <= 0)
{
Fire();
shotCount = UnityEngine.Random.Range(minTimeBetweenShots, maxTimeBetweenShots);
}
}
private void Fire()
{
GameObject projectile = Instantiate(enemyProjectile, transform.position, Quaternion.identity) as GameObject;
projectile.GetComponent<Rigidbody2D>().velocity = new Vector2(0, -projectileSpeed);
AudioSource.PlayClipAtPoint(enemyShootingSound, Camera.main.transform.position, soundVolume);
AudioSource.PlayClipAtPoint(enemyShootingSound2, Camera.main.transform.position, soundVolume);
}
}
|
namespace Game
{
/// <summary>
/// Handles power up type and coords for all power ups
/// </summary>
public class PowerUp
{
/// <summary>
/// Handles power up coords
/// </summary>
/// <value></value>
public Coords Coords {get; set;}
/// <summary>
/// Updates power up coords
/// </summary>
/// <param name="coords"></param>
public PowerUp(Coords coords)
{
Coords = coords;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MenuInteractableObject : MonoBehaviour {
bool selected;
Image My_Image;
Color My_Color; //Original
Transform My_Transform;
void Start () {
My_Image = GetComponent<Image>();
My_Color = GetComponent<Image>().color;
My_Transform = GetComponent<Transform>();
}
public void SetColor(Color color)
{
//My_Color = color;
if (My_Image == null)
{
My_Image = GetComponent<Image>();
}
My_Image.color = color;
}
public void SetScale(Vector2 scale)
{
My_Transform.localScale = scale;
}
public void ResetColor()
{
My_Image.color = Color.white;
}
public void ResetScale()
{
My_Transform.localScale = new Vector3(1, 1, 1);
}
private void OnDrawGizmos()
{
Debug.DrawRay(transform.position, Vector2.right * 100, Color.red);
Debug.DrawRay(transform.position, Vector2.left * 100, Color.red);
Debug.DrawRay(transform.position, Vector2.up * 100, Color.red);
Debug.DrawRay(transform.position, Vector2.down * 100, Color.red);
}
}
|
#version 430
// blockDim == local_size
// gridDim == number of work groups
layout(local_size_x = 112, local_size_y = 1) in; //
struct reduType
{
int result;
float error;
float J[6];
};
layout(std430, binding = 0) buffer TrackData
{
reduType trackOutput [];
};
//layout(binding = 0, r32f) uniform image2D outputData;
layout(std430, binding = 1) buffer OutputData
{
float outputData [];
};
uniform ivec2 imageSize;
shared float S[112][32];
void main()
{
uint sline = gl_LocalInvocationID.x; // 0 - 111
float sums[32];
for (int i = 0; i < 32; ++i)
{
sums[i] = 0.0f;
}
// float * jtj = sums + 7; sums[7] = jtj;
// float * info = sums + 28; sums[28] = info;
for (uint y = gl_WorkGroupID.x; y < imageSize.y; y += gl_NumWorkGroups.x) // y = (0:8); y < 424; y += 8
{
for (uint x = sline; x < imageSize.x; x += gl_WorkGroupSize.x) // x = (0:112); x < 512; x += 112
{
reduType row = trackOutput[(y * imageSize.x) + x];
if (row.result < 1)
{
if (row.result == -4)
{
sums[29] += 1;
}
if (row.result == -5)
{
sums[30] += 1;
}
if (row.result > -4)
{
sums[31] += 1;
}
continue;
}
// Error part
sums[0] += row.error * row.error;
// JTe part
for (int i = 0; i < 6; ++i)
{
sums[i + 1] += row.error * row.J[i];
}
// JTJ part, unfortunatly the double loop is not unrolled well...
sums[7] += row.J[0] * row.J[0];
sums[8] += row.J[0] * row.J[1];
sums[9] += row.J[0] * row.J[2];
sums[10] += row.J[0] * row.J[3];
sums[11] += row.J[0] * row.J[4];
sums[12] += row.J[0] * row.J[5];
sums[13] += row.J[1] * row.J[1];
sums[14] += row.J[1] * row.J[2];
sums[15] += row.J[1] * row.J[3];
sums[16] += row.J[1] * row.J[4];
sums[17] += row.J[1] * row.J[5];
sums[18] += row.J[2] * row.J[2];
sums[19] += row.J[2] * row.J[3];
sums[20] += row.J[2] * row.J[4];
sums[21] += row.J[2] * row.J[5];
sums[22] += row.J[3] * row.J[3];
sums[23] += row.J[3] * row.J[4];
sums[24] += row.J[3] * row.J[5];
sums[25] += row.J[4] * row.J[4];
sums[26] += row.J[4] * row.J[5];
sums[27] += row.J[5] * row.J[5];
sums[28] += 1.0f;
}
}
for (int i = 0; i < 32; ++i)
{
S[sline][i] = sums[i];
}
barrier(); // wait for threads to finish
if (sline < 32)
{
for(uint i = 1; i < gl_WorkGroupSize.x; ++i)
{
S[0][sline] += S[i][sline];
}
outputData[sline + gl_WorkGroupID.x * 32] = S[0][sline];
//imageStore(outputData, ivec2(sline, gl_WorkGroupID.x), vec4(S[0][sline]));
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EasyDev.PL
{
/// <summary>
/// 主键值生成器工厂
/// </summary>
public class GeneratorFactory
{
/// <summary>
/// 创建主键值生成器
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T CreateGenerator<T>()
where T: IGenerator, new ()
{
return new T();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Channels;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace configuration
{
public static class ServiceCollectionExtension
{
public static IServiceCollection AddMyService(this IServiceCollection services, IConfiguration configuration)
{
bool myServiceEnabled = configuration.GetValue<bool>("MyService:Enabled");
if (myServiceEnabled)
{
string myServiceUrl = configuration.GetValue<string>("MyService:Url");
// we can use DI to instantiate our service here
}
else
{
// service is not enabled
}
return services;
}
}
}
|
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour {
private PlayerController controller;
private playerID focus = playerID.P1;
public float transitionSpeed = 200f;
private Vector3 targePos;
private Vector3 activePos;
private Vector3 dist;
void Awake(){
//camera.orthographicSize = ((Screen.height/2.0f / 100f));
controller = GameObject.Find("PlayerManager").GetComponent<PlayerController>();
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
activePos = controller.getPlayerByID(focus).transform.position;
activePos.z = transform.position.z;
if(focus != controller.isActive()){
StopCoroutine("Transition");
focus = controller.isActive();
targePos = controller.getPlayerByID(focus).transform.position;
targePos.z = transform.position.z;
StartCoroutine("Transition");
return;
}
transform.position = activePos;
}
IEnumerator Transition()
{
float t = 0.0f;
Vector3 startingPos = transform.position;
var dist = Vector3.Distance(startingPos, targePos);
while (t < 1.0f)
{
t += (transitionSpeed * Time.deltaTime) /dist; //* (Time.timeScale/transitionDuration);
transform.position = Vector3.Lerp(startingPos, activePos, t);
yield return 0;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FrbaOfertas.AbmRubro
{
public partial class NuevoRubro : Form
{
public String rubro;
public NuevoRubro()
{
InitializeComponent();
}
private void guardar_Click(object sender, EventArgs e)
{
if (rubr_detalle.Text.Count() == 0)
{
MessageBox.Show("Rubro es vacio.", "Rubro nuevo", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
rubro = rubr_detalle.Text;
this.DialogResult = DialogResult.OK;
this.Close();
}
}
}
|
using Epam.Shops.DAL.Interfaces;
using Epam.Shops.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
using System.Linq;
namespace Epam.Shops.DAL
{
public class FeedbackDAO : IFeedbackDAO
{
public bool Add(Feedback newFeedback)
{
int result;
using (var db = new ShopsDB())
{
var id = new SqlParameter("@id", Guid.NewGuid());
var text = new SqlParameter("@text", newFeedback.Text);
var score = new SqlParameter("@score", newFeedback.Score);
var date = new SqlParameter("@date", newFeedback.Date);
var shopId = new SqlParameter("@shop_id", newFeedback.Shop.Id);
var userId = new SqlParameter("@user_id", newFeedback.User.Id);
result = db.Database.ExecuteSqlCommand("AddFeedback @id, @text, @score, @date, @shop_id, @user_id", id, text, score, date, shopId, userId);
}
return result == -1;
}
public IEnumerable<Feedback> GetAll()
{
var feedbacks = new List<Feedback>();
using (var db = new ShopsDB())
{
db.Configuration.LazyLoadingEnabled = false;
var queryResult = db.Feedbacks.SqlQuery("GetAllFeedbacks");
feedbacks = LoadFeedbacks(db, queryResult);
}
return feedbacks;
}
public IEnumerable<Feedback> GetByShop(Guid shopId)
{
var feedbacks = new List<Feedback>();
using (var db = new ShopsDB())
{
db.Configuration.LazyLoadingEnabled = false;
var param = new SqlParameter("@shop_id", shopId);
var queryResult = db.Feedbacks.SqlQuery("GetFeedbacksByShop @shop_id", param);
feedbacks = LoadFeedbacks(db, queryResult);
}
return feedbacks;
}
public IEnumerable<Feedback> GetByUser(Guid userId)
{
var feedbacks = new List<Feedback>();
using (var db = new ShopsDB())
{
db.Configuration.LazyLoadingEnabled = false;
var param = new SqlParameter("@id", userId);
var queryResult = db.Feedbacks.SqlQuery("GetFeedbacksByUser @id", param);
feedbacks = LoadFeedbacks(db, queryResult);
}
return feedbacks;
}
public bool Remove(Guid id)
{
int result;
using (var db = new ShopsDB())
{
var param = new SqlParameter("@id", id);
result = db.Database.ExecuteSqlCommand("RemoveFeedback @id", param);
}
return result != 0;
}
public bool Update(Feedback feedback)
{
int result;
using (var db = new ShopsDB())
{
var id = new SqlParameter("@id", feedback.Id);
var text = new SqlParameter("@text", feedback.Text);
var score = new SqlParameter("@score", feedback.Score);
var date = new SqlParameter("@date", feedback.Date);
var shopId = new SqlParameter("@shop_id", feedback.Shop.Id);
var userId = new SqlParameter("@user_id", feedback.User.Id);
result = db.Database.ExecuteSqlCommand("UpdateFeedback @id, @text, @score, @date, @shop_id, @user_id", id, text, score, date, shopId, userId);
}
return result != 0;
}
private List<Feedback> LoadFeedbacks(ShopsDB db, DbSqlQuery<Feedback> queryResult)
{
var result = new List<Feedback>();
foreach (var item in queryResult.ToArray())
{
db.Entry(item).Reference(t => t.Shop).Load();
db.Entry(item.Shop).Reference(t => t.Category).Load();
db.Entry(item).Reference(t => t.User).Load();
result.Add(item);
}
return result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Task2
{
class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Patronymic { get; set; }
public DateTime Birthday { get; set; }
public int Age
{
get
{
if (DateTime.Now.Month - Birthday.Month < 0 || (DateTime.Now.Month - Birthday.Month == 0 && DateTime.Now.Day - Birthday.Day < 0))
{
return DateTime.Now.Year - Birthday.Year - 1;
}
else
return DateTime.Now.Year - Birthday.Year;
}
}
public User(string fName, string lName, string patronomic, DateTime birthday)
{
FirstName = fName;
LastName = lName;
Patronymic = patronomic;
Birthday = birthday;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace CalculatorService.Domain.Models
{
public class DivResult : ResultOperationBase
{
public int Quotient { get; set; }
public int Remainder { get; set; }
}
}
|
using BradescoPGP.Common.Logging;
using BradescoPGP.Repositorio;
using BradescoPGP.Web.Areas.Portabilidade.Interfaces;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace BradescoPGP.Web.Areas.Portabilidade.Servicos
{
public class MotivoService : IMotivoService
{
private readonly PGPEntities _context;
public MotivoService(DbContext context)
{
_context = context as PGPEntities;
}
public Motivo ObterMotivo(int id)
{
return _context.Motivo.FirstOrDefault(m => m.Id == id);
}
public List<Motivo> ObterTodosMotivos(bool inativos = false)
{
if (inativos)
return _context.Motivo.ToList();
else
return _context.Motivo.Where(m => m.EmUso.HasValue && m.EmUso.Value).ToList();
}
public bool EditarMotivo(int idMotivo, string motivo)
{
var motivoBd = _context.Motivo.FirstOrDefault(m => m.Id == idMotivo);
if (motivoBd == null)
{
Log.Error($"Erro ao editar motivo, pois o mesmo não foi encontrado. Id pesquisado {idMotivo}");
return false;
}
motivoBd.Descricao = motivo;
try
{
_context.SaveChanges();
}
catch (Exception ex)
{
Log.Error($"Erro ao editar motivo", ex);
return false;
}
return true;
}
public bool EditarSubmotivo(int idSubmotivo, string submotivo)
{
var submotivoDb = _context.SubMotivo.FirstOrDefault(s => s.Id == idSubmotivo);
if (submotivoDb == null)
{
Log.Error($"Erro ao editar submotivo, pois o mesmo não foi encontrado. Id pesquisado {idSubmotivo}");
return false;
}
submotivoDb.Descricao = submotivo;
try
{
_context.SaveChanges();
}
catch (Exception ex)
{
Log.Error($"Erro ao editar submotivo", ex);
return false;
}
return true;
}
public bool ExcluirMotivo(int idMotivo)
{
var motivo = _context.Motivo.FirstOrDefault(m => m.Id == idMotivo);
if (motivo == null)
return false;
motivo.EmUso = false;
foreach (var sub in motivo.SubMotivo)
{
sub.EmUso = false;
}
try
{
_context.Entry(motivo).State = EntityState.Modified;
_context.SaveChanges();
return true;
}
catch (Exception)
{
return false;
}
}
public bool ExcluirSubmotivo(int idSubMotivo)
{
var submotivo = _context.SubMotivo.FirstOrDefault(s => s.Id == idSubMotivo);
if (submotivo == null)
return false;
submotivo.EmUso = false;
try
{
_context.Entry(submotivo).State = EntityState.Modified;
_context.SaveChanges();
return true;
}
catch (Exception)
{
return false;
}
}
public bool NovoMotivo(Motivo motivo)
{
if (motivo == null)
return false;
try
{
_context.Motivo.Add(motivo);
_context.SaveChanges();
return true;
}
catch (Exception e)
{
Log.Error("Erro ao cadatrar motivo", e);
return false;
}
}
public bool NovoSubMotivo(SubMotivo subMotivo)
{
try
{
_context.SubMotivo.Add(subMotivo);
_context.SaveChanges();
return true;
}
catch (Exception e)
{
Log.Error("Erro ao criar novo submotivo", e);
return false;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace TwojePrzedszkole.API.Models
{
public class User
{
//Credential Data
public int Id { get; set; }
public string Username { get; set; }
public byte[] PasswordHash { get; set; }
public byte[] PasswordSalt { get; set; }
//Personal Data
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public DateTime Created { get; set; }
public DateTime LastActive { get; set; }
public List<UserGroup> GroupName { get; set; }
//Address Data
public string City { get; set; }
public string Street { get; set; }
public int StreetNo { get; set; }
public string PostalCode { get; set; }
//Children Data
public Collection<Child> Children { get; set; }
}
} |
using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Input;
using System.Globalization;
using System.Collections.Generic;
using System.Windows.Threading;
using Microsoft.Windows.Controls;
namespace PixelRobot
{
public partial class TabbedOptionsDialog
{
public ProcessorProperties ppLocal;
private int xType;
private int unitsType;
private bool renamedRecipe = false;
private string originalRecipeName = "";
ProcessorWidget[] processors;
private int numProcessors;
private int currentProcessor;
public bool retVal;
private bool _familyListValid; // indicates the list of font families is valid
private bool _updatePending; // indicates a call to OnUpdate is scheduled
private bool alreadySetting = false;
private ICollection<FontFamily> _familyCollection; // see FamilyCollection property
public static readonly DependencyProperty SelectedFontFamilyProperty = RegisterFontProperty(
"SelectedFontFamily",
TextBlock.FontFamilyProperty,
new PropertyChangedCallback(SelectedFontFamilyChangedCallback)
);
public FontFamily SelectedFontFamily
{
get { return GetValue(SelectedFontFamilyProperty) as FontFamily; }
set { SetValue(SelectedFontFamilyProperty, value); }
}
public static void SelectedFontFamilyChangedCallback(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
((TabbedOptionsDialog)obj).OnSelectedFontFamilyChanged(e.NewValue as FontFamily);
}
// Helper function for registering font chooser dependency properties other than typographic properties.
private static DependencyProperty RegisterFontProperty(
string propertyName,
DependencyProperty targetProperty,
PropertyChangedCallback changeCallback
)
{
return DependencyProperty.Register(
propertyName,
targetProperty.PropertyType,
typeof(FontChooser),
new FontPropertyMetadata(
targetProperty.DefaultMetadata.DefaultValue,
changeCallback,
targetProperty
)
);
}
// Specialized metadata object for font chooser dependency properties
private class FontPropertyMetadata : FrameworkPropertyMetadata
{
public readonly DependencyProperty TargetProperty;
public FontPropertyMetadata(
object defaultValue,
PropertyChangedCallback changeCallback,
DependencyProperty targetProperty
)
: base(defaultValue, changeCallback)
{
TargetProperty = targetProperty;
}
}
/// <summary>
/// Collection of font families to display in the font family list. By default this is Fonts.SystemFontFamilies,
/// but a client could set this to another collection returned by Fonts.GetFontFamilies, e.g., a collection of
/// application-defined fonts.
/// </summary>
public ICollection<FontFamily> FontFamilyCollection
{
get
{
return (_familyCollection == null) ? Fonts.SystemFontFamilies : _familyCollection;
}
set
{
if (value != _familyCollection)
{
_familyCollection = value;
InvalidateFontFamilyList();
}
}
}
string[] names1 = new string[] { "Custom", "0", "0",
"VGA", "640", "480",
"SVGA", "800", "600",
"XVGA", "1024", "768",
"SXGA", "1280", "1024",
"HD", "1366", "768",
"HD Full", "1920", "1080"};
string[] names2 = new string[] { "Custom", "0", "0",
"--Computer Screens--", "-", "-",
"QVGA", "320", "240",
"VGA", "640", "480",
"SVGA", "800", "600",
"XVGA", "1024", "768",
"SXGA", "1280", "1024",
"SXGA+", "1400", "1050",
"WXGA", "1440", "900",
"UXGA", "1600", "1200",
"WSXGA+", "1680", "1050",
"WUXGA", "1920", "1200",
"--Other Screens--", "-", "-",
"HD", "1366", "768",
"HD+", "1600", "900",
"HD Full", "1920", "1080",
"--Devices--", "-", "-",
"iPod touch", "320", "480",
"Smartphone1", "480", "600",
"Smartphone2", "480", "800",
"Frame1", "480", "234",
"Frame2", "480", "280",
"Frame3", "720", "480",
"Frame4", "800", "480"
};
string[] names3 = new string[] { "Custom", "0", "0", "0", "0", "0", "0",
"--Print Sizes--", "-", "-", "-", "-", "-", "-",
"6x4", "6", "4", "15.24", "10.16", "152.4", "101.6",
"5x7", "5", "7", "12.7", "17.78", "127", "177.8",
"8x10", "8", "10", "20.32", "25.4", "203.2", "254",
"8x12", "8", "12", "20.32", "30.48", "203.2", "304.8",
"A5", "5.827", "8.268", "14.8", "21", "148", "210",
"A4", "8.268", "11.693", "21", "29.7", "210", "297",
"A3", "11.693", "16.535", "29.7", "42", "297", "420",
"UK Passport", "1.378", "1.772", "3.5", "4.5", "35", "45"
};
public TabbedOptionsDialog(ProcessorProperties pp, int i)
{
InitializeComponent();
xType = i;
InitialiseUI();
numProcessors = 1;
ppLocal = pp;
originalRecipeName = ppLocal.recipeName;
SetUIItems();
SetNextPreviousState();
}
public TabbedOptionsDialog(ProcessorWidget[] procs, int num, int start, int p)
{
xType = p;
InitializeComponent();
processors = procs;
numProcessors = num;
currentProcessor = start;
LocaliseLists();
InitialiseUI();
ppLocal = processors[currentProcessor].GetProcessorProperties();
originalRecipeName = ppLocal.recipeName;
SetUIItems();
SetNextPreviousState();
}
private void LocaliseLists()
{
names1[0] = Properties.Resources.Custom;
names2[0] = Properties.Resources.Custom;
names2[3] = Properties.Resources.ListScreens;
names2[36] = Properties.Resources.ListOther;
names2[48] = Properties.Resources.ListPrints;
names3[0] = Properties.Resources.Custom;
names3[7] = Properties.Resources.ListPrints;
}
private void InitialiseUI()
{
QualitySlider.LargeChange = 1;
QualitySlider.SmallChange = 1;
QualitySlider.Minimum = 50;
QualitySlider.Maximum = 95;
fontFamilyList.Visibility = Visibility.Hidden;
formatList.Items.Add("JPEG");
formatList.SelectedIndex = 0;
if (xType > 10)
{
formatList.Items.Add("TIFF");
formatList.Items.Add("PNG");
formatList.Items.Add("Bitmap");
formatList.Items.Add("GIF");
}
resampleList.Items.Add(Properties.Resources.Bicubic);
resampleList.Items.Add(Properties.Resources.Bilinear);
resampleList.Items.Add(Properties.Resources.Nearest);
resampleList.SelectedIndex = 1;
if (xType > 100)
{
ImageDirections.Items.Add(Properties.Resources.TopLeft);
ImageDirections.Items.Add(Properties.Resources.TopCentre);
ImageDirections.Items.Add(Properties.Resources.TopRight);
ImageDirections.Items.Add(Properties.Resources.MiddleLeft);
ImageDirections.Items.Add(Properties.Resources.MiddleCentre);
ImageDirections.Items.Add(Properties.Resources.MiddleRight);
ImageDirections.Items.Add(Properties.Resources.BottomLeft);
ImageDirections.Items.Add(Properties.Resources.BottomCentre);
ImageDirections.Items.Add(Properties.Resources.BottomRight);
ImageDirections.Items.Add(Properties.Resources.CentreFill);
ImageDirections.SelectedIndex = 4;
}
else
{
OptionsTabControl.Items.Remove(WatermarkImageTab);
check3D.Visibility = Visibility.Hidden;
}
scaleList.Items.Add(Properties.Resources.ScaleFit);
scaleList.Items.Add(Properties.Resources.ScaleFill);
if (xType < 3)
{
OptionsTabControl.Items.Remove(WatermarkTab);
OptionsTabControl.Items.Remove(BorderTab);
OptionsTabControl.Items.Remove(VignetteTab);
checkSepia.Visibility = Visibility.Hidden;
checkMirror.Visibility = Visibility.Hidden;
checkMono.Visibility = Visibility.Hidden;
checkFlip.Visibility = Visibility.Hidden;
checkUpscale.Visibility = Visibility.Hidden;
checkRotateFit.Visibility = Visibility.Hidden;
checkDiag.Visibility = Visibility.Hidden;
}
if (xType == 0)
{
for (int i = 0; i < names1.Length; i = i + 3)
{
presetsList.Items.Add(names1[i]);
}
presetsList2.Visibility = Visibility.Hidden;
}
else
{
for (int i = 0; i < names2.Length; i = i + 3)
{
presetsList.Items.Add(names2[i]);
}
for (int i = 0; i < names3.Length; i = i + 7)
{
presetsList2.Items.Add(names3[i]);
}
}
unitsList.Items.Add("in");
unitsList.Items.Add("cm");
unitsList.Items.Add("mm");
string[] userPositions = Properties.Settings.Default.OptionsDialogPosition.Split(';');
if (userPositions.Length == 2)
{
Left = double.Parse(userPositions[0]);
Top = double.Parse(userPositions[1]);
}
else
{
Left = (SystemParameters.PrimaryScreenWidth - (double)GetValue(WidthProperty)) / 2;
Top = (SystemParameters.PrimaryScreenHeight - (double)GetValue(HeightProperty)) / 2;
}
this.Closing += new System.ComponentModel.CancelEventHandler(TabbedOptionsDialog_Closing);
MouseLeftButtonDown += new MouseButtonEventHandler(TabbedOptionsDialog_MouseLeftButtonDown);
}
private void SetUIItems()
{
retVal = false;
alreadySetting = true;
SetUIValues();
SetUIState();
SetPreset();
alreadySetting = false;
if (xType >= 102)
{
Title = String.Format(Properties.Resources.ProcessRecipeName, ppLocal.recipeName);
}
else
{
Title = Properties.Resources.ProcessRecipe;
}
}
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
if (xType > 9)
{
// Hook up events for the font family list and associated text box.
fontFamilyList.SelectionChanged += new SelectionChangedEventHandler(fontFamilyList_SelectionChanged);
// Initialize the font family list and the current family.
if (!_familyListValid)
{
InitializeFontFamilyList();
_familyListValid = true;
OnSelectedFontFamilyChanged(SelectedFontFamily);
}
// Schedule background updates.
ScheduleUpdate();
}
}
// Schedule background initialization of the font famiy list.
private void InvalidateFontFamilyList()
{
if (_familyListValid)
{
fontFamilyList.Items.Clear();
fontFace.Clear();
_familyListValid = false;
ScheduleUpdate();
}
}
// Handle changes to the SelectedFontFamily property
public void OnSelectedFontFamilyChanged(FontFamily family)
{
// If the family list is not valid do nothing for now.
// We'll be called again after the list is initialized.
if (_familyListValid)
{
// Select the family in the list; this will return null if the family is not in the list.
FontFamilyListItem item = SelectFontFamilyListItem(family);
// Set the text box to the family name, if it isn't already.
string displayName = (item != null) ? item.ToString() : FontFamilyListItem.GetDisplayName(family);
if (string.Compare(fontFace.Text, displayName, true, CultureInfo.CurrentCulture) != 0)
{
fontFace.Text = displayName;
fontFace.FontFamily = family;
// fontFamilyList.Visibility = Visibility.Hidden;
}
}
}
// Update font family list based on selection.
// Return list item if there's an exact match, or null if not.
private FontFamilyListItem SelectFontFamilyListItem(string displayName)
{
FontFamilyListItem listItem = fontFamilyList.SelectedItem as FontFamilyListItem;
if (listItem != null && string.Compare(listItem.ToString(), displayName, true, CultureInfo.CurrentCulture) == 0)
{
// Already selected
return listItem;
}
else if (SelectListItem(fontFamilyList, displayName))
{
// Exact match found
return fontFamilyList.SelectedItem as FontFamilyListItem;
}
else
{
// Not in the list
return null;
}
}
// Update list based on selection.
// Return true if there's an exact match, or false if not.
private bool SelectListItem(ListBox list, object value)
{
ItemCollection itemList = list.Items;
// Perform a binary search for the item.
int first = 0;
int limit = itemList.Count;
while (first < limit)
{
int i = first + (limit - first) / 2;
IComparable item = (IComparable)(itemList[i]);
int comparison = item.CompareTo(value);
if (comparison < 0)
{
// Value must be after i
first = i + 1;
}
else if (comparison > 0)
{
// Value must be before i
limit = i;
}
else
{
// Exact match; select the item.
list.SelectedIndex = i;
itemList.MoveCurrentToPosition(i);
list.ScrollIntoView(itemList[i]);
return true;
}
}
// Not an exact match; move current position to the nearest item but don't select it.
if (itemList.Count > 0)
{
int i = Math.Min(first, itemList.Count - 1);
itemList.MoveCurrentToPosition(i);
list.ScrollIntoView(itemList[i]);
}
return false;
}
// Update font family list based on selection.
// Return list item if there's an exact match, or null if not.
private FontFamilyListItem SelectFontFamilyListItem(FontFamily family)
{
FontFamilyListItem listItem = fontFamilyList.SelectedItem as FontFamilyListItem;
if (listItem != null && listItem.FontFamily.Equals(family))
{
// Already selected
return listItem;
}
else if (SelectListItem(fontFamilyList, FontFamilyListItem.GetDisplayName(family)))
{
// Exact match found
return fontFamilyList.SelectedItem as FontFamilyListItem;
}
else
{
// Not in the list
return null;
}
}
private void InitializeFontFamilyList()
{
ICollection<FontFamily> familyCollection = FontFamilyCollection;
if (familyCollection != null)
{
FontFamilyListItem[] items = new FontFamilyListItem[familyCollection.Count];
int i = 0;
foreach (FontFamily family in familyCollection)
{
items[i++] = new FontFamilyListItem(family);
}
Array.Sort<FontFamilyListItem>(items);
foreach (FontFamilyListItem item in items)
{
fontFamilyList.Items.Add(item);
}
}
}
private void fontFamilyList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
FontFamilyListItem item = fontFamilyList.SelectedItem as FontFamilyListItem;
if (item != null)
{
SelectedFontFamily = item.FontFamily;
OnSelectedFontFamilyChanged(SelectedFontFamily);
}
}
private delegate void UpdateCallback();
// Schedule background initialization.
private void ScheduleUpdate()
{
if (!_updatePending)
{
Dispatcher.BeginInvoke(DispatcherPriority.ContextIdle, new UpdateCallback(OnUpdate));
_updatePending = true;
}
}
// Dispatcher callback that performs background initialization.
private void OnUpdate()
{
_updatePending = false;
if (!_familyListValid)
{
// Initialize the font family list.
InitializeFontFamilyList();
_familyListValid = true;
OnSelectedFontFamilyChanged(SelectedFontFamily);
// Defer any other initialization until later.
ScheduleUpdate();
}
}
void TabbedOptionsDialog_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
string userPos = this.Left.ToString() + ";" + this.Top.ToString();
Properties.Settings.Default.OptionsDialogPosition = userPos;
Properties.Settings.Default.Save();
}
void TabbedOptionsDialog_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DragMove();
}
private void ClickOK(object sender, RoutedEventArgs e)
{
if (GetUIValues() == true)
{
if (renamedRecipe == true)
{
// delete originalRecipeName
RegHelper rh = new RegHelper();
rh.DeleteRecipe(originalRecipeName);
renamedRecipe = false;
}
ppLocal.WriteReg();
retVal = true;
this.Close();
}
else
{
System.Windows.MessageBox.Show("One or more entries are invalid. Please check", "Pixel Robot Warning");
}
}
private void ClickCancel(object sender, RoutedEventArgs e)
{
this.Close();
}
private void scaleChanged(object sender, RoutedEventArgs e)
{
SetUIState();
}
private void SetUIValues()
{
alreadySetting = true;
WatermarkColourPicker.SelectedColor = ppLocal.watermarkColour;
BorderColourPicker.SelectedColor = ppLocal.borderColour;
checkApplyBorder.IsChecked = ppLocal.applyBorder;
borderWidth.Text = ppLocal.borderWidth.ToString();
checkSizeIncludes.IsChecked = ppLocal.sizeIncludesBorder;
checkApplyWatermark.IsChecked = ppLocal.applyWatermark;
watermarkOpacity.Text = ppLocal.watermarkOpacity.ToString();
fontFace.Text = ppLocal.watermarkFontFace;
fontFace.FontSize = 20;
fontFace.Foreground = new SolidColorBrush(ppLocal.watermarkColour);
if (ppLocal.watermarkBold)
fontFace.FontWeight = FontWeights.Bold;
if (ppLocal.watermarkItalic)
fontFace.FontStyle = FontStyles.Italic;
FontFamily ff = new FontFamily(ppLocal.watermarkFontFace);
fontFace.FontFamily = ff;
checkDiag.IsChecked = ppLocal.watermarkDiagonal;
check3D.IsChecked = ppLocal.watermark3D;
checkBold.IsChecked = ppLocal.watermarkBold;
checkItalic.IsChecked = ppLocal.watermarkItalic;
watermarkText.Text = ppLocal.watermarkText;
checkApplyWatermarkImage.IsChecked = ppLocal.applyWatermarkImage;
watermarkImageOpacity.Text = ppLocal.watermarkImageOpacity.ToString();
watermarkImageFile.Text = ppLocal.watermarkImageFile;
checkApplyResize.IsChecked = ppLocal.applyResize;
XDim.Text = ppLocal.processSizeW.ToString();
YDim.Text = ppLocal.processSizeH.ToString();
XSiz.Text = ppLocal.physSizeWidth.ToString();
YSiz.Text = ppLocal.physSizeHeight.ToString();
DPI.Text = ppLocal.dpiVal.ToString();
if (ppLocal.fillArea == false)
scaleList.SelectedIndex = 0;
else
scaleList.SelectedIndex = 1;
checkUpscale.IsChecked = ppLocal.resizeUp;
Percentage.Text = ppLocal.processSizePercent.ToString();
checkRotateFit.IsChecked = ppLocal.rotateFit;
checkMono.IsChecked = ppLocal.editMono;
checkSepia.IsChecked = ppLocal.editSepia;
checkFlip.IsChecked = ppLocal.editFlip;
checkMirror.IsChecked = ppLocal.editMirror;
checkAutoRotate.IsChecked = ppLocal.editAutoRotate;
checkApplyVignette.IsChecked = ppLocal.applyVignette;
vignetteOpacity.Text = ppLocal.vignetteOpacity.ToString();
VignetteBlack.IsChecked = ppLocal.vignetteBlack;
VignetteWhite.IsChecked = (ppLocal.vignetteBlack == false);
Folder.Text = ppLocal.targetFolder;
Quality.Text = ppLocal.jpegQual.ToString();
QualitySlider.Value = ppLocal.jpegQual;
resampleList.SelectedIndex = ppLocal.resampleQuality;
formatList.SelectedIndex = (int)ppLocal.outputFormat;
ImageDirections.SelectedIndex = ppLocal.watermarkImageLocation;
if (formatList.SelectedIndex == 4)
labelGIF.Visibility = System.Windows.Visibility.Visible;
else
labelGIF.Visibility = System.Windows.Visibility.Hidden;
switch (ppLocal.resizeBy)
{
case 2:
PercentageLabel.IsChecked = true; break;
case 1:
PhysicalSizeLabel.IsChecked = true; break;
case 0:
default:
PixelSizeLabel.IsChecked = true; break;
}
alreadySetting = true;
unitsList.SelectedIndex = ppLocal.unitsVal;
unitsType = unitsList.SelectedIndex;
textBox_name.Text = ppLocal.recipeName;
alreadySetting = false;
}
private void SetUIState()
{
if (formatList.SelectedIndex != 0)
{
QualLabel.Opacity = 0.5;
Quality.Opacity = 0.5;
QualitySlider.Opacity = 0.5;
Quality.IsEnabled = false;
QualitySlider.IsEnabled = false;
}
else
{
QualLabel.Opacity = 1;
Quality.Opacity = 1;
QualitySlider.Opacity = 1;
Quality.IsEnabled = true;
QualitySlider.IsEnabled = true;
}
if (checkApplyBorder.IsChecked != true)
{
checkSizeIncludes.IsEnabled = false;
checkSizeIncludes.Opacity = 0.5;
borderwLabel.IsEnabled = false;
borderwLabel.Opacity = 0.5;
borderWidth.IsEnabled = false;
borderWidth.Opacity = 0.5;
bordercolLabel.IsEnabled = false;
bordercolLabel.Opacity = 0.5;
BorderColourPicker.IsEnabled = false;
BorderColourPicker.Opacity = 0.5;
}
else
{
checkSizeIncludes.IsEnabled = true;
checkSizeIncludes.Opacity = 1;
borderwLabel.IsEnabled = true;
borderwLabel.Opacity = 1;
borderWidth.IsEnabled = true;
borderWidth.Opacity = 1;
bordercolLabel.IsEnabled = true;
bordercolLabel.Opacity = 1;
BorderColourPicker.IsEnabled = true;
BorderColourPicker.Opacity = 1;
}
if (checkApplyWatermark.IsChecked != true)
{
wmopacityLabel.IsEnabled = false;
watermarkOpacity.IsEnabled = false;
wmcolLabel.IsEnabled = false;
WatermarkColourPicker.Opacity = 0.5;
WatermarkColourPicker.IsEnabled = false;
fontfaceLabel.IsEnabled = false;
fontFace.IsEnabled = false;
checkDiag.IsEnabled = false;
check3D.IsEnabled = false;
checkBold.IsEnabled = false;
checkItalic.IsEnabled = false;
wmopacityLabel.Opacity = 0.5;
watermarkOpacity.Opacity = 0.5;
wmcolLabel.Opacity = 0.5;
fontfaceLabel.Opacity = 0.5;
fontFace.Opacity = 0.5;
check3D.Opacity = 0.5;
checkDiag.Opacity = 0.5;
Expand.IsEnabled = false;
Expand.Opacity = 0.5;
watermarkText.IsEnabled = false;
watermarkText.Opacity = 0.5;
overrideLabel.Opacity = 0.5;
}
else
{
wmopacityLabel.IsEnabled = true;
watermarkOpacity.IsEnabled = true;
wmcolLabel.IsEnabled = true;
WatermarkColourPicker.Opacity = 1;
WatermarkColourPicker.IsEnabled = true;
fontfaceLabel.IsEnabled = true;
fontFace.IsEnabled = true;
check3D.IsEnabled = true;
checkDiag.IsEnabled = true;
checkBold.IsEnabled = true;
checkItalic.IsEnabled = true;
wmopacityLabel.Opacity = 1;
watermarkOpacity.Opacity = 1;
wmcolLabel.Opacity = 1;
fontfaceLabel.Opacity = 1;
fontFace.Opacity = 1;
check3D.Opacity = 1;
checkDiag.Opacity = 1;
Expand.IsEnabled = true;
Expand.Opacity = 1;
watermarkText.IsEnabled = true;
watermarkText.Opacity = 1;
overrideLabel.Opacity = 1;
}
if (checkApplyWatermarkImage.IsChecked != true)
{
wmiopacityLabel.IsEnabled = false;
watermarkImageOpacity.IsEnabled = false;
wmiimageLabel.IsEnabled = false;
watermarkImageFile.IsEnabled = false;
wmlocLabel.IsEnabled = false;
ImageDirections.IsEnabled = false;
BrowseButton.IsEnabled = false;
BrowseButton.Opacity = 0.5;
wmiopacityLabel.Opacity = 0.5;
watermarkImageOpacity.Opacity = 0.5;
wmiimageLabel.Opacity = 0.5;
watermarkImageFile.Opacity = 0.5;
wmlocLabel.Opacity = 0.5;
ImageDirections.Opacity = 0.5;
}
else
{
wmiopacityLabel.IsEnabled = true;
watermarkImageOpacity.IsEnabled = true;
wmiimageLabel.IsEnabled = true;
watermarkImageFile.IsEnabled = true;
wmlocLabel.IsEnabled = true;
ImageDirections.IsEnabled = true;
BrowseButton.IsEnabled = true;
BrowseButton.Opacity = 1;
wmiopacityLabel.Opacity = 1;
watermarkImageOpacity.Opacity = 1;
wmiimageLabel.Opacity = 1;
watermarkImageFile.Opacity = 1;
wmlocLabel.Opacity = 1;
ImageDirections.Opacity = 1;
}
if (checkApplyVignette.IsChecked != true)
{
opacityLabel.IsEnabled = false;
vignetteOpacity.IsEnabled = false;
VignetteBlack.IsEnabled = false;
VignetteWhite.IsEnabled = false;
VignetteBlack.Opacity = 0.5;
VignetteWhite.Opacity = 0.5;
opacityLabel.Opacity = 0.5;
vignetteOpacity.Opacity = 0.5;
}
else
{
opacityLabel.IsEnabled = true;
vignetteOpacity.IsEnabled = true;
opacityLabel.Opacity = 1;
vignetteOpacity.Opacity = 1;
VignetteBlack.IsEnabled = true;
VignetteWhite.IsEnabled = true;
VignetteBlack.Opacity = 1;
VignetteWhite.Opacity = 1;
}
if (checkApplyResize.IsChecked != true)
{
PixelSizeLabel.IsEnabled = false;
presetsList.IsEnabled = false;
XDim.IsEnabled = false;
X.IsEnabled = false;
YDim.IsEnabled = false;
PhysicalSizeLabel.IsEnabled = false;
presetsList2.IsEnabled = false;
XSiz.IsEnabled = false;
X2.IsEnabled = false;
YSiz.IsEnabled = false;
PercentageLabel.IsEnabled = false;
Percentage.IsEnabled = false;
checkUpscale.IsEnabled = false;
ResampleLabel.IsEnabled = false;
resampleList.IsEnabled = false;
scaleList.IsEnabled = false;
checkRotateFit.IsEnabled = false;
DPI.IsEnabled = false;
DPI.Opacity = 0.5;
dpiLabel.Opacity = 0.5;
ScaleGroup.Opacity = 0.5;
PixelSizeLabel.Opacity = 0.5;
presetsList.Opacity = 0.5;
XDim.Opacity = 0.5;
X.Opacity = 0.5;
YDim.Opacity = 0.5;
PhysicalSizeLabel.Opacity = 0.5;
presetsList2.Opacity = 0.5;
XSiz.Opacity = 0.5;
X2.Opacity = 0.5;
YSiz.Opacity = 0.5;
PercentageLabel.Opacity = 0.5;
Percentage.Opacity = 0.5;
checkUpscale.Opacity = 0.5;
ResampleLabel.Opacity = 0.5;
resampleList.Opacity = 0.5;
scaleList.Opacity = 0.5;
ScaleLabel.Opacity = 0.5;
checkRotateFit.Opacity = 0.5;
}
else
{
PixelSizeLabel.IsEnabled = true;
PhysicalSizeLabel.IsEnabled = true;
PercentageLabel.IsEnabled = true;
PixelSizeLabel.Opacity = 1;
PhysicalSizeLabel.Opacity = 1;
PercentageLabel.Opacity = 1;
DPI.IsEnabled = true;
DPI.Opacity = 1;
dpiLabel.Opacity = 1;
if (PercentageLabel.IsChecked == true)
{
XDim.IsEnabled = false;
YDim.IsEnabled = false;
presetsList.IsEnabled = false;
presetsList.Opacity = 0.5;
XDim.Opacity = 0.5;
X.Opacity = 0.5;
YDim.Opacity = 0.5;
presetsList2.IsEnabled = false;
XSiz.IsEnabled = false;
YSiz.IsEnabled = false;
presetsList2.Opacity = 0.5;
XSiz.Opacity = 0.5;
X2.Opacity = 0.5;
YSiz.Opacity = 0.5;
unitsList.Opacity = 0.5;
unitsList.IsEnabled = false;
Percentage.IsEnabled = true;
Percentage.Opacity = 1;
}
else if (PhysicalSizeLabel.IsChecked == true)
{
XDim.IsEnabled = false;
YDim.IsEnabled = false;
presetsList.IsEnabled = false;
presetsList.Opacity = 0.5;
XDim.Opacity = 0.5;
X.Opacity = 0.5;
YDim.Opacity = 0.5;
presetsList2.IsEnabled = true;
XSiz.IsEnabled = true;
YSiz.IsEnabled = true;
presetsList2.Opacity = 1;
XSiz.Opacity = 1;
X2.Opacity = 1;
YSiz.Opacity = 1;
unitsList.Opacity = 1;
unitsList.IsEnabled = true;
Percentage.IsEnabled = false;
Percentage.Opacity = 0.5;
}
else
{
presetsList.IsEnabled = true;
XDim.IsEnabled = true;
YDim.IsEnabled = true;
presetsList.Opacity = 1;
XDim.Opacity = 1;
X.Opacity = 1;
YDim.Opacity = 1;
presetsList2.IsEnabled = false;
XSiz.IsEnabled = false;
YSiz.IsEnabled = false;
presetsList2.Opacity = 0.5;
XSiz.Opacity = 0.5;
X2.Opacity = 0.5;
YSiz.Opacity = 0.5;
unitsList.Opacity = 0.5;
unitsList.IsEnabled = false;
Percentage.IsEnabled = false;
Percentage.Opacity = 0.5;
}
checkUpscale.IsEnabled = true;
ResampleLabel.IsEnabled = true;
resampleList.IsEnabled = true;
scaleList.IsEnabled = true;
checkRotateFit.IsEnabled = true;
checkUpscale.Opacity = 1;
ResampleLabel.Opacity = 1;
resampleList.Opacity = 1;
scaleList.Opacity = 1;
ScaleLabel.Opacity = 1;
checkRotateFit.Opacity = 1;
}
}
private void SetPreset()
{
// if (alreadySetting == false)
// {
// alreadySetting = true;
try
{
double xval = double.Parse(XDim.Text);
double yval = double.Parse(YDim.Text);
double xsval = double.Parse(XSiz.Text);
double ysval = double.Parse(YSiz.Text);
bool set1 = false;
bool set2 = false;
if (xType == 0)
{
for (int i = 0; i < names1.Length; i = i + 3)
{
if ((names1[i + 1] == xval.ToString()) && (names1[i + 2] == yval.ToString()))
{
alreadySetting = true;
presetsList.SelectedIndex = i / 3;
alreadySetting = false;
set1 = true;
}
}
}
else
{
for (int i = 0; i < names2.Length; i = i + 3)
{
if ((names2[i + 1] == xval.ToString()) && (names2[i + 2] == yval.ToString()))
{
alreadySetting = true;
presetsList.SelectedIndex = i / 3;
alreadySetting = false;
set1 = true;
}
}
for (int i = 0; i < names3.Length; i = i + 7)
{
int offsetVal = unitsList.SelectedIndex * 2;
if ((names3[i + 1 + offsetVal] == xsval.ToString()) && (names3[i + 2 + offsetVal] == ysval.ToString()))
{
alreadySetting = true;
presetsList2.SelectedIndex = i / 7;
alreadySetting = false;
set2 = true;
}
}
}
if (set1 == false)
presetsList.SelectedIndex = 0;
if (set2 == false)
presetsList2.SelectedIndex = 0;
}
catch (Exception)
{ }
// alreadySetting = false;
// }
}
private bool GetUIValues()
{
try
{
ppLocal.applyBorder = (checkApplyBorder.IsChecked == true);
ppLocal.borderWidth = int.Parse(borderWidth.Text);
ppLocal.sizeIncludesBorder = (checkSizeIncludes.IsChecked == true);
ppLocal.borderColour = BorderColourPicker.SelectedColor;
ppLocal.applyWatermark = (checkApplyWatermark.IsChecked == true);
ppLocal.watermarkOpacity = int.Parse(watermarkOpacity.Text);
ppLocal.watermarkFontFace = fontFace.Text;
ppLocal.watermarkDiagonal = (checkDiag.IsChecked == true);
ppLocal.watermark3D = (check3D.IsChecked == true);
ppLocal.watermarkBold = (checkBold.IsChecked == true);
ppLocal.watermarkItalic = (checkItalic.IsChecked == true);
ppLocal.watermarkColour = WatermarkColourPicker.SelectedColor;
ppLocal.watermarkText = watermarkText.Text;
ppLocal.applyWatermarkImage = (checkApplyWatermarkImage.IsChecked == true);
ppLocal.watermarkImageOpacity = int.Parse(watermarkImageOpacity.Text);
ppLocal.watermarkImageFile = watermarkImageFile.Text;
ppLocal.applyResize = (checkApplyResize.IsChecked == true);
ppLocal.processSizeW = int.Parse(XDim.Text);
ppLocal.processSizeH = int.Parse(YDim.Text);
ppLocal.physSizeWidth = double.Parse(XSiz.Text);
ppLocal.physSizeHeight = double.Parse(YSiz.Text);
ppLocal.dpiVal = int.Parse(DPI.Text);
ppLocal.unitsVal = unitsList.SelectedIndex;
ppLocal.fillArea = (scaleList.SelectedIndex == 1);
ppLocal.resizeUp = (checkUpscale.IsChecked == true);
if (PercentageLabel.IsChecked == true)
ppLocal.resizeBy = 2;
else if (PhysicalSizeLabel.IsChecked == true)
ppLocal.resizeBy = 1;
else
ppLocal.resizeBy = 0;
ppLocal.processSizePercent = int.Parse(Percentage.Text);
ppLocal.rotateFit = (checkRotateFit.IsChecked == true);
ppLocal.editMono = (checkMono.IsChecked == true);
ppLocal.editSepia = (checkSepia.IsChecked == true);
ppLocal.editMirror = (checkMirror.IsChecked == true);
ppLocal.editFlip = (checkFlip.IsChecked == true);
ppLocal.editAutoRotate = (checkAutoRotate.IsChecked == true);
ppLocal.applyVignette = (checkApplyVignette.IsChecked == true);
ppLocal.vignetteOpacity = int.Parse(vignetteOpacity.Text);
ppLocal.vignetteBlack = (VignetteBlack.IsChecked == true);
ppLocal.targetFolder = Folder.Text;
ppLocal.jpegQual = (int)QualitySlider.Value;
ppLocal.resampleQuality = resampleList.SelectedIndex;
ppLocal.outputFormat = OutputType.JPEG + formatList.SelectedIndex;
ppLocal.watermarkImageLocation = ImageDirections.SelectedIndex;
return true;
}
catch (Exception)
{
return false;
}
}
private void ffChanged(object sender, SelectionChangedEventArgs e)
{
SetUIState();
if (formatList.SelectedIndex == 4)
labelGIF.Visibility = System.Windows.Visibility.Visible;
else
labelGIF.Visibility = System.Windows.Visibility.Hidden;
}
private void presetChanged(object sender, SelectionChangedEventArgs e)
{
if (alreadySetting == false)
{
alreadySetting = true;
int i = presetsList.SelectedIndex;
if (i != 0)
{
int nIndex = i * 3;
if (xType == 0)
{
if (names1[nIndex + 1] == "-")
{
nIndex += 3;
presetsList.SelectedIndex = i + 1;
}
XDim.Text = names1[nIndex + 1];
YDim.Text = names1[nIndex + 2];
}
else
{
if (names2[nIndex + 1] == "-")
{
nIndex += 3;
presetsList.SelectedIndex = i + 1;
}
XDim.Text = names2[nIndex + 1];
YDim.Text = names2[nIndex + 2];
}
}
CalculateSizeFromPixelsAndDPI();
SetPreset();
alreadySetting = false;
}
}
private void preset2Changed(object sender, SelectionChangedEventArgs e)
{
if (alreadySetting == false)
{
alreadySetting = true;
int i = presetsList2.SelectedIndex;
int offsetVal = (unitsList.SelectedIndex * 2);
if (i != 0)
{
int nIndex = i * 7;
if (xType != 0)
{
if (names3[nIndex + 1] == "-")
{
nIndex += 7;
presetsList2.SelectedIndex = i + 1;
}
XSiz.Text = names3[nIndex + 1 + offsetVal];
YSiz.Text = names3[nIndex + 2 + offsetVal];
}
}
CalcluatePixelsFromSizeAndDPI();
SetPreset();
alreadySetting = false;
}
}
private void unitsChanged(object sender, SelectionChangedEventArgs e)
{
if (alreadySetting == false)
{
alreadySetting = true;
switch (unitsList.SelectedIndex)
{
case 2: // mm
XSiz.Minimum = 25;
XSiz.Maximum = 2500;
XSiz.Increment = 1;
YSiz.Minimum = 25;
YSiz.Maximum = 2500;
YSiz.Increment = 1;
break;
case 1: // cm
XSiz.Minimum = 2.5;
XSiz.Maximum = 250;
XSiz.Increment = 0.25;
YSiz.Minimum = 2.5;
YSiz.Maximum = 250;
YSiz.Increment = 0.25;
break;
case 0: // in
default:
XSiz.Minimum = 1;
XSiz.Maximum = 100;
XSiz.Increment = 0.1;
YSiz.Minimum = 1;
YSiz.Maximum = 100;
YSiz.Increment = 0.1;
break;
}
int i = presetsList2.SelectedIndex;
int offsetVal = (unitsList.SelectedIndex * 2);
if (i != 0)
{
int nIndex = i * 7;
if (xType != 0)
{
if (names3[nIndex + 1] == "-")
{
nIndex += 7;
presetsList2.SelectedIndex = i + 1;
}
XSiz.Text = names3[nIndex + 1 + offsetVal];
YSiz.Text = names3[nIndex + 2 + offsetVal];
}
}
else
{
double fX = double.Parse(XSiz.Text);
double fY = double.Parse(YSiz.Text);
double nX = ConvertDouble(fX, unitsType, unitsList.SelectedIndex);
double nY = ConvertDouble(fY, unitsType, unitsList.SelectedIndex);
XSiz.Text = nX.ToString();
YSiz.Text = nY.ToString();
}
alreadySetting = false;
}
unitsType = unitsList.SelectedIndex;
}
private double ConvertDouble(double originalNumber, int oldType, int newType)
{
double returnVal = 0;
// if old one was inches, convert from inches to cm, then if new one is mm, multiply by 10
if (oldType == 0)
{
if (newType == 2)
{
returnVal = originalNumber * 25.4;
}
else
{
returnVal = originalNumber * 2.54;
}
}
else if (oldType == 1)
{
if (newType == 2)
{
returnVal = originalNumber * 10;
}
else
{
returnVal = originalNumber / 2.54;
}
}
else // if (oldType == 2)
{
if (newType == 1)
{
returnVal = originalNumber / 10;
}
else
{
returnVal = originalNumber / 25.4;
}
}
return returnVal;
}
private void fitfillChanged(object sender, SelectionChangedEventArgs e)
{
}
private void CalcluatePixelsFromSizeAndDPI()
{
try
{
double xval = double.Parse(XDim.Text);
double yval = double.Parse(YDim.Text);
double xsval = double.Parse(XSiz.Text);
double ysval = double.Parse(YSiz.Text);
int dpival = int.Parse(DPI.Text);
double pixelsX;
double pixelsY;
if (unitsType == 0)
{
pixelsX = xsval * dpival;
pixelsY = ysval * dpival;
}
else if (unitsType == 1)
{
pixelsX = xsval * dpival / 2.54;
pixelsY = ysval * dpival / 2.54;
}
else
{
pixelsX = xsval * dpival / 25.4;
pixelsY = ysval * dpival / 25.4;
}
int xpix = (int)pixelsX;
int ypix = (int)pixelsY;
alreadySetting = true;
XDim.Text = xpix.ToString();
YDim.Text = ypix.ToString();
alreadySetting = false;
}
catch (Exception)
{ }
}
private void CalculateSizeFromPixelsAndDPI()
{
try
{
double xval = double.Parse(XDim.Text);
double yval = double.Parse(YDim.Text);
double xsval = double.Parse(XSiz.Text);
double ysval = double.Parse(YSiz.Text);
int dpival = int.Parse(DPI.Text);
double inchesX = xval / (double)dpival;
double inchesY = yval / (double)dpival;
if (unitsType == 0)
{
XSiz.Text = inchesX.ToString();
YSiz.Text = inchesY.ToString();
}
else if (unitsType == 1)
{
XSiz.Text = (inchesX * 2.54).ToString();
YSiz.Text = (inchesY * 2.54).ToString();
}
else
{
XSiz.Text = (inchesX * 25.4).ToString();
YSiz.Text = (inchesY * 25.4).ToString();
}
}
catch (Exception)
{
}
}
private void dimsChanged(object sender, TextChangedEventArgs e)
{
SetPreset();
}
private void dimsChanged2(object sender, RoutedPropertyChangedEventArgs<object> e)
{
SetPreset();
}
private void dimsChangedSiz(object sender, RoutedPropertyChangedEventArgs<object> e)
{
if (alreadySetting == false)
{
alreadySetting = true;
CalcluatePixelsFromSizeAndDPI();
SetPreset();
alreadySetting = false;
}
}
private void dimsChangedPix(object sender, RoutedPropertyChangedEventArgs<object> e)
{
if (alreadySetting == false)
{
alreadySetting = true;
CalculateSizeFromPixelsAndDPI();
SetPreset();
alreadySetting = false;
}
}
private void dimsChangedDPI(object sender, RoutedPropertyChangedEventArgs<object> e)
{
if (alreadySetting == false)
{
alreadySetting = true;
if (PhysicalSizeLabel.IsChecked == true) // work out the pixels from the physical size
CalcluatePixelsFromSizeAndDPI();
else if (PixelSizeLabel.IsChecked == true)
CalculateSizeFromPixelsAndDPI();
SetPreset();
alreadySetting = false;
}
}
private void borderCheckChanged(object sender, RoutedEventArgs e)
{
SetUIState();
}
private void watermarkCheckChanged(object sender, RoutedEventArgs e)
{
SetUIState();
}
private void watermarkImageCheckChanged(object sender, RoutedEventArgs e)
{
SetUIState();
}
private void vignetteCheckChanged(object sender, RoutedEventArgs e)
{
SetUIState();
}
private void resizeCheckChanged(object sender, RoutedEventArgs e)
{
SetUIState();
}
private void onFont(object sender, RoutedEventArgs e)
{
FontChooser fontChooser = new FontChooser();
fontChooser.Owner = this;
fontChooser.SetPropertiesFromObject(fontFace);
fontChooser.PreviewSampleText = Properties.Resources.WatermarkText;
fontChooser.SelectedFontSize = 32;
bool? retVal = fontChooser.ShowDialog();
if (retVal == true)
{
fontChooser.ApplyPropertiesToObject(fontFace);
fontFace.Text = fontChooser.SelectedFontFamily.ToString();
fontFace.FontSize = 20;
}
}
private void OnExpand(object sender, RoutedEventArgs e)
{
if (fontFamilyList.Visibility == Visibility.Hidden)
fontFamilyList.Visibility = Visibility.Visible;
else
fontFamilyList.Visibility = Visibility.Hidden;
}
private void BoldChecked(object sender, RoutedEventArgs e)
{
fontFace.FontWeight = FontWeights.Bold;
}
private void BoldUnchecked(object sender, RoutedEventArgs e)
{
fontFace.FontWeight = FontWeights.Normal;
}
private void ItalicChecked(object sender, RoutedEventArgs e)
{
fontFace.FontStyle = FontStyles.Italic;
}
private void ItalicUnchecked(object sender, RoutedEventArgs e)
{
fontFace.FontStyle = FontStyles.Normal;
}
private void ClickPrevious(object sender, RoutedEventArgs e)
{
if (currentProcessor > 0)
{
if (GetUIValues() == true)
{
if (renamedRecipe == true)
{
// delete originalRecipeName
RegHelper rh = new RegHelper();
rh.DeleteRecipe(originalRecipeName);
renamedRecipe = false;
}
ppLocal.WriteReg();
processors[currentProcessor].ResetUI();
currentProcessor--;
ppLocal = processors[currentProcessor].GetProcessorProperties();
originalRecipeName = ppLocal.recipeName;
SetUIItems();
SetNextPreviousState();
}
else
{
System.Windows.MessageBox.Show("One or more entries are invalid. Please check", "Pixel Robot Warning");
}
}
}
private void ClickNext(object sender, RoutedEventArgs e)
{
if (currentProcessor < (numProcessors - 1))
{
if (GetUIValues() == true)
{
if (renamedRecipe == true)
{
// delete originalRecipeName
RegHelper rh = new RegHelper();
rh.DeleteRecipe(originalRecipeName);
renamedRecipe = false;
}
ppLocal.WriteReg(); // write out (possibly with new name)
processors[currentProcessor].ResetUI();
currentProcessor++;
ppLocal = processors[currentProcessor].GetProcessorProperties();
originalRecipeName = ppLocal.recipeName;
SetUIItems();
SetNextPreviousState();
}
else
{
System.Windows.MessageBox.Show("One or more entries are invalid. Please check", "Pixel Robot Warning");
}
}
}
private void SetNextPreviousState()
{
if (xType == 127)
{
PreviousRecipe.IsEnabled = (currentProcessor > 0);
NextRecipe.IsEnabled = (currentProcessor < (numProcessors - 1));
}
else
{
NextRecipe.Visibility = Visibility.Hidden;
PreviousRecipe.Visibility = Visibility.Hidden;
}
}
private void OnClickBrowse(object sender, RoutedEventArgs e)
{
System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();
string currentFile = watermarkImageFile.Text;
if (File.Exists(currentFile))
{
FileInfo info = new FileInfo(currentFile);
dlg.InitialDirectory = info.DirectoryName;
}
else
dlg.InitialDirectory = @"C:\";
dlg.Title = Properties.Resources.WatermarkDlg;
dlg.FileName = watermarkImageFile.Text;
dlg.Filter = "PNG Files|*.png|JPEG Files|*.jpg";
dlg.AddExtension = true;
dlg.ShowDialog();
if (dlg.FileName != null)
{
if (dlg.FileName != "")
{
watermarkImageFile.Text = dlg.FileName;
}
}
}
private void WatermarkColourPicker_SelectedColorChanged(object sender, RoutedPropertyChangedEventArgs<Color> e)
{
SolidColorBrush sb = new SolidColorBrush(WatermarkColourPicker.SelectedColor);
fontFace.Foreground = sb;
}
private void onRename(object sender, RoutedEventArgs e)
{
EditName nn = new EditName();
nn.RecipeName = ppLocal.recipeName;
if (nn.ShowDialog() == true)
{
renamedRecipe = true;
ppLocal.recipeName = nn.RecipeName;
textBox_name.Text = ppLocal.recipeName;
if (xType >= 102)
{
Title = String.Format(Properties.Resources.ProcessRecipeName, ppLocal.recipeName);
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace Quokka.RISCV.Integration.Generator
{
public class TextReplacer
{
public static string ReplaceToken(
string content,
string token,
string replacement)
{
var modified = Regex.Replace(
content,
$"(// BEGIN {token})" + "(.*)" + $"(// END {token})",
$"$1{Environment.NewLine}{replacement}{Environment.NewLine}$3",
RegexOptions.Singleline);
return modified;
}
public string ReplaceToken(string hardwareTemplate, Dictionary<string, string> replacers)
{
// regex replace
foreach (var pair in replacers)
{
hardwareTemplate = ReplaceToken(hardwareTemplate, pair.Key, pair.Value);
}
// token replace
foreach (var pair in replacers)
{
var token = $"{{{pair.Key}}}";
hardwareTemplate = hardwareTemplate.Replace(token, pair.Value);
}
return hardwareTemplate;
}
}
}
|
namespace IdomOffice.Interface.BackOffice.PriceLists
{
public class SeasonUnitService
{
public string Id { get; set; }
public ServiceType ServiceType { get; set; }
public ServiceInterval ServiceInterval { get; set; }
public ServiceUnit ServiceUnit { get; set; }
public PaymentPlace PaymentPlace { get; set; }
public bool IsOptional { get; set; }
public string Description { get; set; }
public System.DateTime FromDate { get; set; }
public System.DateTime ToDate { get; set; }
public int OfOld { get; set; }
public int ToOld { get; set; }
public int OfDay { get; set; }
public int ToDay { get; set; }
public decimal Eur { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameOver : MonoBehaviour
{
[SerializeField] private SnakeHead _head;
[SerializeField] private GameObject _gameOverScreen;
private bool _isGameOver = false;
private void OnEnable()
{
_head.Died += OnDied;
}
private void OnDisable()
{
_head.Died -= OnDied;
}
private void OnDied()
{
_gameOverScreen.SetActive(true);
Time.timeScale = 0;
_isGameOver = true;
}
private void Update()
{
if (Input.anyKeyDown && _isGameOver)
{
_isGameOver = false;
SceneManager.LoadScene(0);
Time.timeScale = 1;
}
}
}
|
//using Microsoft.VisualStudio.TestTools.UnitTesting;
//[assembly: Parallelize(Workers = 2, Scope = ExecutionScope.ClassLevel)]
using NUnit.Framework;
[assembly: Parallelizable(ParallelScope.Fixtures)] |
using System;
class DivideBySevenAndFive
{
static void Main()
{
Console.WriteLine("Infinite loop. If you want to stop, pres CTRL+C !!!");
while (true)
{
int liNumber;
bool lbDivided;
Console.Write("Enter a integer number : ");
if (int.TryParse(Console.ReadLine(), out liNumber))
{
if ((liNumber % 7 == 0) && (liNumber % 5 == 0) && (liNumber != 0))
{
lbDivided = true;
}
else
{
lbDivided = false;
}
Console.WriteLine("is the number {0} divided by 7 and 5? {1}", liNumber, lbDivided);
}
else
{
Console.WriteLine("Only a integer number");
}
}
}
} |
using Compent.Shared.Search.Contract;
using System.Collections.Generic;
using System.Linq;
using Uintra.Core.Search.Entities;
namespace Uintra.Core.Search.Queries
{
public class SearchByTextQuery : UBaseline.Search.Core.SearchByTextQuery//, ISearchQuery<SearchDocument>
{
public string OrderingString { get; set; }
public IEnumerable<int> SearchableTypeIds { get; set; } = Enumerable.Empty<int>();
public bool OnlyPinned { get; set; }
}
} |
using Domain.Entities;
using Infrastructure.Base;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using System;
using System.Linq;
namespace Infrastructure.Test
{
public class CreditoTests
{
UnitOfWork UnitOfWork;
CreditoContext Context;
[SetUp]
public void Setup()
{
var options = new DbContextOptionsBuilder<CreditoContext>().UseSqlServer("Server=localhost;Database=AcmeLtda;Trusted_Connection=True;MultipleActiveResultSets=true").Options;
Context = new CreditoContext(options);
UnitOfWork = new UnitOfWork(Context);
}
[Test]
public void ConsultarCredito()
{
Credito credito = UnitOfWork.CreditoRepository.FindBy(x => x.Id == 1, includeProperties: "Cuotas").FirstOrDefault();
var cuotas = UnitOfWork.CuotaRepository.FindBy(x => x.CreditoId == credito.Id).ToList();
Assert.AreEqual(credito.Cuotas, cuotas);
}
}
} |
using System;
using Vlc.DotNet.Core.Interops.Signatures;
namespace Vlc.DotNet.Core
{
public sealed partial class VlcMediaPlayer
{
private EventCallback myOnMediaPlayerBackwardInternalEventCallback;
public event EventHandler<VlcMediaPlayerBackwardEventArgs> Backward;
private void OnMediaPlayerBackwardInternal(IntPtr ptr)
{
OnMediaPlayerBackward();
}
public void OnMediaPlayerBackward()
{
var del = Backward;
if (del != null)
del(this, new VlcMediaPlayerBackwardEventArgs());
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ReportToPdfConverter.Utility
{
public class ReportCriteriaValue
{
public string ParameterName { get; set; }
public string ParameterValue { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
namespace Kingdee.CAPP.Solidworks.RoutingPlugIn
{
/// <summary>
/// Routing object Context
/// </summary>
public class RoutingContext : DataContext
{
public RoutingContext(string connection) : base(connection) { }
public Table<Routing> Routings;
public Table<ProcessFileRouting> ProcessFileRoutinges;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ClickToCircle : MonoBehaviour
{
public GameObject normalCircle;
public GameObject bigCircle;
public GameObject followingSlider;
public GameObject particles;
public Vector3 initialScale;
public float timeToClose = 2f;
public float timer = 0;
public int alertPoints;
public int perfect = 90;
public int good = 60;
public int careful = 30;
public int fail = 0;
public bool clicked = false;
public bool done;
void Start()
{
initialScale = bigCircle.transform.localScale;
}
void Update()
{
if (clicked) return;
timer += Time.deltaTime;
timer = Mathf.Clamp(timer, 0, timeToClose);
bigCircle.transform.localScale = Vector3.Lerp(initialScale, normalCircle.transform.localScale, timer / timeToClose);
if (timer == timeToClose)
{
timer = 0;
bigCircle.transform.localScale = initialScale;
}
}
private void OnMouseDown()
{
if (clicked) return;
clicked = true;
float score = (timer / timeToClose) * 100;
if (score >= perfect)
{
}
else if (score >= good)
{
AlertIndicator.instance.AddAlertPoints(alertPoints * (1 - (timer / timeToClose)));
}
else if (score >= careful)
{
AlertIndicator.instance.AddAlertPoints(alertPoints * (1 - (timer / timeToClose)));
}
else
{
AlertIndicator.instance.AddAlertPoints(alertPoints);
}
done = true;
if (followingSlider != null) followingSlider.SetActive(true);
if (particles != null) Instantiate(particles, transform.localPosition, Quaternion.identity);
gameObject.SetActive(false);
}
}
|
using System;
namespace TY.SPIMS.POCOs
{
public class PurchaseDetailViewModel
{
public int AutoPartDetailId { get; set; }
public string AutoPartNumber { get; set; }
public string AutoPartName { get; set; }
public int Quantity { get; set; }
public string Unit { get; set; }
public decimal UnitPrice { get; set; }
public decimal DiscountPercent { get; set; }
public decimal DiscountPercent2 { get; set; }
public decimal DiscountPercent3 { get; set; }
public decimal DiscountedPrice { get; set; }
public decimal DiscountedPrice2 { get; set; }
public decimal DiscountedPrice3 { get; set; }
public string DiscountPercents { get; set; }
public decimal TotalDiscount { get; set; }
public decimal TotalAmount { get; set; }
public string InvoiceNumber { get; set; }
public string Supplier { get; set; }
public DateTime? PurchaseDate { get; set; }
}
}
|
using System.Threading.Tasks;
using Welic.App.Services.ServicesViewModels;
namespace Welic.App.Services.ServiceViews
{
public class MessageServices : IMessageService
{
public async Task ShowOkAsync(string Message)
{
await App.Current.MainPage.DisplayAlert("Welic", Message, "OK");
}
public async Task<bool> ShowOkAsync(string title, string Message, string ok, string cancel)
{
return await App.Current.MainPage.DisplayAlert(title, Message, ok, cancel);
}
public async Task ShowOkAsync(string title, string Message, string ok)
{
await App.Current.MainPage.DisplayAlert(title, Message, ok);
}
public MessageServices()
{
}
}
}
|
using System;
using System.Linq;
namespace task6_Rectangle_Position
{
public class task6_Rectangle_Position
{
public static void Main()
{
var rec1 = ReadRectangle();
var rec2 = ReadRectangle();
Console.WriteLine(IsInside(rec1, rec2) ? "Inside": "Not Inside");
}
public static Rectangle ReadRectangle()
{
var input = Console.ReadLine().Split().Select(int.Parse).ToArray();
var rec = new Rectangle() { Top = input[0], Left = input[1], Width= input[2], Height= input[3] } ;
return rec;
}
public static bool IsInside(Rectangle rec1, Rectangle rec2)
{
bool isInsideRec = false;
if (rec1.Left <= rec2.Left && rec1.Right <= rec2.Right && rec1.Top >= rec2.Top && rec1.Bottom <= rec2.Bottom)
{
isInsideRec = true;
}
return isInsideRec;
}
}
}
|
using System.Diagnostics;
namespace EPI.BinaryTree
{
[DebuggerDisplay("Value = {Value}")]
public class BinaryTreeNode<T>
{
private T value;
private BinaryTreeNode<T> left;
private BinaryTreeNode<T> right;
private BinaryTreeNode<T> parent;
public BinaryTreeNode(T val)
{
value = val;
left = null;
right = null;
parent = null;
}
public T Value
{
get
{
return value;
}
}
public BinaryTreeNode<T> Left
{
get
{
return left;
}
set
{
left = value;
if (left != null)
{
left.Parent = this;
}
}
}
public BinaryTreeNode<T> Right
{
get
{
return right;
}
set
{
right = value;
if (right != null)
{
right.Parent = this;
}
}
}
public BinaryTreeNode<T> Parent
{
get
{
return parent;
}
set
{
parent = value;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml;
using System.Xml.Serialization;
/// <summary>
/// Created by Anders Bolin AB2633 datum: 2013-06-02 email: anders@bolin.nu
/// Eget Project i Programmering i .NET: Fortsättningskurs
/// </summary>
namespace InstaControlLibrary.Vagnar
{
[Serializable]
public class UA2 : X2000
{
//Declaring variables
public int m_place1dust, m_place2dust, m_place3dust, m_placeToiletdust;
public int m_place1spots, m_place2spots, m_place3spots, m_placeToiletspots;
public int m_place1garbage, m_place2garbage, m_place3garbage, m_placeToiletgarbage;
public string m_placeExtraName = "", trainnumber;
public bool test = false;
//Public constructor
public UA2()
{
}
public string TrainNumber
{
get { return trainnumber; }
set { trainnumber = value; }
}
//Position 1
public int place1Dust
{
get { return m_place1dust; }
set { m_place1dust = value; }
}
public int place1Spots
{
get { return m_place1spots; }
set { m_place1spots = value; }
}
public int place1Garbage
{
get { return m_place1garbage; }
set { m_place1garbage = value; }
}
//Position 2
public int place2Dust
{
get { return m_place2dust; }
set { m_place2dust = value; }
}
public int place2Spots
{
get { return m_place2spots; }
set { m_place2spots = value; }
}
public int place2Garbage
{
get { return m_place2garbage; }
set { m_place2garbage = value; }
}
//Position 3
public int place3Dust
{
get { return m_place3dust; }
set { m_place3dust = value; }
}
public int place3Spots
{
get { return m_place3spots; }
set { m_place3spots = value; }
}
public int place3Garbage
{
get { return m_place3garbage; }
set { m_place3garbage = value; }
}
//Position Extra
public int placeExtraDust
{
get { return m_placeToiletdust; }
set { m_placeToiletdust = value; }
}
public int placeExtraSpots
{
get { return m_placeToiletspots; }
set { m_placeToiletspots = value; }
}
public int placeExtraGarbage
{
get { return m_placeToiletgarbage; }
set { m_placeToiletgarbage = value; }
}
public String placeExtraName
{
get { return m_placeExtraName; }
set { m_placeExtraName = value; }
}
public override String getWagonSpecificResults()
{
int tally = place1Dust + place1Garbage + place1Spots + place2Dust + place2Garbage + place2Spots +
place3Dust + m_place3garbage + place3Spots + placeExtraDust + placeExtraGarbage + placeExtraSpots;
Console.WriteLine("UA2 tally= " + tally);
if(tally <= 12) { test = true; }
String result = (test ? " Godkänd" : " Ej Godkänd");
string strout = string.Format("{0,-5}{1,9}{2,15}{3,23}\n", wagNum, TrainNumber, wagTyp.ToString(), result);
return strout;
}
}
}
|
using Generics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Generics
{
class Program
{
static void Main(string[] args)
{
Apple apple1 = new Apple(Colour.Green);
Apple apple2 = new Apple(Colour.Red);
Apple apple3 = new Apple(Colour.Green);
var appleCounter = new Counter<Apple>();
var redAppleCounter = new Counter<Apple>(a => a.Colour.Equals(Colour.Red));
appleCounter.Add(apple1);
appleCounter.Add(apple2);
appleCounter.Add(apple3);
redAppleCounter.Add(apple1);
redAppleCounter.Add(apple2);
redAppleCounter.Add(apple3);
Console.WriteLine("Apple Count {0}", appleCounter.Count());
Console.WriteLine("Red Apple Count {0}", redAppleCounter.Count());
Box box1 = new Box();
T t1 = new T();
T t2 = new T();
box1.Add(t1);
box1.Add(t2);
Console.WriteLine("Box1 contains {0} items", box1.Count);
Box box2 = new Box();
T t3 = new T();
T t4 = new T();
T t5 = new T();
box2.Add(t3);
box2.Add(t4);
box2.Add(t5); ;
Console.WriteLine("Box2 contains {0} items", box2.Count);
Cart cart = new Cart();
cart.Add(box1);
cart.Add(box2);
Console.WriteLine("Cart contains {0} items", cart.Count);
Console.ReadLine();
}
}
}
|
using ComInLan.Model.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComInLan.Model.Protocol
{
public class ServerProtocol : Json, IServerProtocol
{
public ServerMessage Message { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XH.Infrastructure.Configurations;
namespace XH.Infrastructure.Storage
{
public class BlobConnectionString : IConfiguration
{
public BlobConnectionString()
{
}
public string Provider { get; set; }
/// <summary>
/// Chroot path. Base for blob resources
/// </summary>
public string RootPath { get; set; }
/// <summary>
/// Blob public base url which blobs can be gets
/// </summary>
public string PublicUrl { get; set; }
/// <summary>
/// Rest part of connection string without Provider, RootPath and PublicUrl parameters
/// </summary>
public string ConnectionString { get; set; }
public static BlobConnectionString Parse(string inputString)
{
var retVal = new BlobConnectionString();
var pairs = ToDictionary(inputString, ";", "=");
if (pairs.ContainsKey("provider"))
{
retVal.Provider = pairs["provider"];
pairs.Remove("provider");
}
if (pairs.ContainsKey("rootPath"))
{
retVal.RootPath = pairs["rootPath"];
pairs.Remove("rootPath");
}
if (pairs.ContainsKey("publicUrl"))
{
retVal.PublicUrl = pairs["publicUrl"];
pairs.Remove("publicUrl");
}
retVal.ConnectionString = ToString(pairs, ";", "=");
return retVal;
}
private static Dictionary<string, string> ToDictionary(string sourceString, string pairSeparator, string valueSeparator)
{
return sourceString.Split(new[] { pairSeparator }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Split(new[] { valueSeparator }, 2, StringSplitOptions.RemoveEmptyEntries))
.ToDictionary(x => x[0], x => x.Length == 2 ? x[1] : string.Empty, StringComparer.OrdinalIgnoreCase);
}
public static string ToString(IEnumerable<KeyValuePair<string, string>> pairs, string pairSeparator, string valueSeparator)
{
var builder = new StringBuilder();
foreach (var pair in pairs)
{
if (builder.Length > 0)
{
builder.Append(pairSeparator);
}
builder.Append(pair.Key);
builder.Append(valueSeparator);
builder.Append(pair.Value);
}
return builder.ToString();
}
public bool IsValid()
{
return true;
}
}
}
|
using System;
using System.Linq;
using Tools;
namespace _243
{
class Program
{
private static int TotientFunc(int num)
{
var primeFactors = NumUtils.ComputePrimeFactorization_Cached(num);
long res = num;
foreach (var primeFactor in primeFactors)
{
res *= primeFactor.Key - 1;
res /= primeFactor.Key;
}
return (int)res;
}
static void Main(string[] args)
{
Decorators.Benchmark(Solve, 15499 / 94744.0);
}
private static int[] _smallPrimes;
static int Solve(double desiredRatio)
{
NumUtils.ResetPrimesCache();
_smallPrimes = NumUtils.EratospheneSeive(100).ToArray();
int approximation = 1;
for (int i = 0; i < _smallPrimes.Length; i++)
{
approximation *= _smallPrimes[i];
double ratio = TotientFunc(approximation) / (double)(approximation - 1);
if (Math.Abs(ratio - desiredRatio) < desiredRatio / 10)
{
if (ratio < desiredRatio)
{
approximation /= _smallPrimes[i];
}
break;
}
}
for (int i = approximation; i < int.MaxValue; i += approximation)
{
double ratio = TotientFunc(i) / (double)(i - 1);
if (ratio < desiredRatio)
{
return i;
}
}
return 0;
}
}
}
|
/// <summary>
/// Summary description for SNRuleController
/// </summary>
namespace com.Sconit.Web.Controllers.SYS
{
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using com.Sconit.Entity.SYS;
using com.Sconit.Service;
using com.Sconit.Web.Models;
using com.Sconit.Web.Models.SearchModels.SYS;
using com.Sconit.Utility;
using Telerik.Web.Mvc;
using System;
/// <summary>
/// This controller response to control the EntityPreference.
/// </summary>
public class SNRuleController : WebAppBaseController
{
#region Properties
/// <summary>
/// Gets or sets the this.GeneMgr which main consider the EntityPreference security
/// </summary>
//public IGenericMgr genericMgr { get; set; }
/// <summary>
/// Gets or sets the this.SystemMgr which main consider the EntityPreference security
/// </summary>
//public ISystemMgr systemMgr { get; set; }
#endregion
/// <summary>
/// hql to get count of the Item
/// </summary>
private static string selectCountStatement = "select count(*) from SNRule as s";
/// <summary>
/// hql to get all of the Item
/// </summary>
private static string selectStatement = "select s from SNRule as s";
private static string selectSNRuleExtStatement = "select s from SNRuleExt as s where s.Code = ?";
/// <summary>
/// hql to get count of the SNRule by SNRule's code
/// </summary>
//private static string duiplicateVerifyStatement = @"select count(*) from SNRule as u where u.Code = ?";
#region public actions
/// <summary>
/// Index action for SNRule controller
/// </summary>
/// <returns>Index view</returns>
//[SconitAuthorize(Permission = "Url_SNRule_View")]
public ActionResult Index()
{
return View();
}
public ActionResult ChooseSNRuleBlock(string id)
{
SNRule snRule = this.genericMgr.FindById<SNRule>(int.Parse(id));
ViewBag.BlockSeq = snRule.BlockSeq;
ViewBag.Id = id;
return PartialView();
}
[HttpPost]
public ActionResult ChooseSNRuleBlock(string Code, bool YearCode, bool MonthCode, bool DayCode, bool SequnceNum, bool FiledRef)
{
IList<char> ChoosedBlockList = new List<char>();
IList<char> UnChoosedBlockList = new List<char>();
//BlockList.Add(FixCode);
if (YearCode)
{
ChoosedBlockList.Add('2');
}
else
{
UnChoosedBlockList.Add('2');
}
if (MonthCode)
{
ChoosedBlockList.Add('3');
}
else
{
UnChoosedBlockList.Add('3');
}
if (DayCode)
{
ChoosedBlockList.Add('4');
}
else
{
UnChoosedBlockList.Add('4');
}
if (FiledRef)
{
ChoosedBlockList.Add('6');
}
else
{
UnChoosedBlockList.Add('6');
}
if (SequnceNum)
{
ChoosedBlockList.Add('5');
}
else
{
UnChoosedBlockList.Add('5');
}
TempData["ChoosedBlockList"] = ChoosedBlockList;
TempData["UnChoosedBlockList"] = UnChoosedBlockList;
//return RedirectToAction("Edit", new { id = Code, blockList = BlockList });
return RedirectToAction("Edit/" + Code);
//return View("New");
}
/// <summary>
/// List action
/// </summary>
/// <param name="command">Telerik GridCommand</param>
/// <param name="searchModel">SNRule Search model</param>
/// <returns>return the result view</returns>
[GridAction(EnableCustomBinding = true)]
//[SconitAuthorize(Permission = "Url_SNRule_View")]
public ActionResult List(GridCommand command, SNRuleSearchModel searchModel)
{
SearchCacheModel searchCacheModel = this.ProcessSearchModel(command, searchModel);
if (searchCacheModel.isBack == true)
{
ViewBag.Page = searchCacheModel.Command.Page==0 ? 1 : searchCacheModel.Command.Page;
}
ViewBag.PageSize = base.ProcessPageSize(command.PageSize);
return View();
}
/// <summary>
/// AjaxList action
/// </summary>
/// <param name="command">Telerik GridCommand</param>
/// <param name="searchModel">SNRule Search Model</param>
/// <returns>return the result action</returns>
[GridAction(EnableCustomBinding = true)]
//[SconitAuthorize(Permission = "Url_SNRule_View")]
public ActionResult _AjaxList(GridCommand command, SNRuleSearchModel searchModel)
{
string replaceFrom = "_AjaxList";
string replaceTo = "List";
this.GetCommand(ref command, searchModel, replaceFrom, replaceTo);
SearchStatementModel searchStatementModel = this.PrepareSearchStatement(command, searchModel);
return PartialView(GetAjaxPageData<SNRule>(searchStatementModel, command));
}
/// <summary>
/// Edit view
/// </summary>
/// <param name="id">SNRule id for edit</param>
/// <returns>return the result view</returns>
[HttpGet]
// [SconitAuthorize(Permission = "Url_SNRule_Edit")]
public ActionResult Edit(string id)
{
string addedItems = "";
string removedItems = "";
if (string.IsNullOrEmpty(id))
{
return HttpNotFound();
}
else
{
IList<char> ChoosedBlockList = (IList<char>)TempData["ChoosedBlockList"];
IList<char> UnChoosedBlockList = (IList<char>)TempData["UnChoosedBlockList"];
SNRule snRule = this.genericMgr.FindById<SNRule>(int.Parse(id));
foreach (var item in ChoosedBlockList)
{
if (!snRule.BlockSeq.Contains(item))
{
addedItems = addedItems + item.ToString();
}
}
foreach (var item in UnChoosedBlockList)
{
if (snRule.BlockSeq.Contains(item))
{
removedItems = removedItems + item.ToString();
}
}
TempData["ChoosedBlockList"] = ChoosedBlockList;
TempData["UnChoosedBlockList"] = UnChoosedBlockList;
ViewBag.AddedItems = addedItems;
ViewBag.RemovedItems = removedItems;
return PartialView(snRule);
}
}
/// <summary>
/// Edit view
/// </summary>
/// <param name="SNRule">SNRule Model</param>
/// <returns>return the result view</returns>
[HttpPost]
//[SconitAuthorize(Permission = "Url_SNRule_Edit")]
public ActionResult Edit(string Code, string YearCode, string MonthCode, string DayCode, string SeqLength,string BlockSeq)
{
SNRule snRule = this.genericMgr.FindById<SNRule>(int.Parse(Code));
snRule.YearCode = YearCode;
snRule.MonthCode = MonthCode;
snRule.DayCode = DayCode;
snRule.SeqLength = Int16.Parse(SeqLength);
snRule.BlockSeq = BlockSeq;
this.genericMgr.Update(snRule);
return RedirectToAction("List");
}
/// <summary>
/// Delete action
/// </summary>
/// <param name="id">SNRule id for delete</param>
/// <returns>return to List action</returns>
//[SconitAuthorize(Permission = "Url_SNRule_Delete")]
public ActionResult Delete(string id)
{
if (string.IsNullOrEmpty(id))
{
return HttpNotFound();
}
else
{
this.genericMgr.DeleteById<SNRule>(int.Parse(id));
SaveSuccessMessage("deleted success");
return RedirectToAction("List");
}
}
[HttpGet]
public ActionResult ExtRuleEdit(string Id)
{
string ChoosedBlocks = "";
string UnChoosedBlocks = "";
foreach (var item in (IList<char>)TempData["ChoosedBlockList"])
{
ChoosedBlocks = ChoosedBlocks + item.ToString();
}
foreach (var item in (IList<char>)TempData["UnChoosedBlockList"])
{
UnChoosedBlocks = UnChoosedBlocks + item.ToString();
}
IList<SNRuleExt> snRuleExtList = new List<SNRuleExt>();
snRuleExtList = this.genericMgr.FindAll<SNRuleExt>(selectSNRuleExtStatement, int.Parse(Id));
snRuleExtList = snRuleExtList.OrderByDescending(i => i.IsChoosed).ThenBy(i=>i.FieldSeq).ToList();
//snRuleExtList = snRuleExtList.OrderBy(i => i.FieldSeq).ToList();
ViewBag.ChoosedBlocks = ChoosedBlocks;
ViewBag.UnChoosedBlocks = UnChoosedBlocks;
return PartialView(snRuleExtList);
}
[HttpPost]
public ActionResult ExtRuleEdit(string Code, string SelectedValue, string UnSelectedValue, string ChoosedBlocks, string UnChoosedBlocks)
{
IList<char> ChoosedBlockList = new List<char>();
IList<char> UnChoosedBlockList = new List<char>();
for (int i = 0; i < ChoosedBlocks.Length; i++)
{
ChoosedBlockList.Add(char.Parse(ChoosedBlocks.Substring(0,1)));
ChoosedBlocks = ChoosedBlocks.Substring(1, ChoosedBlocks.Length - 1);
}
for (int i = 0; i < UnChoosedBlocks.Length; i++)
{
UnChoosedBlockList.Add(char.Parse(UnChoosedBlocks.Substring(0, 1)));
UnChoosedBlocks = UnChoosedBlocks.Substring(1, UnChoosedBlocks.Length - 1);
}
string[] choosedIds = SelectedValue.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
string[] unChoosedIds = UnSelectedValue.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < choosedIds.Length; ++i)
{
UpdateChoosedSNRuleExt(i+1,int.Parse(choosedIds[i]));
}
for (int i = 0; i < unChoosedIds.Length; ++i)
{
UpdateUnChoosedSNRuleExt(int.Parse(unChoosedIds[i]));
}
TempData["ChoosedBlockList"] = ChoosedBlockList;
TempData["UnChoosedBlockList"] = UnChoosedBlockList;
return RedirectToAction("Edit/" + Code);
////IList<SNRuleExt> snRuleExtList = new List<SNRuleExt>();
////snRuleExtList = this.genericMgr.FindAll<SNRuleExt>(selectSNRuleExtStatement, Id);
////return PartialView(snRuleExtList);
}
#endregion
private void UpdateChoosedSNRuleExt(int FieldSeq,int Id)
{
SNRuleExt snRuleExt = new SNRuleExt();
snRuleExt = this.genericMgr.FindById<SNRuleExt>(Id);
snRuleExt.FieldSeq = FieldSeq;
snRuleExt.IsChoosed = true;
this.genericMgr.Update(snRuleExt);
}
private void UpdateUnChoosedSNRuleExt(int Id)
{
SNRuleExt snRuleExt = new SNRuleExt();
snRuleExt = this.genericMgr.FindById<SNRuleExt>(Id);
snRuleExt.FieldSeq = 1000;
snRuleExt.IsChoosed = false;
this.genericMgr.Update(snRuleExt);
}
/// <summary>
/// Search Statement
/// </summary>
/// <param name="command">Telerik GridCommand</param>
/// <param name="searchModel">SNRule Search Model</param>
/// <returns>return SNRule search model</returns>
private SearchStatementModel PrepareSearchStatement(GridCommand command, SNRuleSearchModel searchModel)
{
string whereStatement = string.Empty;
IList<object> param = new List<object>();
HqlStatementHelper.AddEqStatement("Code", searchModel.Code, "s", ref whereStatement, param);
//HqlStatementHelper.AddLikeStatement("SNRuleContent", searchModel.SNRuleContent, HqlStatementHelper.LikeMatchMode.Anywhere, "u", ref whereStatement, param);
//HqlStatementHelper.AddLikeStatement("PostCode", searchModel.PostCode, HqlStatementHelper.LikeMatchMode.Anywhere, "u", ref whereStatement, param);
//HqlStatementHelper.AddLikeStatement("TelPhone", searchModel.TelPhone, HqlStatementHelper.LikeMatchMode.Anywhere, "u", ref whereStatement, param);
//HqlStatementHelper.AddLikeStatement("MobilePhone", searchModel.MobilePhone, HqlStatementHelper.LikeMatchMode.Anywhere, "u", ref whereStatement, param);
//HqlStatementHelper.AddLikeStatement("Fax", searchModel.Fax, HqlStatementHelper.LikeMatchMode.Anywhere, "u", ref whereStatement, param);
//HqlStatementHelper.AddLikeStatement("Email", searchModel.Email, HqlStatementHelper.LikeMatchMode.Anywhere, "u", ref whereStatement, param);
//HqlStatementHelper.AddLikeStatement("ContactPersonName", searchModel.ContactPersonName, HqlStatementHelper.LikeMatchMode.Anywhere, "u", ref whereStatement, param);
//HqlStatementHelper.AddEqStatement("Type", searchModel.Type, "u", ref whereStatement, param);
if (command.SortDescriptors.Count > 0)
{
if (command.SortDescriptors[0].Member == "DocumentsTypeDescription")
{
command.SortDescriptors[0].Member = "Code";
}
}
string sortingStatement = HqlStatementHelper.GetSortingStatement(command.SortDescriptors);
SearchStatementModel searchStatementModel = new SearchStatementModel();
searchStatementModel.SelectCountStatement = selectCountStatement;
searchStatementModel.SelectStatement = selectStatement;
searchStatementModel.WhereStatement = whereStatement;
searchStatementModel.SortingStatement = sortingStatement;
searchStatementModel.Parameters = param.ToArray<object>();
return searchStatementModel;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using MoneyShare.Models;
namespace MoneyShare.Repos
{
public class EmailService : IEmailService
{
IConfiguration _configuration;
private SmtpClient _client;
public EmailService(IConfiguration configuration)
{
_configuration = configuration;
_client = new SmtpClient(_configuration["Email:Host"], Convert.ToInt32(_configuration["Email:Port"]));
_client.Credentials = new NetworkCredential(_configuration["Email:Username"], _configuration["Email:Password"]);
_client.EnableSsl = true;
}
public void EmailTwoFactorCode(MemberModel member)
{
string message = $"Hello {member.LastName}, {member.FirstName}\nYour 2FA code is: {member.TwoFactorCode}";
SendEmailAsync(member.Email, "Authentication code", message);
}
public void EmailForgotPassword(MemberModel member, String link)
{
string message = $"Hello {member.LastName}, {member.FirstName}\nClick the follwing link to reset your password: {link}";
SendEmailAsync(member.Email, "Reset password", message);
}
public Task SendEmailAsync(string recipient, string subject, string message)
{
using (MailMessage mailMessage = new MailMessage(_configuration["Email:From"], recipient, subject, message))
{
try
{
_client.Send(mailMessage);
}
catch (Exception ex)
{
Console.WriteLine("Failed to send email: {0}", ex.ToString());
}
}
return null;
}
}
} |
using Model.Models;
using System.Configuration;
using Mailer;
using Mailer.Model;
using System.Threading.Tasks;
namespace EmailContents
{
public class RegistrationInvitaionEmail
{
public async Task SendUserRegistrationInvitation(string UserId, int ApplicationId, string RefereeId, string ReferralId, string UserType, string CC)
{
EmailMessage message = new EmailMessage();
message.Subject = "Invitation for registration";
//string temp = (ConfigurationManager.AppSettings["SalesManager"]);
string domain = ConfigurationManager.AppSettings["LoginDomain"];
message.To = UserId;
string link = domain + "/Account/Register?uid=" + UserId + "&aid=" + ApplicationId + "&rfeid=" + RefereeId + "&rflid=" + ReferralId + "&utype=" + UserType;
SaleOrderHeader doc = new SaleOrderHeader();
message.Body += "Please use the link to register to the company. <a href='" + link + "' target='_blank'> Click Here </a>";
if (!string.IsNullOrEmpty(CC))
message.CC = CC;
SendEmail se = new SendEmail();
await se.configSendGridasync(message);
}
}
}
|
using System;
using System.Collections.Generic;
#nullable disable
namespace rent_a_car
{
public partial class User
{
public User()
{
Logins = new HashSet<Login>();
}
public int Id { get; set; }
public int Password { get; set; }
public string Ad { get; set; }
public string Soyad { get; set; }
public string Email { get; set; }
public string KisiTuru { get; set; }
public virtual Admin Admin { get; set; }
public virtual Personel Personel { get; set; }
public virtual ICollection<Login> Logins { get; set; }
}
}
|
using System.Collections.Generic;
using UnityEngine;
namespace Events
{
public class GameEvent { }
public enum countertype
{
inittimer = 0,
sessiontimer = 1,
}
public enum characterid
{
player = 0,
enemy = 1,
}
public enum animation
{
none = 0,
idle = 1,
play = 2,
special = 3,
}
public class StartTimerEvent : GameEvent {
public float totalseconds;
public int countertype;
}
public class UpdateTimerEvent : GameEvent {
public float currentseconds;
public int countertype;
}
public class FinishTimerEvent : GameEvent {
public int countertype;
}
public class CounterStatusEvent : GameEvent {
public int counterstatus;
}
public class BattleStartedEvent : GameEvent
{
public int playerhp;
public int playersp;
public int playerinitsp;
public int playerinithp;
public int enemyhp;
public int enemysp;
public int enemyinitsp;
public int enemyinithp;
public int buffqty;
public int healqty;
public int specialcost;
}
public class EnableTurnEvent : GameEvent {
public int characterid;
public int turnstate;
}
public class ActionEvent : GameEvent
{
public int action; //0 attack
//1 defend
//2 special
//3 item
//4 buff
//5 heal
public int damage;
public int item; //0 buff
//1 heal
public float buff;
public int characterid;
}
public class SelectActionEvent : GameEvent
{
public int characterid;
public int action; //0 attack
//1 defend
//2 special
//3 item
}
public class GameOverEvent : GameEvent {
public bool playerwin;
}
public class QteHitEvent : GameEvent {
public bool success;
public int color; //0 Blue, 1 Red, 2 Yellow, 3 Green
}
public class QteLeaveEvent : GameEvent
{
public int qtenoteleave;
}
public class QtePrizeEvent : GameEvent {
public int prizeSP;
public float prizeMultiplier;
public int prizeHP;
public int prizeDamage;
public bool playerturn;
public float effic;
}
public class QtePlayEvent : GameEvent {
public int noteamount;
}
public class QteMissEvent : GameEvent
{
public bool enableinput;
public int color; //0 Blue, 1 Red, 2 Yellow, 3 Green
}
public class AnimEvent : GameEvent
{
public bool playerturn;
public bool camshake;
public int animation;
public bool dontshowUI;
public bool animstate;
public bool choosestate;
public Vector3 modelposition;
}
///////////////WORLD MAP EVENTS//////////////////
public class CollectEvent : GameEvent
{
}
public class DialogueEvent : GameEvent
{
public bool talking;
public Dialogue dialogue;
public bool isshop;
}
public class DialogueStatusEvent : GameEvent
{
public bool dialogueactive;
}
public class BuyEvent : GameEvent
{
public bool isheal;
public int price;
}
public class BeforeSceneUnloadEvent : GameEvent
{
}
public class AfterSceneLoadEvent : GameEvent
{
}
public class ExpandBoundariesEvent : GameEvent
{
public int currentarea;
}
public class QuitGameEvent : GameEvent
{
}
public class PayMoneyEvent : GameEvent
{
public int moneypaid;
}
//PONG EVENTS
public class ScoreEvent : GameEvent
{
public int playerId;
public int scoreData;
public Vector3 playerPosition;
}
public class HitEvent : GameEvent
{
public int playerId;
}
public class WaitEvent : GameEvent
{
public bool waiting;
public KeyCode startKey;
}
public class GameStartEvent : GameEvent
{
public KeyCode startKey;
public int highscore;
}
public class GameOverPongEvent : GameEvent
{
public int playerId;
public KeyCode reloadkey;
public int p1score;
public int p2score;
}
//Inventory Events
public class UseItemEvent : GameEvent
{
public Item item;
}
public class ObtainItemEvent : GameEvent
{
public Item item;
public GameObject rotatingItem;
public bool showMessage;
}
public class LoadEnemyEvent : GameEvent
{
public Enemy_Template enemyTemplate;
public GameObject enemyGameObject;
}
}
|
using gView.Data.Framework.Data.Extensions;
using gView.Framework.Geometry;
using gView.Framework.system;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace gView.Framework.Data.Filters
{
public class QueryFilter : UserData, IQueryFilter, IClone
{
protected List<string> m_fields;
protected Dictionary<string, string> m_alias;
protected string m_whereClause = String.Empty, m_whereClause2 = String.Empty, m_orderBy = "";
protected int m_beginrecord;
protected int m_featureCount;
protected bool m_hasmore, m_nolock = false;
protected string m_fieldPrefix = "", m_fieldPostfix = "";
protected ISpatialReference _featureSRef = null;
public QueryFilter()
{
m_fields = new List<string>();
m_alias = new Dictionary<string, string>();
m_beginrecord = 1;
m_featureCount = 0;
m_hasmore = m_nolock = false;
this.Limit = 0;
this.IgnoreUndefinedFields = false;
}
public QueryFilter(IQueryFilter filter)
: this()
{
if (filter == null)
{
return;
}
string fieldPrefix = filter.fieldPrefix;
string fieldPostfix = filter.fieldPostfix;
// Remove Postfix
filter.fieldPostfix = filter.fieldPrefix = "";
// Get Subfields (without pre, postfix
this.SubFields = filter.SubFields;
// Add Postfix
this.fieldPostfix = filter.fieldPostfix = fieldPostfix;
this.fieldPrefix = filter.fieldPrefix = fieldPrefix;
this.WhereClause = filter.WhereClause;
this.BeginRecord = filter.BeginRecord;
this.OrderBy = filter.OrderBy;
this._featureSRef = (filter.FeatureSpatialReference != null) ? filter.FeatureSpatialReference.Clone() as ISpatialReference : null;
this.ContextLayerDefaultSpatialReference = filter.ContextLayerDefaultSpatialReference != null ?
filter.ContextLayerDefaultSpatialReference.Clone() as ISpatialReference : null;
this.Limit = filter.Limit;
this.IgnoreUndefinedFields = filter.IgnoreUndefinedFields;
this.CancelTracker = filter.CancelTracker;
filter.CopyUserDataTo(this);
}
public string fieldPrefix
{
get { return m_fieldPrefix; }
set { m_fieldPrefix = value; }
}
public string fieldPostfix
{
get { return m_fieldPostfix; }
set { m_fieldPostfix = value; }
}
protected void CopyTo(QueryFilter copyto)
{
copyto.m_fields = new List<string>();
copyto.m_alias = new Dictionary<string, string>();
foreach (string field in m_fields)
{
copyto.m_fields.Add(field);
}
foreach (string alias in m_alias.Keys)
{
copyto.m_alias.Add(alias, m_alias[alias]);
}
copyto.m_whereClause = m_whereClause;
copyto.m_whereClause2 = m_whereClause2;
copyto.m_beginrecord = m_beginrecord;
copyto.m_featureCount = m_featureCount;
copyto.m_hasmore = m_hasmore;
copyto.m_nolock = m_nolock;
copyto.m_fieldPrefix = m_fieldPrefix;
copyto.m_fieldPostfix = m_fieldPostfix;
copyto._featureSRef = _featureSRef;
copyto.CancelTracker = CancelTracker;
copyto.DatasetCachingContext = this.DatasetCachingContext;
this.CopyUserDataTo(copyto);
}
#region IQueryFilter Member
public int BeginRecord
{
get { return m_beginrecord; }
set { m_beginrecord = value; }
}
public int Limit { get; set; }
public virtual void AddField(string fieldname, bool caseSensitive = true)
{
if (String.IsNullOrEmpty(fieldname))
{
return;
}
if (HasField("*") && !(fieldname.Contains("(") && fieldname.Contains(")")))
{
return;
}
if (caseSensitive)
{
if (m_fields.IndexOf(fieldname) != -1)
{
return;
}
}
else
{
string lowerFieldname = fieldname.ToLower();
foreach (var f in m_fields)
{
if (f.ToLower() == lowerFieldname)
{
return;
}
}
}
m_fields.Add(fieldname);
}
public ICancelTracker CancelTracker { get; set; }
public virtual void AddField(string fieldname, string alias)
{
AddField(fieldname);
if (fieldname == "*")
{
return;
}
string a;
if (m_alias.TryGetValue(fieldname, out a))
{
m_alias[fieldname] = alias;
}
else
{
m_alias.Add(fieldname, alias);
}
}
public string Alias(string fieldname)
{
string alias = "";
m_alias.TryGetValue(fieldname, out alias);
return alias;
}
public bool HasField(string fieldname)
{
return m_fields.IndexOf(fieldname) != -1;
}
public IEnumerable<string> QuerySubFields => m_fields?.Select(f => f.ToSubFieldName(m_fieldPrefix, m_fieldPostfix)).ToArray() ?? new string[0];
public string SubFields
{
get
{
var subfields = new StringBuilder();
foreach (string field in m_fields)
{
if (subfields.Length > 0)
{
subfields.Append(" ");
}
subfields.Append(field.ToSubFieldName(m_fieldPrefix, m_fieldPostfix));
}
return subfields.ToString();
}
set
{
m_fields = new List<string>();
if (value != null)
{
if (!value.ToLower().Contains(" as "))
{
value = value.Replace(" ", ",");
}
foreach (string field in value.Replace(";", ",").Split(','))
{
string f = field.Trim();
if (f == "")
{
continue;
}
AddField(f);
}
}
}
}
public virtual string SubFieldsAndAlias
{
get
{
string subfields = "";
foreach (string field in m_fields)
{
if (subfields != "")
{
subfields += ",";
}
if (field == "*")
{
subfields += field;
}
else
{
if (m_fieldPrefix != null && field.IndexOf(m_fieldPrefix) != 0 && field.IndexOf("(") == -1 && field.IndexOf(")") == -1)
{
subfields += m_fieldPrefix;
}
subfields += field;
if (m_fieldPrefix != null && field.IndexOf(m_fieldPostfix, m_fieldPrefix.Length) != field.Length - m_fieldPostfix.Length && field.IndexOf("(") == -1 && field.IndexOf(")") == -1)
{
subfields += m_fieldPostfix;
}
string alias = Alias(field);
if (alias != "" && alias != null)
{
subfields += " as " + alias;
}
}
}
return subfields;
}
}
public string WhereClause
{
get
{
if (m_whereClause.StartsWith("[") || m_whereClause.StartsWith("{"))
{
if (!String.IsNullOrEmpty(m_whereClause2))
{
return m_whereClause2;
}
DisplayFilterCollection dfc = DisplayFilterCollection.FromJSON(m_whereClause);
if (dfc != null)
{
StringBuilder sb = new StringBuilder();
foreach (DisplayFilter df in dfc)
{
if (String.IsNullOrEmpty(df.Filter))
{
continue;
}
if (sb.Length > 0)
{
sb.Append(" OR ");
}
sb.Append(df.Filter);
}
return m_whereClause2 = sb.ToString();
}
}
return m_whereClause;
}
set
{
m_whereClause = (value != null ? value.Trim() : String.Empty);
m_whereClause2 = String.Empty;
}
}
public string JsonWhereClause
{
get
{
if ((m_whereClause.Trim().StartsWith("[") && m_whereClause.Trim().EndsWith("]")) ||
(m_whereClause.Trim().StartsWith("{") && m_whereClause.Trim().EndsWith("}")))
{
return m_whereClause;
}
return String.Empty;
}
}
public string OrderBy
{
get
{
if (String.IsNullOrEmpty(m_orderBy))
{
return String.Empty;
}
if (String.IsNullOrEmpty(m_fieldPostfix) && String.IsNullOrEmpty(m_fieldPrefix))
{
return m_orderBy;
}
StringBuilder sb = new StringBuilder();
foreach (string field in m_orderBy.Replace(",", " ").Split(' '))
{
if (sb.Length > 0 && (field.ToLower() == "asc" || field.ToLower() == "desc"))
{
sb.Append(" " + field);
}
else
{
if (sb.Length > 0)
{
sb.Append(",");
}
if (field.IndexOf(m_fieldPrefix) != 0 && field.IndexOf("(") == -1 && field.IndexOf(")") == -1)
{
sb.Append(m_fieldPrefix);
}
sb.Append(field);
if (field.IndexOf(m_fieldPostfix, Math.Min(m_fieldPrefix.Length, field.Length)) != field.Length - m_fieldPostfix.Length && field.IndexOf("(") == -1 && field.IndexOf(")") == -1)
{
sb.Append(m_fieldPostfix);
}
}
}
return sb.ToString();
}
set
{
m_orderBy = value;
}
}
public bool NoLock
{
get
{
return m_nolock;
}
set
{
m_nolock = value;
}
}
public int LastQueryFeatureCount
{
get { return m_featureCount; }
set { m_featureCount = value; }
}
public bool HasMore
{
get { return m_hasmore; }
set { m_hasmore = value; }
}
virtual public object Clone()
{
QueryFilter filter = new QueryFilter(this);
return filter;
}
public ISpatialReference FeatureSpatialReference
{
get
{
return _featureSRef;
}
set
{
_featureSRef = value;
}
}
public ISpatialReference ContextLayerDefaultSpatialReference { get; set; }
public bool IgnoreUndefinedFields
{
get;
set;
}
public double MapScale { get; set; }
public IDatasetCachingContext DatasetCachingContext { get; set; }
#endregion
#region IClone4 Member
virtual public object Clone(Type type)
{
if (type == typeof(ISpatialFilter))
{
return new SpatialFilter(this);
}
if (type == typeof(IQueryFilter))
{
return new QueryFilter(this);
}
return null;
}
#endregion
}
}
|
using MonoTouch.Dialog;
using Foundation;
using UIKit;
namespace Playground.iOS
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
// class-level declarations
UIWindow window;
private EntryElement login;
private EntryElement password;
public UINavigationController RootNavigationController { get; private set; }
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
// create a new window instance based on the screen size
window = new UIWindow(UIScreen.MainScreen.Bounds);
RootNavigationController = new UINavigationController();
var mainViewController = new CategoryViewController();
mainViewController.NavigationItem.SetRightBarButtonItem(
new UIBarButtonItem("Right",
UIBarButtonItemStyle.Plain,
(sender, args) =>
{
// button was clicked
}), true);
RootNavigationController.PushViewController(mainViewController, false);
window.RootViewController = RootNavigationController;
//window.RootViewController = new DialogViewController(new RootElement("Login")
//{
// new Section("Credentials")
// {
// (login = new EntryElement("Login", "Enter your login", "")),
// (password = new EntryElement("Password","Enter your password","",true))
// },
// new Section()
// {
// new StringElement("Login", delegate
// {
// RootNavigationController = new UINavigationController();
// RootNavigationController.NavigationItem.SetRightBarButtonItem(
// new UIBarButtonItem("Right",
// UIBarButtonItemStyle.Plain,
// (sender,args) => {
// // button was clicked
// }), true);
// var mainViewController = new CategoryViewController();
// RootNavigationController.PushViewController(mainViewController, false);
// window.RootViewController = RootNavigationController;
// })
// }
//});
// make the window visible
window.MakeKeyAndVisible();
return true;
}
}
} |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
namespace MinecraftToolsBoxSDK
{
[ValueConversion(typeof(Color), typeof(String))]
public class ColorToStringConverter : IValueConverter
{
public Object Convert(
Object value, Type targetType, Object parameter, CultureInfo culture)
{
Color colorValue = (Color)value;
return ColorNames.GetColorName(colorValue);
}
public Object ConvertBack(
Object value, Type targetType, Object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public /*internal*/ static class ColorNames
{
#region Public Methods
static ColorNames()
{
m_colorNames = new Dictionary<Color, string>();
FillColorNames();
}
static public String GetColorName(Color colorToSeek)
{
if (m_colorNames.ContainsKey(colorToSeek))
return m_colorNames[colorToSeek];
else
return colorToSeek.ToString();
}
#endregion
#region Private Methods
public static void FillColorNames()
{
Type colorsType = typeof(System.Windows.Media.Colors);
PropertyInfo[] colorsProperties = colorsType.GetProperties();
foreach (PropertyInfo colorProperty in colorsProperties)
{
String colorName = colorProperty.Name;
Color color = (Color)colorProperty.GetValue(null, null);
// Path - Aqua is the same as Magenta - so we add 1 to red to avoid collision
if (colorName == "Aqua")
color.R++;
if (colorName == "Fuchsia")
color.G++;
m_colorNames.Add(color, colorName);
}
}
#endregion
#region Private Members
static private Dictionary<Color, String> m_colorNames;
#endregion
}
public /*internal*/ static class ColorUtils
{
public static String[] GetColorNames()
{
Type colorsType = typeof(System.Windows.Media.Colors);
PropertyInfo[] colorsProperties = colorsType.GetProperties();
ColorConverter convertor = new ColorConverter();
List<String> colorNames = new List<String>();
foreach (PropertyInfo colorProperty in colorsProperties)
{
String colorName = colorProperty.Name;
colorNames.Add(colorName);
Color color = (Color)ColorConverter.ConvertFromString(colorName);
}
//String[] colorNamesArray = new String[colorNames.Count];
return colorNames.ToArray();
}
public static void FireSelectedColorChangedEvent(UIElement issuer, RoutedEvent routedEvent, Color oldColor, Color newColor)
{
RoutedPropertyChangedEventArgs<Color> newEventArgs = new RoutedPropertyChangedEventArgs<Color>(oldColor, newColor)
{
RoutedEvent = routedEvent
};
issuer.RaiseEvent(newEventArgs);
}
private static Color BuildColor(double red, double green, double blue, double m)
{
return Color.FromArgb(
255,
(byte)((red + m) * 255 + 0.5),
(byte)((green + m) * 255 + 0.5),
(byte)((blue + m) * 255 + 0.5));
}
public static void ConvertRgbToHsv(
Color color, out double hue, out double saturation, out double value)
{
double red = color.R / 255.0;
double green = color.G / 255.0;
double blue = color.B / 255.0;
double min = Math.Min(red, Math.Min(green, blue));
double max = Math.Max(red, Math.Max(green, blue));
value = max;
double delta = max - min;
if (value == 0)
saturation = 0;
else
saturation = delta / max;
if (saturation == 0)
hue = 0;
else
{
if (red == max)
hue = (green - blue) / delta;
else if (green == max)
hue = 2 + (blue - red) / delta;
else // blue == max
hue = 4 + (red - green) / delta;
}
hue *= 60;
if (hue < 0)
hue += 360;
}
// Converts an HSV color to an RGB color.
// Algorithm taken from Wikipedia
public static Color ConvertHsvToRgb(double hue, double saturation, double value)
{
double chroma = value * saturation;
if (hue == 360)
hue = 0;
double hueTag = hue / 60;
double x = chroma * (1 - Math.Abs(hueTag % 2 - 1));
double m = value - chroma;
switch ((int)hueTag)
{
case 0:
return BuildColor(chroma, x, 0, m);
case 1:
return BuildColor(x, chroma, 0, m);
case 2:
return BuildColor(0, chroma, x, m);
case 3:
return BuildColor(0, x, chroma, m);
case 4:
return BuildColor(x, 0, chroma, m);
default:
return BuildColor(chroma, 0, x, m);
}
}
public static Color[] GetSpectrumColors(int colorCount)
{
Color[] spectrumColors = new Color[colorCount];
for (int i = 0; i < colorCount; ++i)
{
double hue = (i * 360.0) / colorCount;
spectrumColors[i] = ConvertHsvToRgb(hue, /*saturation*/1.0, /*value*/1.0);
}
return spectrumColors;
}
public static bool TestColorConversion()
{
for (int i = 0; i <= 0xFFFFFF; ++i)
{
byte Red = (byte)(i & 0xFF);
byte Green = (byte)((i & 0xFF00) >> 8);
byte Blue = (byte)((i & 0xFF0000) >> 16);
Color originalColor = Color.FromRgb(Red, Green, Blue);
ConvertRgbToHsv(originalColor, out double hue, out double saturation, out double value);
Color resultColor = ConvertHsvToRgb(hue, saturation, value);
if (originalColor != resultColor)
return false;
}
return true;
}
}
}
|
using System;
namespace MySQL.Model {
public class Player {
public int Id { get; set; }
public DateTime DateOfBirth { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int MembershipNumber { get; set; }
public int PostalCode { get; set; }
public Ranking Ranking { get; set; }
public string Place { get; set; }
public string StreetName { get; set; }
public int StreetNumber { get; set; }
public static Player Generate(int index, DateTime dateOfBirth, string firstName, string lastName, int postalCode, string place, Ranking ranking, string streetName, int streetNumber) {
return new Player {
Id = index,
DateOfBirth = dateOfBirth,
FirstName = firstName,
LastName = lastName,
MembershipNumber = index,
PostalCode = postalCode,
Place = place,
Ranking = ranking,
StreetName = streetName,
StreetNumber = streetNumber
};
}
public override string ToString() {
return String.Format(
"({0}, '{1}', {2}, '{3}', '{4}', {5}, '{6}', '{7}', '{8}', {9})",
this.Id,
this.DateOfBirth.ToString("yyyy-MM-dd"),
this.MembershipNumber,
this.FirstName,
this.LastName,
this.PostalCode,
this.Place,
this.Ranking.ToString(),
this.StreetName,
this.StreetNumber
);
}
}
}
|
using System;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Pobs.Domain;
using Pobs.Domain.Entities;
using Pobs.Tests.Integration.Helpers;
using Pobs.Web.Models.Tags;
using Xunit;
namespace Pobs.Tests.Integration.Tags
{
public class GetUnapprovedTagTests : IDisposable
{
private string _generateTagUrl(string tagSlug) => $"/api/tags/{tagSlug}";
private readonly int _userId;
private readonly Tag _tag;
public GetUnapprovedTagTests()
{
var user = DataHelpers.CreateUser();
_userId = user.Id;
_tag = DataHelpers.CreateTag(user, isApproved: false);
}
[Fact]
public async Task AuthenticatedAsAdmin_ShouldGetTag()
{
using (var server = new IntegrationTestingServer())
using (var client = server.CreateClient())
{
client.AuthenticateAs(_userId, Role.Admin);
var url = _generateTagUrl(_tag.Slug);
var response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
var responseContent = await response.Content.ReadAsStringAsync();
var responseModel = JsonConvert.DeserializeObject<AdminTagModel>(responseContent);
Assert.Equal(_tag.Slug, responseModel.Slug);
Assert.Equal(_tag.Name, responseModel.Name);
Assert.Equal(_tag.Description, responseModel.Description);
Assert.Equal(_tag.MoreInfoUrl, responseModel.MoreInfoUrl);
Assert.Equal(_tag.IsApproved, responseModel.IsApproved);
}
}
[Fact]
public async Task AuthenticatedAsNonAdmin_ShouldGetNotFound()
{
using (var server = new IntegrationTestingServer())
using (var client = server.CreateClient())
{
client.AuthenticateAs(_userId);
var url = _generateTagUrl(_tag.Slug);
var response = await client.GetAsync(url);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
}
public void Dispose()
{
DataHelpers.DeleteUser(_userId);
}
}
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Mateusz Majchrzak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
using System;
using System.Collections.Generic;
namespace Store
{
/// <summary>
/// Common store interface.
/// </summary>
public interface IStore
{
/// <summary>
/// Gets or sets the delegate.
/// </summary>
/// <value>The delegate.</value>
IStoreDelegate Delegate { get; set; }
/// <summary>
/// Checks that store is available on the current device.
/// </summary>
bool IsAvailable { get; }
/// <summary>
/// Downloads products data form store.
/// </summary>
/// <param name="products"></param>
/// <param name="handler"></param>
void Request(IEnumerable<string> identifiers);
/// <summary>
///
/// </summary>
/// <param name="product"></param>
/// <param name="handler"></param>
void Purchase(string identifier);
/// <summary>
///
/// </summary>
void Restore();
}
} |
using UnityEngine;
using System.Collections;
public enum UnitBehaviour {Enemy, Minion }
[RequireComponent(typeof(HitPoints))]
public class Unit : MonoBehaviour {
public UnitBehaviour behaviour = UnitBehaviour.Enemy;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
switch (behaviour) {
case UnitBehaviour.Enemy:
EnemyUpdate();
break;
case UnitBehaviour.Minion:
MinionUpdate();
break;
}
}
void EnemyUpdate() {
//disbale so we don't collide with our selfs
GetComponent<Collider2D>().enabled = false;
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.left, 1f);
Debug.Log(hit.collider);
Debug.DrawRay(transform.position, Vector2.left, Color.green);
if (hit.collider == null) {
//move to the left
transform.Translate(Vector3.left * Time.deltaTime);
}
else if (hit.collider.tag == "Enemy") {
//we are behind a friend, wait
}
else if (hit.collider.tag == "Minion") {
//we are faceing an enemy, attack
}
else if (hit.collider.tag == "TowerBlock") {
//we are facking the tower, attck it!
hit.transform.GetComponent<HitPoints>().Hp--;
}
//re anable so others can collide with us :)
GetComponent<Collider2D>().enabled = true;
}
void MinionUpdate() {
//disbale so we don't collide with our selfs
GetComponent<Collider2D>().enabled = false;
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.right, 1f);
Debug.Log(hit.collider);
Debug.DrawRay(transform.position, Vector2.right, Color.green);
if (hit.collider == null) {
//move to the left
transform.Translate(Vector3.right * Time.deltaTime);
}
else if (hit.collider.tag == "Enemy") {
//we are faceing an enemy, attack
}
else if (hit.collider.tag == "Minion") {
//we are behind a friend, wait
}
//re anable so others can collide with us :)
GetComponent<Collider2D>().enabled = true;
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using EPI.Strings;
using FluentAssertions;
namespace EPI.UnitTests.Strings
{
[TestClass]
public class LookAndSayUnitTest
{
[TestMethod]
public void FindNthNumber_Cases()
{
LookAndSay.FindNthNumber(1).Should().Be(1);
LookAndSay.FindNthNumber(2).Should().Be(11);
LookAndSay.FindNthNumber(3).Should().Be(21);
LookAndSay.FindNthNumber(4).Should().Be(1211);
LookAndSay.FindNthNumber(5).Should().Be(111221);
LookAndSay.FindNthNumber(6).Should().Be(312211);
LookAndSay.FindNthNumber(7).Should().Be(13112221);
LookAndSay.FindNthNumber(8).Should().Be(1113213211);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void FindNthNumber_Invalid()
{
LookAndSay.FindNthNumber(0);
}
}
}
|
using CarsIsland.Core.Entities;
using System;
using System.Threading.Tasks;
namespace CarsIsland.Core.Interfaces
{
public interface ICarReservationRepository : IDataRepository<CarReservation>
{
Task<CarReservation> GetExistingReservationByCarIdAsync(string carId, DateTime rentFrom);
}
}
|
using System;
using System.Collections.ObjectModel;
using System.Security.Authentication;
using System.Threading.Tasks;
using DM7_PPLUS_Integration.Daten;
using DM7_PPLUS_Integration.Implementierung;
using System.Collections.Generic;
using System.Linq;
using DM7_PPLUS_Integration.Implementierung.PPLUS;
using DM7_PPLUS_Integration.Messages.PPLUS;
using Datenstand = DM7_PPLUS_Integration.Daten.Datenstand;
using Datum = DM7_PPLUS_Integration.Daten.Datum;
using Uhrzeit = DM7_PPLUS_Integration.Daten.Uhrzeit;
namespace DM7_PPLUS_Integration
{
internal interface Authentication_Result { }
internal readonly struct Authenticated : Authentication_Result
{
public readonly PPLUS_Handler Handler;
public readonly Token Token;
public Authenticated(PPLUS_Handler handler, Token token)
{
Handler = handler;
Token = token;
}
}
internal readonly struct Not_Authenticated : Authentication_Result { }
public class PPLUS : PPLUS_API
{
public static Task<PPLUS> Connect(string address, string user, string password, string encryptionKey, Log log, TimeSpan? timeout = null)
{
if (!Uri.TryCreate(address, UriKind.Absolute, out var uri)) throw new ArgumentException($"'{address}' ist keine gültige Addresse", nameof(address));
return Task.Run(() =>
{
log.Debug($"Verbinde mit Server {address}");
switch (Authenticate(uri, user, password, encryptionKey, log, timeout))
{
case Authenticated authenticated:
{
try
{
var (_, missing_capabilities) = Negotiate_capabilities(authenticated.Handler.Capabilities(timeout).Result.Value.ToList());
Guard_no_missing_capabilities(missing_capabilities);
return new PPLUS(authenticated.Handler, authenticated.Token, timeout);
}
catch
{
authenticated.Handler.Dispose();
throw;
}
}
case Not_Authenticated _:
throw new AuthenticationException("Nicht authentifiziert");
default:
throw new ArgumentOutOfRangeException();
}
});
}
private static (List<Capability>, List<string>) Negotiate_capabilities(List<Capability> server_capabilities)
{
var best_fitting_capabilites = new List<Capability>();
var missing_capabilities = new List<string>();
void Evaluate(string nicht_zutreffend, params Capability[] one_of_this)
{
foreach (var capability in one_of_this)
{
if (server_capabilities.Contains(capability))
{
best_fitting_capabilites.Add(capability);
return;
}
}
missing_capabilities.Add(nicht_zutreffend);
}
Evaluate("Mitarbeiter - Version 1", Capability.MITARBEITER_V1);
Evaluate("Dienste - Version 1", Capability.DIENSTE_V1);
Evaluate("Beginn von Dienst - Version 1", Capability.BEGINN_VON_DIENST_V1);
Evaluate("Abwesenheiten - Version 1", Capability.ABWESENHEITEN_V1);
Evaluate("Dienstbuchungen - Version 1", Capability.DIENSTBUCHUNGEN_V1);
Evaluate("Soll/Ist Abgleich - Version 1", Capability.SOLL_IST_ABGLEICH_V1);
return (best_fitting_capabilites, missing_capabilities);
}
private static Authentication_Result Authenticate(Uri uri, string user, string password, string encryptionKey, Log log, TimeSpan? timeout)
{
var pplusHandler = new Port($"{uri.Scheme}://{uri.Host}", uri.Port, encryptionKey, log);
var token = pplusHandler.Authenticate(user, password, timeout).Result;
if (token.HasValue) return new Authenticated(pplusHandler, token.Value);
pplusHandler.Dispose();
return new Not_Authenticated();
}
private static void Guard_no_missing_capabilities(List<string> missing_capabilities)
{
if (missing_capabilities.Any()) throw new NotSupportedException($"Folgende Capabilities nicht unterstützt: {string.Join(", ", missing_capabilities)}");
}
private readonly PPLUS_Handler _pplusHandler;
private readonly Token _token;
private readonly TimeSpan? _timeout;
private PPLUS(PPLUS_Handler pplusHandler, Token token, TimeSpan? timeout)
{
_pplusHandler = pplusHandler;
pplusHandler.Dienständerungen_liegen_bereit += () => Dienständerungen_liegen_bereit?.Invoke();
pplusHandler.Mitarbeiteränderungen_liegen_bereit += () => Mitarbeiteränderungen_liegen_bereit?.Invoke();
_token = token;
_timeout = timeout;
}
public int Auswahllisten_Version => 1;
public event Action Mitarbeiteränderungen_liegen_bereit;
public event Action Dienständerungen_liegen_bereit;
public Task<Stammdaten<Mitarbeiter>> Mitarbeiter_abrufen()
{
var (best_fitting, missing) = Negotiate_capabilities(_pplusHandler.Capabilities(_timeout).Result.Value.ToList());
Guard_no_missing_capabilities(missing);
if (best_fitting.Contains(Capability.MITARBEITER_V1))
return Handle_Query<MitarbeiterlisteV1, Stammdaten<Mitarbeiter>>(
new MitarbeiterAbrufenV1(),
Message_mapper.Mitarbeiterlist_als_Stammdaten);
throw new ArgumentOutOfRangeException(nameof(best_fitting), best_fitting, null);
}
public Task<Stammdaten<Mitarbeiter>> Mitarbeiter_abrufen_ab(Datenstand stand)
{
var (best_fitting, missing) = Negotiate_capabilities(_pplusHandler.Capabilities(_timeout).Result.Value.ToList());
Guard_no_missing_capabilities(missing);
if (best_fitting.Contains(Capability.MITARBEITER_V1))
return Handle_Query<MitarbeiterlisteV1, Stammdaten<Mitarbeiter>>(
new MitarbeiterAbrufenAbV1(Message_mapper.Stand_als_Message(stand)),
Message_mapper.Mitarbeiterlist_als_Stammdaten);
throw new ArgumentOutOfRangeException(nameof(best_fitting), best_fitting, null);
}
public Task<Stammdaten<Dienst>> Dienste_abrufen()
{
var (best_fitting, missing) = Negotiate_capabilities(_pplusHandler.Capabilities(_timeout).Result.Value.ToList());
Guard_no_missing_capabilities(missing);
if (best_fitting.Contains(Capability.DIENSTE_V1))
return Handle_Query<DiensteV1, Stammdaten<Dienst>>(
new DiensteAbrufenV1(),
Message_mapper.Dienste_als_Stammdaten);
throw new ArgumentOutOfRangeException(nameof(best_fitting), best_fitting, null);
}
public Task<Uhrzeit?> Dienstbeginn_am(Datum stichtag, int dienstId)
{
var (best_fitting, missing) = Negotiate_capabilities(_pplusHandler.Capabilities(_timeout).Result.Value.ToList());
Guard_no_missing_capabilities(missing);
if (best_fitting.Contains(Capability.BEGINN_VON_DIENST_V1))
return Handle_Query<DienstbeginnV1, Uhrzeit?>(
new DienstbeginnZumStichtagV1(
Message_mapper.Datum_als_Message(stichtag),
(ulong) dienstId),
Message_mapper.Dienstbeginn_aus_Message);
throw new ArgumentOutOfRangeException(nameof(best_fitting), best_fitting, null);
}
public Task<Stammdaten<Dienst>> Dienste_abrufen_ab(Datenstand stand)
{
var (best_fitting, missing) = Negotiate_capabilities(_pplusHandler.Capabilities(_timeout).Result.Value.ToList());
Guard_no_missing_capabilities(missing);
if (best_fitting.Contains(Capability.DIENSTE_V1))
return Handle_Query<DiensteV1, Stammdaten<Dienst>>(
new DiensteAbrufenAbV1(Message_mapper.Stand_als_Message(stand)),
Message_mapper.Dienste_als_Stammdaten);
throw new ArgumentOutOfRangeException(nameof(best_fitting), best_fitting, null);
}
public Task<Dictionary<Datum, ReadOnlyCollection<Dienstbuchung>>> Dienstbuchungen_im_Zeitraum(Datum von, Datum bis, Guid mandantId)
{
var (best_fitting, missing) = Negotiate_capabilities(_pplusHandler.Capabilities(_timeout).Result.Value.ToList());
Guard_no_missing_capabilities(missing);
if (best_fitting.Contains(Capability.DIENSTBUCHUNGEN_V1))
return Handle_Query<DienstbuchungenV1, Dictionary<Datum, ReadOnlyCollection<Dienstbuchung>>>(
new DienstbuchungenImZeitraumV1(Message_mapper.Datum_als_Message(von), Message_mapper.Datum_als_Message(bis), Message_mapper.UUID_aus(mandantId)),
Message_mapper.Dienstbuchungen);
throw new ArgumentOutOfRangeException(nameof(best_fitting), best_fitting, null);
}
public Task<ReadOnlyCollection<Abwesenheit>> Abwesenheiten_im_Zeitraum(Datum von, Datum bis, Guid mandantId)
{
var (best_fitting, missing) = Negotiate_capabilities(_pplusHandler.Capabilities(_timeout).Result.Value.ToList());
Guard_no_missing_capabilities(missing);
if (best_fitting.Contains(Capability.ABWESENHEITEN_V1))
return Handle_Query<AbwesenheitenV1, ReadOnlyCollection<Abwesenheit>>(
new AbwesenheitenImZeitraumV1(Message_mapper.Datum_als_Message(von), Message_mapper.Datum_als_Message(bis), Message_mapper.UUID_aus(mandantId)),
Message_mapper.Abwesenheiten);
throw new ArgumentOutOfRangeException(nameof(best_fitting), best_fitting, null);
}
public Task<Soll_Ist_Abgleich_Verarbeitungsergebnis> Soll_Ist_Abgleich_freigeben(Soll_Ist_Abgleich abgleich)
{
var (best_fitting, missing) = Negotiate_capabilities(_pplusHandler.Capabilities(_timeout).Result.Value.ToList());
Guard_no_missing_capabilities(missing);
if (best_fitting.Contains(Capability.SOLL_IST_ABGLEICH_V1))
return Handle_Command<SollIstAbgleichVerarbeitungsergebnisV1, Soll_Ist_Abgleich_Verarbeitungsergebnis>(
new SollIstAbgleichFreigebenV1(Message_mapper.Soll_Ist_Abgleich_als_Message(abgleich)),
Message_mapper.Soll_Ist_Abgleich_Verarbeitungsergebnis);
throw new ArgumentOutOfRangeException(nameof(best_fitting), best_fitting, null);
}
private async Task<TResult> Handle_Query<TResponse, TResult>(Query query, Func<TResponse, TResult> handler)
{
var response = await _pplusHandler.HandleQuery(_token, query, _timeout);
switch (response)
{
case TResponse message:
{
return handler(message);
}
case IOFehler error:
{
throw new Exception(error.Reason);
}
default:
throw new Exception($"Unerwartetes Response '{response.GetType()}' erhalten");
}
}
private async Task<TResult> Handle_Command<TResponse, TResult>(Command command, Func<TResponse, TResult> handler)
{
var response = await _pplusHandler.HandleCommand(_token, command, _timeout);
switch (response)
{
case TResponse message:
{
return handler(message);
}
case IOFehler error:
{
throw new Exception(error.Reason);
}
default:
throw new Exception($"Unerwartetes Response '{response.GetType()}' erhalten");
}
}
public void Dispose()
{
_pplusHandler?.Dispose();
}
}
} |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using MQTTnet.Formatter;
using MQTTnet.Tests.Mockups;
using System.Threading;
using System.Threading.Tasks;
namespace MQTTnet.Tests.MQTTv5
{
[TestClass]
public class Server_Tests
{
public TestContext TestContext { get; set; }
[TestMethod]
public async Task Will_Message_Send()
{
using (var testEnvironment = new TestEnvironment(TestContext))
{
var receivedMessagesCount = 0;
await testEnvironment.StartServer();
var willMessage = new MqttApplicationMessageBuilder().WithTopic("My/last/will").WithAtMostOnceQoS().Build();
var clientOptions = new MqttClientOptionsBuilder().WithWillMessage(willMessage).WithProtocolVersion(MqttProtocolVersion.V500);
var c1 = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithProtocolVersion(MqttProtocolVersion.V500));
c1.UseApplicationMessageReceivedHandler(c => Interlocked.Increment(ref receivedMessagesCount));
await c1.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("#").Build());
var c2 = await testEnvironment.ConnectClient(clientOptions);
c2.Dispose(); // Dispose will not send a DISCONNECT pattern first so the will message must be sent.
await Task.Delay(1000);
Assert.AreEqual(1, receivedMessagesCount);
}
}
[TestMethod]
public async Task Validate_IsSessionPresent()
{
using (var testEnvironment = new TestEnvironment(TestContext))
{
// Create server with persistent sessions enabled
await testEnvironment.StartServer(o => o.WithPersistentSessions());
const string ClientId = "Client1";
// Create client without clean session and long session expiry interval
var client1 = await testEnvironment.ConnectClient(o => o
.WithProtocolVersion(MqttProtocolVersion.V500)
.WithTcpServer("127.0.0.1", testEnvironment.ServerPort)
.WithSessionExpiryInterval(9999)
.WithCleanSession(false)
.WithClientId(ClientId)
.Build()
);
// Disconnect; empty session should remain on server
await client1.DisconnectAsync();
// Simulate some time delay between connections
await Task.Delay(1000);
// Reconnect the same client ID to existing session
var client2 = testEnvironment.CreateClient();
var options = testEnvironment.Factory.CreateClientOptionsBuilder()
.WithProtocolVersion(MqttProtocolVersion.V500)
.WithTcpServer("127.0.0.1", testEnvironment.ServerPort)
.WithSessionExpiryInterval(9999)
.WithCleanSession(false)
.WithClientId(ClientId)
.Build();
var result = await client2.ConnectAsync(options).ConfigureAwait(false);
await client2.DisconnectAsync();
// Session should be present
Assert.IsTrue(result.IsSessionPresent, "Session not present");
}
}
}
}
|
using Microsoft.EntityFrameworkCore;
using WebShop.API.Models;
using WebShop.Data.Repository.Contract;
namespace WebShop.Data.Repository
{
public class FakeUnitOfWork : IUnitOfWork
{
private readonly WebShopContext _context;
public FakeUnitOfWork(DbContextOptions options)
{
_context = new WebShopContext(options); ;
Category = new CategoryRepo(_context);
Product = new FakeProductRepo(_context);
Order = new FakeOrderRepo(_context);
}
public ICategoryRepo Category { get; private set; }
public IProductRepo Product { get; private set; }
public IOrderRepo Order { get; private set; }
public FakeCORSRepo CORS { get; private set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace mec.DataModelLayer.Models
{
public class PageParam
{
public int ItemsPerPage { get; set; }
public int CurrentPage { get; set; }
}
}
|
using System;
namespace DesignPatterns.Command.Example1
{
/// <summary>
/// RECEIVER
/// </summary>
public class Television : IElectronicDevice
{
private int volume = 0;
public void Off()
{
Console.WriteLine("TV is off");
}
public void On()
{
Console.WriteLine("TV is on");
}
public void VolumenDown()
{
volume--;
Console.WriteLine($"TV volume is at: {volume}");
}
public void VolumeUp()
{
volume++;
Console.WriteLine($"TV volume is at: {volume}");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Memento
{
class ItemFactura
{
public int Orden { get; set; }
public string Descripcion {get;set;}
public decimal Precio { get; set; }
}
}
|
//Travis Kroll
//9-10-19
//This program will take input from a "customer" and process/print a reciept with the number of oz, tip, tax, topping costs, discount, and total price.
using System;
class YogurtShop {
public static void Main () {
double Original_Oz,NumberToppings,Discount,Tip,Tax,RealOz,OzPrice,TopPrice,TaxedTotal,TotalTax,RealDiscount,RealTip,FinalTotal,PreTip,PreDiscount;
string A,B,C,D;
Tax = .0725;
//requesting info from the customer about their order
Console.WriteLine ("Hello Customer!");
Console.WriteLine ("How many Oz of yogurt would you like?");
A = Console.ReadLine ();
Original_Oz = double.Parse(A);
Console.WriteLine ("How many toppings would you like? They cost 50 cents each.");
B = Console.ReadLine ();
NumberToppings = double.Parse(B);
Console.WriteLine ("If you have a coupon please enter the percent of discount. For example if you have a 25% off, please just enter 25. If you don't have a coupon, please enter 0. The max discount is 50%!!");
C = Console.ReadLine ();
Discount = double.Parse(C);
Console.WriteLine ("If you would like to give a tip please enter the percent you would like to tip. For example a 20% tip would be entered as 20. For no tip please enter 0.");
D = Console.ReadLine ();
Tip = double.Parse (D);
//Computing different totals for the reciept
RealOz = (Original_Oz-.25);
OzPrice = RealOz*.17;
TopPrice = NumberToppings*.50;
TotalTax = (OzPrice+TopPrice)*Tax;
TaxedTotal = (OzPrice+TopPrice+TotalTax);
//Applying tip and discount
PreDiscount = Discount/100;
RealDiscount = TaxedTotal*PreDiscount;
PreTip = Tip/100;
RealTip = TaxedTotal*PreTip;
//Calculating total
FinalTotal = TaxedTotal-RealDiscount+RealTip;
//Printing out totals
Console.WriteLine ("# of Oz ordered without a cup: "+RealOz);
Console.WriteLine ("Topping Costs: ${0:0.00}",TopPrice);
Console.WriteLine ("Sales tax: ${0:0.00}",TotalTax);
Console.WriteLine ("Your discount of "+Discount+"% saved you ${0:0.00}",RealDiscount);
Console.WriteLine ("Your "+Tip+"% came out to a total of ${0:0.00}",RealTip);
Console.WriteLine ("Your order came to a grand total of ${0:0.00}",FinalTotal);
Console.WriteLine ("Thank you, come again soon!");
}
} |
using Xamarin.Forms;
namespace CollectionViewIssue.Pages
{
public class DailyEntryPageModel
{
public DailyEntryPageModel()
{
MetersViewModel = new MetersViewModel();
TanksViewModel = new TanksViewModel();
TanksViewModel.IsVisible = true;
}
public Command ButtonClick
{
get
{
return new Command(button =>
{
Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
{
MetersViewModel.IsVisible = false;
TanksViewModel.IsVisible = false;
switch ((string)button)
{
case "Tanks":
TanksViewModel.Load();
TanksViewModel.IsVisible = true;
break;
case "Meters":
MetersViewModel.Load();
MetersViewModel.IsVisible = true;
break;
}
});
});
}
}
public void Load()
{
Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
{
if (TanksViewModel.IsVisible)
{
TanksViewModel.Load();
}
if (MetersViewModel.IsVisible)
{
MetersViewModel.Load();
}
});
}
public TanksViewModel TanksViewModel { get; set; }
public MetersViewModel MetersViewModel { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SudokuConsole
{
class SudokuBL
{
public List<List<string>> sudokuData;
public SudokuBL()
{
sudokuData = new List<List<string>>() {
new List<string>() { "3","4,","5"},
new List<string>() { },
new List<string>() { },
new List<string>() { },
new List<string>() { },
new List<string>() { },
new List<string>() { },
new List<string>() { },
new List<string>() { }
};
}
}
}
|
namespace DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.EmbeddedContentItemsGraphSyncer
{
public interface IBagPartEmbeddedContentItemsGraphSyncer : IEmbeddedContentItemsGraphSyncer
{
}
}
|
using NUnit.Framework;
namespace CS.Sandbox.Db
{
[TestFixture]
class SQLiteMemoryTest
{
}
}
|
using System;
namespace SIEI_Entites
{
public class RegistrationEntites
{
}
}
|
using gView.Framework.Data;
using gView.Framework.Geometry;
using gView.Framework.OGC.GML;
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace gView.Interoperability.OGC.Dataset.GML
{
internal class GMLFile
{
private Dataset _gmlDataset = null;
private string _filename = String.Empty, _errMsg = String.Empty;
private XmlDocument _doc = null;
private XmlNamespaceManager _ns = null;
private static IFormatProvider _nhi = System.Globalization.CultureInfo.InvariantCulture.NumberFormat;
private GmlVersion _gmlVersion = GmlVersion.v1;
private GMLFile() { }
async static public Task<GMLFile> Create(string filename)
{
try
{
var file = new GMLFile();
file._gmlDataset = new Dataset();
await file._gmlDataset.SetConnectionString(filename);
if (!await file._gmlDataset.Open())
{
file._gmlDataset = null;
}
file._filename = filename;
file._doc = new XmlDocument();
file._doc.Load(file._filename);
file._ns = new XmlNamespaceManager(file._doc.NameTable);
file._ns.AddNamespace("GML", "http://www.opengis.net/gml");
file._ns.AddNamespace("WFS", "http://www.opengis.net/wfs");
file._ns.AddNamespace("OGC", "http://www.opengis.net/ogc");
file._ns.AddNamespace("myns", file._gmlDataset.targetNamespace);
return file;
}
catch
{
return null;
}
}
public bool Delete()
{
if (_gmlDataset != null)
{
return _gmlDataset.Delete();
}
return false;
}
async public static Task<bool> Create(string filename, IGeometryDef geomDef, FieldCollection fields, GmlVersion gmlVersion)
{
try
{
FileInfo fi = new FileInfo(filename);
string name = fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length);
string gml_filename = fi.FullName.Substring(0, fi.FullName.Length - fi.Extension.Length) + ".gml";
string xsd_filename = fi.FullName.Substring(0, fi.FullName.Length - fi.Extension.Length) + ".xsd";
FeatureClass featureClass = await FeatureClass.CreateAsync(null, name, fields);
XmlSchemaWriter schemaWriter = new XmlSchemaWriter(featureClass);
string schema = schemaWriter.Write();
using (var sw = new StreamWriter(xsd_filename, false, Encoding.UTF8))
{
sw.WriteLine(schema.Trim());
}
using (var sw = new StreamWriter(gml_filename, false, Encoding.UTF8))
{
sw.Write(@"<?xml version=""1.0"" encoding=""UTF-8""?>
<gml:FeatureCollection xmlns:gml=""http://www.opengis.net/gml""
xmlns:xlink=""http://www.w3.org/1999/xlink""
xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
xmlns:gv=""http://www.gViewGIS.com/server""
xsi:schemaLocation=""http://www.gview.com/gml " + name + @".xsd"">".Trim());
string boundingBox = GeometryTranslator.Geometry2GML(new Envelope(), String.Empty, gmlVersion);
sw.WriteLine(@"
<gml:boundedBy>");
sw.Write(boundingBox);
sw.Write(@"
</gml:boundedBy>");
sw.Write(@"
</gml:FeatureCollection>");
}
return true;
}
catch (Exception ex)
{
string errMsg = ex.Message;
return false;
}
}
private IEnvelope Envelope
{
get
{
if (_doc == null)
{
return null;
}
try
{
XmlNode envNode = _doc.SelectSingleNode("GML:FeatureCollection/GML:boundedBy", _ns);
if (envNode == null)
{
return null;
}
return GeometryTranslator.GML2Geometry(envNode.InnerXml, _gmlVersion) as IEnvelope;
}
catch (Exception ex)
{
_errMsg = ex.Message;
return null;
}
}
set
{
if (_doc == null || value == null)
{
return;
}
try
{
XmlNode coords = _doc.SelectSingleNode("GML:FeatureCollection/GML:boundedBy/GML:Box/GML:coordinates", _ns);
if (coords == null)
{
return;
}
coords.InnerText =
value.minx.ToString(_nhi) + "," + value.miny.ToString(_nhi) + " " +
value.maxx.ToString(_nhi) + "," + value.maxy.ToString(_nhi);
}
catch
{
}
}
}
private bool UpdateEnvelope(IEnvelope append)
{
if (append == null)
{
return true;
}
IEnvelope envelope = this.Envelope;
if (envelope == null)
{
return false;
}
if (envelope.minx == 0.0 && envelope.maxx == 0.0 &&
envelope.miny == 0.0 && envelope.maxy == 0.0)
{
envelope = append;
}
else
{
envelope.Union(append);
}
this.Envelope = envelope;
return true;
}
public bool AppendFeature(IFeatureClass fc, IFeature feature)
{
if (_doc == null || fc == null || feature == null)
{
return false;
}
XmlNode featureCollection = _doc.SelectSingleNode("GML:FeatureCollection", _ns);
if (featureCollection == null)
{
return false;
}
XmlNode featureMember = _doc.CreateElement("gml", "featureMember", _ns.LookupNamespace("GML"));
XmlNode featureclass = _doc.CreateElement("gv", fc.Name, _ns.LookupNamespace("myns"));
featureMember.AppendChild(featureclass);
if (feature.Shape != null)
{
try
{
string geom = GeometryTranslator.Geometry2GML(feature.Shape, String.Empty, _gmlVersion);
geom = @"<gml:theGeometry xmlns:gml=""http://www.opengis.net/gml"">" + geom + "</gml:theGeometry>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(geom);
XmlNode geomNode = _doc.CreateElement("gv", fc.ShapeFieldName.Replace("#", ""), _ns.LookupNamespace("myns"));
foreach (XmlNode node in doc.ChildNodes[0].ChildNodes)
{
geomNode.AppendChild(_doc.ImportNode(node, true));
}
if (!UpdateEnvelope(feature.Shape.Envelope))
{
_errMsg = "Can't update envelope...";
return false;
}
featureclass.AppendChild(geomNode);
}
catch (Exception ex)
{
_errMsg = ex.Message;
return false;
}
}
foreach (FieldValue fv in feature.Fields)
{
XmlNode attrNode = _doc.CreateElement("gv", fv.Name.Replace("#", ""), _ns.LookupNamespace("myns"));
if (fv.Value != null)
{
attrNode.InnerText = fv.Value.ToString();
}
featureclass.AppendChild(attrNode);
}
featureCollection.AppendChild(featureMember);
return true;
}
public bool Flush()
{
if (_doc == null)
{
return false;
}
try
{
FileInfo fi = new FileInfo(_filename);
if (fi.Exists)
{
fi.Delete();
}
_doc.Save(_filename);
return true;
}
catch (Exception ex)
{
_errMsg = ex.Message;
return false;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
namespace Storyblok.Sdk.Content.Types
{
public class Tag
{
public string Name { get; set; }
[JsonProperty(PropertyName = "taggings_count")]
public int Taggings { get; set; }
}
}
|
using Xamarin.Forms;
namespace RRExpress.Express.Views {
public partial class MyOrderDetailView : ContentView {
public MyOrderDetailView() {
InitializeComponent();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Euler_Logic.Problems.AdventOfCode.Y2022 {
public class Problem18 : AdventOfCodeBase {
public override string ProblemName => "Advent of Code 2022: 18";
public override string GetAnswer() {
return Answer1(Input()).ToString();
}
public override string GetAnswer2() {
return Answer2(Input()).ToString();
}
private int Answer1(List<string> input) {
var state = new State();
SetPoints(input, state);
SetSides(state);
return CountSides(state);
}
private int Answer2(List<string> input) {
var state = new State();
SetPoints(input, state);
SetSides(state);
SetMin(state);
return CountOutside(state);
}
private int CountOutside(State state) {
state.Outside = new HashSet<Tuple<int, int, int>>();
foreach (var side in state.Min.Sides) {
if (IsOutside(state, side)) {
Recursive(state, side);
}
}
int count = 0;
foreach (var point in state.Outside) {
var sides = GetSides(point);
foreach (var side in sides) {
if (state.Hash.Contains(side)) count++;
}
}
return count;
}
private void Recursive(State state, Tuple<int, int, int> startPoint) {
var list = new LinkedList<Tuple<int, int, int>>();
list.AddFirst(startPoint);
state.Outside.Add(startPoint);
do {
var point = list.First.Value;
// Easy sides
var sides = GetSides(point);
foreach (var side in sides) {
if (IsOutside(state, side) && !state.Outside.Contains(side)) {
state.Outside.Add(side);
list.AddLast(side);
}
}
// Tricky Diagonals
var key1 = new Tuple<int, int, int>(point.Item1 + 1, point.Item2 + 1, point.Item3);
var key2 = new Tuple<int, int, int>(point.Item1 + 1, point.Item2, point.Item3);
var key3 = new Tuple<int, int, int>(point.Item1, point.Item2 + 1, point.Item3);
if (!state.Hash.Contains(key2) || !state.Hash.Contains(key3)) {
if (IsOutside(state, key1) && !state.Outside.Contains(key1)) {
state.Outside.Add(key1);
list.AddLast(key1);
}
}
key1 = new Tuple<int, int, int>(point.Item1 + 1, point.Item2 - 1, point.Item3);
key2 = new Tuple<int, int, int>(point.Item1 + 1, point.Item2, point.Item3);
key3 = new Tuple<int, int, int>(point.Item1, point.Item2 - 1, point.Item3);
if (!state.Hash.Contains(key2) || !state.Hash.Contains(key3)) {
if (IsOutside(state, key1) && !state.Outside.Contains(key1)) {
state.Outside.Add(key1);
list.AddLast(key1);
}
}
key1 = new Tuple<int, int, int>(point.Item1 - 1, point.Item2 + 1, point.Item3);
key2 = new Tuple<int, int, int>(point.Item1 - 1, point.Item2, point.Item3);
key3 = new Tuple<int, int, int>(point.Item1, point.Item2 + 1, point.Item3);
if (!state.Hash.Contains(key2) || !state.Hash.Contains(key3)) {
if (IsOutside(state, key1) && !state.Outside.Contains(key1)) {
state.Outside.Add(key1);
list.AddLast(key1);
}
}
key1 = new Tuple<int, int, int>(point.Item1 - 1, point.Item2 - 1, point.Item3);
key2 = new Tuple<int, int, int>(point.Item1 - 1, point.Item2, point.Item3);
key3 = new Tuple<int, int, int>(point.Item1, point.Item2 - 1, point.Item3);
if (!state.Hash.Contains(key2) || !state.Hash.Contains(key3)) {
if (IsOutside(state, key1) && !state.Outside.Contains(key1)) {
state.Outside.Add(key1);
list.AddLast(key1);
}
}
key1 = new Tuple<int, int, int>(point.Item1 + 1, point.Item2, point.Item3 + 1);
key2 = new Tuple<int, int, int>(point.Item1 + 1, point.Item2, point.Item3);
key3 = new Tuple<int, int, int>(point.Item1, point.Item2, point.Item3 + 1);
if (!state.Hash.Contains(key2) || !state.Hash.Contains(key3)) {
if (IsOutside(state, key1) && !state.Outside.Contains(key1)) {
state.Outside.Add(key1);
list.AddLast(key1);
}
}
key1 = new Tuple<int, int, int>(point.Item1 + 1, point.Item2, point.Item3 - 1);
key2 = new Tuple<int, int, int>(point.Item1 + 1, point.Item2, point.Item3);
key3 = new Tuple<int, int, int>(point.Item1, point.Item2, point.Item3 - 1);
if (!state.Hash.Contains(key2) || !state.Hash.Contains(key3)) {
if (IsOutside(state, key1) && !state.Outside.Contains(key1)) {
state.Outside.Add(key1);
list.AddLast(key1);
}
}
key1 = new Tuple<int, int, int>(point.Item1 - 1, point.Item2, point.Item3 + 1);
key2 = new Tuple<int, int, int>(point.Item1 - 1, point.Item2, point.Item3);
key3 = new Tuple<int, int, int>(point.Item1, point.Item2, point.Item3 + 1);
if (!state.Hash.Contains(key2) || !state.Hash.Contains(key3)) {
if (IsOutside(state, key1) && !state.Outside.Contains(key1)) {
state.Outside.Add(key1);
list.AddLast(key1);
}
}
key1 = new Tuple<int, int, int>(point.Item1 - 1, point.Item2, point.Item3 - 1);
key2 = new Tuple<int, int, int>(point.Item1 - 1, point.Item2, point.Item3);
key3 = new Tuple<int, int, int>(point.Item1, point.Item2, point.Item3 - 1);
if (!state.Hash.Contains(key2) || !state.Hash.Contains(key3)) {
if (IsOutside(state, key1) && !state.Outside.Contains(key1)) {
state.Outside.Add(key1);
list.AddLast(key1);
}
}
key1 = new Tuple<int, int, int>(point.Item1, point.Item2 + 1, point.Item3 + 1);
key2 = new Tuple<int, int, int>(point.Item1, point.Item2 + 1, point.Item3);
key3 = new Tuple<int, int, int>(point.Item1, point.Item2, point.Item3 + 1);
if (!state.Hash.Contains(key2) || !state.Hash.Contains(key3)) {
if (IsOutside(state, key1) && !state.Outside.Contains(key1)) {
state.Outside.Add(key1);
list.AddLast(key1);
}
}
key1 = new Tuple<int, int, int>(point.Item1, point.Item2 + 1, point.Item3 - 1);
key2 = new Tuple<int, int, int>(point.Item1, point.Item2 + 1, point.Item3);
key3 = new Tuple<int, int, int>(point.Item1, point.Item2, point.Item3 - 1);
if (!state.Hash.Contains(key2) || !state.Hash.Contains(key3)) {
if (IsOutside(state, key1) && !state.Outside.Contains(key1)) {
state.Outside.Add(key1);
list.AddLast(key1);
}
}
key1 = new Tuple<int, int, int>(point.Item1, point.Item2 - 1, point.Item3 + 1);
key2 = new Tuple<int, int, int>(point.Item1, point.Item2 - 1, point.Item3);
key3 = new Tuple<int, int, int>(point.Item1, point.Item2, point.Item3 + 1);
if (!state.Hash.Contains(key2) || !state.Hash.Contains(key3)) {
if (IsOutside(state, key1) && !state.Outside.Contains(key1)) {
state.Outside.Add(key1);
list.AddLast(key1);
}
}
key1 = new Tuple<int, int, int>(point.Item1, point.Item2 - 1, point.Item3 - 1);
key2 = new Tuple<int, int, int>(point.Item1, point.Item2 - 1, point.Item3);
key3 = new Tuple<int, int, int>(point.Item1, point.Item2, point.Item3 - 1);
if (!state.Hash.Contains(key2) || !state.Hash.Contains(key3)) {
if (IsOutside(state, key1) && !state.Outside.Contains(key1)) {
state.Outside.Add(key1);
list.AddLast(key1);
}
}
list.RemoveFirst();
} while (list.Count > 0);
}
private bool IsOutside(State state, Tuple<int, int, int> point) {
if (state.Hash.Contains(point)) return false;
var sides = GetSides(point);
return sides.Any(x => state.Hash.Contains(x));
}
private void SetMin(State state) {
var lowest = state.Points
.OrderBy(x => x.Key.Item1)
.ThenBy(x => x.Key.Item2)
.ThenBy(x => x.Key.Item3)
.First();
state.Min = lowest;
}
private int CountSides(State state) {
int count = 0;
foreach (var point in state.Points) {
foreach (var side in point.Sides) {
if (!state.Hash.Contains(side)) count++;
}
}
return count;
}
private void SetSides(State state) {
foreach (var point in state.Points) {
point.Sides = GetSides(point.Key);
}
}
private List<Tuple<int, int, int>> GetSides(Tuple<int, int,int> point) {
var sides = new List<Tuple<int, int, int>>();
sides.Add(new Tuple<int, int, int>(point.Item1 + 1, point.Item2, point.Item3));
sides.Add(new Tuple<int, int, int>(point.Item1 - 1, point.Item2, point.Item3));
sides.Add(new Tuple<int, int, int>(point.Item1, point.Item2 + 1, point.Item3));
sides.Add(new Tuple<int, int, int>(point.Item1, point.Item2 - 1, point.Item3));
sides.Add(new Tuple<int, int, int>(point.Item1, point.Item2, point.Item3 + 1));
sides.Add(new Tuple<int, int, int>(point.Item1, point.Item2, point.Item3 - 1));
return sides;
}
private void SetPoints(List<string> input, State state) {
state.Points = input.Select(line => {
var split = line.Split(',');
return new Point() {
Key = new Tuple<int, int, int>(Convert.ToInt32(split[0]), Convert.ToInt32(split[1]), Convert.ToInt32(split[2])),
Sides = new List<Tuple<int, int, int>>()
};
}).ToList();
state.Hash = new HashSet<Tuple<int, int, int>>(state.Points.Select(x => x.Key));
}
private class State {
public List<Point> Points { get; set; }
public Point Min { get; set; }
public HashSet<Tuple<int, int, int>> Hash { get; set; }
public HashSet<Tuple<int, int, int>> Outside { get; set; }
}
public class Point {
public Tuple<int, int, int> Key { get; set; }
public List<Tuple<int, int, int>> Sides { get; set; }
}
}
}
|
using System.Collections.Generic;
namespace Euler_Logic.Problems.AdventOfCode.Y2017 {
public class Problem19 : AdventOfCodeBase {
private Dictionary<int, Dictionary<int, enumGridType>> _grid;
private Dictionary<int, Dictionary<int, char>> _letters;
private char[] _pickupLetters;
private int _steps;
private enum enumGridType {
Path,
Intersection,
Letter
}
public override string ProblemName {
get { return "Advent of Code 2017: 19"; }
}
public override string GetAnswer() {
return Answer1(Input()).ToString();
}
public override string GetAnswer2() {
return Answer2(Input()).ToString();
}
private string Answer1(List<string> input) {
GetGrid(input);
PickupLetters();
return new string(_pickupLetters);
}
private int Answer2(List<string> input) {
GetGrid(input);
PickupLetters();
return _steps;
}
private void PickupLetters() {
int x = GetStartX();
int y = 0;
var directionX = new List<int>() { 0, 1, 0, -1 };
var directionY = new List<int>() { -1, 0, 1, 0 };
int direction = 2;
_pickupLetters = new char[CountLetters()];
int letterIndex = 0;
do {
_steps++;
switch (_grid[x][y]) {
case enumGridType.Intersection:
int lastDirection = direction;
while (!_grid.ContainsKey(x + directionX[direction]) || !_grid[x + directionX[direction]].ContainsKey(y + directionY[direction])) {
do {
direction = (direction + 1) % 4;
} while ((lastDirection + 2) % 4 == direction);
}
break;
case enumGridType.Letter:
_pickupLetters[letterIndex] = _letters[x][y];
letterIndex++;
break;
}
x += directionX[direction];
y += directionY[direction];
} while (_grid.ContainsKey(x) && _grid[x].ContainsKey(y));
}
private int GetStartX() {
foreach (var x in _grid) {
if (x.Value.ContainsKey(0)) {
return x.Key;
}
}
return -1;
}
private int CountLetters() {
int count = 0;
foreach (var x in _letters) {
count += x.Value.Count;
}
return count;
}
private void GetGrid(List<string> input) {
_letters = new Dictionary<int, Dictionary<int, char>>();
_grid = new Dictionary<int, Dictionary<int, enumGridType>>();
for (int y = 0; y < input.Count; y++) {
for (int x = 0; x < input[y].Length; x++) {
switch (input[y][x]) {
case ' ':
break;
case '-':
case '|':
if (!_grid.ContainsKey(x)) {
_grid.Add(x, new Dictionary<int, enumGridType>());
}
_grid[x].Add(y, enumGridType.Path);
break;
case '+':
if (!_grid.ContainsKey(x)) {
_grid.Add(x, new Dictionary<int, enumGridType>());
}
_grid[x].Add(y, enumGridType.Intersection);
break;
default:
if (!_grid.ContainsKey(x)) {
_grid.Add(x, new Dictionary<int, enumGridType>());
}
_grid[x].Add(y, enumGridType.Letter);
if (!_letters.ContainsKey(x)) {
_letters.Add(x, new Dictionary<int, char>());
}
_letters[x].Add(y, input[y][x]);
break;
}
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace com.bigbraintank.autoadmin.angular
{
//var loginApp = angular.module('loginApp', ['ngStorage']);
public class Application : Generator
{
private List<String> applicationNames = new List<String>();
public void init(List<Object> objects)
{
foreach(var obj in objects)
{
var applicationName = (Attribute.GetCustomAttributes(obj.GetType())
.Where(a => a is annotations.angular.Application)
.FirstOrDefault()
as annotations.angular.Application)
.getName();
if (!applicationNames.Contains(applicationName))
{
applicationNames.Add(applicationName);
}
}
}
public List<String> getApplicationNames()
{
return applicationNames;
}
public string generateJavascript(string applicationName)
{
return String.Format("var {0}App = angular.module('{0}App', []);", applicationName.ToLower());
}
}
}
|
// Code generated by Microsoft (R) AutoRest Code Generator 0.9.7.0
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ApartmentApps.Client;
using ApartmentApps.Client.Models;
using Microsoft.Rest;
using Newtonsoft.Json.Linq;
namespace ApartmentApps.Client
{
internal partial class Payments : IServiceOperations<ApartmentAppsAPIService>, IPayments
{
/// <summary>
/// Initializes a new instance of the Payments class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal Payments(ApartmentAppsAPIService client)
{
this._client = client;
}
private ApartmentAppsAPIService _client;
/// <summary>
/// Gets a reference to the
/// ApartmentApps.Client.ApartmentAppsAPIService.
/// </summary>
public ApartmentAppsAPIService Client
{
get { return this._client; }
}
/// <param name='addBankAccount'>
/// Required.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<AddBankAccountResult>> AddBankAccountWithOperationResponseAsync(AddBankAccountBindingModel addBankAccount, CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Validate
if (addBankAccount == null)
{
throw new ArgumentNullException("addBankAccount");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("addBankAccount", addBankAccount);
ServiceClientTracing.Enter(invocationId, this, "AddBankAccountAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/api/Payments/AddBankAccount";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Serialize Request
string requestContent = null;
JToken requestDoc = addBankAccount.SerializeJson(null);
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
if (statusCode != HttpStatusCode.OK)
{
HttpOperationException<object> ex = new HttpOperationException<object>();
ex.Request = httpRequest;
ex.Response = httpResponse;
ex.Body = null;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
HttpOperationResponse<AddBankAccountResult> result = new HttpOperationResponse<AddBankAccountResult>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
AddBankAccountResult resultModel = new AddBankAccountResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null)
{
resultModel.DeserializeJson(responseDoc);
}
result.Body = resultModel;
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <param name='addCreditCard'>
/// Required.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<AddCreditCardResult>> AddCreditCardWithOperationResponseAsync(AddCreditCardBindingModel addCreditCard, CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Validate
if (addCreditCard == null)
{
throw new ArgumentNullException("addCreditCard");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("addCreditCard", addCreditCard);
ServiceClientTracing.Enter(invocationId, this, "AddCreditCardAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/api/Payments/AddCreditCard";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Serialize Request
string requestContent = null;
JToken requestDoc = addCreditCard.SerializeJson(null);
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
if (statusCode != HttpStatusCode.OK)
{
HttpOperationException<object> ex = new HttpOperationException<object>();
ex.Request = httpRequest;
ex.Response = httpResponse;
ex.Body = null;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
HttpOperationResponse<AddCreditCardResult> result = new HttpOperationResponse<AddCreditCardResult>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
AddCreditCardResult resultModel = new AddCreditCardResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null)
{
resultModel.DeserializeJson(responseDoc);
}
result.Body = resultModel;
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<IList<string>>> GetPaymentHistoryWithOperationResponseAsync(CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
ServiceClientTracing.Enter(invocationId, this, "GetPaymentHistoryAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/api/Payments/GetPaymentHistory";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
if (statusCode != HttpStatusCode.OK)
{
HttpOperationException<object> ex = new HttpOperationException<object>();
ex.Request = httpRequest;
ex.Response = httpResponse;
ex.Body = null;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
HttpOperationResponse<IList<string>> result = new HttpOperationResponse<IList<string>>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
IList<string> resultModel = new List<string>();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null)
{
resultModel = StringCollection.DeserializeJson(responseDoc);
}
result.Body = resultModel;
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<IList<PaymentOptionBindingModel>>> GetPaymentOptionsWithOperationResponseAsync(CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
ServiceClientTracing.Enter(invocationId, this, "GetPaymentOptionsAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/api/Payments/GetPaymentOptions";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
if (statusCode != HttpStatusCode.OK)
{
HttpOperationException<object> ex = new HttpOperationException<object>();
ex.Request = httpRequest;
ex.Response = httpResponse;
ex.Body = null;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
HttpOperationResponse<IList<PaymentOptionBindingModel>> result = new HttpOperationResponse<IList<PaymentOptionBindingModel>>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
IList<PaymentOptionBindingModel> resultModel = new List<PaymentOptionBindingModel>();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null)
{
resultModel = PaymentOptionBindingModelCollection.DeserializeJson(responseDoc);
}
result.Body = resultModel;
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <param name='paymentOptionId'>
/// Required.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<PaymentListBindingModel>> GetPaymentSummaryWithOperationResponseAsync(int paymentOptionId, CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("paymentOptionId", paymentOptionId);
ServiceClientTracing.Enter(invocationId, this, "GetPaymentSummaryAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/api/Payments/PaymentSummary";
List<string> queryParameters = new List<string>();
queryParameters.Add("paymentOptionId=" + Uri.EscapeDataString(paymentOptionId.ToString()));
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
if (statusCode != HttpStatusCode.OK)
{
HttpOperationException<object> ex = new HttpOperationException<object>();
ex.Request = httpRequest;
ex.Response = httpResponse;
ex.Body = null;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
HttpOperationResponse<PaymentListBindingModel> result = new HttpOperationResponse<PaymentListBindingModel>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
PaymentListBindingModel resultModel = new PaymentListBindingModel();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null)
{
resultModel.DeserializeJson(responseDoc);
}
result.Body = resultModel;
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<PaymentListBindingModel>> GetRentSummaryWithOperationResponseAsync(CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
ServiceClientTracing.Enter(invocationId, this, "GetRentSummaryAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/api/Payments/RentSummary";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
if (statusCode != HttpStatusCode.OK)
{
HttpOperationException<object> ex = new HttpOperationException<object>();
ex.Request = httpRequest;
ex.Response = httpResponse;
ex.Body = null;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
HttpOperationResponse<PaymentListBindingModel> result = new HttpOperationResponse<PaymentListBindingModel>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
PaymentListBindingModel resultModel = new PaymentListBindingModel();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null)
{
resultModel.DeserializeJson(responseDoc);
}
result.Body = resultModel;
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <param name='makePaymentBindingModel'>
/// Required.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<MakePaymentResult>> MakePaymentWithOperationResponseAsync(MakePaymentBindingModel makePaymentBindingModel, CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Validate
if (makePaymentBindingModel == null)
{
throw new ArgumentNullException("makePaymentBindingModel");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("makePaymentBindingModel", makePaymentBindingModel);
ServiceClientTracing.Enter(invocationId, this, "MakePaymentAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/api/Payments/MakePayment";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Serialize Request
string requestContent = null;
JToken requestDoc = makePaymentBindingModel.SerializeJson(null);
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
if (statusCode != HttpStatusCode.OK)
{
HttpOperationException<object> ex = new HttpOperationException<object>();
ex.Request = httpRequest;
ex.Response = httpResponse;
ex.Body = null;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
HttpOperationResponse<MakePaymentResult> result = new HttpOperationResponse<MakePaymentResult>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
MakePaymentResult resultModel = new MakePaymentResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null)
{
resultModel.DeserializeJson(responseDoc);
}
result.Body = resultModel;
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<string>> UpdateForteStateWithOperationResponseAsync(CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
ServiceClientTracing.Enter(invocationId, this, "UpdateForteStateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/api/Payments/UpdateForteState";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
if (statusCode != HttpStatusCode.OK)
{
HttpOperationException<object> ex = new HttpOperationException<object>();
ex.Request = httpRequest;
ex.Response = httpResponse;
ex.Body = null;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
HttpOperationResponse<string> result = new HttpOperationResponse<string>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
string resultModel = default(string);
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null)
{
resultModel = responseDoc.ToString(Newtonsoft.Json.Formatting.Indented);
}
result.Body = resultModel;
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
}
}
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Mime;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using CommandLineParser.Arguments;
using CommandLineParser.Exceptions;
namespace ProjectReferenceChecker
{
class Program
{
static void Main(string[] args)
{
var parser = new CommandLineParser.CommandLineParser
{
ShowUsageOnEmptyCommandline = false,
AcceptSlash = true
};
//Optional
var wait = new SwitchArgument(
'w', "wait",
"Wait for console input after output is completed", false)
{ Optional = true };
parser.Arguments.Add(wait);
var searchPath = new ValueArgument<string>(
'p', "searchPath",
"Directory path to search for and list files")
{ Optional = true };
parser.Arguments.Add(searchPath);
try
{
parser.ParseCommandLine(args);
var dirSearchPath = string.IsNullOrEmpty(searchPath.Value) ? Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) : searchPath.Value;
Console.Write("Scanning...");
var results = new ConcurrentBag<string>();
if (dirSearchPath != null)
{
var d = new DirectoryInfo(dirSearchPath);
var files = d.GetFiles("*.*", SearchOption.AllDirectories);
Parallel.ForEach(files, file =>
{
var relativePath = file.FullName.Replace(dirSearchPath, "");
var assemblyFileVersionInfo = FileVersionInfo.GetVersionInfo(file.FullName);
var assemblyFileInfo = new FileInfo(file.FullName);
var version = string.IsNullOrEmpty(assemblyFileVersionInfo.FileVersion)
? "0.0.0.0"
: assemblyFileVersionInfo.FileVersion;
var lastModified = string.Format($"{assemblyFileInfo.LastWriteTime.ToShortDateString()} {assemblyFileInfo.LastWriteTime.ToShortTimeString()}");
results.Add($"{lastModified.PadRight(20)} {version.PadRight(20)} {relativePath} ");
});
}
Console.WriteLine("Done.");
var counter = 0;
foreach (var result in results)
{
counter++;
Console.WriteLine($"{counter.ToString().PadRight(8)} {result}");
}
if (wait.Value)
{
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
Environment.ExitCode = 0; //Success
}
catch (CommandLineException e)
{
Console.WriteLine("Unknown CommandLineException error: " + e.Message);
}
}
}
}
|
using AlgorithmProblems.Arrays.ArraysHelper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlgorithmProblems.Sorting
{
/// <summary>
/// This uses insertion sort, but is more performant.
///
/// We will partition the original list into sublist.
/// The sublist will not be contiguous. We will get an increment and get all element with that increment.
/// For eg, if increment is 2, 0,2,4,6,8 is one sublist and the other is 1,3,5,7.
///
/// Do the insertion sort on the sublist.
/// Decrease the increment value by 1 till the final increment value is 1.
/// The final sublist containing all the elements will be sorted
///
/// This is also an adaptive algo as insertion sort is adaptive
///
/// Getting the exact running time is difficult as it depends on the increment value.
/// And there is no science behind choosing the increment value.
///
/// The running time is between O(N) to O(N^2)
/// The space requirement is O(1)
///
/// </summary>
class ShellSort
{
public static int[] Sort(int[] arr)
{
// We have picked an increment in random
int increment = arr.Length / 2;
while(increment >=1)
{
for(int startIndex = 0; startIndex<increment; startIndex++)
{
ModifiedInsertionSort(arr, startIndex, increment);
}
increment = increment/2;
}
return arr;
}
public static void ModifiedInsertionSort(int[] arr, int startIndex, int increment)
{
for(int i=startIndex; i<arr.Length; i = i+ increment)
{
int indexOfNewElement = i;
for(int j= i-increment; j>=0; j = j-increment)
{
if (arr[indexOfNewElement] < arr[j])
{
Swap(arr, indexOfNewElement, j);
indexOfNewElement = j;
}
else
{
break;
}
}
}
}
/// <summary>
/// Swap the elements in the 2 different index in the array arr
/// </summary>
/// <param name="arr">array are reference types, hence changing value of array here will be reflected in the original method making the call</param>
/// <param name="index1ToSwap">first index whose element needs to be swapped with index2ToSwap</param>
/// <param name="index2ToSwap">second index whose element needs to be swapped with index1ToSwap</param>
private static void Swap(int[] arr, int index1ToSwap, int index2ToSwap)
{
int temp = arr[index1ToSwap];
arr[index1ToSwap] = arr[index2ToSwap];
arr[index2ToSwap] = temp;
}
public static void TestSorting()
{
int[] arr = ArrayHelper.CreateArray(10);
Console.WriteLine("The unsorted array is as shown below:");
ArrayHelper.PrintArray(arr);
arr = Sort(arr);
Console.WriteLine("The sorted array is as shown below:");
ArrayHelper.PrintArray(arr);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
public class SubmitScore : MenuAction
{
public HiscoreTextbox hiScore;
public void TakeAction()
{
hiScore.SubmitHiScore();
}
}
|
using Cs_Notas.Dominio.Entities;
using Cs_Notas.Dominio.Interfaces.Repositorios;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_Notas.Infra.Data.Repositorios
{
public class RepositorioEscrituras: RepositorioBase<Escrituras>, IRepositorioEscrituras
{
public Escrituras ObterEscrituraPorSeloLivroFolhaAto(string selo, string aleatorio, string livro, int folhainicio, int folhaFim, int ato)
{
return Db.Escrituras.Where(p => p.SeloEscritura == selo && p.Aleatorio == aleatorio && p.LivroEscritura == livro && p.FolhasInicio == folhainicio && p.FolhasFim == folhaFim && p.NumeroAto == ato).FirstOrDefault();
}
public List<Escrituras> ObterEscriturasPorPeriodo(DateTime dataInicio, DateTime dataFim)
{
return Db.Escrituras.Where( p => p.DataAtoRegistro >= dataInicio && p.DataAtoRegistro <= dataFim).OrderByDescending(p => p.DataAtoRegistro).ToList();
}
public List<Escrituras> ObterEscriturarPorLivro(string livro)
{
return Db.Escrituras.Where(p => p.LivroEscritura == livro).OrderByDescending(p => p.DataAtoRegistro).ToList();
}
public List<Escrituras> ObterEscriturarPorAto(int numeroAto)
{
return Db.Escrituras.Where(p => p.NumeroAto == numeroAto).OrderByDescending(p => p.DataAtoRegistro).ToList();
}
public List<Escrituras> ObterEscriturarPorSelo(string selo)
{
return Db.Escrituras.Where(p => p.SeloEscritura == selo).OrderByDescending(p => p.DataAtoRegistro).ToList();
}
public List<Escrituras> ObterEscriturarPorParticipante(List<int> idsAto)
{
var escrituras = new List<Escrituras>();
for (int i = 0; i < idsAto.Count(); i++)
{
escrituras.Add(Db.Escrituras.Where(p => p.EscriturasId == idsAto[i]).OrderByDescending(p => p.DataAtoRegistro).FirstOrDefault());
}
return escrituras;
}
}
}
|
namespace Sentry.Internal;
internal static class Json
{
public static T Parse<T>(byte[] json, Func<JsonElement, T> factory)
{
using var jsonDocument = JsonDocument.Parse(json);
return factory.Invoke(jsonDocument.RootElement);
}
public static T Parse<T>(string json, Func<JsonElement, T> factory)
{
using var jsonDocument = JsonDocument.Parse(json);
return factory.Invoke(jsonDocument.RootElement);
}
public static T Load<T>(string filePath, Func<JsonElement, T> factory)
{
using var file = File.OpenRead(filePath);
using var jsonDocument = JsonDocument.Parse(file);
return factory.Invoke(jsonDocument.RootElement);
}
}
|
using System;
using System.Collections.Generic;
namespace CompiledValidators
{
/// <summary>
/// Represents a validator with static or validator-specific error messages.
/// </summary>
public class ErrorMessageValidatorInfo : ValidatorInfo
{
private readonly Func<string> _errorMessageFactory;
private string _errorMessage;
/// <summary>
/// Initializes a new instance of the <see cref="ErrorMessageValidatorInfo"/> class.
/// </summary>
/// <param name="validator">The validator this object describes.</param>
/// <param name="errorMessage">The static error message.</param>
public ErrorMessageValidatorInfo(object validator, string errorMessage)
: base(validator)
{
if (errorMessage == null) throw new ArgumentNullException("errorMessage");
_errorMessage = errorMessage;
}
/// <summary>
/// Initializes a new instance of the <see cref="ErrorMessageValidatorInfo"/> class.
/// </summary>
/// <param name="validator">The validator this object describes.</param>
/// <param name="errorMessage">A function that provides the error message for this validator.</param>
public ErrorMessageValidatorInfo(object validator, Func<string> errorMessage)
: base(validator)
{
if (errorMessage == null) throw new ArgumentNullException("errorMessage");
_errorMessageFactory = errorMessage;
}
/// <summary>
/// Gets the error message for this validator.
/// </summary>
/// <returns>An error message.</returns>
public string GetErrorMessage()
{
if (_errorMessage == null)
lock (_errorMessageFactory)
if (_errorMessage == null)
_errorMessage = _errorMessageFactory();
return _errorMessage;
}
}
/// <summary>
/// Represents a validator with instance-specific error messages.
/// </summary>
public class MemberErrorValidatorInfo : ValidatorInfo
{
private readonly Func<object, IEnumerable<MemberValidationErrorMessage>> _errorFactory;
/// <summary>
/// Initializes a new instance of the <see cref="MemberErrorValidatorInfo"/> class.
/// </summary>
/// <param name="validator">The validator this object describes.</param>
/// <param name="errors">A function that given an invalid object, provides the errors specific to this validator.</param>
public MemberErrorValidatorInfo(object validator, Func<object, IEnumerable<MemberValidationErrorMessage>> errors)
: base(validator)
{
if (errors == null) throw new ArgumentNullException("errors");
_errorFactory = errors;
}
/// <summary>
/// Gets the error messages this validator produces.
/// </summary>
/// <param name="obj">The object that is being validated.</param>
/// <returns>A list of errors this validator has produced.</returns>
public IEnumerable<MemberValidationErrorMessage> GetErrorMessages(object obj)
{
return _errorFactory(obj);
}
}
/// <summary>
/// Represents a validator with no error message.
/// </summary>
public class ValidatorInfo
{
/// <summary>
/// Initializes a new instance of the <see cref="ValidatorInfo"/> class.
/// </summary>
/// <param name="validator">The validator this object describes.</param>
public ValidatorInfo(object validator)
{
Validator = validator;
}
/// <summary>
/// Gets the validator this object describes.
/// </summary>
public object Validator { get; private set; }
}
}
|
using System.Collections.Generic;
namespace BattleEngine.Engine
{
public class BattleCommandsProvider
{
private List<BattleEngineCommand> _collection;
public BattleCommandsProvider()
{
_collection = new List<BattleEngineCommand>();
}
public BattleCommandsProvider add(BattleEngineCommand command)
{
_collection.Add(command);
return this;
}
public IEnumerable<BattleEngineCommand> commands
{
get { return _collection; }
}
}
}
|
using System;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace WeChatRedPacketSample
{
public class WeChatClient : IWeChatClient
{
static readonly string _WeChatRedPacketApiEndpoint = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
ICertificateFinder m_CertificateFinder;
public WeChatClient(ICertificateFinder finder)
{
if (finder == null)
throw new ArgumentNullException("finder");
m_CertificateFinder = finder;
}
public async Task<string> PostAsync(string data)
{
var certHandler = new WebRequestHandler();
certHandler.ClientCertificateOptions = ClientCertificateOption.Manual;
certHandler.UseDefaultCredentials = false;
var cert = m_CertificateFinder.Find();
certHandler.ClientCertificates.Add(cert);
using (var client = new HttpClient(certHandler, true))
{
var response = await client.PostAsync(_WeChatRedPacketApiEndpoint, new StringContent(data, Encoding.UTF8, "application/xml"));
var responseData = await response.Content.ReadAsByteArrayAsync();
var result = Encoding.UTF8.GetString(responseData);
return result;
}
}
}
}
|
/*
* Class that represents the Scene card of a Set.
* Copyright (c) Yulo Leake 2016
*/
using System;
using System.Collections.Generic;
using Deadwood.Model.Rooms;
namespace Deadwood.Model
{
class Scene
{
public readonly string name;
public readonly string desc;
public readonly int sceneNum;
public int budget { get; private set; }
public bool revealed { get; private set; }
public Dictionary<string, Role> starRoleDict { get; private set; }
public Set set { get; private set; }
public Scene(string name, string desc, int sceneNum, int budget, Dictionary<string, Role> starRoleDict)
{
this.name = name;
this.desc = desc;
this.sceneNum = sceneNum;
this.budget = budget;
this.revealed = false;
this.starRoleDict = starRoleDict;
}
public void OnMoveInto()
{
if (!revealed)
{
// Reveal the Scene
this.revealed = true;
}
}
public void AssignSet(Set set)
{
this.set = set;
}
// See if any players are acting as a star
public bool HasStarringActor()
{
foreach(Role r in starRoleDict.Values)
{
if (r.IsTaken())
{
// There is a player who is acting as a star, return true
return true;
}
}
// No players are acting as a star, return false
return false;
}
// Free all stars and the set it is attached to
public void WrapScene()
{
// Probably not necessary, but just in case
foreach(Role r in starRoleDict.Values)
{
if (r.IsTaken())
{
r.FreeRole();
}
}
// Remove itself from the set
this.set.FreeScene();
this.set = null;
}
}
}
|
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
namespace BridgeProject
{
static public class ClassBuilder
{
static public object CreateInstance(Type type)
{
// data:
if (type == typeof(IntData))
return new IntData();
else if (type == typeof(BoolData))
return new BoolData();
else if (type == typeof(CardsDistribution))
return new CardsDistribution();
else if (type == typeof(ZoneSwitcher))
return new ZoneSwitcher();
else if (type == typeof(PairSwitcher))
return new PairSwitcher();
else if (type == typeof(QuarterSwitcher))
return new QuarterSwitcher();
else if (type == typeof(FitsSwitcher))
return new FitsSwitcher();
else if (type == typeof(OnersSwitcher))
return new OnersSwitcher();
else if (type == typeof(Contract))
return new Contract();
else if (type == typeof(Result))
return new Result();
else if (type == typeof(SimpleScore))
return new SimpleScore();
// controls:
else if (type == typeof(DealInfoControl))
return new DealInfoControl();
else if (type == typeof(DealInfoControl_split))
return new DealInfoControl_split();
else if (type == typeof(ShowTextControl))
return new ShowTextControl();
else if (type == typeof(ShowTextControl_Center))
return new ShowTextControl_Center();
else if (type == typeof(SwitcherControl_Orange))
return new SwitcherControl_Orange();
else if (type == typeof(SwitcherControl_Orange_Center))
return new SwitcherControl_Orange_Center();
else if (type == typeof(ContractSelectControl))
return new ContractSelectControl();
else if (type == typeof(ResultSelectControl))
return new ResultSelectControl();
else if (type == typeof(ShowSimpleScore))
return new ShowSimpleScore();
else if (type == typeof(TextBoxInTable))
return new TextBoxInTable();
// unknown:
else
{
throw new Exception("Конструктор объектов: неизвестный тип " + type.ToString());
return type.Assembly.CreateInstance(type.AssemblyQualifiedName);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using kata_payslip_v2.DataObjects;
using kata_payslip_v2.Interfaces;
using Microsoft.VisualBasic.FileIO;
namespace kata_payslip_v2
{
public class CsvFileInputHandler : IInputHandler
{
private string FilePath { get; }
private TextFieldParser FileFieldParser;
private Dictionary<string, int> MonthIntegerDictionary;
public CsvFileInputHandler(Dictionary<string, int> monthIntegerDictionary, string filePath)
{
MonthIntegerDictionary = monthIntegerDictionary;
FilePath = filePath;
FileFieldParser = new TextFieldParser(filePath);
FileFieldParser.TextFieldType = FieldType.Delimited;
FileFieldParser.SetDelimiters(",");
FileFieldParser.ReadFields(); // Skipping the first header line in the file
}
public UserInputInformation? GetNextUserInputInformation()
{
if (FileFieldParser.EndOfData)
{
FileFieldParser.Close();
return null;
}
var fields = FileFieldParser.ReadFields();
var userInputInformation = ParseCsvFields(fields);
return userInputInformation;
}
private UserInputInformation ParseCsvFields(string[] rowFields)
{
var userInputInformation = new UserInputInformation();
userInputInformation.Name = rowFields[0];
userInputInformation.Surname = rowFields[1];
userInputInformation.Salary = ParseSalary(rowFields[2]);
userInputInformation.SuperRate = ParseSuperRate(rowFields[3]);
var paymentPeriod = ParsePaymentPeriod(rowFields[4]);
userInputInformation.PaymentStartDate = paymentPeriod.PaymentStartDate;
userInputInformation.PaymentEndDate = paymentPeriod.PaymentEndDate;
return userInputInformation;
}
private uint ParseSalary(string inputString)
{
return uint.Parse(inputString);
}
private uint ParseSuperRate(string inputString)
{
return uint.Parse(inputString.Replace("%", ""));
}
private PaymentPeriod ParsePaymentPeriod(string inputString)
{
var paymentPeriod = new PaymentPeriod();
var dateInputs = inputString.ToLower().Split(" ");
dateInputs.ToList().Remove("-");
paymentPeriod.PaymentStartDate = ParseDateTime(dateInputs[0], dateInputs[1]);
paymentPeriod.PaymentEndDate = ParseDateTime(dateInputs[3], dateInputs[4]);
return paymentPeriod;
}
private DateTime ParseDateTime(string dayString, string monthString)
{
var monthInteger = MonthIntegerDictionary[monthString];
var dayInteger = uint.Parse(dayString);
return new DateTime(1, monthInteger, checked((int) dayInteger));
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LightingBook.Tests.Api.Dto.GetItinerary.Request.Hotel
{
public class Location
{
public string Code { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
}
}
|
using System;
using Framework.Core.Common;
using OpenQA.Selenium;
using Tests.Pages.Van.SocialOrg;
namespace Tests.Pages.TaskMaster
{
public class Badges : SocialOrgNav
{
public Badges (Driver driver) : base(driver){}
public IWebElement AddBadge { get { return _driver.FindElement(By.CssSelector("input[value='Add New Badge']")); } }
public Badge AddNewBadge()
{
_driver.Click(AddBadge);
return new Badge(_driver);
}
public Badge EditBadge(int index)
{
IWebElement parentElement =
_driver.FindElement(By.CssSelector(String.Format("div.box badge:nth-of-type({0})", index)));
parentElement.FindElement(By.CssSelector("a[href]")).Click();
return new Badge(_driver);
}
public class Badge: Badges
{
public Badge(Driver driver) : base(driver){}
public void SetBadgeImage(int index)
{
_driver.FindElement(By.CssSelector(String.Format("li[data-id='{0}']", index))).Click();
}
public IWebElement BadgeName { get { return _driver.FindElement(By.CssSelector("input#Name")); } }
public IWebElement BadgeMessage { get { return _driver.FindElement(By.CssSelector("textarea#Description")); } }
public IWebElement FacebookWallPostText { get { return _driver.FindElement(By.CssSelector("textarea#DefaultWallPostText")); } }
public IWebElement StatusOff { get { return _driver.FindElement(By.CssSelector("input#IsActive_false")); } }
public IWebElement StatusOn { get { return _driver.FindElement(By.CssSelector("input#IsActiv_true")); } }
public IWebElement AwardBadgeUserFirst { get { return _driver.FindElement(By.CssSelector("select#BadgeAwardFirstDifferentiator")); } }
public IWebElement CreateOrSave { get { return _driver.FindElement(By.CssSelector("input[type='submit']")); } }
public IWebElement Cancel { get { return _driver.FindElement(By.CssSelector("span.secondaryAction")); } }
public void SetBadgeName(string name)
{
_driver.SendKeys(BadgeName, name);
}
public void SetBadgeMessgae(string msg)
{
_driver.SendKeys(BadgeMessage, msg);
}
public void SetFacebookText(string msg)
{
_driver.SendKeys(FacebookWallPostText, msg);
}
public void SetAwardBadgeUserFirst(string val)
{
_driver.SelectOptionByValue(AwardBadgeUserFirst, val);
}
public void SetAwardBadgeUserSecond(string val)
{
IWebElement awardBadgeUserSecond =
_driver.FindElement(By.CssSelector("select#BadgeAwardSecondDifferentiator"));
_driver.SelectOptionByValue(awardBadgeUserSecond,val);
}
public void ClickCreate()
{
_driver.Click(CreateOrSave);
}
public void ClickCancel()
{
_driver.Click(Cancel);
}
public void ClickStatusOff()
{
_driver.Click(StatusOff);
}
public void ClickStatusOn()
{
_driver.Click(StatusOn);
}
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class StrategyTile : MonoBehaviour
{
private static readonly IDictionary<string, Color> TypeToColor = new Dictionary<string, Color>()
{
{ "Bridge", new Color(0.5f, 0, 0f) },
{ "Grass", new Color(0.9f, 0.6f, 0) },
{ "Mountain", Color.red },
{ "Tree", new Color(0, 0.5f, 0) },
{ "Wall", Color.black },
{ "Water", Color.blue },
};
public string TileNote = "<no note>";
public string TileType = "<no type>";
public int NumberOfClicks = 0;
private void OnDrawGizmosSelected()
{
Vector3 position = this.transform.position;
position.x += 8;
position.y -= 8;
Color drawColor;
if (!StrategyTile.TypeToColor.TryGetValue(this.TileType, out drawColor))
{
drawColor = Color.black;
}
Color fillColor = drawColor;
fillColor.a = 0.25f;
Gizmos.color = fillColor;
Gizmos.DrawCube(position, new Vector3(16, 16, 0));
Gizmos.color = drawColor;
Gizmos.DrawWireCube(position, new Vector3(16, 16, 0));
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace neuros.Neurons
{
public class RNeuron : Neuron
{
double alpha = 1.5;
public RNeuron(int m) : base(m)
{
}
protected override double Activator(double x)
{
return 1 / (1 + Math.Exp(-alpha * x));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Les8Exercise4
{
//Ронжин Л.
//4. *Используя полученные знания и класс TrueFalse в качестве шаблона, разработать собственную утилиту
//хранения данных(Например: Дни рождения, Траты, Напоминалка, Английские слова и другие).
//Сделано нечто на подобии прайса с ценой и количеством товара.
static class Program
{
/// <summary>
/// Главная точка входа для приложения.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GuideBook : MonoBehaviour {
private static GuideBook Instances;
[SerializeField] private List<Sprite> images; // slot in image for up to 24 for the guidebook
private Image thisImage; //put image in
private int index = 0;
private void Awake()
{
Instances = this;
}
// Use this for initialization
void Start () {
thisImage = GetComponent<Image>();
thisImage.sprite = images[index];
}
//press to go to the next image
public void NextImage()
{
index += 1;
if (index >= images.Count)
{
index = images.Count;
return;
}
thisImage.sprite = images[index];
}
//press to go to the previous image
public void PreviousImage()
{
index -= 1;
if (index < 0)
{
index = 0;
return;
}
thisImage.sprite = images[index];
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BinaryAdder
{
class Program
{
public static void Main(string[] args)
{
Add("00", "0");
//Add your 2 binary values here
}
public static string Add(string a, string b)
{
int number_one = ConvertToInteger(a);
int number_two = ConvertToInteger(b);
if (number_one == 0)
{
if (number_two == 0)
{
return "0";
}
}
Console.WriteLine(ConvertToBinary(number_one + number_two));
Console.ReadLine();
return "";
}
public static int ConvertToInteger(string b)
{
var num = new int[100];
var p = 1;
var result = 0;
var c = b.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
var ci = (c[i]).ToString();
if (ci == "0")
{
num[i] = 0;
}
else if (ci == "1")
{
num[i] = 1;
}
}
for (int i = c.Length - 1; i >= 0; --i)
{
result = result + num[i] * p;
p = p * 2;
}
return result;
}
public static string ConvertToBinary(int number)
{
const int mask = 1;
var binary = string.Empty;
while (number > 0)
{
binary = (number & mask) + binary;
number = number >> 1;
}
return binary;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;
using System.ComponentModel;
using System.Windows.Controls;
using System.Windows.Media;
using TraceWizard.Entities;
using TraceWizard.Services;
using TraceWizard.Reporters;
namespace TraceWizard.TwApp {
public class AggregateReportPanel : UserControl {
public AggregateReportPanel(Analyses analyses) {
Initialize();
int row = 0;
int column = 0;
DisplaySummary(analyses, row, column);
}
void Initialize() {
this.Margin = new Thickness(6, 6, 6, 6);
this.VerticalAlignment = VerticalAlignment.Top;
}
void DisplaySummary(Analyses analyses, int rowExternal, int columnExternal) {
var stackPanel = new StackPanel();
this.Content = stackPanel;
var textBlock = new TextBlock();
textBlock.Text = "In this unfinished report, we display aggregate statistics (e.g., average volume of traces).";
textBlock.FontWeight = FontWeights.Bold;
stackPanel.Children.Add(textBlock);
var grid = new Grid();
grid.HorizontalAlignment = HorizontalAlignment.Left;
grid.Margin = new Thickness(6, 6, 6, 6);
stackPanel.Children.Add(grid);
int row = 0;
ColumnDefinition columnDefinition = new ColumnDefinition();
columnDefinition.Width = GridLength.Auto;
grid.ColumnDefinitions.Add(columnDefinition);
columnDefinition = new ColumnDefinition();
columnDefinition.Width = GridLength.Auto;
grid.ColumnDefinitions.Add(columnDefinition);
RowDefinition rowDefinition;
rowDefinition = new RowDefinition();
grid.RowDefinitions.Add(rowDefinition);
textBlock = new TextBlock();
textBlock.Text = "KeyCodes" + ":";
textBlock.HorizontalAlignment = HorizontalAlignment.Right;
textBlock.Padding = new Thickness(0, 0, 6, 0);
Grid.SetRow(textBlock, row);
Grid.SetColumn(textBlock, 0);
grid.Children.Add(textBlock);
textBlock = new TextBlock();
string keyCodes = string.Empty;
foreach (Analysis analysis in analyses) {
keyCodes += analysis.KeyCode + " ";
}
textBlock.Text = keyCodes;
textBlock.FontWeight = FontWeights.Normal;
textBlock.Padding = new Thickness(6, 0, 0, 0);
Grid.SetRow(textBlock, row++);
Grid.SetColumn(textBlock, 1);
grid.Children.Add(textBlock);
rowDefinition = new RowDefinition();
grid.RowDefinitions.Add(rowDefinition);
textBlock = new TextBlock();
textBlock.Text = "Number of Traces" + ":";
textBlock.HorizontalAlignment = HorizontalAlignment.Right;
textBlock.Padding = new Thickness(0, 0, 6, 0);
Grid.SetRow(textBlock, row);
Grid.SetColumn(textBlock, 0);
grid.Children.Add(textBlock);
textBlock = new TextBlock();
textBlock.Text = (analyses.Count).ToString();
textBlock.FontWeight = FontWeights.Normal;
textBlock.Padding = new Thickness(6, 0, 0, 0);
Grid.SetRow(textBlock, row++);
Grid.SetColumn(textBlock, 1);
grid.Children.Add(textBlock);
rowDefinition = new RowDefinition();
grid.RowDefinitions.Add(rowDefinition);
textBlock = new TextBlock();
textBlock.Text = "Average volume" + ":";
textBlock.HorizontalAlignment = HorizontalAlignment.Right;
textBlock.Padding = new Thickness(0, 0, 6, 0);
Grid.SetRow(textBlock, row);
Grid.SetColumn(textBlock, 0);
grid.Children.Add(textBlock);
textBlock = new TextBlock();
textBlock.Text = (analyses.VolumeAverage).ToString("0.0");
textBlock.FontWeight = FontWeights.Normal;
textBlock.Padding = new Thickness(6, 0, 0, 0);
Grid.SetRow(textBlock, row++);
Grid.SetColumn(textBlock, 1);
grid.Children.Add(textBlock);
Grid.SetRow(grid, rowExternal);
Grid.SetColumn(grid, columnExternal);
}
}
public class AggregateReporter : IProgressOperation, Reporter {
List<string> analysisFiles;
Analyses analyses;
string s = string.Empty;
AggregateReportPanel panel = null;
public UIElement Report() {
analysisFiles = TwFile.GetAnalysisFilesIncludingZipped();
if (analysisFiles.Count != 0) {
InitProgressWindow();
ReportDone();
}
return panel;
}
void InitProgressWindow() {
this._total = 0;
this._current = 0;
this._isCancelationPending = false;
this._keyCode = null;
ProgressWindow progressWindow = new ProgressWindow(this);
progressWindow.Topmost = false;
progressWindow.Owner = Application.Current.MainWindow;
progressWindow.ShowInTaskbar = false;
progressWindow.ShowDialog();
}
string GetKeyCode(string fileName) {
return System.IO.Path.GetFileNameWithoutExtension(fileName);
}
void ReportLow() {
this.Total = analysisFiles.Count;
analyses = new Analyses();
foreach (string analysisFile in analysisFiles) {
if (this._isCancelationPending == true) break;
++this.Current;
this.KeyCode = GetKeyCode(analysisFile);
Analysis analysis = Services.TwServices.CreateAnalysis(analysisFile);
analyses.Add(analysis);
}
analyses.Update();
}
void ReportDone() {
panel = new AggregateReportPanel(analyses);
}
void worker_DoWork(object sender, DoWorkEventArgs e) {
ReportLow();
}
private int _total;
private int _current;
private bool _isCancelationPending;
private string _keyCode;
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
OnComplete(EventArgs.Empty);
}
protected virtual void OnProgressChanged(EventArgs e) {
if (this.ProgressChanged != null) {
this.ProgressChanged(this, e);
}
}
protected virtual void OnProgressTotalChanged(EventArgs e) {
if (this.ProgressTotalChanged != null) {
this.ProgressTotalChanged(this, e);
}
}
protected virtual void OnComplete(EventArgs e) {
if (this.Complete != null) {
this.Complete(this, e);
}
}
public int Total {
get {
return this._total;
}
private set {
this._total = value;
OnProgressTotalChanged(EventArgs.Empty);
}
}
public int Current {
get {
return this._current;
}
private set {
this._current = value;
OnProgressChanged(EventArgs.Empty);
}
}
public string KeyCode {
get {
return this._keyCode;
}
private set {
this._keyCode = value;
OnProgressChanged(EventArgs.Empty);
}
}
public void Start() {
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
worker.RunWorkerAsync();
}
public void CancelAsync() {
this._isCancelationPending = true;
}
public event EventHandler ProgressChanged;
public event EventHandler ProgressTotalChanged;
public event EventHandler Complete;
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using socket.io;
using System.Text;
public class JsonTest : MonoBehaviour {
// Use this for initialization
void Start () {
var socket = Socket.Connect("http://ec2-52-78-8-84.ap-northeast-2.compute.amazonaws.com:3000/");
int[,] arr = new int[11,23];
for(int i = 0; i<11; i++)
{
for (int j = 0; j < 23; j++)
{
arr[i, j] = 0;
}
}
byte[] buffer = intArrayToBuffer(arr);
//string str = BitConverter.ToString(buffer);//case 1
string str = Convert.ToBase64String(buffer);//case 2
//byte[] buffer2 = strToBuffer(str);
//int[,] arr2 = bufferToIntArray(buffer2, 2, 2);
Debug.Log(str.Length);
socket.On("result",result);
socket.On("connect", () =>{
socket.Emit("test",str);
});
}
byte[] strToBuffer2(string str)
{
return Convert.FromBase64String(str);
}
byte[] strToBuffer(string str)
{
String[] arr = str.Split('-');
byte[] buffer = new byte[arr.Length];
for (int i = 0; i < buffer.Length; i++)
buffer[i] = Convert.ToByte(arr[i], 16);
return buffer;
}
int[,] bufferToIntArray(byte[] buffer,int rowSize,int colSize)
{
if(buffer.Length != rowSize * colSize * sizeof(int))
{
throw new ArgumentException("buffer.length is not equal (rowSize * colSize * sizeof(int))");
}
int[,] arr = new int[rowSize, colSize];
Buffer.BlockCopy(buffer, 0, arr, 0, arr.Length * sizeof(int));
return arr;
}
byte[] intArrayToBuffer(int[,] arr)
{
byte[] buffer = new byte[arr.Length*sizeof(int)];
Buffer.BlockCopy(arr, 0, buffer,0, buffer.Length);
return buffer;
}
void result(string data)
{
Debug.Log(data);
Debug.Log(data.Length);
string str = data.Substring(1, data.Length - 2);
Debug.Log(str);
byte[] buffer3 = strToBuffer2(str);
int[,] arr3 = bufferToIntArray(buffer3, 11, 23);
Debug.Log(arr3[1, 1]);
}
// Update is called once per frame
void Update () {
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.